opencode-claude-memory 1.7.6 → 1.7.8
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 +104 -213
- package/dist/agents.d.ts +12 -0
- package/dist/agents.js +69 -0
- package/dist/config.d.ts +112 -0
- package/dist/config.js +79 -0
- package/dist/extraction/ExtractionCoordinator.d.ts +62 -0
- package/dist/extraction/ExtractionCoordinator.js +386 -0
- package/dist/extraction/autodream.d.ts +33 -0
- package/dist/extraction/autodream.js +85 -0
- package/dist/extraction/forkSession.d.ts +37 -0
- package/dist/extraction/forkSession.js +133 -0
- package/dist/extraction/lock.d.ts +29 -0
- package/dist/extraction/lock.js +191 -0
- package/dist/extraction/prompts.d.ts +5 -0
- package/dist/extraction/prompts.js +78 -0
- package/dist/extraction/state.d.ts +38 -0
- package/dist/extraction/state.js +159 -0
- package/dist/hooks/ignore.d.ts +6 -0
- package/dist/hooks/ignore.js +53 -0
- package/dist/hooks/messages.d.ts +14 -0
- package/dist/hooks/messages.js +96 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +50 -633
- package/dist/prompt/sections.d.ts +7 -0
- package/dist/{prompt.js → prompt/sections.js} +16 -72
- package/dist/prompt/systemPrompt.d.ts +7 -0
- package/dist/prompt/systemPrompt.js +64 -0
- package/dist/recall/RecallCoordinator.d.ts +36 -0
- package/dist/recall/RecallCoordinator.js +140 -0
- package/dist/recall/format.d.ts +17 -0
- package/dist/{recall.js → recall/format.js} +13 -36
- package/dist/{recallSelector.d.ts → recall/selector.d.ts} +26 -16
- package/dist/recall/selector.js +92 -0
- package/dist/sdk.d.ts +12 -0
- package/dist/sdk.js +8 -0
- package/dist/store/MemoryStore.d.ts +41 -0
- package/dist/store/MemoryStore.js +105 -0
- package/dist/store/frontmatter.d.ts +25 -0
- package/dist/store/frontmatter.js +61 -0
- package/dist/store/indexFile.d.ts +15 -0
- package/dist/store/indexFile.js +153 -0
- package/dist/{paths.d.ts → store/paths.d.ts} +7 -6
- package/dist/store/paths.js +187 -0
- package/dist/store/scan.d.ts +29 -0
- package/dist/store/scan.js +112 -0
- package/dist/tools.d.ts +9 -0
- package/dist/tools.js +142 -0
- package/dist/util/exclusiveFile.d.ts +11 -0
- package/dist/util/exclusiveFile.js +108 -0
- package/dist/util/legacyShellHook.d.ts +3 -0
- package/dist/util/legacyShellHook.js +23 -0
- package/dist/util/log.d.ts +6 -0
- package/dist/util/log.js +29 -0
- package/dist/util/ownedSessions.d.ts +7 -0
- package/dist/util/ownedSessions.js +39 -0
- package/dist/util/timeout.d.ts +5 -0
- package/dist/util/timeout.js +39 -0
- package/package.json +15 -8
- package/bin/opencode-memory +0 -1436
- package/dist/memory.d.ts +0 -25
- package/dist/memory.js +0 -203
- package/dist/memoryScan.d.ts +0 -20
- package/dist/memoryScan.js +0 -106
- package/dist/nativeExtraction.d.ts +0 -2
- package/dist/nativeExtraction.js +0 -38
- package/dist/paths.js +0 -141
- package/dist/prompt.d.ts +0 -4
- package/dist/recall.d.ts +0 -12
- package/dist/recallSelector.js +0 -154
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const FRONTMATTER_EXAMPLE: string[];
|
|
2
|
+
export declare const TYPES_SECTION: string;
|
|
3
|
+
export declare const WHAT_NOT_TO_SAVE: string;
|
|
4
|
+
export declare const WHEN_TO_ACCESS: string;
|
|
5
|
+
export declare const TRUSTING_RECALL: string;
|
|
6
|
+
export declare const PERSISTENCE_SECTION: string;
|
|
7
|
+
export declare function buildSearchingPastContextSection(memoryDir: string, projectDir: string): string[];
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import { getMemoryDir, ENTRYPOINT_NAME, MAX_ENTRYPOINT_LINES, getProjectDir } from "./paths.js";
|
|
1
|
+
// Constant prompt text ported from Claude Code's memoryTypes.ts / memdir.ts.
|
|
2
|
+
import { MEMORY_TYPES } from "../store/frontmatter.js";
|
|
4
3
|
// Port of Claude Code's MEMORY_FRONTMATTER_EXAMPLE from memoryTypes.ts
|
|
5
|
-
const FRONTMATTER_EXAMPLE = [
|
|
4
|
+
export const FRONTMATTER_EXAMPLE = [
|
|
6
5
|
"```markdown",
|
|
7
6
|
"---",
|
|
8
7
|
"name: {{memory name}}",
|
|
@@ -14,7 +13,7 @@ const FRONTMATTER_EXAMPLE = [
|
|
|
14
13
|
"```",
|
|
15
14
|
];
|
|
16
15
|
// Port of Claude Code's TYPES_SECTION_INDIVIDUAL from memoryTypes.ts
|
|
17
|
-
const TYPES_SECTION = [
|
|
16
|
+
export const TYPES_SECTION = [
|
|
18
17
|
"## Types of memory",
|
|
19
18
|
"",
|
|
20
19
|
"There are several discrete types of memory that you can store in your memory system:",
|
|
@@ -36,7 +35,7 @@ const TYPES_SECTION = [
|
|
|
36
35
|
"<type>",
|
|
37
36
|
" <name>feedback</name>",
|
|
38
37
|
" <description>Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>",
|
|
39
|
-
|
|
38
|
+
' <when_to_save>Any time the user corrects your approach ("no not that", "don\'t", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>',
|
|
40
39
|
" <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>",
|
|
41
40
|
" <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>",
|
|
42
41
|
" <examples>",
|
|
@@ -53,7 +52,7 @@ const TYPES_SECTION = [
|
|
|
53
52
|
"<type>",
|
|
54
53
|
" <name>project</name>",
|
|
55
54
|
" <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>",
|
|
56
|
-
|
|
55
|
+
' <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>',
|
|
57
56
|
" <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>",
|
|
58
57
|
" <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>",
|
|
59
58
|
" <examples>",
|
|
@@ -81,7 +80,7 @@ const TYPES_SECTION = [
|
|
|
81
80
|
"",
|
|
82
81
|
].join("\n");
|
|
83
82
|
// Port of Claude Code's WHAT_NOT_TO_SAVE_SECTION from memoryTypes.ts
|
|
84
|
-
const WHAT_NOT_TO_SAVE = [
|
|
83
|
+
export const WHAT_NOT_TO_SAVE = [
|
|
85
84
|
"## What NOT to save in memory",
|
|
86
85
|
"",
|
|
87
86
|
"- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.",
|
|
@@ -93,7 +92,7 @@ const WHAT_NOT_TO_SAVE = [
|
|
|
93
92
|
"These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.",
|
|
94
93
|
].join("\n");
|
|
95
94
|
// Port of Claude Code's WHEN_TO_ACCESS_SECTION from memoryTypes.ts
|
|
96
|
-
const WHEN_TO_ACCESS = [
|
|
95
|
+
export const WHEN_TO_ACCESS = [
|
|
97
96
|
"## When to access memories",
|
|
98
97
|
"- When memories seem relevant, or the user references prior-conversation work.",
|
|
99
98
|
"- You MUST access memory when the user explicitly asks you to check, recall, or remember.",
|
|
@@ -101,7 +100,7 @@ const WHEN_TO_ACCESS = [
|
|
|
101
100
|
"- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.",
|
|
102
101
|
].join("\n");
|
|
103
102
|
// Port of Claude Code's TRUSTING_RECALL_SECTION from memoryTypes.ts
|
|
104
|
-
const TRUSTING_RECALL = [
|
|
103
|
+
export const TRUSTING_RECALL = [
|
|
105
104
|
"## Before recommending from memory",
|
|
106
105
|
"",
|
|
107
106
|
"A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:",
|
|
@@ -114,10 +113,16 @@ const TRUSTING_RECALL = [
|
|
|
114
113
|
"",
|
|
115
114
|
"A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot.",
|
|
116
115
|
].join("\n");
|
|
116
|
+
export const PERSISTENCE_SECTION = [
|
|
117
|
+
"## Memory and other forms of persistence",
|
|
118
|
+
"Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.",
|
|
119
|
+
"- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.",
|
|
120
|
+
"- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.",
|
|
121
|
+
].join("\n");
|
|
117
122
|
// Port of Claude Code's buildSearchingPastContextSection() from memdir.ts.
|
|
118
123
|
// Guides the model to grep memory files and session transcripts when
|
|
119
124
|
// looking for past context, rather than guessing or hallucinating.
|
|
120
|
-
function buildSearchingPastContextSection(memoryDir, projectDir) {
|
|
125
|
+
export function buildSearchingPastContextSection(memoryDir, projectDir) {
|
|
121
126
|
const memSearch = `grep -rn "<search term>" ${memoryDir} --include="*.md"`;
|
|
122
127
|
const transcriptSearch = `grep -rn "<search term>" ${projectDir}/ --include="*.jsonl"`;
|
|
123
128
|
return [
|
|
@@ -136,64 +141,3 @@ function buildSearchingPastContextSection(memoryDir, projectDir) {
|
|
|
136
141
|
"",
|
|
137
142
|
];
|
|
138
143
|
}
|
|
139
|
-
export function buildMemorySystemPrompt(worktree, recalledMemoriesSection, options = {}) {
|
|
140
|
-
const memoryDir = getMemoryDir(worktree);
|
|
141
|
-
const projectDir = getProjectDir(worktree);
|
|
142
|
-
const indexContent = readIndex(worktree);
|
|
143
|
-
const includeIndex = options.includeIndex ?? true;
|
|
144
|
-
const howToSave = [
|
|
145
|
-
"## How to save memories",
|
|
146
|
-
"",
|
|
147
|
-
"Saving a memory is a two-step process:",
|
|
148
|
-
"",
|
|
149
|
-
'**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:',
|
|
150
|
-
"",
|
|
151
|
-
...FRONTMATTER_EXAMPLE,
|
|
152
|
-
"",
|
|
153
|
-
`**Step 2** — add a pointer to that file in \`${ENTRYPOINT_NAME}\`. \`${ENTRYPOINT_NAME}\` is an index, not a memory — each entry should be one line, under ~150 characters: \`- [Title](file.md) — one-line hook\`. It has no frontmatter. Never write memory content directly into \`${ENTRYPOINT_NAME}\`.`,
|
|
154
|
-
"",
|
|
155
|
-
`- \`${ENTRYPOINT_NAME}\` is always loaded into your conversation context — lines after ${MAX_ENTRYPOINT_LINES} will be truncated, so keep the index concise`,
|
|
156
|
-
"- Keep the name, description, and type fields in memory files up-to-date with the content",
|
|
157
|
-
"- Organize memory semantically by topic, not chronologically",
|
|
158
|
-
"- Update or remove memories that turn out to be wrong or outdated",
|
|
159
|
-
"- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.",
|
|
160
|
-
].join("\n");
|
|
161
|
-
const lines = [
|
|
162
|
-
"# Auto Memory",
|
|
163
|
-
"",
|
|
164
|
-
`You have a persistent, file-based memory system at \`${memoryDir}\`. This directory already exists — write to it directly (do not run mkdir or check for its existence).`,
|
|
165
|
-
"",
|
|
166
|
-
"You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.",
|
|
167
|
-
"",
|
|
168
|
-
"If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.",
|
|
169
|
-
"",
|
|
170
|
-
TYPES_SECTION,
|
|
171
|
-
WHAT_NOT_TO_SAVE,
|
|
172
|
-
"",
|
|
173
|
-
howToSave,
|
|
174
|
-
"",
|
|
175
|
-
WHEN_TO_ACCESS,
|
|
176
|
-
"",
|
|
177
|
-
TRUSTING_RECALL,
|
|
178
|
-
"",
|
|
179
|
-
"## Memory and other forms of persistence",
|
|
180
|
-
"Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.",
|
|
181
|
-
"- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.",
|
|
182
|
-
"- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.",
|
|
183
|
-
"",
|
|
184
|
-
...buildSearchingPastContextSection(memoryDir, projectDir),
|
|
185
|
-
];
|
|
186
|
-
if (includeIndex) {
|
|
187
|
-
if (indexContent.trim()) {
|
|
188
|
-
const { content: truncated } = truncateEntrypoint(indexContent);
|
|
189
|
-
lines.push(`## ${ENTRYPOINT_NAME}`, "", truncated);
|
|
190
|
-
}
|
|
191
|
-
else {
|
|
192
|
-
lines.push(`## ${ENTRYPOINT_NAME}`, "", `Your ${ENTRYPOINT_NAME} is currently empty. When you save new memories, they will appear here.`);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
if (recalledMemoriesSection?.trim()) {
|
|
196
|
-
lines.push("", recalledMemoriesSection);
|
|
197
|
-
}
|
|
198
|
-
return lines.join("\n");
|
|
199
|
-
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { MemoryStore } from "../store/MemoryStore.js";
|
|
2
|
+
export declare const AUTO_MEMORY_MARKER = "<!-- opencode-claude-memory -->";
|
|
3
|
+
export declare const RECALLED_MEMORIES_HEADING = "## Recalled Memories";
|
|
4
|
+
export type BuildMemorySystemPromptOptions = {
|
|
5
|
+
includeIndex?: boolean;
|
|
6
|
+
};
|
|
7
|
+
export declare function buildMemorySystemPrompt(store: Pick<MemoryStore, "memoryDir" | "projectDir" | "readIndex">, recalledMemoriesSection?: string, options?: BuildMemorySystemPromptOptions): string;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { truncateEntrypoint } from "../store/indexFile.js";
|
|
2
|
+
import { ENTRYPOINT_NAME, MAX_ENTRYPOINT_LINES } from "../store/paths.js";
|
|
3
|
+
import { buildSearchingPastContextSection, FRONTMATTER_EXAMPLE, PERSISTENCE_SECTION, TRUSTING_RECALL, TYPES_SECTION, WHAT_NOT_TO_SAVE, WHEN_TO_ACCESS, } from "./sections.js";
|
|
4
|
+
// First line of every system prompt segment this plugin injects. The messages transform uses it to
|
|
5
|
+
// find (and, on ignore-memory turns, strip) the plugin's own segment without guessing from headings.
|
|
6
|
+
export const AUTO_MEMORY_MARKER = "<!-- opencode-claude-memory -->";
|
|
7
|
+
export const RECALLED_MEMORIES_HEADING = "## Recalled Memories";
|
|
8
|
+
export function buildMemorySystemPrompt(store, recalledMemoriesSection, options = {}) {
|
|
9
|
+
const includeIndex = options.includeIndex ?? true;
|
|
10
|
+
const howToSave = [
|
|
11
|
+
"## How to save memories",
|
|
12
|
+
"",
|
|
13
|
+
"Saving a memory is a two-step process:",
|
|
14
|
+
"",
|
|
15
|
+
"**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:",
|
|
16
|
+
"",
|
|
17
|
+
...FRONTMATTER_EXAMPLE,
|
|
18
|
+
"",
|
|
19
|
+
`**Step 2** — add a pointer to that file in \`${ENTRYPOINT_NAME}\`. \`${ENTRYPOINT_NAME}\` is an index, not a memory — each entry should be one line, under ~150 characters: \`- [Title](file.md) — one-line hook\`. It has no frontmatter. Never write memory content directly into \`${ENTRYPOINT_NAME}\`.`,
|
|
20
|
+
"",
|
|
21
|
+
`- \`${ENTRYPOINT_NAME}\` is always loaded into your conversation context — lines after ${MAX_ENTRYPOINT_LINES} will be truncated, so keep the index concise`,
|
|
22
|
+
"- Keep the name, description, and type fields in memory files up-to-date with the content",
|
|
23
|
+
"- Organize memory semantically by topic, not chronologically",
|
|
24
|
+
"- Update or remove memories that turn out to be wrong or outdated",
|
|
25
|
+
"- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.",
|
|
26
|
+
].join("\n");
|
|
27
|
+
const lines = [
|
|
28
|
+
AUTO_MEMORY_MARKER,
|
|
29
|
+
"# Auto Memory",
|
|
30
|
+
"",
|
|
31
|
+
`You have a persistent, file-based memory system at \`${store.memoryDir}\`. This directory already exists — write to it directly (do not run mkdir or check for its existence).`,
|
|
32
|
+
"",
|
|
33
|
+
"You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.",
|
|
34
|
+
"",
|
|
35
|
+
"If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.",
|
|
36
|
+
"",
|
|
37
|
+
TYPES_SECTION,
|
|
38
|
+
WHAT_NOT_TO_SAVE,
|
|
39
|
+
"",
|
|
40
|
+
howToSave,
|
|
41
|
+
"",
|
|
42
|
+
WHEN_TO_ACCESS,
|
|
43
|
+
"",
|
|
44
|
+
TRUSTING_RECALL,
|
|
45
|
+
"",
|
|
46
|
+
PERSISTENCE_SECTION,
|
|
47
|
+
"",
|
|
48
|
+
...buildSearchingPastContextSection(store.memoryDir, store.projectDir),
|
|
49
|
+
];
|
|
50
|
+
if (includeIndex) {
|
|
51
|
+
const indexContent = store.readIndex();
|
|
52
|
+
if (indexContent.trim()) {
|
|
53
|
+
const { content: truncated } = truncateEntrypoint(indexContent);
|
|
54
|
+
lines.push(`## ${ENTRYPOINT_NAME}`, "", truncated);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
lines.push(`## ${ENTRYPOINT_NAME}`, "", `Your ${ENTRYPOINT_NAME} is currently empty. When you save new memories, they will appear here.`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (recalledMemoriesSection?.trim()) {
|
|
61
|
+
lines.push("", recalledMemoriesSection);
|
|
62
|
+
}
|
|
63
|
+
return lines.join("\n");
|
|
64
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { AgentRegistry } from "../agents.js";
|
|
2
|
+
import type { MemoryConfig } from "../config.js";
|
|
3
|
+
import type { ChatMessage, OpencodeClient, PluginEvent } from "../sdk.js";
|
|
4
|
+
import type { MemoryStore } from "../store/MemoryStore.js";
|
|
5
|
+
import type { Logger } from "../util/log.js";
|
|
6
|
+
import type { OwnedSessions } from "../util/ownedSessions.js";
|
|
7
|
+
import { type RecalledMemory } from "./format.js";
|
|
8
|
+
export declare const SESSION_STATE_TTL_MS: number;
|
|
9
|
+
export declare const SELECTOR_GRACE_MS = 60000;
|
|
10
|
+
export type RecallCoordinatorDeps = {
|
|
11
|
+
store: MemoryStore;
|
|
12
|
+
config: MemoryConfig;
|
|
13
|
+
client: OpencodeClient | undefined;
|
|
14
|
+
directory: string;
|
|
15
|
+
owned: OwnedSessions;
|
|
16
|
+
agents: AgentRegistry;
|
|
17
|
+
log: Logger;
|
|
18
|
+
now?: () => number;
|
|
19
|
+
};
|
|
20
|
+
export declare class RecallCoordinator {
|
|
21
|
+
private readonly deps;
|
|
22
|
+
private readonly sessions;
|
|
23
|
+
private warnedMissingSessionID;
|
|
24
|
+
private readonly now;
|
|
25
|
+
constructor(deps: RecallCoordinatorDeps);
|
|
26
|
+
onMessagesTransform(output: {
|
|
27
|
+
messages: ChatMessage[];
|
|
28
|
+
}): void;
|
|
29
|
+
takeRecalled(sessionID: string | undefined): Promise<RecalledMemory[]>;
|
|
30
|
+
isIgnored(sessionID: string | undefined): boolean;
|
|
31
|
+
onEvent(event: PluginEvent): void;
|
|
32
|
+
get trackedSessions(): number;
|
|
33
|
+
private race;
|
|
34
|
+
private evictStale;
|
|
35
|
+
private startPrefetch;
|
|
36
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { deriveIgnoredFromHistory, detectIgnoreMemory, detectResumeMemory, stripAutoMemoryParts, } from "../hooks/ignore.js";
|
|
2
|
+
import { buildTurnID, collectSurfacedMemoryKeys, extractRecentTools, getLastUserQuery } from "../hooks/messages.js";
|
|
3
|
+
import { surfaceKey } from "../store/scan.js";
|
|
4
|
+
import { recallSelectedMemories } from "./format.js";
|
|
5
|
+
import { selectRelevantMemoryFilenames } from "./selector.js";
|
|
6
|
+
export const SESSION_STATE_TTL_MS = 60 * 60 * 1000;
|
|
7
|
+
export const SELECTOR_GRACE_MS = 60_000;
|
|
8
|
+
const TIMEOUT = Symbol("recall-timeout");
|
|
9
|
+
function isUsefulRecallQuery(query) {
|
|
10
|
+
const trimmed = query?.trim();
|
|
11
|
+
if (!trimmed)
|
|
12
|
+
return false;
|
|
13
|
+
if (/\s/.test(trimmed))
|
|
14
|
+
return true;
|
|
15
|
+
return /[㐀-鿿]/.test(trimmed) && trimmed.length >= 4;
|
|
16
|
+
}
|
|
17
|
+
export class RecallCoordinator {
|
|
18
|
+
deps;
|
|
19
|
+
sessions = new Map();
|
|
20
|
+
warnedMissingSessionID = false;
|
|
21
|
+
now;
|
|
22
|
+
constructor(deps) {
|
|
23
|
+
this.deps = deps;
|
|
24
|
+
this.now = deps.now ?? Date.now;
|
|
25
|
+
}
|
|
26
|
+
// `experimental.chat.messages.transform`: derive the turn state and start the selector prefetch.
|
|
27
|
+
onMessagesTransform(output) {
|
|
28
|
+
const turn = getLastUserQuery(output.messages);
|
|
29
|
+
const { sessionID } = turn;
|
|
30
|
+
if (!sessionID) {
|
|
31
|
+
if (detectIgnoreMemory(turn.query))
|
|
32
|
+
output.messages = stripAutoMemoryParts(output.messages);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (this.deps.owned.has(sessionID))
|
|
36
|
+
return;
|
|
37
|
+
const now = this.now();
|
|
38
|
+
this.evictStale(now);
|
|
39
|
+
const state = this.sessions.get(sessionID) ?? {
|
|
40
|
+
updatedAt: now,
|
|
41
|
+
ignored: deriveIgnoredFromHistory(output.messages),
|
|
42
|
+
};
|
|
43
|
+
state.updatedAt = now;
|
|
44
|
+
const turnID = buildTurnID(sessionID, turn);
|
|
45
|
+
if (state.turnID !== turnID) {
|
|
46
|
+
if (detectIgnoreMemory(turn.query))
|
|
47
|
+
state.ignored = true;
|
|
48
|
+
else if (state.ignored && detectResumeMemory(turn.query))
|
|
49
|
+
state.ignored = false;
|
|
50
|
+
state.turnID = turnID;
|
|
51
|
+
state.prefetch = state.ignored ? undefined : this.startPrefetch(sessionID, turnID, turn.query, output.messages);
|
|
52
|
+
}
|
|
53
|
+
this.sessions.set(sessionID, state);
|
|
54
|
+
if (state.ignored)
|
|
55
|
+
output.messages = stripAutoMemoryParts(output.messages);
|
|
56
|
+
}
|
|
57
|
+
// `experimental.chat.system.transform`: wait for the prefetch (bounded by recall.waitMs) and hand
|
|
58
|
+
// the result over exactly once. On timeout the prefetch keeps running for the next LLM call.
|
|
59
|
+
async takeRecalled(sessionID) {
|
|
60
|
+
if (!sessionID) {
|
|
61
|
+
if (!this.warnedMissingSessionID) {
|
|
62
|
+
this.warnedMissingSessionID = true;
|
|
63
|
+
this.deps.log("warn", "system.transform received no sessionID; memory recall is disabled for this call");
|
|
64
|
+
}
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
const state = this.sessions.get(sessionID);
|
|
68
|
+
const prefetch = state?.prefetch;
|
|
69
|
+
if (!state || state.ignored || !prefetch || prefetch.consumed)
|
|
70
|
+
return [];
|
|
71
|
+
const result = await this.race(prefetch.promise, this.deps.config.recall.waitMs);
|
|
72
|
+
if (result === TIMEOUT)
|
|
73
|
+
return [];
|
|
74
|
+
prefetch.consumed = true;
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
isIgnored(sessionID) {
|
|
78
|
+
return sessionID !== undefined && this.sessions.get(sessionID)?.ignored === true;
|
|
79
|
+
}
|
|
80
|
+
onEvent(event) {
|
|
81
|
+
if (event.type === "session.deleted")
|
|
82
|
+
this.sessions.delete(event.properties.info.id);
|
|
83
|
+
}
|
|
84
|
+
get trackedSessions() {
|
|
85
|
+
return this.sessions.size;
|
|
86
|
+
}
|
|
87
|
+
race(promise, waitMs) {
|
|
88
|
+
let timer;
|
|
89
|
+
const timeout = new Promise((resolve) => {
|
|
90
|
+
timer = setTimeout(() => resolve(TIMEOUT), waitMs);
|
|
91
|
+
});
|
|
92
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
93
|
+
if (timer)
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
// Drops the turn cache of sessions idle for longer than the TTL. An ignored session keeps its
|
|
98
|
+
// entry (only the cache is cleared) so the instruction survives until the session is deleted.
|
|
99
|
+
evictStale(now) {
|
|
100
|
+
const cutoff = now - SESSION_STATE_TTL_MS;
|
|
101
|
+
for (const [id, state] of this.sessions) {
|
|
102
|
+
if (state.updatedAt >= cutoff)
|
|
103
|
+
continue;
|
|
104
|
+
if (state.ignored) {
|
|
105
|
+
state.prefetch = undefined;
|
|
106
|
+
state.turnID = undefined;
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
this.sessions.delete(id);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
startPrefetch(sessionID, turnID, query, messages) {
|
|
114
|
+
const { client, config, store, owned, agents, directory } = this.deps;
|
|
115
|
+
if (!config.recall.enabled || !client || !isUsefulRecallQuery(query))
|
|
116
|
+
return undefined;
|
|
117
|
+
const alreadySurfaced = collectSurfacedMemoryKeys(messages);
|
|
118
|
+
const recentTools = extractRecentTools(messages);
|
|
119
|
+
const headers = store.scan().filter((header) => !alreadySurfaced.has(surfaceKey(header)));
|
|
120
|
+
if (headers.length === 0)
|
|
121
|
+
return undefined;
|
|
122
|
+
const promise = selectRelevantMemoryFilenames({
|
|
123
|
+
client,
|
|
124
|
+
directory,
|
|
125
|
+
parentSessionID: sessionID,
|
|
126
|
+
query,
|
|
127
|
+
memories: headers,
|
|
128
|
+
recentTools,
|
|
129
|
+
agent: config.agents.recall,
|
|
130
|
+
tools: agents.toolsFor(config.agents.recall),
|
|
131
|
+
timeoutMs: config.recall.timeoutMs,
|
|
132
|
+
maxMemories: config.recall.maxMemories,
|
|
133
|
+
onSessionCreated: (id) => owned.add(id),
|
|
134
|
+
onSessionFinished: (id) => owned.release(id, SELECTOR_GRACE_MS),
|
|
135
|
+
})
|
|
136
|
+
.then((selected) => recallSelectedMemories(headers, selected, alreadySurfaced, { maxMemories: config.recall.maxMemories }))
|
|
137
|
+
.catch(() => []);
|
|
138
|
+
return { turnID, promise, consumed: false };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type MemoryHeader } from "../store/scan.js";
|
|
2
|
+
export type RecalledMemory = {
|
|
3
|
+
fileName: string;
|
|
4
|
+
filePath: string;
|
|
5
|
+
name: string;
|
|
6
|
+
type: string;
|
|
7
|
+
description: string;
|
|
8
|
+
content: string;
|
|
9
|
+
ageInDays: number;
|
|
10
|
+
};
|
|
11
|
+
export declare function truncateMemoryContent(content: string): string;
|
|
12
|
+
export type RecallSelectionOptions = {
|
|
13
|
+
maxMemories?: number;
|
|
14
|
+
now?: number;
|
|
15
|
+
};
|
|
16
|
+
export declare function recallSelectedMemories(headers: readonly MemoryHeader[], selectedFilenames: readonly string[], alreadySurfaced?: ReadonlySet<string>, options?: RecallSelectionOptions): RecalledMemory[];
|
|
17
|
+
export declare function formatRecalledMemories(memories: readonly RecalledMemory[]): string;
|
|
@@ -1,29 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { RECALLED_MEMORIES_HEADING } from "../prompt/systemPrompt.js";
|
|
2
|
+
import { readMemoryBody, surfaceKey } from "../store/scan.js";
|
|
3
3
|
const MAX_MEMORY_LINES = 200;
|
|
4
4
|
const MAX_MEMORY_BYTES = 4096;
|
|
5
5
|
const encoder = new TextEncoder();
|
|
6
|
-
function
|
|
7
|
-
try {
|
|
8
|
-
const raw = readFileSync(filePath, "utf-8");
|
|
9
|
-
const trimmed = raw.trim();
|
|
10
|
-
if (!trimmed.startsWith("---"))
|
|
11
|
-
return trimmed;
|
|
12
|
-
const lines = trimmed.split("\n");
|
|
13
|
-
let closingIdx = -1;
|
|
14
|
-
for (let i = 1; i < lines.length; i++) {
|
|
15
|
-
if (lines[i].trimEnd() === "---") {
|
|
16
|
-
closingIdx = i;
|
|
17
|
-
break;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return closingIdx === -1 ? trimmed : lines.slice(closingIdx + 1).join("\n").trim();
|
|
21
|
-
}
|
|
22
|
-
catch {
|
|
23
|
-
return "";
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
function truncateMemoryContent(content) {
|
|
6
|
+
export function truncateMemoryContent(content) {
|
|
27
7
|
const maxLines = content.split("\n").slice(0, MAX_MEMORY_LINES);
|
|
28
8
|
const lineTruncated = maxLines.join("\n");
|
|
29
9
|
if (encoder.encode(lineTruncated).length <= MAX_MEMORY_BYTES) {
|
|
@@ -42,25 +22,22 @@ function truncateMemoryContent(content) {
|
|
|
42
22
|
}
|
|
43
23
|
return kept.join("\n");
|
|
44
24
|
}
|
|
45
|
-
function memorySurfaceKey(header) {
|
|
46
|
-
return `${header.name ?? header.filename.replace(/\.md$/, "").replace(/.*\//, "")}|${header.type ?? "user"}`;
|
|
47
|
-
}
|
|
48
25
|
function recalledMemoryFromHeader(header, content, now) {
|
|
49
|
-
const nameFromFilename = header.filename.replace(/\.md$/, "").replace(/.*\//, "");
|
|
50
26
|
return {
|
|
51
27
|
fileName: header.filename,
|
|
52
28
|
filePath: header.filePath,
|
|
53
|
-
name: header.name
|
|
54
|
-
type: header.type
|
|
55
|
-
description: header.description
|
|
29
|
+
name: header.name,
|
|
30
|
+
type: header.type,
|
|
31
|
+
description: header.description,
|
|
56
32
|
content: truncateMemoryContent(content),
|
|
57
33
|
ageInDays: Math.max(0, Math.floor((now - header.mtimeMs) / (1000 * 60 * 60 * 24))),
|
|
58
34
|
};
|
|
59
35
|
}
|
|
60
|
-
export function recallSelectedMemories(headers, selectedFilenames, alreadySurfaced = new Set()) {
|
|
36
|
+
export function recallSelectedMemories(headers, selectedFilenames, alreadySurfaced = new Set(), options = {}) {
|
|
61
37
|
if (selectedFilenames.length === 0)
|
|
62
38
|
return [];
|
|
63
|
-
const
|
|
39
|
+
const maxMemories = options.maxMemories ?? 5;
|
|
40
|
+
const now = options.now ?? Date.now();
|
|
64
41
|
const byFilename = new Map(headers.map((header) => [header.filename, header]));
|
|
65
42
|
const recalled = [];
|
|
66
43
|
const seen = new Set();
|
|
@@ -69,10 +46,10 @@ export function recallSelectedMemories(headers, selectedFilenames, alreadySurfac
|
|
|
69
46
|
continue;
|
|
70
47
|
seen.add(filename);
|
|
71
48
|
const header = byFilename.get(filename);
|
|
72
|
-
if (!header || alreadySurfaced.has(
|
|
49
|
+
if (!header || alreadySurfaced.has(surfaceKey(header)))
|
|
73
50
|
continue;
|
|
74
|
-
recalled.push(recalledMemoryFromHeader(header,
|
|
75
|
-
if (recalled.length >=
|
|
51
|
+
recalled.push(recalledMemoryFromHeader(header, readMemoryBody(header.filePath), now));
|
|
52
|
+
if (recalled.length >= maxMemories)
|
|
76
53
|
break;
|
|
77
54
|
}
|
|
78
55
|
return recalled;
|
|
@@ -90,7 +67,7 @@ export function formatRecalledMemories(memories) {
|
|
|
90
67
|
return `### ${memory.name} (${memory.type})${ageWarning}\n${memory.content}`;
|
|
91
68
|
});
|
|
92
69
|
return [
|
|
93
|
-
|
|
70
|
+
RECALLED_MEMORIES_HEADING,
|
|
94
71
|
"",
|
|
95
72
|
"The following memories were automatically selected as relevant to this conversation. They may be outdated — verify against current state before relying on them.",
|
|
96
73
|
"",
|
|
@@ -1,27 +1,37 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type OpencodeClient } from "../sdk.js";
|
|
2
|
+
import { type MemoryHeader } from "../store/scan.js";
|
|
2
3
|
export declare const SELECT_MEMORIES_SYSTEM_PROMPT = "You are selecting memories that will be useful to OpenCode as it processes a user's query. You will be given the user's query and a list of available memory files with their filenames and descriptions.\n\nReturn a list of filenames for the memories that will clearly be useful to OpenCode as it processes the user's query (up to 5). Only include memories that you are certain will be helpful based on their name and description.\n- If you are unsure if a memory will be useful in processing the user's query, then do not include it in your list. Be selective and discerning.\n- If there are no memories in the list that would clearly be useful, feel free to return an empty list.\n- If a list of recently-used tools is provided, do not select memories that are usage reference or API documentation for those tools (OpenCode is already exercising them). DO still select memories containing warnings, gotchas, or known issues about those tools \u2014 active use is exactly when those matter.\n";
|
|
3
|
-
export declare const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
export declare const SELECT_MEMORIES_FORMAT: {
|
|
5
|
+
readonly type: "json_schema";
|
|
6
|
+
readonly schema: {
|
|
7
|
+
readonly type: "object";
|
|
8
|
+
readonly properties: {
|
|
9
|
+
readonly selected_memories: {
|
|
10
|
+
readonly type: "array";
|
|
11
|
+
readonly items: {
|
|
12
|
+
readonly type: "string";
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
readonly required: readonly ["selected_memories"];
|
|
17
|
+
readonly additionalProperties: false;
|
|
9
18
|
};
|
|
10
19
|
};
|
|
20
|
+
export declare const RECALL_SELECTOR_TITLE = "opencode-memory recall selector";
|
|
11
21
|
export type SelectRelevantMemoryFilenamesInput = {
|
|
12
|
-
client:
|
|
22
|
+
client: OpencodeClient;
|
|
13
23
|
directory: string;
|
|
14
24
|
parentSessionID: string;
|
|
15
25
|
query: string;
|
|
16
|
-
memories: MemoryHeader[];
|
|
26
|
+
memories: readonly MemoryHeader[];
|
|
17
27
|
recentTools: readonly string[];
|
|
18
|
-
selectorSessionIDs: Set<string>;
|
|
19
28
|
agent: string;
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
29
|
+
tools?: Record<string, boolean>;
|
|
30
|
+
timeoutMs: number;
|
|
31
|
+
maxMemories: number;
|
|
32
|
+
onSessionCreated?: (sessionID: string) => void;
|
|
33
|
+
onSessionFinished?: (sessionID: string) => void;
|
|
24
34
|
};
|
|
25
|
-
export declare function
|
|
26
|
-
export declare function
|
|
35
|
+
export declare function extractSelectedMemories(response: unknown): string[];
|
|
36
|
+
export declare function buildSelectorQuery(query: string, memories: readonly MemoryHeader[], recentTools: readonly string[]): string;
|
|
27
37
|
export declare function selectRelevantMemoryFilenames(input: SelectRelevantMemoryFilenamesInput): Promise<string[]>;
|