-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathclaude.ts
More file actions
207 lines (180 loc) · 6.93 KB
/
Copy pathclaude.ts
File metadata and controls
207 lines (180 loc) · 6.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
import { homedir } from 'os'
import { log } from '../debug'
import { makeHookCommand } from '../hooks'
import { shellQuote } from '../shell-quote'
import type { AgentSpawnOpts } from './index'
// Claude Code strips unknown fields when it normalizes settings.json,
// so dedup recognizes our entries by the status-dir path baked into
// the hook command instead of a sidecar marker.
const HARNESS_HOOK_COMMAND_SIGNATURE = '/tmp/harness-status'
export const defaultCommand = 'claude'
export const assignsSessionId = true
export const hookEvents = [
'UserPromptSubmit',
'PreToolUse',
'PostToolUse',
'Stop',
'Notification'
]
interface HookEntry {
matcher?: string
hooks: { type: string; command: string; timeout?: number }[]
}
interface SettingsFile {
hooks?: Record<string, HookEntry[]>
[key: string]: unknown
}
function globalSettingsPath(): string {
return join(homedir(), '.claude', 'settings.json')
}
function worktreeSettingsPath(worktreePath: string): string {
return join(worktreePath, '.claude', 'settings.local.json')
}
function readSettings(path: string): SettingsFile {
try {
return JSON.parse(readFileSync(path, 'utf-8'))
} catch {
return {}
}
}
function writeSettings(path: string, settings: SettingsFile): void {
const dir = join(path, '..')
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
writeFileSync(path, JSON.stringify(settings, null, 2))
}
function makeHarnessHookEntry(command: string): HookEntry {
return {
hooks: [{ type: 'command', command, timeout: 5 }]
}
}
function isHarnessHookEntry(entry: HookEntry): boolean {
return !!entry.hooks?.some(
(h) => typeof h.command === 'string' && h.command.includes(HARNESS_HOOK_COMMAND_SIGNATURE)
)
}
function removeOldHarnessEntries(entries: HookEntry[]): HookEntry[] {
return entries.filter((entry) => !isHarnessHookEntry(entry))
}
export function hooksInstalled(): boolean {
const settings = readSettings(globalSettingsPath())
const hooks = settings.hooks
if (!hooks) return false
for (const entries of Object.values(hooks)) {
for (const entry of entries) {
if (isHarnessHookEntry(entry)) return true
}
}
return false
}
export function installHooks(): void {
const path = globalSettingsPath()
log('hooks', `installing Claude hooks into ${path}`)
const settings = readSettings(path)
if (!settings.hooks) settings.hooks = {}
for (const event of Object.keys(settings.hooks)) {
settings.hooks[event] = removeOldHarnessEntries(settings.hooks[event])
}
for (const event of hookEvents) {
if (!settings.hooks[event]) settings.hooks[event] = []
settings.hooks[event].push(makeHarnessHookEntry(makeHookCommand(event)))
}
writeSettings(path, settings)
}
/** Remove our entries from ~/.claude/settings.json but leave any user-authored
* hooks + unrelated keys intact. No-op if we're not installed. */
export function uninstallHooks(): void {
const path = globalSettingsPath()
if (!existsSync(path)) return
const settings = readSettings(path)
if (!settings.hooks) return
for (const event of Object.keys(settings.hooks)) {
settings.hooks[event] = removeOldHarnessEntries(settings.hooks[event])
if (settings.hooks[event].length === 0) delete settings.hooks[event]
}
if (Object.keys(settings.hooks).length === 0) delete settings.hooks
writeSettings(path, settings)
log('hooks', `uninstalled Claude hooks from ${path}`)
}
/** Strip any legacy Harness entries from a worktree's .claude/settings.local.json.
* Returns true if the file was modified. Leaves user-authored hooks alone. */
export function stripHooksFromWorktree(worktreePath: string): boolean {
const path = worktreeSettingsPath(worktreePath)
if (!existsSync(path)) return false
const settings = readSettings(path)
if (!settings.hooks) return false
let changed = false
for (const event of Object.keys(settings.hooks)) {
const before = settings.hooks[event].length
settings.hooks[event] = removeOldHarnessEntries(settings.hooks[event])
if (settings.hooks[event].length !== before) changed = true
if (settings.hooks[event].length === 0) delete settings.hooks[event]
}
if (!changed) return false
if (Object.keys(settings.hooks).length === 0) delete settings.hooks
writeSettings(path, settings)
log('hooks', `stripped legacy Harness entries from ${path}`)
return true
}
export function sessionFileExists(cwd: string, sessionId: string): boolean {
try {
const encoded = cwd.replace(/[^a-zA-Z0-9]/g, '-')
return existsSync(join(homedir(), '.claude', 'projects', encoded, `${sessionId}.jsonl`))
} catch {
return false
}
}
export function listSessions(
cwd: string
): Array<{ sessionId: string; mtimeMs: number }> {
try {
const encoded = cwd.replace(/[^a-zA-Z0-9]/g, '-')
const dir = join(homedir(), '.claude', 'projects', encoded)
const out: Array<{ sessionId: string; mtimeMs: number }> = []
for (const file of readdirSync(dir)) {
if (!file.endsWith('.jsonl')) continue
try {
out.push({
sessionId: file.replace(/\.jsonl$/, ''),
mtimeMs: statSync(join(dir, file)).mtimeMs
})
} catch {
// Raced unlink between readdir and stat — skip.
}
}
out.sort((a, b) => b.mtimeMs - a.mtimeMs)
return out
} catch {
return []
}
}
export function latestSessionId(cwd: string): string | null {
return listSessions(cwd)[0]?.sessionId ?? null
}
export function buildSpawnArgs(opts: AgentSpawnOpts): string {
const modelFlag = opts.model && !opts.command.includes('--model') ? ` --model ${shellQuote(opts.model)}` : ''
const mcpFlag = opts.mcpConfigPath ? ` --mcp-config ${shellQuote(opts.mcpConfigPath)}` : ''
const nameFlag = opts.sessionName ? ` --name ${shellQuote(opts.sessionName)}` : ''
const systemPromptFlag = opts.systemPrompt ? ` --append-system-prompt ${shellQuote(opts.systemPrompt)}` : ''
const tuiPrefix = opts.tuiFullscreen ? 'CLAUDE_CODE_NO_FLICKER=1 ' : ''
const cmd = `${tuiPrefix}${opts.command}${modelFlag}${mcpFlag}${nameFlag}${systemPromptFlag}`
// Fork: branch the source session into a new one. Claude mints the new id
// and we discover it from the first hook event (no --session-id to pin).
if (opts.forkFromSessionId) {
return `${cmd} --resume ${opts.forkFromSessionId} --fork-session`
}
if (opts.teleportSessionId && opts.sessionId) {
const exists = sessionFileExists(opts.cwd, opts.sessionId)
if (!exists) {
return `${cmd} --teleport ${opts.teleportSessionId} --session-id ${opts.sessionId}`
}
}
if (!opts.sessionId) {
return opts.initialPrompt ? `${cmd} ${shellQuote(opts.initialPrompt)}` : cmd
}
const exists = sessionFileExists(opts.cwd, opts.sessionId)
if (exists) return `${cmd} --resume ${opts.sessionId}`
const base = `${cmd} --session-id ${opts.sessionId}`
return opts.initialPrompt ? `${base} ${shellQuote(opts.initialPrompt)}` : base
}