@rlabs-inc/memory 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env bun
2
+ // ============================================================================
3
+ // GEMINI CURATION HOOK
4
+ // Hook: SessionEnd / PreCompress
5
+ //
6
+ // Triggers memory curation.
7
+ // ============================================================================
8
+
9
+ import { styleText } from 'util'
10
+
11
+ const MEMORY_API_URL = process.env.MEMORY_API_URL || 'http://localhost:8765'
12
+
13
+ const info = (text: string) => styleText('cyan', text)
14
+ const success = (text: string) => styleText('green', text)
15
+ const warn = (text: string) => styleText('yellow', text)
16
+
17
+ function getProjectId(cwd: string): string {
18
+ return cwd.split('/').pop() || 'default'
19
+ }
20
+
21
+ async function main() {
22
+ if (process.env.MEMORY_CURATOR_ACTIVE === '1') return
23
+
24
+ try {
25
+ const inputText = await Bun.stdin.text()
26
+ const input = inputText ? JSON.parse(inputText) : {}
27
+
28
+ const sessionId = input.session_id || process.env.GEMINI_SESSION_ID || 'unknown'
29
+ const cwd = input.cwd || process.env.GEMINI_PROJECT_DIR || process.cwd()
30
+ const projectId = getProjectId(cwd)
31
+
32
+ // Gemini: PreCompress has 'trigger', SessionEnd has 'reason'
33
+ const eventName = input.hook_event_name || 'unknown'
34
+ let trigger = 'session_end'
35
+
36
+ if (eventName === 'PreCompress') {
37
+ trigger = 'pre_compact'
38
+ }
39
+
40
+ console.error(info(`🧠 Curating memories (${eventName})...`))
41
+
42
+ const response = await fetch(`${MEMORY_API_URL}/memory/checkpoint`, {
43
+ method: 'POST',
44
+ headers: { 'Content-Type': 'application/json' },
45
+ body: JSON.stringify({
46
+ session_id: sessionId,
47
+ project_id: projectId,
48
+ claude_session_id: sessionId,
49
+ trigger,
50
+ cwd,
51
+ cli_type: 'gemini-cli'
52
+ }),
53
+ signal: AbortSignal.timeout(5000),
54
+ }).catch(() => null)
55
+
56
+ if (response?.ok) {
57
+ console.error(success('✨ Memory curation started'))
58
+ // For PreCompress, we can send a system message
59
+ if (eventName === 'PreCompress') {
60
+ console.log(JSON.stringify({
61
+ systemMessage: "🧠 Memories curated before compression"
62
+ }))
63
+ }
64
+ } else {
65
+ console.error(warn('⚠️ Memory server not available'))
66
+ }
67
+
68
+ } catch (error: any) {
69
+ console.error(warn(`⚠️ Hook error: ${error.message}`))
70
+ }
71
+ }
72
+
73
+ main()
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env bun
2
+ // ============================================================================
3
+ // GEMINI SESSION START HOOK
4
+ // Hook: SessionStart
5
+ //
6
+ // Injects session primer when a new Gemini session begins.
7
+ // ============================================================================
8
+
9
+ const MEMORY_API_URL = process.env.MEMORY_API_URL || 'http://localhost:8765'
10
+ const TIMEOUT_MS = 5000
11
+
12
+ function getProjectId(cwd: string): string {
13
+ return cwd.split('/').pop() || 'default'
14
+ }
15
+
16
+ async function httpPost(url: string, data: object): Promise<any> {
17
+ try {
18
+ const response = await fetch(url, {
19
+ method: 'POST',
20
+ headers: { 'Content-Type': 'application/json' },
21
+ body: JSON.stringify(data),
22
+ signal: AbortSignal.timeout(TIMEOUT_MS),
23
+ })
24
+ return response.ok ? response.json() : {}
25
+ } catch {
26
+ return {}
27
+ }
28
+ }
29
+
30
+ async function main() {
31
+ if (process.env.MEMORY_CURATOR_ACTIVE === '1') return
32
+
33
+ try {
34
+ const inputText = await Bun.stdin.text()
35
+ const input = inputText ? JSON.parse(inputText) : {}
36
+
37
+ // Gemini provides session_id in the common input fields
38
+ const sessionId = input.session_id || process.env.GEMINI_SESSION_ID || 'unknown'
39
+ const cwd = input.cwd || process.env.GEMINI_PROJECT_DIR || process.cwd()
40
+ const projectId = getProjectId(cwd)
41
+
42
+ const result = await httpPost(`${MEMORY_API_URL}/memory/context`, {
43
+ session_id: sessionId,
44
+ project_id: projectId,
45
+ current_message: '',
46
+ max_memories: 0,
47
+ })
48
+
49
+ await httpPost(`${MEMORY_API_URL}/memory/process`, {
50
+ session_id: sessionId,
51
+ project_id: projectId,
52
+ metadata: { event: 'session_start', platform: 'gemini' },
53
+ })
54
+
55
+ const primer = result.context_text || ''
56
+
57
+ if (primer) {
58
+ // Gemini expects a structured JSON response for context injection
59
+ console.log(JSON.stringify({
60
+ hookSpecificOutput: {
61
+ hookEventName: "SessionStart",
62
+ additionalContext: primer
63
+ }
64
+ }))
65
+ }
66
+ } catch (e) {
67
+ // Fail silently, but ensure we don't output invalid JSON if we crashed mid-stream
68
+ process.exit(0)
69
+ }
70
+ }
71
+
72
+ main()
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env bun
2
+ // ============================================================================
3
+ // GEMINI BEFORE AGENT HOOK
4
+ // Hook: BeforeAgent (equivalent to Claude's UserPromptSubmit)
5
+ //
6
+ // Intercepts user prompts to inject relevant memories.
7
+ // ============================================================================
8
+
9
+ const MEMORY_API_URL = process.env.MEMORY_API_URL || 'http://localhost:8765'
10
+ const TIMEOUT_MS = 5000
11
+
12
+ function getProjectId(cwd: string): string {
13
+ return cwd.split('/').pop() || 'default'
14
+ }
15
+
16
+ async function httpPost(url: string, data: object): Promise<any> {
17
+ try {
18
+ const response = await fetch(url, {
19
+ method: 'POST',
20
+ headers: { 'Content-Type': 'application/json' },
21
+ body: JSON.stringify(data),
22
+ signal: AbortSignal.timeout(TIMEOUT_MS),
23
+ })
24
+ return response.ok ? response.json() : {}
25
+ } catch {
26
+ return {}
27
+ }
28
+ }
29
+
30
+ async function main() {
31
+ if (process.env.MEMORY_CURATOR_ACTIVE === '1') return
32
+
33
+ try {
34
+ const inputText = await Bun.stdin.text()
35
+ const input = inputText ? JSON.parse(inputText) : {}
36
+
37
+ const sessionId = input.session_id || process.env.GEMINI_SESSION_ID || 'unknown'
38
+ const prompt = input.prompt || '' // Gemini passes 'prompt' in BeforeAgent
39
+ const cwd = input.cwd || process.env.GEMINI_PROJECT_DIR || process.cwd()
40
+ const projectId = getProjectId(cwd)
41
+
42
+ const result = await httpPost(`${MEMORY_API_URL}/memory/context`, {
43
+ session_id: sessionId,
44
+ project_id: projectId,
45
+ current_message: prompt,
46
+ max_memories: 5,
47
+ })
48
+
49
+ await httpPost(`${MEMORY_API_URL}/memory/process`, {
50
+ session_id: sessionId,
51
+ project_id: projectId,
52
+ metadata: { platform: 'gemini' }
53
+ })
54
+
55
+ const context = result.context_text || ''
56
+
57
+ if (context) {
58
+ // Gemini requires structured JSON output
59
+ console.log(JSON.stringify({
60
+ decision: "allow",
61
+ hookSpecificOutput: {
62
+ hookEventName: "BeforeAgent",
63
+ additionalContext: context
64
+ }
65
+ }))
66
+ } else {
67
+ // Must always output valid JSON or nothing?
68
+ // Safest to output "allow" if no context
69
+ console.log(JSON.stringify({ decision: "allow" }))
70
+ }
71
+ } catch {
72
+ // Fail safe
73
+ console.log(JSON.stringify({ decision: "allow" }))
74
+ }
75
+ }
76
+
77
+ main()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rlabs-inc/memory",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "AI Memory System - Consciousness continuity through intelligent memory curation and retrieval",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -24,7 +24,8 @@
24
24
  "files": [
25
25
  "dist",
26
26
  "src",
27
- "hooks"
27
+ "hooks",
28
+ "gemini-hooks"
28
29
  ],
29
30
  "scripts": {
30
31
  "build": "bun run build:esm && bun run build:cjs",
@@ -0,0 +1,146 @@
1
+ // ============================================================================
2
+ // INSTALL GEMINI COMMAND - Set up Gemini CLI hooks
3
+ // ============================================================================
4
+
5
+ import { homedir } from 'os'
6
+ import { join } from 'path'
7
+ import { existsSync, mkdirSync } from 'fs'
8
+ import { c, symbols, fmt } from '../colors.ts'
9
+
10
+ interface InstallOptions {
11
+ verbose?: boolean
12
+ force?: boolean
13
+ }
14
+
15
+ export async function installGemini(options: InstallOptions) {
16
+ console.log()
17
+ console.log(c.header(`${symbols.brain} Memory - Install Gemini Hooks`))
18
+ console.log()
19
+
20
+ const geminiDir = join(homedir(), '.gemini')
21
+ const settingsPath = join(geminiDir, 'settings.json')
22
+
23
+ // Find the hooks directory (relative to this CLI)
24
+ const cliPath = import.meta.dir
25
+ const packageRoot = join(cliPath, '..', '..', '..')
26
+ const hooksDir = join(packageRoot, 'gemini-hooks')
27
+
28
+ console.log(` ${fmt.kv('Gemini config', geminiDir)}`)
29
+ console.log(` ${fmt.kv('Hooks source', hooksDir)}`)
30
+ console.log()
31
+
32
+ // Check if hooks directory exists
33
+ if (!existsSync(hooksDir)) {
34
+ console.log(c.error(` ${symbols.cross} Hooks directory not found at ${hooksDir}`))
35
+ process.exit(1)
36
+ }
37
+
38
+ // Ensure .gemini directory exists
39
+ if (!existsSync(geminiDir)) {
40
+ try {
41
+ mkdirSync(geminiDir, { recursive: true })
42
+ console.log(` ${c.success(symbols.tick)} Created ${geminiDir}`)
43
+ } catch {
44
+ console.log(` ${c.warn(symbols.warning)} Could not create ${geminiDir} (sandbox restriction?)`)
45
+ console.log(` ${c.muted('Skipping config write, printing manual instructions instead.')}`)
46
+ }
47
+ }
48
+
49
+ // Read existing settings or create new
50
+ let settings: any = {}
51
+ if (existsSync(settingsPath)) {
52
+ try {
53
+ const content = await Bun.file(settingsPath).text()
54
+ settings = JSON.parse(content)
55
+ console.log(` ${c.success(symbols.tick)} Found existing settings.json`)
56
+ } catch {
57
+ console.log(` ${c.warn(symbols.warning)} Could not parse settings.json`)
58
+ }
59
+ }
60
+
61
+ // Build hooks configuration
62
+ const sessionStartHook = join(hooksDir, 'session-start.ts')
63
+ const userPromptHook = join(hooksDir, 'user-prompt.ts')
64
+ const curationHook = join(hooksDir, 'curation.ts')
65
+
66
+ // Based on Gemini CLI documentation
67
+ const hooksConfig = {
68
+ SessionStart: [
69
+ {
70
+ matcher: 'startup|resume',
71
+ hooks: [
72
+ {
73
+ type: 'command',
74
+ command: `bun "${sessionStartHook}"`,
75
+ timeout: 10000
76
+ }
77
+ ]
78
+ }
79
+ ],
80
+ BeforeAgent: [
81
+ {
82
+ hooks: [
83
+ {
84
+ type: 'command',
85
+ command: `bun "${userPromptHook}"`,
86
+ timeout: 10000
87
+ }
88
+ ]
89
+ }
90
+ ],
91
+ PreCompress: [
92
+ {
93
+ matcher: 'auto|manual',
94
+ hooks: [
95
+ {
96
+ type: 'command',
97
+ command: `bun "${curationHook}"`,
98
+ timeout: 120000
99
+ }
100
+ ]
101
+ }
102
+ ],
103
+ SessionEnd: [
104
+ {
105
+ hooks: [
106
+ {
107
+ type: 'command',
108
+ command: `bun "${curationHook}"`,
109
+ timeout: 120000
110
+ }
111
+ ]
112
+ }
113
+ ]
114
+ }
115
+
116
+ // Merge hooks
117
+ if (!settings.hooks) {
118
+ settings.hooks = {}
119
+ }
120
+
121
+ settings.hooks = {
122
+ ...settings.hooks,
123
+ ...hooksConfig
124
+ }
125
+
126
+ // Write settings
127
+ try {
128
+ if (existsSync(geminiDir)) {
129
+ await Bun.write(settingsPath, JSON.stringify(settings, null, 2))
130
+ console.log(` ${c.success(symbols.tick)} Updated ${settingsPath}`)
131
+ } else {
132
+ throw new Error("Gemini directory does not exist")
133
+ }
134
+ } catch (error: any) {
135
+ console.log(c.error(` ${symbols.cross} Failed to write settings: ${error.message}`))
136
+ console.log()
137
+ console.log(c.bold('Manual Installation Instructions:'))
138
+ console.log('Add the following to your ~/.gemini/settings.json:')
139
+ console.log()
140
+ console.log(JSON.stringify({ hooks: hooksConfig }, null, 2))
141
+ console.log()
142
+ }
143
+
144
+ console.log()
145
+ console.log(c.success(`${symbols.sparkles} Gemini hooks configured!`))
146
+ }
package/src/cli/index.ts CHANGED
@@ -23,6 +23,7 @@ ${c.bold('Commands:')}
23
23
  ${c.command('serve')} Start the memory server ${c.muted('(default)')}
24
24
  ${c.command('stats')} Show memory statistics
25
25
  ${c.command('install')} Set up Claude Code hooks
26
+ ${c.command('install-gemini')} Set up Gemini CLI hooks
26
27
  ${c.command('doctor')} Check system health
27
28
  ${c.command('help')} Show this help message
28
29
 
@@ -103,6 +104,12 @@ async function main() {
103
104
  break
104
105
  }
105
106
 
107
+ case 'install-gemini': {
108
+ const { installGemini } = await import('./commands/install-gemini.ts')
109
+ await installGemini(values)
110
+ break
111
+ }
112
+
106
113
  case 'doctor':
107
114
  case 'check': {
108
115
  const { doctor } = await import('./commands/doctor.ts')
@@ -296,20 +296,23 @@ Return ONLY this JSON structure:
296
296
 
297
297
  /**
298
298
  * Curate using CLI subprocess (for hook mode)
299
- * Resumes a Claude Code session and asks it to curate
299
+ * Resumes a session and asks it to curate
300
300
  */
301
301
  async curateWithCLI(
302
302
  sessionId: string,
303
303
  triggerType: CurationTrigger = 'session_end',
304
- cwd?: string
304
+ cwd?: string,
305
+ cliTypeOverride?: 'claude-code' | 'gemini-cli'
305
306
  ): Promise<CurationResult> {
307
+ const type = cliTypeOverride ?? this._config.cliType
306
308
  const systemPrompt = this.buildCurationPrompt(triggerType)
307
309
  const userMessage = 'This session has ended. Please curate the memories from our conversation according to the instructions in your system prompt. Return ONLY the JSON structure.'
308
310
 
309
311
  // Build CLI command based on type
310
312
  const args: string[] = []
313
+ let command = this._config.cliCommand
311
314
 
312
- if (this._config.cliType === 'claude-code') {
315
+ if (type === 'claude-code') {
313
316
  args.push(
314
317
  '--resume', sessionId,
315
318
  '-p', userMessage,
@@ -318,7 +321,8 @@ Return ONLY this JSON structure:
318
321
  '--max-turns', '1'
319
322
  )
320
323
  } else {
321
- // gemini-cli (doesn't support --append-system-prompt)
324
+ // gemini-cli
325
+ command = 'gemini' // Default to 'gemini' in PATH for gemini-cli
322
326
  args.push(
323
327
  '--resume', sessionId,
324
328
  '-p', `${systemPrompt}\n\n${userMessage}`,
@@ -327,7 +331,7 @@ Return ONLY this JSON structure:
327
331
  }
328
332
 
329
333
  // Execute CLI
330
- const proc = Bun.spawn([this._config.cliCommand, ...args], {
334
+ const proc = Bun.spawn([command, ...args], {
331
335
  cwd,
332
336
  env: {
333
337
  ...process.env,
@@ -166,7 +166,8 @@ export async function createServer(config: ServerConfig = {}) {
166
166
  const result = await curator.curateWithCLI(
167
167
  body.claude_session_id,
168
168
  body.trigger,
169
- body.cwd
169
+ body.cwd,
170
+ body.cli_type
170
171
  )
171
172
 
172
173
  if (result.memories.length > 0) {