openhermes 1.13.1 → 2.5.0

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.
Files changed (78) hide show
  1. package/README.md +125 -206
  2. package/autorecall.mjs +79 -12
  3. package/bootstrap.mjs +122 -25
  4. package/curator.mjs +4 -40
  5. package/harness/commands/harness-audit.md +1 -1
  6. package/harness/commands/learn.md +2 -2
  7. package/harness/commands/memory-search.md +2 -2
  8. package/harness/constitution/soul.md +16 -4
  9. package/harness/instructions/RUNTIME.md +6 -3
  10. package/harness/prompts/architect.txt +14 -0
  11. package/harness/prompts/build-cpp.md +15 -1
  12. package/harness/prompts/build-error-resolver.md +15 -9
  13. package/harness/prompts/build-go.md +14 -0
  14. package/harness/prompts/build-java.md +15 -1
  15. package/harness/prompts/build-kotlin.md +15 -1
  16. package/harness/prompts/build-rust.md +14 -0
  17. package/harness/prompts/code-reviewer.md +15 -9
  18. package/harness/prompts/doc-updater.md +13 -0
  19. package/harness/prompts/docs-lookup.md +11 -0
  20. package/harness/prompts/e2e-runner.txt +12 -0
  21. package/harness/prompts/explore.md +16 -4
  22. package/harness/prompts/harness-optimizer.md +12 -0
  23. package/harness/prompts/loop-operator.md +11 -0
  24. package/harness/prompts/planner.md +15 -9
  25. package/harness/prompts/refactor-cleaner.md +14 -0
  26. package/harness/prompts/review-cpp.md +14 -1
  27. package/harness/prompts/review-database.md +13 -0
  28. package/harness/prompts/review-go.md +13 -0
  29. package/harness/prompts/review-java.md +14 -1
  30. package/harness/prompts/review-kotlin.md +13 -0
  31. package/harness/prompts/review-python.md +14 -1
  32. package/harness/prompts/review-rust.md +13 -0
  33. package/harness/prompts/security-reviewer.md +15 -9
  34. package/harness/prompts/tdd-guide.md +14 -0
  35. package/harness/rules/audit.md +2 -2
  36. package/harness/rules/delegation.md +0 -2
  37. package/harness/rules/handoff.md +267 -0
  38. package/harness/rules/memory-management.md +4 -4
  39. package/harness/rules/precedence.md +1 -1
  40. package/harness/rules/retrieval.md +5 -5
  41. package/harness/rules/runtime-guards.md +1 -1
  42. package/harness/rules/self-heal.md +1 -1
  43. package/harness/rules/session-start.md +5 -5
  44. package/harness/rules/skills-management.md +2 -2
  45. package/harness/rules/verification.md +4 -4
  46. package/index.mjs +6 -2
  47. package/lib/ambient-memory.mjs +167 -0
  48. package/lib/handoff.mjs +176 -0
  49. package/lib/hardening.mjs +13 -8
  50. package/lib/memory-tools-plugin.mjs +107 -54
  51. package/lib/ohc/block-sync.mjs +69 -0
  52. package/lib/ohc/compress/search.mjs +152 -0
  53. package/lib/ohc/compress/state.mjs +76 -0
  54. package/lib/ohc/config.mjs +172 -16
  55. package/lib/ohc/message-ids.mjs +168 -0
  56. package/lib/ohc/notify.mjs +150 -0
  57. package/lib/ohc/protected-patterns.mjs +54 -0
  58. package/lib/ohc/prune-apply.mjs +134 -0
  59. package/lib/ohc/pruner.mjs +406 -55
  60. package/lib/ohc/reaper.mjs +12 -3
  61. package/lib/ohc/state.mjs +246 -15
  62. package/lib/ohc/strategies/deduplication.mjs +72 -0
  63. package/lib/ohc/strategies/index.mjs +2 -0
  64. package/lib/ohc/strategies/purge-errors.mjs +43 -0
  65. package/lib/ohc/token-utils.mjs +26 -0
  66. package/lib/ohc/updater.mjs +36 -13
  67. package/lib/paths.mjs +0 -3
  68. package/lib/search.mjs +48 -0
  69. package/package.json +1 -1
  70. package/schemas/audit.schema.json +22 -1
  71. package/schemas/backlog.schema.json +23 -2
  72. package/schemas/checkpoint.schema.json +23 -2
  73. package/schemas/constraint.schema.json +23 -2
  74. package/schemas/decision.schema.json +23 -2
  75. package/schemas/instinct.schema.json +23 -2
  76. package/schemas/mistake.schema.json +23 -2
  77. package/schemas/verification_receipt.schema.json +23 -2
  78. package/skill-builder.mjs +12 -23
@@ -2,29 +2,185 @@ import fs from "node:fs"
2
2
  import path from "node:path"
3
3
  import os from "node:os"
4
4
 
5
- const CONFIG_PATH = path.join(os.homedir(), ".config", "opencode", "ohc.json")
5
+ const GLOBAL_DIR = path.join(os.homedir(), ".config", "opencode")
6
+ const GLOBAL_PATH = path.join(GLOBAL_DIR, "ohc.json")
7
+ const GLOBAL_PATH_JSONC = path.join(GLOBAL_DIR, "ohc.jsonc")
6
8
 
7
- const DEFAULTS = { enabled: true, max: 200000, min: 50000 }
9
+ const DEFAULTS = {
10
+ enabled: true,
11
+ notification: "chat",
12
+ notificationMode: "detailed",
13
+ max: 150000,
14
+ min: 50000,
15
+ manualMode: { enabled: false, automaticStrategies: true },
16
+ turnProtection: { enabled: false, turns: 4 },
17
+ protectedFilePatterns: [],
18
+ compress: {
19
+ maxContextLimit: 150000,
20
+ minContextLimit: 50000,
21
+ nudgeFrequency: 5,
22
+ iterationNudgeThreshold: 15,
23
+ nudgeForce: "soft",
24
+ protectedTools: ["task", "skill", "todowrite", "todoread"],
25
+ protectUserMessages: false,
26
+ summaryBuffer: true,
27
+ },
28
+ strategies: {
29
+ deduplication: { enabled: true, protectedTools: [] },
30
+ purgeErrors: { enabled: true, turns: 4, protectedTools: [] },
31
+ },
32
+ }
8
33
 
9
- function writeDefaults() {
10
- try {
11
- fs.mkdirSync(path.dirname(CONFIG_PATH), { recursive: true })
12
- fs.writeFileSync(CONFIG_PATH, JSON.stringify(DEFAULTS, null, 2) + "\n", "utf8")
13
- } catch {}
34
+ function findOpencodeDir(startDir) {
35
+ let current = startDir
36
+ while (current && current.length > 3) {
37
+ const candidate = path.join(current, ".opencode")
38
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
39
+ return candidate
40
+ }
41
+ const parent = path.dirname(current)
42
+ if (parent === current) break
43
+ current = parent
44
+ }
45
+ return null
14
46
  }
15
47
 
16
- export function loadConfig() {
17
- let raw = {}
48
+ function loadFile(filePath) {
18
49
  try {
19
- raw = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8"))
50
+ const content = fs.readFileSync(filePath, "utf8").trim()
51
+ if (!content) return null
52
+ if (filePath.endsWith(".jsonc")) {
53
+ const stripped = content
54
+ .replace(/"(?:[^"\\]|\\.)*"|\/\/.*/gm, m => m.startsWith('"') ? m : "")
55
+ .replace(/\/\*[\s\S]*?\*\//g, "")
56
+ return JSON.parse(stripped)
57
+ }
58
+ return JSON.parse(content)
20
59
  } catch {
21
- writeDefaults()
22
- return { ...DEFAULTS }
60
+ return null
61
+ }
62
+ }
63
+
64
+ function mergeDeep(base, override) {
65
+ if (!override || typeof override !== "object") return base
66
+ const result = { ...base }
67
+ for (const key of Object.keys(override)) {
68
+ if (override[key] === undefined) continue
69
+ if (typeof override[key] === "object" && !Array.isArray(override[key]) && override[key] !== null) {
70
+ result[key] = mergeDeep(base[key] || {}, override[key])
71
+ } else {
72
+ result[key] = override[key]
73
+ }
74
+ }
75
+ return result
76
+ }
77
+
78
+ function mergeArrays(base, override) {
79
+ if (!override || !Array.isArray(override)) return base
80
+ return [...new Set([...base, ...override])]
81
+ }
82
+
83
+ function mergeManualMode(base, override) {
84
+ if (!override || typeof override !== "object") return base
85
+ return {
86
+ enabled: override.enabled ?? base.enabled,
87
+ automaticStrategies: override.automaticStrategies ?? base.automaticStrategies,
88
+ }
89
+ }
90
+
91
+ function mergeTurnProtection(base, override) {
92
+ if (!override || typeof override !== "object") return base
93
+ return {
94
+ enabled: override.enabled ?? base.enabled,
95
+ turns: override.turns ?? base.turns,
96
+ }
97
+ }
98
+
99
+ function mergeCompress(base, override) {
100
+ if (!override || typeof override !== "object") return base
101
+ return {
102
+ maxContextLimit: override.maxContextLimit ?? base.maxContextLimit,
103
+ minContextLimit: override.minContextLimit ?? base.minContextLimit,
104
+ nudgeFrequency: override.nudgeFrequency ?? base.nudgeFrequency,
105
+ iterationNudgeThreshold: override.iterationNudgeThreshold ?? base.iterationNudgeThreshold,
106
+ nudgeForce: override.nudgeForce ?? base.nudgeForce,
107
+ protectedTools: mergeArrays(base.protectedTools, override.protectedTools),
108
+ protectUserMessages: override.protectUserMessages ?? base.protectUserMessages,
109
+ summaryBuffer: override.summaryBuffer ?? base.summaryBuffer,
23
110
  }
111
+ }
112
+
113
+ function mergeStrategies(base, override) {
114
+ if (!override || typeof override !== "object") return base
115
+ return {
116
+ deduplication: {
117
+ enabled: override.deduplication?.enabled ?? base.deduplication.enabled,
118
+ protectedTools: mergeArrays(base.deduplication.protectedTools, override.deduplication?.protectedTools),
119
+ },
120
+ purgeErrors: {
121
+ enabled: override.purgeErrors?.enabled ?? base.purgeErrors.enabled,
122
+ turns: override.purgeErrors?.turns ?? base.purgeErrors.turns,
123
+ protectedTools: mergeArrays(base.purgeErrors.protectedTools, override.purgeErrors?.protectedTools),
124
+ },
125
+ }
126
+ }
24
127
 
128
+ function mergeLayer(base, data) {
129
+ if (!data) return base
25
130
  return {
26
- enabled: raw.enabled !== false,
27
- max: typeof raw.max === "number" && raw.max > 0 ? raw.max : DEFAULTS.max,
28
- min: typeof raw.min === "number" ? Math.max(10000, raw.min) : DEFAULTS.min,
131
+ enabled: data.enabled ?? base.enabled,
132
+ notification: data.notification ?? base.notification,
133
+ notificationMode: data.notificationMode ?? base.notificationMode,
134
+ max: data.max ?? base.max,
135
+ min: data.min ?? base.min,
136
+ manualMode: mergeManualMode(base.manualMode, data.manualMode),
137
+ turnProtection: mergeTurnProtection(base.turnProtection, data.turnProtection),
138
+ protectedFilePatterns: mergeArrays(base.protectedFilePatterns, data.protectedFilePatterns),
139
+ compress: mergeCompress(base.compress, data.compress),
140
+ strategies: mergeStrategies(base.strategies, data.strategies),
29
141
  }
30
- }
142
+ }
143
+
144
+ export function loadConfig(ctx) {
145
+ let config = { ...DEFAULTS }
146
+
147
+ const layers = [
148
+ { path: fs.existsSync(GLOBAL_PATH_JSONC) ? GLOBAL_PATH_JSONC : (fs.existsSync(GLOBAL_PATH) ? GLOBAL_PATH : null), name: "global" },
149
+ ]
150
+
151
+ const opencodeConfigDir = process.env.OPENCODE_CONFIG_DIR
152
+ if (opencodeConfigDir) {
153
+ const cdJsonc = path.join(opencodeConfigDir, "ohc.jsonc")
154
+ const cdJson = path.join(opencodeConfigDir, "ohc.json")
155
+ const cdPath = fs.existsSync(cdJsonc) ? cdJsonc : (fs.existsSync(cdJson) ? cdJson : null)
156
+ if (cdPath) layers.push({ path: cdPath, name: "configDir" })
157
+ }
158
+
159
+ if (ctx?.directory) {
160
+ const opencodeDir = findOpencodeDir(ctx.directory)
161
+ if (opencodeDir) {
162
+ const pjJsonc = path.join(opencodeDir, "ohc.jsonc")
163
+ const pjJson = path.join(opencodeDir, "ohc.json")
164
+ const pjPath = fs.existsSync(pjJsonc) ? pjJsonc : (fs.existsSync(pjJson) ? pjJson : null)
165
+ if (pjPath) layers.push({ path: pjPath, name: "project" })
166
+ }
167
+ }
168
+
169
+ for (const layer of layers) {
170
+ if (!layer.path) continue
171
+ const data = loadFile(layer.path)
172
+ if (data) config = mergeLayer(config, data)
173
+ }
174
+
175
+ config.max = typeof config.max === "number" && config.max > 0 ? config.max : DEFAULTS.max
176
+ config.min = typeof config.min === "number" ? Math.max(10000, Math.min(config.min, config.max - 10000)) : DEFAULTS.min
177
+
178
+ return config
179
+ }
180
+
181
+ function writeDefaults() {
182
+ fs.mkdirSync(GLOBAL_DIR, { recursive: true })
183
+ if (!fs.existsSync(GLOBAL_PATH) && !fs.existsSync(GLOBAL_PATH_JSONC)) {
184
+ fs.writeFileSync(GLOBAL_PATH, JSON.stringify(DEFAULTS, null, 2) + "\n", "utf8")
185
+ }
186
+ }
@@ -0,0 +1,168 @@
1
+ const MESSAGE_REF_REGEX = /^ohc(\d{4})$/
2
+ const BLOCK_REF_REGEX = /^bk([1-9]\d*)$/
3
+ const OHCTAG = "ohc-ref"
4
+
5
+ export function formatMessageRef(index) {
6
+ if (!Number.isInteger(index) || index < 1 || index > 9999) {
7
+ throw new Error(`OHC ref index out of bounds: ${index}`)
8
+ }
9
+ return `ohc${index.toString().padStart(4, "0")}`
10
+ }
11
+
12
+ export function formatBlockRef(blockId) {
13
+ if (!Number.isInteger(blockId) || blockId < 1) {
14
+ throw new Error(`Invalid block ID: ${blockId}`)
15
+ }
16
+ return `bk${blockId}`
17
+ }
18
+
19
+ export function parseMessageRef(ref) {
20
+ const m = (ref || "").trim().toLowerCase().match(MESSAGE_REF_REGEX)
21
+ if (!m) return null
22
+ const idx = parseInt(m[1], 10)
23
+ return Number.isInteger(idx) && idx >= 1 && idx <= 9999 ? idx : null
24
+ }
25
+
26
+ export function parseBlockRef(ref) {
27
+ const m = (ref || "").trim().toLowerCase().match(BLOCK_REF_REGEX)
28
+ if (!m) return null
29
+ const id = parseInt(m[1], 10)
30
+ return Number.isInteger(id) ? id : null
31
+ }
32
+
33
+ export function parseBoundaryId(id) {
34
+ const norm = (id || "").trim().toLowerCase()
35
+ const msgIdx = parseMessageRef(norm)
36
+ if (msgIdx !== null) {
37
+ return { kind: "message", ref: formatMessageRef(msgIdx), index: msgIdx }
38
+ }
39
+ const bkId = parseBlockRef(norm)
40
+ if (bkId !== null) {
41
+ return { kind: "compressed-block", ref: formatBlockRef(bkId), blockId: bkId }
42
+ }
43
+ return null
44
+ }
45
+
46
+ function escapeXml(s) {
47
+ return String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
48
+ }
49
+
50
+ export function formatOhcTag(ref, attrs) {
51
+ const serialized = Object.entries(attrs || {})
52
+ .filter(([, v]) => typeof v === "string" && v.length > 0)
53
+ .sort(([a], [b]) => a.localeCompare(b))
54
+ .map(([k, v]) => ` ${k}="${escapeXml(v)}"`)
55
+ .join("")
56
+ return `\n<${OHCTAG}${serialized}>${ref}</${OHCTAG}>`
57
+ }
58
+
59
+ export function isIgnoredUserMessage(message) {
60
+ if (!message?.info || message.info.role !== "user") return false
61
+ const parts = Array.isArray(message.parts) ? message.parts : []
62
+ if (parts.length === 0) return true
63
+ return parts.every(p => p.ignored)
64
+ }
65
+
66
+ export function assignMessageRefs(state, messages) {
67
+ let assigned = 0
68
+ let skippedFirstUser = false
69
+
70
+ for (const msg of messages) {
71
+ if (isIgnoredUserMessage(msg)) continue
72
+
73
+ if (state.isSubAgent && !skippedFirstUser && msg.info.role === "user") {
74
+ skippedFirstUser = true
75
+ continue
76
+ }
77
+
78
+ const rawId = msg.info?.id
79
+ if (typeof rawId !== "string" || !rawId) continue
80
+
81
+ const existing = state.messageIds.byRawId.get(rawId)
82
+ if (existing) {
83
+ if (state.messageIds.byRef.get(existing) !== rawId) {
84
+ state.messageIds.byRef.set(existing, rawId)
85
+ }
86
+ continue
87
+ }
88
+
89
+ const ref = allocateNextRef(state)
90
+ state.messageIds.byRawId.set(rawId, ref)
91
+ state.messageIds.byRef.set(ref, rawId)
92
+ assigned++
93
+ }
94
+
95
+ return assigned
96
+ }
97
+
98
+ function allocateNextRef(state) {
99
+ let candidate = Number.isInteger(state.messageIds.nextRef)
100
+ ? Math.max(1, state.messageIds.nextRef)
101
+ : 1
102
+
103
+ for (let attempt = 0; attempt < 9999; attempt++) {
104
+ if (candidate > 9999) candidate = 1
105
+ const ref = formatMessageRef(candidate)
106
+ if (!state.messageIds.byRef.has(ref)) {
107
+ state.messageIds.nextRef = candidate + 1
108
+ return ref
109
+ }
110
+ candidate++
111
+ }
112
+
113
+ state.messageIds.nextRef = 1
114
+ return formatMessageRef(1)
115
+ }
116
+
117
+ export function injectMessageIds(state, messages) {
118
+ for (const msg of messages) {
119
+ if (isIgnoredUserMessage(msg)) continue
120
+ const msgRef = state.messageIds.byRawId.get(msg.info?.id)
121
+ if (!msgRef) continue
122
+ const tag = formatOhcTag(msgRef)
123
+
124
+ if (msg.info.role === "user") {
125
+ let injected = false
126
+ for (const part of msg.parts) {
127
+ if (part.type === "text") {
128
+ part.text += tag
129
+ injected = true
130
+ break
131
+ }
132
+ }
133
+ if (!injected) {
134
+ msg.parts.push({ type: "text", text: tag })
135
+ }
136
+ continue
137
+ }
138
+
139
+ if (msg.info.role !== "assistant") continue
140
+
141
+ let hasContent = Array.isArray(msg.parts) && msg.parts.some(p => p.type === "text" || p.type === "tool")
142
+ if (!hasContent) continue
143
+
144
+ let injected = false
145
+ for (const part of msg.parts) {
146
+ if (part.type !== "tool" || typeof part.state?.output !== "string") continue
147
+ part.state.output = (part.state.output || "") + tag
148
+ injected = true
149
+ break
150
+ }
151
+
152
+ if (injected) continue
153
+
154
+ const lastText = [...msg.parts].reverse().find(p => p.type === "text")
155
+ if (lastText) {
156
+ lastText.text += tag
157
+ continue
158
+ }
159
+
160
+ const firstToolIdx = msg.parts.findIndex(p => p.type === "tool")
161
+ const synth = { type: "text", text: tag }
162
+ if (firstToolIdx === -1) {
163
+ msg.parts.push(synth)
164
+ } else {
165
+ msg.parts.splice(firstToolIdx, 0, synth)
166
+ }
167
+ }
168
+ }
@@ -0,0 +1,150 @@
1
+ function formatTokenCount(tokens) {
2
+ if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}K`.replace(".0K", "K")
3
+ return String(tokens)
4
+ }
5
+
6
+ function buildProgressBar(prunedCount, visibleCount, width) {
7
+ width = width || 30
8
+ const total = prunedCount + visibleCount
9
+ if (total === 0) return `\u2502${"\u2591".repeat(width)}\u2502 0% active`
10
+ const activeRatio = visibleCount / total
11
+ const activeW = Math.round(activeRatio * width)
12
+ const prunedW = width - activeW
13
+ const bar = "\u2588".repeat(Math.min(activeW, width)) + "\u2591".repeat(Math.min(prunedW, width))
14
+ return `\u2502${bar.slice(0, width)}\u2502 ${Math.round(activeRatio * 100)}% active`
15
+ }
16
+
17
+ function buildMinimal(count, tokensRemoved, savedTotal, blockCount) {
18
+ const label = "Compression"
19
+ return `\u25A3 OHC | ~${formatTokenCount(savedTotal)} saved total \u2014 ${label}`
20
+ }
21
+
22
+ function buildDetailed(count, tokensRemoved, savedTotal, blockCount, prunedCount, visibleCount, summary) {
23
+ const label = "Compression"
24
+ let msg = `\u25A3 OHC | ~${formatTokenCount(savedTotal)} saved total`
25
+ if (prunedCount + visibleCount > 0) {
26
+ msg += `\n\n${buildProgressBar(prunedCount, visibleCount)}`
27
+ }
28
+ msg += `\n\n\u25A3 ${label} #${blockCount}`
29
+ msg += `\n\u2192 ${count} message${count === 1 ? "" : "s"} removed`
30
+ if (summary) msg += `\n\u2192 Summary: ${summary}`
31
+ return msg
32
+ }
33
+
34
+ function buildStrategyNotification(strategy, count, detail) {
35
+ return `\u25A3 OHC | ${strategy}: ${count} pruned${detail ? ` (${detail})` : ""}`
36
+ }
37
+
38
+ export async function sendCompressNotification(client, sessionId, config, count, summary, tokensRemoved, savedTotal, blockCount, prunedCount, visibleCount) {
39
+ if (count === 0) return false
40
+
41
+ const notifType = config.notification ?? "toast"
42
+ const notifMode = config.notificationMode ?? "minimal"
43
+
44
+ if (notifType === "off") return false
45
+
46
+ if (notifType === "toast") {
47
+ const message = notifMode === "minimal"
48
+ ? buildMinimal(count, tokensRemoved, savedTotal, blockCount)
49
+ : buildDetailed(count, tokensRemoved, savedTotal, blockCount, prunedCount, visibleCount, summary)
50
+ try {
51
+ await client.tui.showToast({
52
+ body: {
53
+ title: "OHC: Compression",
54
+ message,
55
+ variant: "info",
56
+ duration: 5000,
57
+ },
58
+ })
59
+ } catch {}
60
+ return true
61
+ }
62
+
63
+ try {
64
+ await client.session.prompt({
65
+ path: { id: sessionId },
66
+ body: {
67
+ noReply: true,
68
+ parts: [{ type: "text", text: buildDetailed(count, tokensRemoved, savedTotal, blockCount, prunedCount, visibleCount, summary), ignored: true }],
69
+ },
70
+ })
71
+ } catch {}
72
+ return true
73
+ }
74
+
75
+ export async function sendStrategyNotification(client, sessionId, config, strategy, count, detail) {
76
+ if (count === 0) return false
77
+ const notifType = config.notification ?? "toast"
78
+ if (notifType === "off") return false
79
+
80
+ const message = buildStrategyNotification(strategy, count, detail)
81
+
82
+ if (notifType === "toast") {
83
+ try {
84
+ await client.tui.showToast({
85
+ body: {
86
+ title: `OHC: ${strategy}`,
87
+ message,
88
+ variant: "info",
89
+ duration: 3000,
90
+ },
91
+ })
92
+ } catch {}
93
+ return true
94
+ }
95
+
96
+ try {
97
+ await client.session.prompt({
98
+ path: { id: sessionId },
99
+ body: {
100
+ noReply: true,
101
+ parts: [{ type: "text", text: message, ignored: true }],
102
+ },
103
+ })
104
+ } catch {}
105
+ return true
106
+ }
107
+
108
+ export async function sendMemoryNotification(client, sessionId, config, action, cls, id, summary) {
109
+ const notifType = config.notification ?? "toast"
110
+ const notifMode = config.notificationMode ?? "minimal"
111
+
112
+ if (notifType === "off") return false
113
+
114
+ const buildHeader = (action, summary) => `[Memory] ${summary}`
115
+ const buildDetailed = (action, cls, id, summary) => {
116
+ let msg = `\u25A3 Memory ${action}`
117
+ if (cls) msg += `\n\u2192 Class: ${cls}`
118
+ if (id) msg += `\n\u2192 ID: ${id}`
119
+ if (summary) msg += `\n\u2192 ${summary}`
120
+ return msg
121
+ }
122
+
123
+ if (notifType === "toast") {
124
+ const message = notifMode === "minimal"
125
+ ? buildHeader(action, summary)
126
+ : buildDetailed(action, cls, id, summary)
127
+ try {
128
+ await client.tui.showToast({
129
+ body: {
130
+ title: "Memory",
131
+ message,
132
+ variant: "info",
133
+ duration: 4000,
134
+ },
135
+ })
136
+ } catch {}
137
+ return true
138
+ }
139
+
140
+ try {
141
+ await client.session.prompt({
142
+ path: { id: sessionId },
143
+ body: {
144
+ noReply: true,
145
+ parts: [{ type: "text", text: buildDetailed(action, cls, id, summary), ignored: true }],
146
+ },
147
+ })
148
+ } catch {}
149
+ return true
150
+ }
@@ -0,0 +1,54 @@
1
+ const DEFAULT_PROTECTED_TOOLS = new Set([
2
+ "task", "skill", "todowrite", "todoread",
3
+ "compress", "batch", "plan_enter", "plan_exit",
4
+ "write", "edit",
5
+ ])
6
+
7
+ export function isToolNameProtected(toolName, extraProtected = []) {
8
+ if (DEFAULT_PROTECTED_TOOLS.has(toolName)) return true
9
+ return extraProtected.includes(toolName)
10
+ }
11
+
12
+ export function getFilePathsFromParameters(tool, params) {
13
+ if (!params || typeof params !== "object") return []
14
+ if (params.filePath) return [params.filePath]
15
+ if (params.file_path) return [params.file_path]
16
+ if (params.path) return [params.path]
17
+ if (params.target) return [params.target]
18
+ if (params.directory) return [params.directory]
19
+ if (tool === "glob" && params.pattern) return [params.pattern]
20
+ return []
21
+ }
22
+
23
+ export function isFilePathProtected(filePaths, protectedPatterns = []) {
24
+ if (!protectedPatterns?.length) return false
25
+ if (!filePaths?.length) return false
26
+ for (const fp of filePaths) {
27
+ for (const pattern of protectedPatterns) {
28
+ if (globMatch(fp, pattern)) return true
29
+ }
30
+ }
31
+ return false
32
+ }
33
+
34
+ function globMatch(filePath, pattern) {
35
+ const regexStr = pattern
36
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
37
+ .replace(/\*/g, ".*")
38
+ .replace(/\?/g, ".")
39
+ try {
40
+ return new RegExp(`^${regexStr}$`, "i").test(filePath)
41
+ } catch {
42
+ return filePath.toLowerCase() === pattern.toLowerCase()
43
+ }
44
+ }
45
+
46
+ export function getTurnProtectionTags(state) {
47
+ const config = state.protectedTurns || {}
48
+ if (!config.enabled || !config.turns) return []
49
+ const threshold = state.currentTurn - config.turns
50
+ return [...state.toolIdList].filter(id => {
51
+ const entry = state.toolParameters.get(id)
52
+ return entry && entry.turn > threshold
53
+ })
54
+ }