pantheon-opencode 1.6.1 → 1.6.2-beta.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/AGENTS.global.md +11 -11
- package/AGENTS.md +2 -2
- package/CHANGELOG.md +29 -0
- package/README.md +100 -19
- package/README.pt-BR.md +27 -11
- package/bin/pantheon-init.mjs +106 -19
- package/package.json +3 -2
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/scripts/build-agents-md.mjs +1 -1
- package/scripts/doctor.mjs +213 -45
- package/scripts/install/agents-md.mjs +2 -1
- package/scripts/install/config-migration.mjs +344 -393
- package/scripts/install/config-paths.mjs +15 -0
- package/scripts/install/mcp-permissions.mjs +164 -0
- package/scripts/install/opencode-version.mjs +31 -13
- package/scripts/install/opencode-wildcard.mjs +106 -0
- package/scripts/install/opencode.mjs +240 -69
- package/scripts/install/plan-artifact.mjs +12 -1
- package/scripts/install/plugin.mjs +17 -1
- package/scripts/install/v2-capabilities.mjs +5 -6
- package/scripts/package-evidence.mjs +1 -0
- package/scripts/sandbox-env.sh +174 -0
- package/scripts/setup-v2-config.mjs +1703 -0
- package/scripts/setup.mjs +415 -0
- package/scripts/sync-tui.mjs +9 -1
- package/scripts/test-opencode-v2-sandbox.sh +438 -151
- package/scripts/update-skills-lock.mjs +30 -0
- package/skills-lock.json +10 -10
- package/src/agents/aphrodite.md +5 -2
- package/src/agents/apollo.md +5 -0
- package/src/agents/athena.md +6 -1
- package/src/agents/demeter.md +5 -1
- package/src/agents/gaia.md +4 -0
- package/src/agents/hephaestus.md +6 -1
- package/src/agents/hermes.md +6 -3
- package/src/agents/iris.md +5 -1
- package/src/agents/mnemosyne.md +20 -50
- package/src/agents/nyx.md +5 -1
- package/src/agents/prometheus.md +4 -0
- package/src/agents/talos.md +4 -0
- package/src/agents/themis.md +4 -0
- package/src/agents/zeus.md +9 -3
- package/src/instructions/agent-return-format.instructions.md +1 -1
- package/src/instructions/memory-protocol.instructions.md +3 -3
- package/src/instructions/test-economy.instructions.md +6 -6
- package/src/mcp/pantheon_vision.py +37 -36
- package/src/pantheon/cost-command.ts +30 -133
- package/src/pantheon/model-pricing.ts +1 -536
- package/src/pantheon/v2-vision.ts +34 -29
- package/src/pantheon/vision.ts +43 -10
- package/src/plugin-v2.ts +30 -53
- package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +749 -0
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +1 -0
- package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
- package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
- package/src/plugins/tui/dist/quota-adapters.js +1142 -0
- package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
- package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
- package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
- package/src/plugins/tui/dist/quota-cli.js +184 -0
- package/src/plugins/tui/dist/quota-cli.js.map +1 -0
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +684 -0
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +1 -0
- package/src/plugins/tui/dist/server-v2.d.ts +14 -0
- package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
- package/src/plugins/tui/dist/server-v2.js +796 -0
- package/src/plugins/tui/dist/server-v2.js.map +1 -0
- package/src/plugins/tui/dist/tui-v2.d.ts +375 -53
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +5876 -530
- package/src/plugins/tui/dist/tui-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +118 -0
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +1 -0
- package/src/plugins/tui/dist/usage-history-worker.js +25 -0
- package/src/plugins/tui/dist/usage-history-worker.js.map +1 -0
- package/src/plugins/tui/index-v2.ts +3 -6
- package/src/plugins/tui/package-lock.json +17 -2
- package/src/plugins/tui/package.json +6 -3
- package/src/plugins/tui/src/context-gauge.ts +59 -0
- package/src/plugins/tui/src/cost-data.ts +607 -0
- package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
- package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
- package/src/plugins/tui/src/index-v2.tsx +231 -240
- package/src/plugins/tui/src/model-pricing.ts +536 -0
- package/src/plugins/tui/src/model-usage-limits.ts +4 -0
- package/src/plugins/tui/src/quota-adapters.ts +1598 -0
- package/src/plugins/tui/src/quota-cli.ts +237 -0
- package/src/plugins/tui/src/quota-rpc.ts +373 -0
- package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
- package/src/plugins/tui/src/quota-v2.tsx +1238 -0
- package/src/plugins/tui/src/server-v2.ts +985 -0
- package/src/plugins/tui/src/sidebar-width.ts +129 -0
- package/src/plugins/tui/src/usage-history-contract.ts +217 -0
- package/src/plugins/tui/src/usage-history-validation.ts +104 -0
- package/src/plugins/tui/src/usage-history-view.tsx +236 -0
- package/src/plugins/tui/src/usage-history-worker.ts +25 -0
- package/src/plugins/tui/src/usage-view-model.ts +272 -0
- package/src/plugins/tui/tsconfig.typecheck.json +6 -1
- package/src/plugins/tui/tsdown.config.ts +44 -5
- package/src/routing.yml +72 -13
- package/src/skills/README.md +4 -0
- package/src/skills/agent-coordination/SKILL.md +0 -3
- package/src/skills/artifact-management/SKILL.md +0 -3
- package/src/skills/auto-continue/SKILL.md +0 -3
- package/src/skills/code-review-checklist/SKILL.md +0 -3
- package/src/skills/context-compression/SKILL.md +0 -3
- package/src/skills/memory-bank/SKILL.md +6 -28
- package/src/skills/session-goal/SKILL.md +0 -3
- package/src/skills/simplify/SKILL.md +5 -4
- package/src/skills/tdd-with-agents/SKILL.md +0 -3
- package/src/skills/visual-review-pipeline/SKILL.md +0 -1
- package/src/pantheon/memory-context.ts +0 -1017
|
@@ -1,1017 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Ambient memory injection for the OpenCode V2 runtime.
|
|
3
|
-
*
|
|
4
|
-
* `pantheon-memory` is pull-only: an entry is recalled only when the agent
|
|
5
|
-
* decides to call `memory_search`. V2 exposes a per-request `context` hook, so
|
|
6
|
-
* the most relevant entries can be added to `system` once per session without
|
|
7
|
-
* asking the model to look for them. This module owns everything except the
|
|
8
|
-
* hook registration itself: config resolution, the read-only SQLite query, the
|
|
9
|
-
* char-budgeted rendering, and the once-per-session cache.
|
|
10
|
-
*
|
|
11
|
-
* ## What it reads
|
|
12
|
-
*
|
|
13
|
-
* The memory store at `$PANTHEON_HOME/memory/memory.db` (path resolution
|
|
14
|
-
* mirrors `src/mcp/_pantheon_paths.py`: `PANTHEON_HOME` →
|
|
15
|
-
* `$XDG_CONFIG_HOME/opencode` → `~/.config/opencode`), opened with
|
|
16
|
-
* `node:sqlite`'s `DatabaseSync` in `readOnly` mode — the same access path
|
|
17
|
-
* `cost-command.ts` uses for `opencode.db`. This module never creates a
|
|
18
|
-
* directory, never creates a database, never writes a pragma, never migrates a
|
|
19
|
-
* schema, and never writes a row. (A read-only connection to a WAL database can
|
|
20
|
-
* still make SQLite create its `-shm`/`-wal` index sidecars next to the file —
|
|
21
|
-
* that is the WAL index, not a memory write, and it is the only filesystem
|
|
22
|
-
* effect this module can have.) A missing file, an unreadable file, an
|
|
23
|
-
* unexpected schema, or a runtime without `node:sqlite` all return "no
|
|
24
|
-
* injection".
|
|
25
|
-
*
|
|
26
|
-
* ## What it injects
|
|
27
|
-
*
|
|
28
|
-
* Top-K (default 3) entries ranked by FTS5 BM25 for the session's FIRST user
|
|
29
|
-
* message, capped at a total character budget (default 1200) with per-entry
|
|
30
|
-
* truncation marked `…[truncated]`. Expired entries (`expires_at` non-null and
|
|
31
|
-
* in the past) are excluded in SQL, exactly like `memory_search`.
|
|
32
|
-
*
|
|
33
|
-
* ## Query duplication (accepted, and pinned by a test)
|
|
34
|
-
*
|
|
35
|
-
* `buildFtsQuery` re-implements `_build_fts_query` from
|
|
36
|
-
* `src/mcp/memory_mcp.py:314` (`_build_fts_query`) — the stopword list, the
|
|
37
|
-
* 4-character prefix
|
|
38
|
-
* threshold and the `"term"*` shape. The duplication is deliberate: the MCP
|
|
39
|
-
* server is a separate Python process and this runs inside the plugin runtime,
|
|
40
|
-
* and a subprocess per request would be worse than ~60 lines. Drift is caught
|
|
41
|
-
* by `tests/pantheon/memory-context.test.ts`, which parses `_STOPWORDS` and
|
|
42
|
-
* `_MIN_PREFIX_LEN` out of the Python source and asserts equality with
|
|
43
|
-
* {@link MEMORY_STOPWORDS} / {@link MIN_PREFIX_LEN}.
|
|
44
|
-
*
|
|
45
|
-
* Terms are always quoted and their embedded quotes doubled, so user text can
|
|
46
|
-
* never become FTS5 syntax and never reaches SQL as anything but a bound
|
|
47
|
-
* parameter.
|
|
48
|
-
*
|
|
49
|
-
* ## Fail-open
|
|
50
|
-
*
|
|
51
|
-
* Every exported entry point returns a value; nothing throws to the host.
|
|
52
|
-
* {@link buildMemoryInjection} reports `skip` and optional `detail` instead, so
|
|
53
|
-
* the plugin decides what to log (once per session) and whether to touch
|
|
54
|
-
* `system` at all.
|
|
55
|
-
*
|
|
56
|
-
* @module memory-context
|
|
57
|
-
*/
|
|
58
|
-
|
|
59
|
-
import { existsSync } from 'node:fs'
|
|
60
|
-
import { homedir } from 'node:os'
|
|
61
|
-
import { join } from 'node:path'
|
|
62
|
-
|
|
63
|
-
/** Stable marker carried by the injected system part; also the dedupe key. */
|
|
64
|
-
export const MEMORY_CONTEXT_MARKER = '<!-- pantheon-memory-context:v1 -->'
|
|
65
|
-
|
|
66
|
-
/** Config keys accepted under `options.memory_injection`. */
|
|
67
|
-
export const MEMORY_INJECTION_CONFIG_KEYS = [
|
|
68
|
-
'enabled',
|
|
69
|
-
'maxEntries',
|
|
70
|
-
'maxChars',
|
|
71
|
-
'namespace',
|
|
72
|
-
] as const
|
|
73
|
-
|
|
74
|
-
export interface MemoryInjectionConfig {
|
|
75
|
-
/** Opt-in switch. Default `false`: the hook output stays byte-identical. */
|
|
76
|
-
enabled: boolean
|
|
77
|
-
/** Entries to inject (1–10). Default 3. */
|
|
78
|
-
maxEntries: number
|
|
79
|
-
/** Total character budget for the injected system part. Default 1200. */
|
|
80
|
-
maxChars: number
|
|
81
|
-
/**
|
|
82
|
-
* Namespace filter. `null` (the default) means NO filter, which is what
|
|
83
|
-
* `memory_search(query)` does when its optional `namespace` argument is
|
|
84
|
-
* omitted (`memory_mcp.py`: `namespace: str | None = None`, documented at
|
|
85
|
-
* `docs/MEMORY.md`: "searches without a namespace filter can return matches
|
|
86
|
-
* from any namespace"). `default` is the STORAGE default of the column, not
|
|
87
|
-
* the search default, so it is not used here.
|
|
88
|
-
*/
|
|
89
|
-
namespace: string | null
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** Defaults. `enabled:false` keeps ambient injection opt-in. */
|
|
93
|
-
export const DEFAULT_MEMORY_INJECTION_CONFIG: MemoryInjectionConfig = {
|
|
94
|
-
enabled: false,
|
|
95
|
-
maxEntries: 3,
|
|
96
|
-
maxChars: 1200,
|
|
97
|
-
namespace: null,
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** Hard bounds so a typo cannot inject a megabyte of memories. */
|
|
101
|
-
const MAX_ENTRIES_LIMIT = 10
|
|
102
|
-
const MAX_CHARS_LIMIT = 8000
|
|
103
|
-
/** Below this, the header plus one truncated entry cannot fit. */
|
|
104
|
-
const MIN_CHARS_LIMIT = 100
|
|
105
|
-
|
|
106
|
-
/** Minimum characters left for an entry body before it is dropped. */
|
|
107
|
-
const MIN_ENTRY_ROOM = 24
|
|
108
|
-
|
|
109
|
-
/** Suffix appended to a per-entry truncation. */
|
|
110
|
-
export const TRUNCATION_SUFFIX = '…[truncated]'
|
|
111
|
-
|
|
112
|
-
/** Search-text bounds: a huge prompt must not build a huge MATCH expression. */
|
|
113
|
-
const MAX_SEARCH_CHARS = 4000
|
|
114
|
-
const MAX_SEARCH_TERMS = 32
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Function words with no retrieval signal, copied verbatim from
|
|
118
|
-
* `src/mcp/memory_mcp.py:229` (`_STOPWORDS`). Order and membership are pinned
|
|
119
|
-
* by the drift test.
|
|
120
|
-
*/
|
|
121
|
-
export const MEMORY_STOPWORDS: ReadonlySet<string> = new Set([
|
|
122
|
-
'a',
|
|
123
|
-
'about',
|
|
124
|
-
'above',
|
|
125
|
-
'after',
|
|
126
|
-
'again',
|
|
127
|
-
'against',
|
|
128
|
-
'all',
|
|
129
|
-
'am',
|
|
130
|
-
'an',
|
|
131
|
-
'and',
|
|
132
|
-
'any',
|
|
133
|
-
'are',
|
|
134
|
-
'as',
|
|
135
|
-
'at',
|
|
136
|
-
'be',
|
|
137
|
-
'because',
|
|
138
|
-
'been',
|
|
139
|
-
'before',
|
|
140
|
-
'being',
|
|
141
|
-
'below',
|
|
142
|
-
'between',
|
|
143
|
-
'both',
|
|
144
|
-
'but',
|
|
145
|
-
'by',
|
|
146
|
-
'can',
|
|
147
|
-
'cannot',
|
|
148
|
-
'could',
|
|
149
|
-
'did',
|
|
150
|
-
'do',
|
|
151
|
-
'does',
|
|
152
|
-
'doing',
|
|
153
|
-
'done',
|
|
154
|
-
'down',
|
|
155
|
-
'during',
|
|
156
|
-
'each',
|
|
157
|
-
'few',
|
|
158
|
-
'for',
|
|
159
|
-
'from',
|
|
160
|
-
'further',
|
|
161
|
-
'had',
|
|
162
|
-
'has',
|
|
163
|
-
'have',
|
|
164
|
-
'having',
|
|
165
|
-
'he',
|
|
166
|
-
'her',
|
|
167
|
-
'here',
|
|
168
|
-
'hers',
|
|
169
|
-
'him',
|
|
170
|
-
'his',
|
|
171
|
-
'how',
|
|
172
|
-
'i',
|
|
173
|
-
'if',
|
|
174
|
-
'in',
|
|
175
|
-
'into',
|
|
176
|
-
'is',
|
|
177
|
-
'it',
|
|
178
|
-
'its',
|
|
179
|
-
'itself',
|
|
180
|
-
'just',
|
|
181
|
-
'me',
|
|
182
|
-
'more',
|
|
183
|
-
'most',
|
|
184
|
-
'my',
|
|
185
|
-
'no',
|
|
186
|
-
'nor',
|
|
187
|
-
'not',
|
|
188
|
-
'now',
|
|
189
|
-
'of',
|
|
190
|
-
'off',
|
|
191
|
-
'on',
|
|
192
|
-
'once',
|
|
193
|
-
'only',
|
|
194
|
-
'or',
|
|
195
|
-
'other',
|
|
196
|
-
'our',
|
|
197
|
-
'ours',
|
|
198
|
-
'out',
|
|
199
|
-
'over',
|
|
200
|
-
'own',
|
|
201
|
-
'same',
|
|
202
|
-
'she',
|
|
203
|
-
'should',
|
|
204
|
-
'so',
|
|
205
|
-
'some',
|
|
206
|
-
'such',
|
|
207
|
-
'than',
|
|
208
|
-
'that',
|
|
209
|
-
'the',
|
|
210
|
-
'their',
|
|
211
|
-
'theirs',
|
|
212
|
-
'them',
|
|
213
|
-
'then',
|
|
214
|
-
'there',
|
|
215
|
-
'these',
|
|
216
|
-
'they',
|
|
217
|
-
'this',
|
|
218
|
-
'those',
|
|
219
|
-
'through',
|
|
220
|
-
'to',
|
|
221
|
-
'too',
|
|
222
|
-
'under',
|
|
223
|
-
'until',
|
|
224
|
-
'up',
|
|
225
|
-
'very',
|
|
226
|
-
'was',
|
|
227
|
-
'we',
|
|
228
|
-
'were',
|
|
229
|
-
'what',
|
|
230
|
-
'when',
|
|
231
|
-
'where',
|
|
232
|
-
'which',
|
|
233
|
-
'while',
|
|
234
|
-
'who',
|
|
235
|
-
'whom',
|
|
236
|
-
'why',
|
|
237
|
-
'will',
|
|
238
|
-
'with',
|
|
239
|
-
'would',
|
|
240
|
-
'you',
|
|
241
|
-
'your',
|
|
242
|
-
'yours',
|
|
243
|
-
])
|
|
244
|
-
|
|
245
|
-
/** Shortest token still worth a prefix match (`memory_mcp.py:_MIN_PREFIX_LEN`). */
|
|
246
|
-
export const MIN_PREFIX_LEN = 4
|
|
247
|
-
|
|
248
|
-
// ─── Config ─────────────────────────────────────────────────────────────
|
|
249
|
-
|
|
250
|
-
/**
|
|
251
|
-
* Read `options.memory_injection` (the V2 config copy, read like
|
|
252
|
-
* `context_pruner`). Malformed input yields the defaults — config parsing must
|
|
253
|
-
* never take the hook down.
|
|
254
|
-
*/
|
|
255
|
-
export function resolveMemoryInjectionConfig(options: unknown): MemoryInjectionConfig {
|
|
256
|
-
const base = (): MemoryInjectionConfig => ({ ...DEFAULT_MEMORY_INJECTION_CONFIG })
|
|
257
|
-
try {
|
|
258
|
-
const raw = (options as { memory_injection?: unknown } | null | undefined)?.memory_injection
|
|
259
|
-
if (raw === null || raw === undefined || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
260
|
-
return base()
|
|
261
|
-
}
|
|
262
|
-
const obj = raw as Record<string, unknown>
|
|
263
|
-
const bounded = (value: unknown, fallback: number, min: number, max: number): number => {
|
|
264
|
-
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
|
|
265
|
-
return Math.min(max, Math.max(min, Math.floor(value)))
|
|
266
|
-
}
|
|
267
|
-
let namespace: string | null = null
|
|
268
|
-
if (typeof obj.namespace === 'string') {
|
|
269
|
-
const trimmed = obj.namespace.trim()
|
|
270
|
-
namespace = trimmed === '' ? null : trimmed
|
|
271
|
-
}
|
|
272
|
-
return {
|
|
273
|
-
enabled: typeof obj.enabled === 'boolean' ? obj.enabled : false,
|
|
274
|
-
maxEntries: bounded(
|
|
275
|
-
obj.maxEntries,
|
|
276
|
-
DEFAULT_MEMORY_INJECTION_CONFIG.maxEntries,
|
|
277
|
-
1,
|
|
278
|
-
MAX_ENTRIES_LIMIT,
|
|
279
|
-
),
|
|
280
|
-
maxChars: bounded(
|
|
281
|
-
obj.maxChars,
|
|
282
|
-
DEFAULT_MEMORY_INJECTION_CONFIG.maxChars,
|
|
283
|
-
MIN_CHARS_LIMIT,
|
|
284
|
-
MAX_CHARS_LIMIT,
|
|
285
|
-
),
|
|
286
|
-
namespace,
|
|
287
|
-
}
|
|
288
|
-
} catch {
|
|
289
|
-
return base()
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
/**
|
|
294
|
-
* Describe why a `memory_injection` block would be partially ignored, without
|
|
295
|
-
* changing the fail-open resolution. Empty means "absent or fully valid".
|
|
296
|
-
* Unknown keys are reported because a silent typo (`maxEntry` instead of
|
|
297
|
-
* `maxEntries`) is otherwise invisible.
|
|
298
|
-
*/
|
|
299
|
-
export function describeMemoryInjectionConfigIssues(options: unknown): string[] {
|
|
300
|
-
try {
|
|
301
|
-
const raw = (options as { memory_injection?: unknown } | null | undefined)?.memory_injection
|
|
302
|
-
if (raw === undefined || raw === null) return []
|
|
303
|
-
if (typeof raw !== 'object' || Array.isArray(raw)) return ['memory_injection is not an object']
|
|
304
|
-
const obj = raw as Record<string, unknown>
|
|
305
|
-
const issues: string[] = []
|
|
306
|
-
const accepted = MEMORY_INJECTION_CONFIG_KEYS as readonly string[]
|
|
307
|
-
for (const key of Object.keys(obj)) {
|
|
308
|
-
if (!accepted.includes(key)) issues.push(`unknown key "${key}"`)
|
|
309
|
-
}
|
|
310
|
-
if ('enabled' in obj && typeof obj.enabled !== 'boolean') {
|
|
311
|
-
issues.push('"enabled" must be a boolean')
|
|
312
|
-
}
|
|
313
|
-
for (const [key, min, max] of [
|
|
314
|
-
['maxEntries', 1, MAX_ENTRIES_LIMIT],
|
|
315
|
-
['maxChars', MIN_CHARS_LIMIT, MAX_CHARS_LIMIT],
|
|
316
|
-
] as const) {
|
|
317
|
-
if (!(key in obj)) continue
|
|
318
|
-
const value = obj[key]
|
|
319
|
-
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
320
|
-
issues.push(`"${key}" must be a number`)
|
|
321
|
-
continue
|
|
322
|
-
}
|
|
323
|
-
if (value < min) issues.push(`"${key}" must be >= ${min}`)
|
|
324
|
-
if (value > max) issues.push(`"${key}" must be <= ${max}`)
|
|
325
|
-
}
|
|
326
|
-
if ('namespace' in obj && obj.namespace !== null && typeof obj.namespace !== 'string') {
|
|
327
|
-
issues.push('"namespace" must be a string or null')
|
|
328
|
-
}
|
|
329
|
-
return issues
|
|
330
|
-
} catch {
|
|
331
|
-
return ['memory_injection could not be inspected']
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// ─── Path resolution ────────────────────────────────────────────────────
|
|
336
|
-
|
|
337
|
-
/**
|
|
338
|
-
* Resolve the Pantheon config dir, mirroring `_pantheon_paths.py`
|
|
339
|
-
* (`PANTHEON_HOME` → `$XDG_CONFIG_HOME/opencode` → `~/.config/opencode`).
|
|
340
|
-
*/
|
|
341
|
-
function resolvePantheonHome(env: NodeJS.ProcessEnv = process.env): string {
|
|
342
|
-
const explicit = env.PANTHEON_HOME?.trim()
|
|
343
|
-
if (explicit !== undefined && explicit !== '') return explicit
|
|
344
|
-
const xdg = env.XDG_CONFIG_HOME?.trim()
|
|
345
|
-
const base = xdg !== undefined && xdg !== '' ? xdg : join(homedir(), '.config')
|
|
346
|
-
return join(base, 'opencode')
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/** `$PANTHEON_HOME/memory/memory.db`. */
|
|
350
|
-
export function resolveMemoryDbPath(env: NodeJS.ProcessEnv = process.env): string {
|
|
351
|
-
return join(resolvePantheonHome(env), 'memory', 'memory.db')
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
// ─── SQLite boundary ────────────────────────────────────────────────────
|
|
355
|
-
|
|
356
|
-
/** The subset of `node:sqlite` this module needs. */
|
|
357
|
-
export interface MemorySqliteStatement {
|
|
358
|
-
all(...params: unknown[]): unknown[]
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
export interface MemorySqliteDatabase {
|
|
362
|
-
prepare(sql: string): MemorySqliteStatement
|
|
363
|
-
close(): void
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
export interface MemorySqliteModule {
|
|
367
|
-
DatabaseSync: new (path: string, options?: { readOnly?: boolean }) => MemorySqliteDatabase
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
let cachedSqlite: MemorySqliteModule | null | undefined
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* Load `node:sqlite` synchronously, or return `null`.
|
|
374
|
-
*
|
|
375
|
-
* `process.getBuiltinModule` (Node ≥ 22.3) is used instead of a dynamic import
|
|
376
|
-
* because the `context` hook is synchronous and the host will not await a
|
|
377
|
-
* promise. `node:sqlite` (Node ≥ 22.5) therefore cannot exist on a runtime
|
|
378
|
-
* where `getBuiltinModule` is missing, so a single path covers both. The
|
|
379
|
-
* failure is cached: a runtime that lacks the module never pays for the probe
|
|
380
|
-
* twice.
|
|
381
|
-
*/
|
|
382
|
-
function loadMemorySqlite(): MemorySqliteModule | null {
|
|
383
|
-
if (cachedSqlite !== undefined) return cachedSqlite
|
|
384
|
-
try {
|
|
385
|
-
const getBuiltin = (process as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule
|
|
386
|
-
if (typeof getBuiltin !== 'function') {
|
|
387
|
-
cachedSqlite = null
|
|
388
|
-
return null
|
|
389
|
-
}
|
|
390
|
-
const mod = getBuiltin('node:sqlite') as MemorySqliteModule | undefined
|
|
391
|
-
cachedSqlite = mod !== undefined && typeof mod?.DatabaseSync === 'function' ? mod : null
|
|
392
|
-
} catch {
|
|
393
|
-
cachedSqlite = null
|
|
394
|
-
}
|
|
395
|
-
return cachedSqlite
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
export type MemorySkipReason =
|
|
399
|
-
| 'disabled'
|
|
400
|
-
| 'no-sqlite'
|
|
401
|
-
| 'no-db'
|
|
402
|
-
| 'schema'
|
|
403
|
-
| 'no-system'
|
|
404
|
-
| 'no-message'
|
|
405
|
-
| 'no-terms'
|
|
406
|
-
| 'empty'
|
|
407
|
-
| 'error'
|
|
408
|
-
|
|
409
|
-
export interface MemoryRow {
|
|
410
|
-
namespace: string
|
|
411
|
-
key: string | null
|
|
412
|
-
value: string
|
|
413
|
-
created_at: string
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
export interface MemoryInjectionResult {
|
|
417
|
-
/** The system-part text, or `null` when nothing is injected. */
|
|
418
|
-
text: string | null
|
|
419
|
-
/** Entries actually rendered. */
|
|
420
|
-
entries: number
|
|
421
|
-
/** Characters in `text` (`0` when `text` is null). */
|
|
422
|
-
chars: number
|
|
423
|
-
/** Why nothing was injected; `null` on success. */
|
|
424
|
-
skip: MemorySkipReason | null
|
|
425
|
-
/** One-line diagnostic detail for the plugin log (never user content). */
|
|
426
|
-
detail?: string
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
export interface MemoryInjectionDeps {
|
|
430
|
-
/** Explicit database path (tests / unusual installs). */
|
|
431
|
-
dbPath?: string
|
|
432
|
-
/** Environment used for path resolution. Default: `process.env`. */
|
|
433
|
-
env?: NodeJS.ProcessEnv
|
|
434
|
-
/** Injectable `node:sqlite` loader. Default: {@link loadMemorySqlite}. */
|
|
435
|
-
sqliteLoader?: () => MemorySqliteModule | null
|
|
436
|
-
/** Clock. Default: `Date.now`. */
|
|
437
|
-
now?: () => number
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
const REQUIRED_TABLES = ['memories', 'memories_fts'] as const
|
|
441
|
-
const REQUIRED_COLUMNS = ['id', 'namespace', 'key', 'value', 'created_at'] as const
|
|
442
|
-
|
|
443
|
-
interface OpenFailure {
|
|
444
|
-
skip: Extract<MemorySkipReason, 'no-sqlite' | 'no-db' | 'schema' | 'error'>
|
|
445
|
-
detail: string
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
interface OpenSuccess {
|
|
449
|
-
db: MemorySqliteDatabase
|
|
450
|
-
/** Whether `memories.expires_at` exists (added by TTL support). */
|
|
451
|
-
hasExpiry: boolean
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
function isFailure(value: OpenSuccess | OpenFailure): value is OpenFailure {
|
|
455
|
-
return 'skip' in value
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
function errorMessage(error: unknown): string {
|
|
459
|
-
return error instanceof Error ? error.message : String(error)
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/** Open the memory database read-only and validate the shape this module needs. */
|
|
463
|
-
function openMemoryDb(dbPath: string, sqlite: MemorySqliteModule): OpenSuccess | OpenFailure {
|
|
464
|
-
if (!existsSync(dbPath)) {
|
|
465
|
-
return { skip: 'no-db', detail: `memory database not found at ${dbPath}` }
|
|
466
|
-
}
|
|
467
|
-
let db: MemorySqliteDatabase
|
|
468
|
-
try {
|
|
469
|
-
db = new sqlite.DatabaseSync(dbPath, { readOnly: true })
|
|
470
|
-
} catch (error) {
|
|
471
|
-
return {
|
|
472
|
-
skip: 'no-db',
|
|
473
|
-
detail: `memory database could not be opened read-only: ${errorMessage(error)}`,
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
try {
|
|
477
|
-
const tables = db
|
|
478
|
-
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?)")
|
|
479
|
-
.all(...REQUIRED_TABLES)
|
|
480
|
-
.map((row) => (row as { name?: unknown }).name)
|
|
481
|
-
.filter((name): name is string => typeof name === 'string')
|
|
482
|
-
const missingTables = REQUIRED_TABLES.filter((name) => !tables.includes(name))
|
|
483
|
-
if (missingTables.length > 0) {
|
|
484
|
-
db.close()
|
|
485
|
-
return { skip: 'schema', detail: `missing table(s) ${missingTables.join(', ')}` }
|
|
486
|
-
}
|
|
487
|
-
const columns = db
|
|
488
|
-
.prepare('PRAGMA table_info(memories)')
|
|
489
|
-
.all()
|
|
490
|
-
.map((row) => (row as { name?: unknown }).name)
|
|
491
|
-
.filter((name): name is string => typeof name === 'string')
|
|
492
|
-
const missingColumns = REQUIRED_COLUMNS.filter((name) => !columns.includes(name))
|
|
493
|
-
if (missingColumns.length > 0) {
|
|
494
|
-
db.close()
|
|
495
|
-
return { skip: 'schema', detail: `missing column(s) ${missingColumns.join(', ')}` }
|
|
496
|
-
}
|
|
497
|
-
return { db, hasExpiry: columns.includes('expires_at') }
|
|
498
|
-
} catch (error) {
|
|
499
|
-
try {
|
|
500
|
-
db.close()
|
|
501
|
-
} catch {
|
|
502
|
-
// Best-effort close; the diagnostic below is what matters.
|
|
503
|
-
}
|
|
504
|
-
return { skip: 'schema', detail: `schema probe failed: ${errorMessage(error)}` }
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
// ─── FTS query builder (mirror of memory_mcp.py:314) ────────────────────
|
|
509
|
-
|
|
510
|
-
/**
|
|
511
|
-
* Build an FTS5 `MATCH` expression from free-text input.
|
|
512
|
-
*
|
|
513
|
-
* SOURCE OF TRUTH: `_build_fts_query` in `src/mcp/memory_mcp.py` (`:314` on the
|
|
514
|
-
* tree this was ported from — the SYMBOL is the contract, the line number
|
|
515
|
-
* drifts with any unrelated edit above it). Same stopword filter, same
|
|
516
|
-
* 4-character prefix threshold, same `OR`-joined `"term"*` shape. Two
|
|
517
|
-
* deliberate additions: embedded double quotes are doubled so a quote in user
|
|
518
|
-
* text cannot break out of the quoted term, and the term count is capped at
|
|
519
|
-
* {@link MAX_SEARCH_TERMS}.
|
|
520
|
-
*
|
|
521
|
-
* @returns The expression, or `''` when no searchable term survives.
|
|
522
|
-
*/
|
|
523
|
-
export function buildFtsQuery(query: string): string {
|
|
524
|
-
if (typeof query !== 'string') return ''
|
|
525
|
-
const words = query.split(/\s+/).filter((word) => word !== '')
|
|
526
|
-
if (words.length === 0) return ''
|
|
527
|
-
const content = words.filter((word) => !MEMORY_STOPWORDS.has(word.toLowerCase()))
|
|
528
|
-
if (content.length === 0) return ''
|
|
529
|
-
return content
|
|
530
|
-
.slice(0, MAX_SEARCH_TERMS)
|
|
531
|
-
.map((word) => {
|
|
532
|
-
// A double quote inside an FTS5 string is escaped by doubling it.
|
|
533
|
-
const escaped = word.replace(/"/g, '""')
|
|
534
|
-
return escaped.length >= MIN_PREFIX_LEN ? `"${escaped}"*` : `"${escaped}"`
|
|
535
|
-
})
|
|
536
|
-
.join(' OR ')
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
// ─── Session message → search text ──────────────────────────────────────
|
|
540
|
-
|
|
541
|
-
/**
|
|
542
|
-
* Extract the text of the session's FIRST user message.
|
|
543
|
-
*
|
|
544
|
-
* V2 message shape (measured on opencode v2.1.2, see the `context-pruner`
|
|
545
|
-
* module docstring): `{ id?, role, content: [{ type: 'text', text }],
|
|
546
|
-
* metadata? }`. A bare string `content` is also accepted. Returns `null` when
|
|
547
|
-
* there is no non-empty user text.
|
|
548
|
-
*/
|
|
549
|
-
export function extractFirstUserText(messages: unknown): string | null {
|
|
550
|
-
if (!Array.isArray(messages)) return null
|
|
551
|
-
for (const message of messages) {
|
|
552
|
-
if (message === null || typeof message !== 'object') continue
|
|
553
|
-
const candidate = message as { role?: unknown; content?: unknown }
|
|
554
|
-
if (candidate.role !== 'user') continue
|
|
555
|
-
const text = messageText(candidate.content)
|
|
556
|
-
if (text !== null) return text.slice(0, MAX_SEARCH_CHARS)
|
|
557
|
-
}
|
|
558
|
-
return null
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
function messageText(content: unknown): string | null {
|
|
562
|
-
if (typeof content === 'string') {
|
|
563
|
-
const trimmed = content.trim()
|
|
564
|
-
return trimmed === '' ? null : trimmed
|
|
565
|
-
}
|
|
566
|
-
if (!Array.isArray(content)) return null
|
|
567
|
-
const pieces: string[] = []
|
|
568
|
-
for (const part of content) {
|
|
569
|
-
if (part === null || typeof part !== 'object') continue
|
|
570
|
-
const entry = part as { type?: unknown; text?: unknown }
|
|
571
|
-
if (typeof entry.text !== 'string') continue
|
|
572
|
-
if (entry.type !== undefined && entry.type !== 'text') continue
|
|
573
|
-
if (entry.text.trim() === '') continue
|
|
574
|
-
pieces.push(entry.text)
|
|
575
|
-
}
|
|
576
|
-
if (pieces.length === 0) return null
|
|
577
|
-
return pieces.join(' ').trim()
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
// ─── Rendering ──────────────────────────────────────────────────────────
|
|
581
|
-
|
|
582
|
-
/** Collapse whitespace so one entry stays one readable line. */
|
|
583
|
-
function normalizeValue(value: string): string {
|
|
584
|
-
return value.replace(/\s+/g, ' ').trim()
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
function entryLabel(row: MemoryRow): string {
|
|
588
|
-
const namespace = typeof row.namespace === 'string' ? row.namespace.trim() : ''
|
|
589
|
-
const key = typeof row.key === 'string' ? row.key.trim() : ''
|
|
590
|
-
if (key !== '') return namespace === '' ? key : `${namespace}/${key}`
|
|
591
|
-
return namespace === '' ? 'memory' : namespace
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
/** Header of the injected part; counts against the budget. */
|
|
595
|
-
function payloadHeader(): string {
|
|
596
|
-
return (
|
|
597
|
-
`${MEMORY_CONTEXT_MARKER}\n` +
|
|
598
|
-
'Pantheon memory (auto-injected, read-only; call memory_search for more):'
|
|
599
|
-
)
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
/**
|
|
603
|
-
* Render rows into the budgeted system-part text.
|
|
604
|
-
*
|
|
605
|
-
* The whole payload — header and entries — is bounded by `maxChars`. The room
|
|
606
|
-
* left after the header is split evenly between the rows that will be shown
|
|
607
|
-
* (at most `maxEntries`), so one huge entry cannot consume the budget of the
|
|
608
|
-
* others: an ambient block that recollects ONE memory is not the same feature
|
|
609
|
-
* as one that recollects three. An entry that does not fit its share is
|
|
610
|
-
* truncated with {@link TRUNCATION_SUFFIX}; an entry with less than
|
|
611
|
-
* {@link MIN_ENTRY_ROOM} characters of room is dropped. Returns `null` when not
|
|
612
|
-
* even one entry fits.
|
|
613
|
-
*/
|
|
614
|
-
export function renderMemoryContext(
|
|
615
|
-
rows: readonly MemoryRow[],
|
|
616
|
-
maxChars: number,
|
|
617
|
-
maxEntries: number = Array.isArray(rows) ? rows.length : 0,
|
|
618
|
-
): { text: string; entries: number } | null {
|
|
619
|
-
if (!Array.isArray(rows) || rows.length === 0) return null
|
|
620
|
-
if (typeof maxChars !== 'number' || !Number.isFinite(maxChars)) return null
|
|
621
|
-
const header = payloadHeader()
|
|
622
|
-
if (header.length + TRUNCATION_SUFFIX.length + MIN_ENTRY_ROOM > maxChars) return null
|
|
623
|
-
const slots = Math.max(1, Math.min(rows.length, Math.floor(maxEntries) || 1))
|
|
624
|
-
const perEntryFloor = MIN_ENTRY_ROOM + TRUNCATION_SUFFIX.length
|
|
625
|
-
const share = Math.max(perEntryFloor, Math.floor((maxChars - header.length) / slots))
|
|
626
|
-
let text = header
|
|
627
|
-
let entries = 0
|
|
628
|
-
for (const row of rows) {
|
|
629
|
-
if (row === null || typeof row !== 'object') continue
|
|
630
|
-
const value = normalizeValue(typeof row.value === 'string' ? row.value : '')
|
|
631
|
-
if (value === '') continue
|
|
632
|
-
const line = `\n- ${entryLabel(row)}: ${value}`
|
|
633
|
-
const available = maxChars - text.length
|
|
634
|
-
if (available <= 0) break
|
|
635
|
-
// A per-entry share, never more than what is left in the total budget.
|
|
636
|
-
const lineCap = Math.min(share, available)
|
|
637
|
-
if (line.length <= lineCap) {
|
|
638
|
-
text += line
|
|
639
|
-
entries++
|
|
640
|
-
continue
|
|
641
|
-
}
|
|
642
|
-
if (lineCap <= TRUNCATION_SUFFIX.length) break
|
|
643
|
-
const room = lineCap - TRUNCATION_SUFFIX.length
|
|
644
|
-
if (room < MIN_ENTRY_ROOM) break
|
|
645
|
-
text += `${line.slice(0, room)}${TRUNCATION_SUFFIX}`
|
|
646
|
-
entries++
|
|
647
|
-
}
|
|
648
|
-
if (entries === 0) return null
|
|
649
|
-
return { text, entries }
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
// ─── Query + build ──────────────────────────────────────────────────────
|
|
653
|
-
|
|
654
|
-
/** ISO-8601 UTC with second precision, matching `_now_iso` in `memory_mcp.py`. */
|
|
655
|
-
function nowIso(now: () => number): string {
|
|
656
|
-
return new Date(now()).toISOString().replace(/\.\d{3}Z$/, 'Z')
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
/**
|
|
660
|
-
* Read the top-K matching rows. All caller-supplied values are bound
|
|
661
|
-
* parameters; the only text this function concatenates is its own SQL.
|
|
662
|
-
*/
|
|
663
|
-
function queryMemoryRows(
|
|
664
|
-
db: MemorySqliteDatabase,
|
|
665
|
-
ftsQuery: string,
|
|
666
|
-
config: MemoryInjectionConfig,
|
|
667
|
-
hasExpiry: boolean,
|
|
668
|
-
referenceTime: string,
|
|
669
|
-
): MemoryRow[] {
|
|
670
|
-
const params: unknown[] = [ftsQuery]
|
|
671
|
-
let filters = ''
|
|
672
|
-
if (hasExpiry) {
|
|
673
|
-
// Lexicographic comparison of stored ISO-8601 UTC strings is
|
|
674
|
-
// chronological, so no date parsing is needed in SQL. Rows written before
|
|
675
|
-
// TTL support have expires_at NULL and stay visible.
|
|
676
|
-
filters += ' AND (memories.expires_at IS NULL OR memories.expires_at > ?)'
|
|
677
|
-
params.push(referenceTime)
|
|
678
|
-
}
|
|
679
|
-
if (config.namespace !== null) {
|
|
680
|
-
filters += ' AND memories.namespace = ?'
|
|
681
|
-
params.push(config.namespace)
|
|
682
|
-
}
|
|
683
|
-
params.push(config.maxEntries)
|
|
684
|
-
const rows = db
|
|
685
|
-
.prepare(
|
|
686
|
-
`SELECT memories.namespace AS namespace, memories.key AS key,
|
|
687
|
-
memories.value AS value, memories.created_at AS created_at
|
|
688
|
-
FROM memories_fts
|
|
689
|
-
JOIN memories ON memories.id = memories_fts.rowid
|
|
690
|
-
WHERE memories_fts MATCH ?${filters}
|
|
691
|
-
ORDER BY rank LIMIT ?`,
|
|
692
|
-
)
|
|
693
|
-
.all(...params)
|
|
694
|
-
return rows as MemoryRow[]
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
const SKIP: MemorySkipReason[] = [
|
|
698
|
-
'disabled',
|
|
699
|
-
'no-sqlite',
|
|
700
|
-
'no-db',
|
|
701
|
-
'schema',
|
|
702
|
-
'no-system',
|
|
703
|
-
'no-message',
|
|
704
|
-
'no-terms',
|
|
705
|
-
'empty',
|
|
706
|
-
'error',
|
|
707
|
-
]
|
|
708
|
-
|
|
709
|
-
/**
|
|
710
|
-
* Environment variable that adds the raw error message to an `error` skip.
|
|
711
|
-
* OFF by default: that message can contain SQL and the FTS `MATCH` expression,
|
|
712
|
-
* which is built from the session's first user message.
|
|
713
|
-
*/
|
|
714
|
-
export const MEMORY_INJECTION_DEBUG_ENV = 'PANTHEON_MEMORY_INJECTION_DEBUG'
|
|
715
|
-
|
|
716
|
-
/**
|
|
717
|
-
* A STABLE classification for an unexpected failure — never the message body.
|
|
718
|
-
*
|
|
719
|
-
* An SQLite/FTS error message echoes the failing statement, and that statement
|
|
720
|
-
* carries the `MATCH` expression built from the user's first message, so a raw
|
|
721
|
-
* message would copy user content into `hooks.log`. Node's sqlite errors carry
|
|
722
|
-
* a stable `code` (`ERR_SQLITE_ERROR`, `ERR_INVALID_STATE`, …) and a `name`;
|
|
723
|
-
* either identifies the failure class without the body. Anything that does not
|
|
724
|
-
* look like an enum falls back to `unknown`.
|
|
725
|
-
*/
|
|
726
|
-
export function classifyMemoryError(error: unknown): string {
|
|
727
|
-
const stable = (value: unknown): string | null =>
|
|
728
|
-
typeof value === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,39}$/.test(value) ? value : null
|
|
729
|
-
try {
|
|
730
|
-
if (error === null || typeof error !== 'object') return 'unknown'
|
|
731
|
-
const code = stable((error as { code?: unknown }).code)
|
|
732
|
-
if (code !== null) return code
|
|
733
|
-
const name = stable((error as { name?: unknown }).name)
|
|
734
|
-
if (name !== null && name !== 'Error') return name
|
|
735
|
-
return 'unknown'
|
|
736
|
-
} catch {
|
|
737
|
-
return 'unknown'
|
|
738
|
-
}
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
/**
|
|
742
|
-
* The `detail` attached to an `error` skip: the classification only, unless
|
|
743
|
-
* {@link MEMORY_INJECTION_DEBUG_ENV} is `1`. The debug form is deliberately not
|
|
744
|
-
* the default — with it on, `hooks.log` can contain memory text and prompt
|
|
745
|
-
* fragments.
|
|
746
|
-
*/
|
|
747
|
-
export function errorDetail(error: unknown): string {
|
|
748
|
-
const classification = `code=${classifyMemoryError(error)}`
|
|
749
|
-
if (process.env[MEMORY_INJECTION_DEBUG_ENV] !== '1') return classification
|
|
750
|
-
return `${classification} message=${errorMessage(error)}`
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
function fail(skip: MemorySkipReason, detail?: string): MemoryInjectionResult {
|
|
754
|
-
return {
|
|
755
|
-
text: null,
|
|
756
|
-
entries: 0,
|
|
757
|
-
chars: 0,
|
|
758
|
-
skip: SKIP.includes(skip) ? skip : 'error',
|
|
759
|
-
...(detail === undefined ? {} : { detail }),
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
/**
|
|
764
|
-
* Build the injection payload for one session's first request.
|
|
765
|
-
*
|
|
766
|
-
* Never throws. Returns `{ text: null, skip }` for every failure — a disabled
|
|
767
|
-
* config, a runtime without `node:sqlite`, a missing/unreadable/mismatched
|
|
768
|
-
* database, a message with no searchable terms, or an empty result set.
|
|
769
|
-
*/
|
|
770
|
-
export function buildMemoryInjection(
|
|
771
|
-
messages: unknown,
|
|
772
|
-
config: MemoryInjectionConfig,
|
|
773
|
-
deps: MemoryInjectionDeps = {},
|
|
774
|
-
): MemoryInjectionResult {
|
|
775
|
-
try {
|
|
776
|
-
if (config === null || typeof config !== 'object' || !config.enabled) {
|
|
777
|
-
return fail('disabled')
|
|
778
|
-
}
|
|
779
|
-
const searchText = extractFirstUserText(messages)
|
|
780
|
-
if (searchText === null) return fail('no-message')
|
|
781
|
-
const ftsQuery = buildFtsQuery(searchText)
|
|
782
|
-
if (ftsQuery === '') return fail('no-terms')
|
|
783
|
-
const sqlite = (deps.sqliteLoader ?? loadMemorySqlite)()
|
|
784
|
-
if (sqlite === null) {
|
|
785
|
-
return fail('no-sqlite', 'node:sqlite is unavailable in this runtime')
|
|
786
|
-
}
|
|
787
|
-
const dbPath = deps.dbPath ?? resolveMemoryDbPath(deps.env)
|
|
788
|
-
const opened = openMemoryDb(dbPath, sqlite)
|
|
789
|
-
if (isFailure(opened)) return fail(opened.skip, opened.detail)
|
|
790
|
-
let rows: MemoryRow[]
|
|
791
|
-
try {
|
|
792
|
-
rows = queryMemoryRows(
|
|
793
|
-
opened.db,
|
|
794
|
-
ftsQuery,
|
|
795
|
-
config,
|
|
796
|
-
opened.hasExpiry,
|
|
797
|
-
nowIso(deps.now ?? Date.now),
|
|
798
|
-
)
|
|
799
|
-
} finally {
|
|
800
|
-
try {
|
|
801
|
-
opened.db.close()
|
|
802
|
-
} catch {
|
|
803
|
-
// A close failure must not mask the query result.
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
if (rows.length === 0) return fail('empty')
|
|
807
|
-
const rendered = renderMemoryContext(rows, config.maxChars, config.maxEntries)
|
|
808
|
-
if (rendered === null) return fail('empty', 'no entry fit the character budget')
|
|
809
|
-
return {
|
|
810
|
-
text: rendered.text,
|
|
811
|
-
entries: rendered.entries,
|
|
812
|
-
chars: rendered.text.length,
|
|
813
|
-
skip: null,
|
|
814
|
-
}
|
|
815
|
-
} catch (error) {
|
|
816
|
-
return fail('error', errorDetail(error))
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
// ─── Once-per-session cache ─────────────────────────────────────────────
|
|
821
|
-
|
|
822
|
-
/** Sessions whose payload is memoized before the oldest is evicted. */
|
|
823
|
-
export const MEMORY_CACHE_MAX_SESSIONS = 64
|
|
824
|
-
|
|
825
|
-
/**
|
|
826
|
-
* Bounded, insertion-ordered memo of one payload per session id.
|
|
827
|
-
*
|
|
828
|
-
* The payload is computed on the session's first request and replayed on every
|
|
829
|
-
* later one, so a session never re-queries the store per request. A `null` text
|
|
830
|
-
* is cached too: a disabled/missing store must not be re-probed per request
|
|
831
|
-
* either. Sessions without a usable id are never cached (nothing to key on).
|
|
832
|
-
*/
|
|
833
|
-
export class MemoryInjectionCache {
|
|
834
|
-
private readonly entries = new Map<string, MemoryInjectionResult>()
|
|
835
|
-
|
|
836
|
-
get size(): number {
|
|
837
|
-
return this.entries.size
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
clear(): void {
|
|
841
|
-
this.entries.clear()
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
/** Forget one session (used when the host deletes it). */
|
|
845
|
-
delete(sessionID: unknown): void {
|
|
846
|
-
if (typeof sessionID !== 'string') return
|
|
847
|
-
this.entries.delete(sessionID)
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
/** Return the memoized payload, computing and storing it on a miss. */
|
|
851
|
-
resolve(sessionID: unknown, compute: () => MemoryInjectionResult): MemoryInjectionResult {
|
|
852
|
-
const key = typeof sessionID === 'string' && sessionID.trim() !== '' ? sessionID : null
|
|
853
|
-
if (key === null) return compute()
|
|
854
|
-
const cached = this.entries.get(key)
|
|
855
|
-
if (cached !== undefined) return cached
|
|
856
|
-
const value = compute()
|
|
857
|
-
if (this.entries.size >= MEMORY_CACHE_MAX_SESSIONS) {
|
|
858
|
-
const oldest = this.entries.keys().next()
|
|
859
|
-
if (!oldest.done) this.entries.delete(oldest.value)
|
|
860
|
-
}
|
|
861
|
-
this.entries.set(key, value)
|
|
862
|
-
return value
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
// ─── Hook application ───────────────────────────────────────────────────
|
|
867
|
-
|
|
868
|
-
/** How many session ids the one-line-per-session log keeps before it resets. */
|
|
869
|
-
export const MEMORY_INJECTION_LOG_MAX_SESSIONS = 512
|
|
870
|
-
|
|
871
|
-
/** Session ids already reported (one line per session, success or failure). */
|
|
872
|
-
const loggedSessions = new Set<string>()
|
|
873
|
-
|
|
874
|
-
/** Test seam: forget which sessions were already reported. */
|
|
875
|
-
export function resetMemoryInjectionLogState(): void {
|
|
876
|
-
loggedSessions.clear()
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
let configWarned = false
|
|
880
|
-
|
|
881
|
-
/** Test seam: forget that an invalid config was reported. */
|
|
882
|
-
export function resetMemoryInjectionConfigWarned(): void {
|
|
883
|
-
configWarned = false
|
|
884
|
-
}
|
|
885
|
-
|
|
886
|
-
/** Skips that are ordinary conditions rather than faults, so they stay silent. */
|
|
887
|
-
const SILENT_SKIPS: ReadonlySet<MemorySkipReason> = new Set<MemorySkipReason>([
|
|
888
|
-
'disabled',
|
|
889
|
-
'no-message',
|
|
890
|
-
'no-terms',
|
|
891
|
-
'empty',
|
|
892
|
-
])
|
|
893
|
-
|
|
894
|
-
/**
|
|
895
|
-
* Whether a `system` part array already carries the injected marker.
|
|
896
|
-
*
|
|
897
|
-
* Accepts the measured part shape (`{ type: 'text', text }`) and a bare string,
|
|
898
|
-
* and never throws, so it is safe to call on host input of unknown shape.
|
|
899
|
-
*/
|
|
900
|
-
export function hasMemoryContextMarker(system: unknown): boolean {
|
|
901
|
-
if (!Array.isArray(system)) return false
|
|
902
|
-
try {
|
|
903
|
-
return system.some((entry) => {
|
|
904
|
-
if (typeof entry === 'string') return entry.includes(MEMORY_CONTEXT_MARKER)
|
|
905
|
-
if (entry === null || typeof entry !== 'object') return false
|
|
906
|
-
const text = (entry as { text?: unknown }).text
|
|
907
|
-
return typeof text === 'string' && text.includes(MEMORY_CONTEXT_MARKER)
|
|
908
|
-
})
|
|
909
|
-
} catch {
|
|
910
|
-
return false
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
/**
|
|
915
|
-
* Report an invalid `memory_injection` block ONCE per process, naming the
|
|
916
|
-
* ignored keys and the accepted ones, while resolution still falls back to the
|
|
917
|
-
* defaults. Without this a typo (`maxEntry`) is invisible: the engine keeps its
|
|
918
|
-
* default and the operator believes the setting took effect.
|
|
919
|
-
*/
|
|
920
|
-
export function warnInvalidMemoryInjectionConfig(
|
|
921
|
-
options: unknown,
|
|
922
|
-
log: (line: string) => void,
|
|
923
|
-
): void {
|
|
924
|
-
if (configWarned) return
|
|
925
|
-
try {
|
|
926
|
-
const issues = describeMemoryInjectionConfigIssues(options)
|
|
927
|
-
if (issues.length === 0) return
|
|
928
|
-
configWarned = true
|
|
929
|
-
log(
|
|
930
|
-
`[memory-context] ignored invalid memory_injection config: ${issues.join('; ')}; ` +
|
|
931
|
-
`accepted keys: ${MEMORY_INJECTION_CONFIG_KEYS.join(', ')}`,
|
|
932
|
-
)
|
|
933
|
-
} catch {
|
|
934
|
-
// A validator must never break setup; silence is the only safe fallback.
|
|
935
|
-
configWarned = true
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
/**
|
|
940
|
-
* The one-line log entry for a session, or `null` when nothing should be
|
|
941
|
-
* written.
|
|
942
|
-
*
|
|
943
|
-
* ONCE PER SESSION, failures included: the hook runs on every model step, so
|
|
944
|
-
* without the dedupe a successful injection would log on each request and a
|
|
945
|
-
* broken store would log until the session ends. A skip that only means "there
|
|
946
|
-
* was nothing to recall" (`no-message`, `no-terms`, `empty`, `disabled`) is not
|
|
947
|
-
* a fault and writes nothing; `no-sqlite`, `no-db`, `schema` and `error` do,
|
|
948
|
-
* because they mean this feature is inert and only a log line can say so.
|
|
949
|
-
*/
|
|
950
|
-
export function formatMemoryInjectionLogLine(
|
|
951
|
-
sessionID: unknown,
|
|
952
|
-
result: MemoryInjectionResult,
|
|
953
|
-
seen: Set<string> = loggedSessions,
|
|
954
|
-
): string | null {
|
|
955
|
-
if (result.text === null && (result.skip === null || SILENT_SKIPS.has(result.skip))) return null
|
|
956
|
-
const key = typeof sessionID === 'string' && sessionID !== '' ? sessionID : 'unknown'
|
|
957
|
-
if (seen.has(key)) return null
|
|
958
|
-
if (seen.size >= MEMORY_INJECTION_LOG_MAX_SESSIONS) seen.clear()
|
|
959
|
-
seen.add(key)
|
|
960
|
-
if (result.text !== null) {
|
|
961
|
-
return `[memory-context] injected entries=${result.entries} chars=${result.chars} session=${key}`
|
|
962
|
-
}
|
|
963
|
-
return (
|
|
964
|
-
`[memory-context] no injection session=${key} skip=${result.skip}` +
|
|
965
|
-
(result.detail === undefined ? '' : `: ${result.detail}`)
|
|
966
|
-
)
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
/**
|
|
970
|
-
* The whole memory step of the `context` hook: append the session's payload to
|
|
971
|
-
* a normalized `system` part array, once.
|
|
972
|
-
*
|
|
973
|
-
* `system` is accepted as `unknown` on purpose: the caller passes whatever the
|
|
974
|
-
* host sent, and only an `Array` is ever touched. When it IS an array it must
|
|
975
|
-
* already be `Array<{ type: 'text', text }>` — the host rejects any other shape
|
|
976
|
-
* — and this function only ever PUSHES one such part. It returns silently when
|
|
977
|
-
* injection is disabled, when the marker is already present (a later request of
|
|
978
|
-
* the same session, or a retry), or when the store yields nothing. Never throws:
|
|
979
|
-
* an ambient feature must not be able to break the request it decorates.
|
|
980
|
-
*
|
|
981
|
-
* ENABLED BUT UNUSABLE IS OBSERVABLE: with `enabled: true` and no usable
|
|
982
|
-
* `system` array there is nothing to push into, so the feature cannot work —
|
|
983
|
-
* and that is reported once per session as `skip=no-system` instead of
|
|
984
|
-
* vanishing. A feature that is switched on and silently does nothing is worse
|
|
985
|
-
* than one that is switched off, because the operator has no signal at all.
|
|
986
|
-
*/
|
|
987
|
-
export function applyMemoryInjection(
|
|
988
|
-
system: unknown,
|
|
989
|
-
messages: unknown,
|
|
990
|
-
sessionID: unknown,
|
|
991
|
-
config: MemoryInjectionConfig,
|
|
992
|
-
cache: MemoryInjectionCache,
|
|
993
|
-
log?: (line: string) => void,
|
|
994
|
-
): void {
|
|
995
|
-
try {
|
|
996
|
-
if (config === null || typeof config !== 'object' || !config.enabled) return
|
|
997
|
-
if (!Array.isArray(system)) {
|
|
998
|
-
const line = formatMemoryInjectionLogLine(sessionID, {
|
|
999
|
-
text: null,
|
|
1000
|
-
entries: 0,
|
|
1001
|
-
chars: 0,
|
|
1002
|
-
skip: 'no-system',
|
|
1003
|
-
detail:
|
|
1004
|
-
system === undefined || system === null ? 'system absent' : 'system is not an array',
|
|
1005
|
-
})
|
|
1006
|
-
if (line !== null) log?.(line)
|
|
1007
|
-
return
|
|
1008
|
-
}
|
|
1009
|
-
if (hasMemoryContextMarker(system)) return
|
|
1010
|
-
const result = cache.resolve(sessionID, () => buildMemoryInjection(messages, config))
|
|
1011
|
-
if (result.text !== null) system.push({ type: 'text', text: result.text })
|
|
1012
|
-
const line = formatMemoryInjectionLogLine(sessionID, result)
|
|
1013
|
-
if (line !== null) log?.(line)
|
|
1014
|
-
} catch {
|
|
1015
|
-
// Fail-open by contract.
|
|
1016
|
-
}
|
|
1017
|
-
}
|