@joe-broadhead/opencode-mem 0.0.0-stage → 0.6.1

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/src/util.js ADDED
@@ -0,0 +1,176 @@
1
+ import { createHash } from "node:crypto"
2
+
3
+ /** @param {Date} [d] */
4
+ export function nowIso(d = new Date()) {
5
+ return d.toISOString()
6
+ }
7
+
8
+ export function shortHash(value, length = 12) {
9
+ return createHash("sha1").update(String(value)).digest("hex").slice(0, length)
10
+ }
11
+
12
+ export function oneLine(value, max = 400) {
13
+ const text = String(value ?? "")
14
+ .replace(/\s+/g, " ")
15
+ .trim()
16
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
17
+ }
18
+
19
+ export function clampText(value, max) {
20
+ const text = String(value ?? "")
21
+ if (!Number.isFinite(max) || max <= 0) return ""
22
+ return text.length > max ? text.slice(0, Math.max(0, max - 1)) + "…" : text
23
+ }
24
+
25
+ /** Delimiters this plugin wraps untrusted memory in. The single list every fence check uses. */
26
+ export const FENCE_TAGS = Object.freeze([
27
+ "mem_pinned",
28
+ "recalled_memory",
29
+ "knowledge",
30
+ "knowledge_assets",
31
+ "mem_checkpoint",
32
+ "mem_compaction",
33
+ "mem_protocol",
34
+ "forget_preview",
35
+ "forget_copies",
36
+ ])
37
+
38
+ /**
39
+ * Neutralize a closing fence tag inside interpolated, untrusted content.
40
+ *
41
+ * Memory text is a data channel. A persona, atom, or wiki page that contains
42
+ * `</mem_pinned>` must not be able to end the delimited block and make the rest
43
+ * of its content look like host instructions, so every closing tag for a fence
44
+ * this plugin emits is rewritten to its HTML entity form.
45
+ *
46
+ * @param {unknown} value
47
+ * @param {readonly string[]} [tags]
48
+ */
49
+ export function neutralizeFenceClosers(value, tags = FENCE_TAGS) {
50
+ let text = String(value ?? "")
51
+ for (const tag of tags) {
52
+ const pattern = new RegExp(`</\\s*${tag}\\s*>`, "gi")
53
+ text = text.replace(pattern, (match) => `&lt;${match.slice(1)}`)
54
+ }
55
+ return text
56
+ }
57
+
58
+ /**
59
+ * Set a key in an insertion-ordered Map or Set and evict the oldest entries
60
+ * beyond `max`. Re-setting a key moves it to the newest position, so the
61
+ * structure behaves as a small LRU instead of growing for the life of the host.
62
+ *
63
+ * @template K, V
64
+ * @param {Map<K, V> | Set<K>} store
65
+ * @param {K} key
66
+ * @param {V} [value]
67
+ * @param {number} [max]
68
+ */
69
+ export function rememberBounded(store, key, value, max = 500) {
70
+ store.delete(key)
71
+ if (store instanceof Map) store.set(key, value)
72
+ else store.add(key)
73
+ while (store.size > max) {
74
+ const oldest = store.keys().next().value
75
+ if (oldest === undefined) break
76
+ store.delete(oldest)
77
+ }
78
+ return store
79
+ }
80
+
81
+ const SECRET_PATTERNS = Object.freeze([
82
+ // Authorization-style headers consume the whole value, including a scheme.
83
+ [/\b(authorization|x-api-key)\b["']?(\s*[:=]\s*)[^\r\n,;]+/gi, "$1$2[redacted]"],
84
+ // Token assignments, passwords, and API keys. The value may be quoted.
85
+ [
86
+ /\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|passwd|secret)\b["']?(\s*[:=]\s*)(?:"[^"\n]*"|'[^'\n]*'|[^\s,;]+)/gi,
87
+ "$1$2[redacted]",
88
+ ],
89
+ [/\bBearer\s+[A-Za-z0-9._~+/=-]{3,}/gi, "Bearer [redacted]"],
90
+ [/\bsk-[A-Za-z0-9_-]{6,}/g, "[redacted-key]"],
91
+ [/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{8,}\b/g, "[redacted-token]"],
92
+ ])
93
+
94
+ /** Redact values that look like credentials. Used on every text this plugin stores or logs. */
95
+ export function redactSecrets(value) {
96
+ let text = String(value ?? "")
97
+ for (const [pattern, replacement] of SECRET_PATTERNS) text = text.replace(pattern, replacement)
98
+ return text
99
+ }
100
+
101
+ /**
102
+ * One line describing the capture spool: pending depth, quarantined entries,
103
+ * claims in flight, and the age of the oldest pending entry.
104
+ *
105
+ * @param {{ pending?: number, quarantined?: number, inflight?: number, oldest?: string | null } | number} stats
106
+ */
107
+ export function describeSpool(stats) {
108
+ if (typeof stats === "number") return `${stats} pending`
109
+ const parts = [`${stats?.pending ?? 0} pending`, `${stats?.quarantined ?? 0} quarantined`]
110
+ if (stats?.inflight) parts.push(`${stats.inflight} in flight`)
111
+ if (stats?.pending && stats?.oldest) parts.push(`oldest ${stats.oldest}`)
112
+ return parts.join(", ")
113
+ }
114
+
115
+ /**
116
+ * One line describing the pinned bootstrap: how many sessions have a block,
117
+ * how many are served stale after a failed refresh, and the last miss. With a
118
+ * session, its own state comes first.
119
+ *
120
+ * @param {any} bootstrap
121
+ */
122
+ export function describeBootstrap(bootstrap) {
123
+ if (!bootstrap) return "unknown"
124
+ const parts = []
125
+ const session = bootstrap.session
126
+ if (session) {
127
+ if (session.block && session.stale) parts.push(`this session: stale (${oneLine(session.miss?.reason ?? "refresh failed", 120)})`)
128
+ else if (session.block) parts.push("this session: pinned")
129
+ else if (session.miss) parts.push(`this session: missing (${oneLine(session.miss.reason, 120)})`)
130
+ else parts.push("this session: empty")
131
+ }
132
+ parts.push(`${bootstrap.pinned ?? 0} pinned`, `${bootstrap.stale ?? 0} stale`, `${bootstrap.misses ?? 0} misses`)
133
+ if (bootstrap.lastMiss) parts.push(`last miss ${bootstrap.lastMiss.at}: ${oneLine(bootstrap.lastMiss.reason, 120)}`)
134
+ return parts.join(", ")
135
+ }
136
+
137
+ export function isPlainObject(value) {
138
+ return typeof value === "object" && value !== null && !Array.isArray(value)
139
+ }
140
+
141
+ export function toPositiveInt(value, fallback) {
142
+ const n = Number(value)
143
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback
144
+ }
145
+
146
+ export function slug(value) {
147
+ return String(value ?? "")
148
+ .toLowerCase()
149
+ .replace(/[^a-z0-9._-]+/g, "-")
150
+ .replace(/^-+|-+$/g, "")
151
+ .slice(0, 64) || "item"
152
+ }
153
+
154
+ export function sleep(ms) {
155
+ return new Promise((resolve) => setTimeout(resolve, ms))
156
+ }
157
+
158
+ export function errorMessage(error) {
159
+ if (error instanceof Error) return error.message
160
+ return String(error)
161
+ }
162
+
163
+ /**
164
+ * Compare a dotted version against a minimum. Only the newest OpenCode release
165
+ * is supported, so the plugin refuses to load on older hosts.
166
+ */
167
+ export function versionAtLeast(version, major, minor, patch = 0) {
168
+ const parts = String(version ?? "")
169
+ .split(".")
170
+ .map((part) => Number.parseInt(part, 10))
171
+ if (parts.length < 2 || parts.some((part) => !Number.isFinite(part))) return false
172
+ const [a = 0, b = 0, c = 0] = parts
173
+ if (a !== major) return a > major
174
+ if (b !== minor) return b > minor
175
+ return c >= patch
176
+ }