@oyasmi/pipiclaw 0.7.5 → 0.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,262 @@
1
+ import { Type } from "typebox";
2
+ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
3
+ import { logSecurityEvent } from "../security/logger.js";
4
+ import { guardPath } from "../security/path-guard.js";
5
+ import { shellEscape } from "../shared/shell-escape.js";
6
+ import { DEFAULT_MAX_BYTES, truncateHead } from "./truncate.js";
7
+ /**
8
+ * Structured content search over the sandbox filesystem. The execution layer is deliberately thin
9
+ * — one `grep -rnH -B1 -A3` invocation through the shared Executor, so it works identically on the
10
+ * host and inside the Docker (busybox) sandbox with no native dependency. The value lives in the
11
+ * JS-side output shaping: per-file grouping, per-file and per-page caps, and a final byte bound, so
12
+ * a broad search can never flood the model's context the way raw `bash grep -rn` would.
13
+ */
14
+ const CONTEXT_BEFORE = 1;
15
+ const CONTEXT_AFTER = 3;
16
+ const LINE_MAX_CHARS = 512;
17
+ /** Match cap per file: tight for multi-file scopes (anti-monopoly), generous for a single file. */
18
+ const MULTI_FILE_PER_FILE_MATCHES = 20;
19
+ const SINGLE_FILE_MATCHES = 200;
20
+ /** Files shown per page; `skip` pages through the rest. */
21
+ const FILE_PAGE_LIMIT = 20;
22
+ const SEARCH_TIMEOUT_SECONDS = 30;
23
+ /** Directories never worth scanning; filtered in JS since busybox grep lacks --exclude-dir. */
24
+ const IGNORED_DIR_SEGMENTS = new Set(["node_modules", ".git", ".hg", ".svn", "dist", "build", ".next", ".cache"]);
25
+ const grepSchema = Type.Object({
26
+ label: Type.String({ description: "Brief description of what you're searching for and why (shown to user)" }),
27
+ pattern: Type.String({ description: "Extended regular expression (ERE) to search for in file contents." }),
28
+ path: Type.Optional(Type.String({ description: "File or directory to search. Defaults to the workspace root." })),
29
+ glob: Type.Optional(Type.String({
30
+ description: 'Filename filter for directory searches, e.g. "*.ts". Matched against the basename.',
31
+ })),
32
+ caseSensitive: Type.Optional(Type.Boolean({ description: "Case-sensitive match. Defaults to true." })),
33
+ skip: Type.Optional(Type.Integer({ minimum: 0, description: "File-page offset for paging through many matching files." })),
34
+ });
35
+ function formatPathBlockMessage(resolvedPath, category, reason) {
36
+ const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
37
+ if (reason) {
38
+ lines.push(`Reason: ${reason}`);
39
+ }
40
+ if (resolvedPath) {
41
+ lines.push(`Resolved path: ${resolvedPath}`);
42
+ }
43
+ return lines.join("\n");
44
+ }
45
+ /** Convert a simple `*`/`?` glob into an anchored regex matched against a basename. */
46
+ function globToRegExp(glob) {
47
+ const escaped = glob
48
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
49
+ .replace(/\*/g, ".*")
50
+ .replace(/\?/g, ".");
51
+ return new RegExp(`^${escaped}$`);
52
+ }
53
+ function truncateLine(text) {
54
+ return text.length > LINE_MAX_CHARS ? `${text.slice(0, LINE_MAX_CHARS)}…` : text;
55
+ }
56
+ function isIgnoredPath(relPath) {
57
+ return relPath.split("/").some((segment) => IGNORED_DIR_SEGMENTS.has(segment));
58
+ }
59
+ /**
60
+ * Parse `grep -rnH -B -A` output into ordered per-file entries. Match lines are `path:N:text`;
61
+ * context lines are `path-N-text`. Context is attributed by anchoring on the current match file's
62
+ * exact path string, so a hyphen or colon inside a filename can never misattribute a line. Before
63
+ * context (which precedes a file's first match) is buffered until that match names the file.
64
+ */
65
+ function parseGrepOutput(stdout) {
66
+ const files = new Map();
67
+ let currentFile;
68
+ const pendingContext = [];
69
+ const ensure = (file) => {
70
+ let entries = files.get(file);
71
+ if (!entries) {
72
+ entries = [];
73
+ files.set(file, entries);
74
+ }
75
+ return entries;
76
+ };
77
+ const attributeContext = (raw, file) => {
78
+ const prefix = `${file}-`;
79
+ if (!raw.startsWith(prefix)) {
80
+ return false;
81
+ }
82
+ const rest = raw.slice(prefix.length);
83
+ const sep = rest.indexOf("-");
84
+ if (sep < 0) {
85
+ return false;
86
+ }
87
+ const lineNum = Number.parseInt(rest.slice(0, sep), 10);
88
+ if (!Number.isFinite(lineNum)) {
89
+ return false;
90
+ }
91
+ ensure(file).push({ line: lineNum, text: rest.slice(sep + 1), isMatch: false });
92
+ return true;
93
+ };
94
+ for (const raw of stdout.split("\n")) {
95
+ if (raw === "" || raw === "--") {
96
+ continue;
97
+ }
98
+ const matchDelim = raw.match(/^(.+?):(\d+):/);
99
+ if (matchDelim) {
100
+ const file = matchDelim[1];
101
+ const line = Number.parseInt(matchDelim[2], 10);
102
+ const text = raw.slice(matchDelim[0].length);
103
+ currentFile = file;
104
+ // Retro-attribute any before-context buffered ahead of this file's first match.
105
+ for (const buffered of pendingContext.splice(0)) {
106
+ attributeContext(buffered, file);
107
+ }
108
+ ensure(file).push({ line, text, isMatch: true });
109
+ continue;
110
+ }
111
+ // Context line: attribute to the current file, else buffer for the next match.
112
+ if (!currentFile || !attributeContext(raw, currentFile)) {
113
+ pendingContext.push(raw);
114
+ }
115
+ }
116
+ return files;
117
+ }
118
+ function renderFileGroup(file, entries, perFileMatchCap) {
119
+ const lines = [`== ${file} ==`];
120
+ let matchesShown = 0;
121
+ let capped = false;
122
+ for (const entry of entries) {
123
+ if (entry.isMatch && matchesShown >= perFileMatchCap) {
124
+ capped = true;
125
+ break;
126
+ }
127
+ const marker = entry.isMatch ? "*" : " ";
128
+ lines.push(`${marker}${entry.line}:${truncateLine(entry.text)}`);
129
+ if (entry.isMatch) {
130
+ matchesShown++;
131
+ }
132
+ }
133
+ return { text: lines.join("\n"), capped, matchesShown };
134
+ }
135
+ export function createGrepTool(executor, options = {}) {
136
+ const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
137
+ const securityContext = options.securityContext ?? {
138
+ workspaceDir: process.cwd(),
139
+ workspacePath: process.cwd(),
140
+ cwd: process.cwd(),
141
+ };
142
+ return {
143
+ name: "grep",
144
+ label: "grep",
145
+ description: "Search file contents with an extended regular expression across a file or directory tree. Output is " +
146
+ "grouped by file, capped per file, paginated, and token-bounded — prefer this over `bash grep -rn`, which " +
147
+ "floods context. Match lines are marked with `*`, context lines with a space.",
148
+ parameters: grepSchema,
149
+ execute: async (_toolCallId, { pattern, path, glob, caseSensitive, skip, }, signal) => {
150
+ if (!pattern.trim()) {
151
+ throw new Error("Pattern must not be empty.");
152
+ }
153
+ const searchPath = path?.trim() || ".";
154
+ if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
155
+ const guardResult = guardPath(searchPath, "read", { ...securityContext, config: securityConfig.pathGuard });
156
+ if (!guardResult.allowed) {
157
+ logSecurityEvent(securityContext.workspaceDir, securityConfig, {
158
+ type: "path",
159
+ tool: "grep",
160
+ channelId: options.channelId,
161
+ rawPath: searchPath,
162
+ operation: "read",
163
+ resolvedPath: guardResult.resolvedPath,
164
+ category: guardResult.category,
165
+ reason: guardResult.reason,
166
+ });
167
+ throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
168
+ }
169
+ }
170
+ const flags = ["-rnH", "-E", `-B${CONTEXT_BEFORE}`, `-A${CONTEXT_AFTER}`];
171
+ if (caseSensitive === false) {
172
+ flags.push("-i");
173
+ }
174
+ // `--` terminates flags so a pattern beginning with `-` is not read as one.
175
+ const command = `grep ${flags.join(" ")} -- ${shellEscape(pattern)} ${shellEscape(searchPath)}`;
176
+ const result = await executor.exec(command, { timeout: SEARCH_TIMEOUT_SECONDS, signal });
177
+ // grep exit code 1 = no matches (normal), 0 = matches, >=2 = error.
178
+ if (result.code >= 2) {
179
+ const stderr = result.stderr.trim();
180
+ throw new Error(`grep failed: ${stderr || `exit code ${result.code}`}. Check the regex (ERE syntax) and that the path exists.`);
181
+ }
182
+ const globRegExp = glob ? globToRegExp(glob) : undefined;
183
+ const parsed = parseGrepOutput(result.stdout);
184
+ // Filter ignored dirs and (for directory scopes) the optional glob, on the basename.
185
+ const files = [];
186
+ for (const [file, entries] of parsed) {
187
+ const normalized = file.replace(/^\.\//, "");
188
+ if (isIgnoredPath(normalized)) {
189
+ continue;
190
+ }
191
+ if (globRegExp) {
192
+ const base = normalized.split("/").pop() ?? normalized;
193
+ if (!globRegExp.test(base)) {
194
+ continue;
195
+ }
196
+ }
197
+ files.push([normalized, entries]);
198
+ }
199
+ if (files.length === 0) {
200
+ const scope = glob ? `${searchPath} (glob ${glob})` : searchPath;
201
+ return {
202
+ content: [
203
+ {
204
+ type: "text",
205
+ text: `No matches found in ${scope}. Try a broader pattern, drop the glob, or widen the path.`,
206
+ },
207
+ ],
208
+ details: { kind: "grep", matchCount: 0, fileCount: 0 },
209
+ };
210
+ }
211
+ files.sort((a, b) => a[0].localeCompare(b[0]));
212
+ const isSingleFile = files.length === 1;
213
+ const perFileMatchCap = isSingleFile ? SINGLE_FILE_MATCHES : MULTI_FILE_PER_FILE_MATCHES;
214
+ const startOffset = skip && skip > 0 ? skip : 0;
215
+ const page = files.slice(startOffset, startOffset + FILE_PAGE_LIMIT);
216
+ if (page.length === 0) {
217
+ return {
218
+ content: [
219
+ {
220
+ type: "text",
221
+ text: `No more matching files (skip=${startOffset} is past the last of ${files.length}).`,
222
+ },
223
+ ],
224
+ details: { kind: "grep", matchCount: 0, fileCount: files.length },
225
+ };
226
+ }
227
+ const blocks = [];
228
+ let shownMatchCount = 0;
229
+ let anyFileCapped = false;
230
+ for (const [file, entries] of page) {
231
+ const { text, capped, matchesShown } = renderFileGroup(file, entries, perFileMatchCap);
232
+ blocks.push(text);
233
+ shownMatchCount += matchesShown;
234
+ anyFileCapped = anyFileCapped || capped;
235
+ }
236
+ const footerLines = [];
237
+ if (anyFileCapped) {
238
+ footerLines.push(`[Some files were capped at ${perFileMatchCap} matches; narrow the pattern for the rest.]`);
239
+ }
240
+ const moreFiles = files.length - (startOffset + page.length);
241
+ if (moreFiles > 0) {
242
+ footerLines.push(`[${moreFiles} more matching file(s). Use skip=${startOffset + page.length} for the next page.]`);
243
+ }
244
+ const body = blocks.join("\n\n");
245
+ const footer = footerLines.length > 0 ? `\n\n${footerLines.join("\n")}` : "";
246
+ const truncation = truncateHead(body);
247
+ let outputText = truncation.content + footer;
248
+ if (truncation.truncated) {
249
+ outputText += `\n\n[Output truncated at ${DEFAULT_MAX_BYTES / 1024}KB; narrow the pattern or path to see the rest.]`;
250
+ }
251
+ return {
252
+ content: [{ type: "text", text: outputText }],
253
+ details: {
254
+ kind: "grep",
255
+ matchCount: shownMatchCount,
256
+ fileCount: files.length,
257
+ shownFileCount: page.length,
258
+ },
259
+ };
260
+ },
261
+ };
262
+ }
@@ -1,3 +1,4 @@
1
+ import { getChannelJobManager } from "../agent/job-manager.js";
1
2
  import { APP_HOME_DIR } from "../paths.js";
2
3
  import { loadSecurityConfig } from "../security/config.js";
3
4
  import { createSubAgentTool } from "../subagents/tool.js";
@@ -26,6 +27,10 @@ export function createPipiclawTools(options) {
26
27
  webConfig: toolsConfig.tools.web,
27
28
  toolsConfig,
28
29
  rtkEnabled: toolsConfig.tools.rtk.enabled,
30
+ // Background jobs are opt-in; when off, bash `async` errors and the job tool is not registered.
31
+ jobManager: toolsConfig.tools.jobs.enabled
32
+ ? getChannelJobManager(options.channelId, options.executor)
33
+ : undefined,
29
34
  getCurrentModel: options.getCurrentModel,
30
35
  getAvailableModels: options.getAvailableModels,
31
36
  resolveApiKey: options.resolveApiKey,
@@ -0,0 +1,13 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "typebox";
3
+ import type { ChannelJobManager } from "../agent/job-manager.js";
4
+ declare const jobSchema: Type.TObject<{
5
+ label: Type.TString;
6
+ op: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"poll">, Type.TLiteral<"cancel">]>;
7
+ ids: Type.TOptional<Type.TArray<Type.TString>>;
8
+ }>;
9
+ export interface JobToolOptions {
10
+ jobManager: ChannelJobManager;
11
+ }
12
+ export declare function createJobTool(options: JobToolOptions): AgentTool<typeof jobSchema>;
13
+ export {};
@@ -0,0 +1,92 @@
1
+ import { Type } from "typebox";
2
+ import { truncateTail } from "./truncate.js";
3
+ const jobSchema = Type.Object({
4
+ label: Type.String({ description: "Brief description of what you're checking (shown to user)" }),
5
+ op: Type.Union([Type.Literal("list"), Type.Literal("poll"), Type.Literal("cancel")], {
6
+ description: '"list" a snapshot of background jobs, "poll" to wait (briefly) for one to finish, or "cancel" jobs by id.',
7
+ }),
8
+ ids: Type.Optional(Type.Array(Type.String(), {
9
+ description: "Job ids for poll/cancel. For poll, omit to watch all running jobs.",
10
+ })),
11
+ });
12
+ function formatDuration(ms) {
13
+ const seconds = Math.round(ms / 1000);
14
+ if (seconds < 60) {
15
+ return `${seconds}s`;
16
+ }
17
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
18
+ }
19
+ function formatJobLine(job) {
20
+ const exit = job.exitCode !== undefined ? `, exit ${job.exitCode}` : "";
21
+ return `- [${job.id}] ${job.label} — ${job.status} (${formatDuration(job.durationMs)}${exit})`;
22
+ }
23
+ export function createJobTool(options) {
24
+ const { jobManager } = options;
25
+ async function completedDetail(jobs) {
26
+ const sections = [];
27
+ for (const job of jobs) {
28
+ const output = await jobManager.readOutput(job.id);
29
+ const tail = output ? truncateTail(output.text).content : "";
30
+ const body = tail.trim() ? tail : "(no output)";
31
+ const path = output ? `\nFull output: ${output.spillFile}` : "";
32
+ sections.push(`### [${job.id}] ${job.label} — ${job.status}${job.exitCode !== undefined ? `, exit ${job.exitCode}` : ""}\n${body}${path}`);
33
+ }
34
+ return sections;
35
+ }
36
+ return {
37
+ name: "job",
38
+ label: "job",
39
+ description: "Inspect and control background bash jobs (started with bash async:true). op=list shows a snapshot; " +
40
+ "op=poll waits briefly for a running job to finish and returns its output; op=cancel stops jobs by id. " +
41
+ "To be woken when a long job is likely done, schedule a check-in with event_manage instead of blocking.",
42
+ parameters: jobSchema,
43
+ execute: async (_toolCallId, { op, ids }, signal) => {
44
+ if (op === "cancel") {
45
+ if (!ids || ids.length === 0) {
46
+ throw new Error("cancel requires at least one job id.");
47
+ }
48
+ const outcomes = await jobManager.cancel(ids, signal);
49
+ const text = outcomes.map((outcome) => `- [${outcome.id}] ${outcome.status}`).join("\n");
50
+ return {
51
+ content: [{ type: "text", text: `Cancel results:\n${text}` }],
52
+ details: { kind: "job", op: "cancel", outcomes },
53
+ };
54
+ }
55
+ if (op === "list") {
56
+ const jobs = await jobManager.list(signal);
57
+ if (jobs.length === 0) {
58
+ return {
59
+ content: [{ type: "text", text: "No background jobs." }],
60
+ details: { kind: "job", op: "list", jobs },
61
+ };
62
+ }
63
+ return {
64
+ content: [{ type: "text", text: jobs.map(formatJobLine).join("\n") }],
65
+ details: { kind: "job", op: "list", jobs },
66
+ };
67
+ }
68
+ // poll
69
+ const jobs = await jobManager.poll(ids, signal);
70
+ if (jobs.length === 0) {
71
+ return {
72
+ content: [{ type: "text", text: "No matching running jobs to wait for." }],
73
+ details: { kind: "job", op: "poll", jobs },
74
+ };
75
+ }
76
+ const finished = jobs.filter((job) => job.status !== "running");
77
+ const running = jobs.filter((job) => job.status === "running");
78
+ const parts = [];
79
+ if (finished.length > 0) {
80
+ parts.push(`## Finished (${finished.length})`, ...(await completedDetail(finished)));
81
+ }
82
+ if (running.length > 0) {
83
+ parts.push(`## Still running (${running.length})`, ...running.map(formatJobLine));
84
+ parts.push("Poll again to keep waiting, or schedule a check-in with event_manage.");
85
+ }
86
+ return {
87
+ content: [{ type: "text", text: parts.join("\n\n") }],
88
+ details: { kind: "job", op: "poll", jobs },
89
+ };
90
+ },
91
+ };
92
+ }
@@ -0,0 +1,24 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import type { Api, Model } from "@earendil-works/pi-ai";
3
+ import { Type } from "typebox";
4
+ import type { MemoryCandidateStore } from "../memory/candidates.js";
5
+ import { type ChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
6
+ declare const memoryManageSchema: Type.TObject<{
7
+ label: Type.TString;
8
+ op: Type.TUnion<[Type.TLiteral<"save">, Type.TLiteral<"search">, Type.TLiteral<"forget">]>;
9
+ content: Type.TOptional<Type.TString>;
10
+ query: Type.TOptional<Type.TString>;
11
+ target: Type.TOptional<Type.TString>;
12
+ kind: Type.TOptional<Type.TUnion<[Type.TLiteral<"preference">, Type.TLiteral<"fact">, Type.TLiteral<"decision">, Type.TLiteral<"constraint">, Type.TLiteral<"open-loop">]>>;
13
+ }>;
14
+ export interface MemoryManageToolOptions {
15
+ channelId: string;
16
+ channelDir: string;
17
+ workspaceDir: string;
18
+ memoryCandidateStore: MemoryCandidateStore;
19
+ getCurrentModel: () => Model<Api>;
20
+ resolveApiKey: (model: Model<Api>) => Promise<string>;
21
+ channelMemoryQueue?: ChannelMemoryQueue;
22
+ }
23
+ export declare function createMemoryManageTool(options: MemoryManageToolOptions): AgentTool<typeof memoryManageSchema>;
24
+ export {};
@@ -0,0 +1,150 @@
1
+ import { Type } from "typebox";
2
+ import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
3
+ import { applyChannelMemoryOps, getChannelMemoryPath, parseChannelMemoryEntries } from "../memory/files.js";
4
+ import { recallRelevantMemory } from "../memory/recall.js";
5
+ import { appendMemoryReviewLog } from "../memory/review-log.js";
6
+ import { readOptionalTextFile } from "../shared/fs-utils.js";
7
+ const memoryManageSchema = Type.Object({
8
+ label: Type.String({ description: "Brief description of the memory change (shown to user)" }),
9
+ op: Type.Union([Type.Literal("save"), Type.Literal("search"), Type.Literal("forget")], {
10
+ description: '"save" a durable fact, "search" this channel\'s stored memory on demand, or "forget" a stored entry the user asked you to drop.',
11
+ }),
12
+ content: Type.Optional(Type.String({
13
+ description: "For save: the durable fact as a single self-contained, keyword-rich sentence, written so future keyword search can find it.",
14
+ })),
15
+ query: Type.Optional(Type.String({ description: "For search: what to look for in stored memory." })),
16
+ target: Type.Optional(Type.String({
17
+ description: "For forget: text identifying the stored entry to remove. Must match exactly one entry; use search first to confirm the wording.",
18
+ })),
19
+ kind: Type.Optional(Type.Union([
20
+ Type.Literal("preference"),
21
+ Type.Literal("fact"),
22
+ Type.Literal("decision"),
23
+ Type.Literal("constraint"),
24
+ Type.Literal("open-loop"),
25
+ ], { description: "For save: what kind of durable memory this is." })),
26
+ });
27
+ function textResult(text, details) {
28
+ return { content: [{ type: "text", text }], details };
29
+ }
30
+ export function createMemoryManageTool(options) {
31
+ const queue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
32
+ async function save(content, kind) {
33
+ const trimmed = (content ?? "").trim();
34
+ if (!trimmed) {
35
+ return textResult("No content provided; nothing was saved.", {
36
+ kind: "memory_manage",
37
+ op: "save",
38
+ saved: false,
39
+ });
40
+ }
41
+ // Serialize through the shared channel memory queue so this never races with background
42
+ // consolidation/maintenance on the same channel's files.
43
+ const result = await queue.run(options.channelId, () => applyChannelMemoryOps(options.channelDir, [{ op: "add", content: trimmed }]));
44
+ options.memoryCandidateStore.invalidate(getChannelMemoryPath(options.channelDir));
45
+ return textResult(`Saved to channel memory${kind ? ` (${kind})` : ""}.`, {
46
+ kind: "memory_manage",
47
+ op: "save",
48
+ saved: result.added > 0,
49
+ });
50
+ }
51
+ async function search(query) {
52
+ const trimmed = (query ?? "").trim();
53
+ if (!trimmed) {
54
+ return textResult("Provide a query to search stored memory.", {
55
+ kind: "memory_manage",
56
+ op: "search",
57
+ resultCount: 0,
58
+ });
59
+ }
60
+ // Reuse the recall scoring pipeline (single source of scoring truth) but scoped to the
61
+ // distilled durable files and with model rerank off, so this stays a cheap deterministic
62
+ // point-query distinct from the passive per-turn recall injection.
63
+ const model = options.getCurrentModel();
64
+ const { items } = await recallRelevantMemory({
65
+ query: trimmed,
66
+ channelId: options.channelId,
67
+ workspaceDir: options.workspaceDir,
68
+ channelDir: options.channelDir,
69
+ allowedSources: ["channel-memory", "channel-history"],
70
+ maxCandidates: 8,
71
+ maxInjected: 8,
72
+ maxChars: 4000,
73
+ rerankWithModel: false,
74
+ autoRerank: false,
75
+ model,
76
+ resolveApiKey: options.resolveApiKey,
77
+ candidateStore: options.memoryCandidateStore,
78
+ });
79
+ if (items.length === 0) {
80
+ return textResult(`No stored memory matched "${trimmed}". Try a broader query, or the fact may not be saved yet.`, { kind: "memory_manage", op: "search", resultCount: 0 });
81
+ }
82
+ const rendered = items
83
+ .map((item, index) => `${index + 1}. [${item.source}/${item.title}] ${item.content}`)
84
+ .join("\n");
85
+ return textResult(`Found ${items.length} stored memory entr${items.length === 1 ? "y" : "ies"}:\n\n${rendered}`, {
86
+ kind: "memory_manage",
87
+ op: "search",
88
+ resultCount: items.length,
89
+ });
90
+ }
91
+ async function forget(target) {
92
+ const trimmed = (target ?? "").trim();
93
+ if (!trimmed) {
94
+ return textResult("Provide the text of the entry to forget.", {
95
+ kind: "memory_manage",
96
+ op: "forget",
97
+ forgotten: false,
98
+ });
99
+ }
100
+ const memoryPath = getChannelMemoryPath(options.channelDir);
101
+ const existing = await readOptionalTextFile(memoryPath);
102
+ const entries = parseChannelMemoryEntries(existing);
103
+ const needle = trimmed.toLowerCase();
104
+ const matches = entries.filter((entry) => entry.content === trimmed || entry.content.toLowerCase().includes(needle));
105
+ if (matches.length === 0) {
106
+ return textResult(`No stored memory entry matched "${trimmed}"; nothing was removed.`, {
107
+ kind: "memory_manage",
108
+ op: "forget",
109
+ forgotten: false,
110
+ });
111
+ }
112
+ if (matches.length > 1) {
113
+ // Never guess which entry to delete; make the model disambiguate.
114
+ const candidates = matches.map((entry, index) => `${index + 1}. ${entry.content}`).join("\n");
115
+ throw new Error(`"${trimmed}" matched ${matches.length} entries; be more specific so only one is removed:\n${candidates}`);
116
+ }
117
+ const removed = matches[0];
118
+ await queue.run(options.channelId, () => applyChannelMemoryOps(options.channelDir, [{ op: "invalidate", targetId: removed.id, reason: "user forget" }]));
119
+ options.memoryCandidateStore.invalidate(memoryPath);
120
+ // Audit trail: record what was forgotten so the maintenance log can answer "who dropped what,
121
+ // when, and why" — the `.memory-backups/` copy is a recovery aid, not an audit record.
122
+ await appendMemoryReviewLog(options.channelDir, {
123
+ timestamp: new Date().toISOString(),
124
+ channelId: options.channelId,
125
+ reason: "user-forget",
126
+ actions: [{ op: "forget", target: removed.content, matchedBy: trimmed }],
127
+ }).catch(() => { });
128
+ return textResult(`Forgot: ${removed.content}`, { kind: "memory_manage", op: "forget", forgotten: true });
129
+ }
130
+ return {
131
+ name: "memory_manage",
132
+ label: "memory_manage",
133
+ description: "Manage this channel's durable MEMORY.md: save a durable fact the user asks you to remember, search stored " +
134
+ "memory on demand mid-task, or forget an entry the user asks you to drop. Prefer this over editing MEMORY.md " +
135
+ "directly — it serializes with background consolidation and keeps memory recallable. Not for transient task state.",
136
+ parameters: memoryManageSchema,
137
+ execute: async (_toolCallId, args) => {
138
+ switch (args.op) {
139
+ case "save":
140
+ return save(args.content, args.kind);
141
+ case "search":
142
+ return search(args.query);
143
+ case "forget":
144
+ return forget(args.target);
145
+ default:
146
+ throw new Error('Unsupported memory op. Use "save", "search", or "forget".');
147
+ }
148
+ },
149
+ };
150
+ }