claude-session-continuity-mcp 1.15.1 → 1.16.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.
package/README.md CHANGED
@@ -81,6 +81,24 @@ If you want zero-config, offline, no-cost memory that just *happens* while you w
81
81
 
82
82
  ---
83
83
 
84
+ ## Works with Codex CLI too (v1.16.0+)
85
+
86
+ Beyond Claude Code, this also supports **OpenAI Codex CLI**. If `~/.codex` exists,
87
+ the installer registers the same hooks in `~/.codex/hooks.json` (SessionStart,
88
+ UserPromptSubmit, PreCompact, Stop), and the hooks auto-detect the host and emit
89
+ the right output format (Codex's `hookSpecificOutput.additionalContext`).
90
+
91
+ The same local `sessions.db` is shared, so context carries across both agents:
92
+ what you did in Codex is available in Claude Code and vice versa.
93
+
94
+ **Scope:** session save + context injection work on both. Codex file-change
95
+ tracking (PostToolUse) isn't wired yet — session save already covers most of it
96
+ via transcript parsing. Codex's `transcript_path` is treated as an unstable
97
+ interface (it can be null at startup), so host detection uses an installer-injected
98
+ `--codex` marker rather than relying on the path.
99
+
100
+ ---
101
+
84
102
  ## Quick Start
85
103
 
86
104
  ### Recommended: Global Installation
@@ -16,6 +16,9 @@ const CLAUDE_DIR = path.join(os.homedir(), '.claude');
16
16
  const SETTINGS_FILE = path.join(CLAUDE_DIR, 'settings.json');
17
17
  const LEGACY_SETTINGS_FILE = path.join(CLAUDE_DIR, 'settings.local.json');
18
18
  const MCP_CONFIG_FILE = path.join(os.homedir(), '.claude.json');
19
+ // Codex CLI (2026-07-09): hooks register in ~/.codex/hooks.json (same JSON shape as Claude)
20
+ const CODEX_DIR = path.join(os.homedir(), '.codex');
21
+ const CODEX_HOOKS_FILE = path.join(CODEX_DIR, 'hooks.json');
19
22
  // 설치된 패키지 경로 찾기
20
23
  function getPackagePath() {
21
24
  // 1. 글로벌 설치 확인
@@ -123,6 +126,44 @@ function installMcpServer() {
123
126
  return false;
124
127
  }
125
128
  }
129
+ /**
130
+ * Register the same hooks in ~/.codex/hooks.json for OpenAI Codex CLI (2026-07-09).
131
+ * Only runs if ~/.codex exists (Codex installed). Preserves user's existing hooks;
132
+ * replaces only ours (matched by the claude-hook- command prefix).
133
+ */
134
+ function installCodexHooks() {
135
+ if (!fs.existsSync(CODEX_DIR))
136
+ return; // Codex not installed -> skip silently
137
+ const OUR_PREFIX = 'claude-hook-';
138
+ let hooksConfig = { hooks: {} };
139
+ if (fs.existsSync(CODEX_HOOKS_FILE)) {
140
+ try {
141
+ hooksConfig = JSON.parse(fs.readFileSync(CODEX_HOOKS_FILE, 'utf-8'));
142
+ }
143
+ catch {
144
+ hooksConfig = { hooks: {} };
145
+ }
146
+ }
147
+ const hooks = hooksConfig.hooks || {};
148
+ const merge = (event, ourEntries) => {
149
+ const existing = (hooks[event] || []);
150
+ const userEntries = existing.filter(e => !(e.hooks || []).some(h => h.command && h.command.includes(OUR_PREFIX)));
151
+ hooks[event] = [...userEntries, ...ourEntries];
152
+ };
153
+ // Codex uses the same event names as Claude (SessionStart/UserPromptSubmit/Stop...).
154
+ // Append "--codex" so hooks detect the host reliably: Codex passes transcript_path
155
+ // as null at SessionStart, so the argv marker is the only dependable signal.
156
+ merge('SessionStart', [{ hooks: [{ type: 'command', command: 'npm exec -- claude-hook-session-start --codex' }] }]);
157
+ merge('UserPromptSubmit', [{ hooks: [{ type: 'command', command: 'npm exec -- claude-hook-user-prompt --codex' }] }]);
158
+ merge('PreCompact', [{ hooks: [{ type: 'command', command: 'npm exec -- claude-hook-pre-compact --codex' }] }]);
159
+ merge('Stop', [{ hooks: [{ type: 'command', command: 'npm exec -- claude-hook-session-end --codex' }] }]);
160
+ hooksConfig.hooks = hooks;
161
+ try {
162
+ fs.writeFileSync(CODEX_HOOKS_FILE, JSON.stringify(hooksConfig, null, 2));
163
+ console.log('✅ Codex CLI hooks installed (~/.codex/hooks.json)');
164
+ }
165
+ catch { /* non-fatal: Codex hooks are optional */ }
166
+ }
126
167
  function install() {
127
168
  console.log('');
128
169
  console.log('╔════════════════════════════════════════════════════════════╗');
@@ -170,6 +211,9 @@ function install() {
170
211
  ]);
171
212
  settings.hooks = hooks;
172
213
  saveSettings(settings);
214
+ // Codex CLI hooks (2026-07-09): register the same hooks in ~/.codex/hooks.json
215
+ // if Codex is present. Hooks auto-detect the host and emit the right output format.
216
+ installCodexHooks();
173
217
  console.log('✅ Hooks installed (npm exec mode - works with local or global install!)');
174
218
  console.log(' SessionStart: context auto-load');
175
219
  console.log(' UserPromptSubmit: relevant memory injection');
@@ -224,6 +268,24 @@ function uninstall() {
224
268
  settings.hooks = hooks;
225
269
  }
226
270
  saveSettings(settings);
271
+ // Also remove our hooks from Codex (2026-07-09), preserving user's hooks.
272
+ if (fs.existsSync(CODEX_HOOKS_FILE)) {
273
+ try {
274
+ const cfg = JSON.parse(fs.readFileSync(CODEX_HOOKS_FILE, 'utf-8'));
275
+ const ch = cfg.hooks || {};
276
+ for (const event of ['SessionStart', 'UserPromptSubmit', 'PreCompact', 'Stop']) {
277
+ const existing = (ch[event] || []);
278
+ const remaining = existing.filter(e => !(e.hooks || []).some(h => h.command && h.command.includes(OUR_PREFIX)));
279
+ if (remaining.length === 0)
280
+ delete ch[event];
281
+ else
282
+ ch[event] = remaining;
283
+ }
284
+ cfg.hooks = ch;
285
+ fs.writeFileSync(CODEX_HOOKS_FILE, JSON.stringify(cfg, null, 2));
286
+ }
287
+ catch { /* non-fatal */ }
288
+ }
227
289
  console.log('✅ Hooks removed successfully!');
228
290
  }
229
291
  function status() {
@@ -14,7 +14,7 @@ import * as path from 'path';
14
14
  import * as readline from 'readline';
15
15
  import * as crypto from 'crypto';
16
16
  import Database from 'better-sqlite3';
17
- import { logHookError } from '../utils/logger.js';
17
+ import { logHookError, isCodexHost } from '../utils/logger.js';
18
18
  function detectWorkspaceRoot(cwd) {
19
19
  let current = cwd;
20
20
  const root = path.parse(current).root;
@@ -207,6 +207,8 @@ function parseUserText(entry) {
207
207
  }
208
208
  // system-reminder, local-command 태그 제거
209
209
  text = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trim();
210
+ // Codex support (2026-07-09): Codex injects <environment_context> into the first user message -> strip it
211
+ text = text.replace(/<environment_context>[\s\S]*?<\/environment_context>/g, '').trim();
210
212
  text = text.replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>/g, '').trim();
211
213
  text = text.replace(/<command-name>[\s\S]*?<\/command-name>/g, '').trim();
212
214
  text = text.replace(/<command-message>[\s\S]*?<\/command-message>/g, '').trim();
@@ -237,6 +239,64 @@ function extractTextFromContent(content) {
237
239
  }
238
240
  return '';
239
241
  }
242
+ /**
243
+ * Codex support (2026-07-09): normalize a Codex CLI rollout JSONL line into the
244
+ * Claude transcript entry shape, so the rest of parseTranscriptSinglePass
245
+ * (role/content/timestamp/commit/user-request extraction) can be reused as-is.
246
+ *
247
+ * Codex format: {timestamp, type, payload}
248
+ * - payload.type=message, role=user/assistant, content[].text (input_text/output_text)
249
+ * - payload.type=function_call, arguments={command:["zsh","-lc","git commit..."]}
250
+ * - payload.type=session_meta (first line, ignored)
251
+ * - reasoning/token_count etc. are ignored
252
+ * Returns a Claude-shaped entry ({type, timestamp, message:{content:[...]}}) or null (skip).
253
+ */
254
+ function normalizeCodexLine(codexEntry) {
255
+ const p = codexEntry.payload;
256
+ if (!p)
257
+ return null;
258
+ const ts = codexEntry.timestamp;
259
+ // 1. user/assistant message -> text block
260
+ if (p.type === 'message' && (p.role === 'user' || p.role === 'assistant')) {
261
+ const text = (p.content || [])
262
+ .filter(c => c.type === 'input_text' || c.type === 'output_text' || c.type === 'text')
263
+ .map(c => c.text || '')
264
+ .join('\n');
265
+ if (!text)
266
+ return null;
267
+ return {
268
+ type: p.role === 'user' ? 'user' : 'assistant',
269
+ timestamp: ts,
270
+ message: { content: [{ type: 'text', text }] },
271
+ };
272
+ }
273
+ // 2. function_call(shell) -> tool_use block (for git commit extraction).
274
+ // Codex passes command as an argv array (["zsh","-lc","git commit -m ..."]).
275
+ if (p.type === 'function_call' && p.arguments) {
276
+ let cmd = '';
277
+ try {
278
+ const args = JSON.parse(p.arguments);
279
+ if (Array.isArray(args.command)) {
280
+ // Codex uses ["zsh","-lc","<actual cmd>"]. The commit regex requires
281
+ // "^git" or "&& git", so strip the shell wrapper (zsh/bash -lc/-c)
282
+ // and keep only the actual command.
283
+ const a = args.command;
284
+ cmd = (a.length >= 3 && /^(zsh|bash|sh)$/.test(a[0]) && /^-[lc]+$/.test(a[1]))
285
+ ? a.slice(2).join(' ')
286
+ : a.join(' ');
287
+ }
288
+ }
289
+ catch { /* arguments not JSON -> skip */ }
290
+ if (!cmd)
291
+ return null;
292
+ return {
293
+ type: 'assistant',
294
+ timestamp: ts,
295
+ message: { content: [{ type: 'tool_use', input: { command: cmd } }] },
296
+ };
297
+ }
298
+ return null; // skip reasoning/token_count/session_meta etc.
299
+ }
240
300
  /**
241
301
  * Single-Pass Transcript Parser
242
302
  * JSONL을 1회 스트림으로 읽으며 모든 데이터를 동시 추출
@@ -254,6 +314,8 @@ async function parseTranscriptSinglePass(transcriptPath) {
254
314
  };
255
315
  if (!transcriptPath || !fs.existsSync(transcriptPath))
256
316
  return result;
317
+ // Host detection: Codex uses ~/.codex/sessions/...rollout-*.jsonl, Claude uses ~/.claude/projects/...
318
+ const isCodex = isCodexHost(transcriptPath); // shared detection (argv marker or path)
257
319
  // commit 추출용 패턴
258
320
  const commitPatterns = [
259
321
  /git commit.*?-m\s*"\$\(cat <<'?EOF'?\n(.+?)(?:\n\n|\nCo-Authored|\nEOF)/s,
@@ -277,7 +339,11 @@ async function parseTranscriptSinglePass(transcriptPath) {
277
339
  if (!line.trim())
278
340
  continue;
279
341
  try {
280
- const entry = JSON.parse(line);
342
+ const rawEntry = JSON.parse(line);
343
+ // For Codex, normalize the rollout line into a Claude entry shape. Skipped lines (reasoning etc.) return null.
344
+ const entry = isCodex ? normalizeCodexLine(rawEntry) : rawEntry;
345
+ if (!entry)
346
+ continue;
281
347
  const role = entry.type || entry.role || '';
282
348
  const content = entry.message?.content;
283
349
  // === 0. Timestamp 추출 (세션 duration 계산용) ===
@@ -5,7 +5,7 @@
5
5
  import * as fs from 'fs';
6
6
  import * as path from 'path';
7
7
  import Database from 'better-sqlite3';
8
- import { logHookError } from '../utils/logger.js';
8
+ import { logHookError, emitContext, isCodexHost } from '../utils/logger.js';
9
9
  function detectWorkspaceRoot(cwd) {
10
10
  let current = cwd;
11
11
  const root = path.parse(current).root;
@@ -259,10 +259,13 @@ async function main() {
259
259
  const dbPath = path.join(workspaceRoot, '.claude', 'sessions.db');
260
260
  const context = loadContext(dbPath, project);
261
261
  if (context) {
262
- console.log(`\n<session-context project="${project}">\n${context}\n</session-context>\n`);
262
+ emitContext(`\n<session-context project="${project}">\n${context}\n</session-context>\n`, 'SessionStart', input.transcript_path);
263
263
  }
264
264
  else {
265
- console.log(`\n[Session] Project: ${project} (no context yet)\n`);
265
+ // Only Claude gets the "no context" placeholder; Codex would just get empty context.
266
+ if (!isCodexHost(input.transcript_path)) {
267
+ console.log(`\n[Session] Project: ${project} (no context yet)\n`);
268
+ }
266
269
  }
267
270
  process.exit(0);
268
271
  }
@@ -5,7 +5,7 @@
5
5
  import * as fs from 'fs';
6
6
  import * as path from 'path';
7
7
  import Database from 'better-sqlite3';
8
- import { logHookError } from '../utils/logger.js';
8
+ import { logHookError, emitContext } from '../utils/logger.js';
9
9
  function detectWorkspaceRoot(cwd) {
10
10
  let current = cwd;
11
11
  const root = path.parse(current).root;
@@ -482,7 +482,7 @@ async function main() {
482
482
  const pastSection = formatPastWork(pastWork);
483
483
  db.close();
484
484
  if (pastSection) {
485
- console.log(`\n<past-context project="${project}">\n${pastSection}\n</past-context>\n`);
485
+ emitContext(`\n<past-context project="${project}">\n${pastSection}\n</past-context>\n`, 'UserPromptSubmit', input.transcript_path);
486
486
  }
487
487
  }
488
488
  catch { /* ignore */ }
@@ -503,7 +503,7 @@ async function main() {
503
503
  const content = m.content.length > 120 ? m.content.slice(0, 120) + '...' : m.content;
504
504
  lines.push(`- [${m.memory_type}] ${content}`);
505
505
  }
506
- console.log(`\n<triggered-context project="${project ?? 'global'}" keywords="${triggerKws.join(',')}">\n${lines.join('\n')}\n</triggered-context>\n`);
506
+ emitContext(`\n<triggered-context project="${project ?? 'global'}" keywords="${triggerKws.join(',')}">\n${lines.join('\n')}\n</triggered-context>\n`, 'UserPromptSubmit', input.transcript_path);
507
507
  }
508
508
  }
509
509
  }
@@ -25,4 +25,21 @@ export declare const logger: Logger;
25
25
  * 로그 위치: $HOOK_ERROR_LOG > cwd/.claude/hook-errors.log > ~/.claude/hook-errors.log
26
26
  */
27
27
  export declare function logHookError(hook: string, err: unknown): void;
28
+ /**
29
+ * Detect whether the hook is running under OpenAI Codex CLI (vs Claude Code).
30
+ *
31
+ * Two signals (either is sufficient):
32
+ * 1. A "--codex" argv marker injected by our installer into ~/.codex/hooks.json.
33
+ * This is the reliable signal — Codex passes transcript_path as null at
34
+ * SessionStart (fresh session, rollout not yet written), so path alone fails.
35
+ * 2. Transcript path under ~/.codex/sessions/...rollout-*.jsonl (fallback for
36
+ * Stop/UserPromptSubmit where the rollout already exists).
37
+ */
38
+ export declare function isCodexHost(transcriptPath?: string): boolean;
39
+ /**
40
+ * Emit context to stdout in the host's expected format (Codex support, 2026-07-09).
41
+ * - Claude Code injects raw stdout text directly.
42
+ * - Codex CLI expects {hookSpecificOutput:{hookEventName, additionalContext}}.
43
+ */
44
+ export declare function emitContext(context: string, hookEventName: string, transcriptPath?: string): void;
28
45
  export {};
@@ -138,3 +138,35 @@ export function logHookError(hook, err) {
138
138
  }
139
139
  catch { /* never throw from the error logger */ }
140
140
  }
141
+ /**
142
+ * Detect whether the hook is running under OpenAI Codex CLI (vs Claude Code).
143
+ *
144
+ * Two signals (either is sufficient):
145
+ * 1. A "--codex" argv marker injected by our installer into ~/.codex/hooks.json.
146
+ * This is the reliable signal — Codex passes transcript_path as null at
147
+ * SessionStart (fresh session, rollout not yet written), so path alone fails.
148
+ * 2. Transcript path under ~/.codex/sessions/...rollout-*.jsonl (fallback for
149
+ * Stop/UserPromptSubmit where the rollout already exists).
150
+ */
151
+ export function isCodexHost(transcriptPath) {
152
+ if (process.argv.includes('--codex'))
153
+ return true;
154
+ if (!transcriptPath)
155
+ return false;
156
+ return transcriptPath.includes('/.codex/sessions/') || /rollout-.*\.jsonl$/.test(transcriptPath);
157
+ }
158
+ /**
159
+ * Emit context to stdout in the host's expected format (Codex support, 2026-07-09).
160
+ * - Claude Code injects raw stdout text directly.
161
+ * - Codex CLI expects {hookSpecificOutput:{hookEventName, additionalContext}}.
162
+ */
163
+ export function emitContext(context, hookEventName, transcriptPath) {
164
+ if (isCodexHost(transcriptPath)) {
165
+ process.stdout.write(JSON.stringify({
166
+ hookSpecificOutput: { hookEventName, additionalContext: context },
167
+ }));
168
+ }
169
+ else {
170
+ console.log(context);
171
+ }
172
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-session-continuity-mcp",
3
- "version": "1.15.1",
3
+ "version": "1.16.0",
4
4
  "description": "Session Continuity for Claude Code - Never re-explain your project again",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",