Replace hardcoded PowerShell status hooks with stdin-forwarding hooks that send full Claude Code hook data (tool_input, tool_response, prompt, session_id, model, etc.) to /api/claude-hook endpoint. - PowerShell hooks read stdin JSON and POST to /api/claude-hook - Server derives status for backward-compat FAB animations - Server extracts assistant_response from transcript on Stop events - New /api/claude-permission endpoint with Promise-based allow/deny flow - HookNotifications.vue: toast system showing session, prompt, tool use, tool results, notifications, and final assistant response - WebSocket broadcast for claude-hook and claude-permission message types
126 lines
4.3 KiB
TypeScript
126 lines
4.3 KiB
TypeScript
import { jsonResponse, errorResponse } from '../utils/cors'
|
|
import { PORT_TERMINAL } from '../config'
|
|
import { existsSync, readFileSync } from 'fs'
|
|
|
|
type ClaudeStatus = 'idle' | 'processing' | 'toolUse' | 'toolDone' | 'reading' | 'writing' | 'sessionStart' | 'subagentStart' | 'subagentStop' | 'notification' | 'permissionRequest' | 'thinking'
|
|
|
|
interface HookPayload {
|
|
hook_event_name?: string
|
|
session_id?: string
|
|
tool_name?: string
|
|
tool_input?: unknown
|
|
tool_response?: unknown
|
|
prompt?: string
|
|
cwd?: string
|
|
model?: string
|
|
source?: string
|
|
transcript_path?: string
|
|
message?: string
|
|
notification_type?: string
|
|
stop_hook_active?: boolean
|
|
tool_use_id?: string
|
|
[key: string]: unknown
|
|
}
|
|
|
|
function deriveStatus(payload: HookPayload): { status: ClaudeStatus, tool?: string } {
|
|
const event = payload.hook_event_name
|
|
const toolName = payload.tool_name
|
|
|
|
switch (event) {
|
|
case 'SessionStart':
|
|
return { status: 'sessionStart' }
|
|
case 'UserPromptSubmit':
|
|
return { status: 'processing' }
|
|
case 'PreToolUse':
|
|
if (toolName && /^(Read|Glob|Grep)$/.test(toolName)) {
|
|
return { status: 'reading', tool: toolName }
|
|
}
|
|
if (toolName && /^(Edit|Write)$/.test(toolName)) {
|
|
return { status: 'writing', tool: toolName }
|
|
}
|
|
return { status: 'toolUse', tool: toolName }
|
|
case 'PostToolUse':
|
|
return { status: 'toolDone', tool: toolName }
|
|
case 'PermissionRequest':
|
|
return { status: 'permissionRequest', tool: toolName }
|
|
case 'Notification':
|
|
return { status: 'notification' }
|
|
case 'Stop':
|
|
return { status: 'idle' }
|
|
default:
|
|
return { status: 'processing' }
|
|
}
|
|
}
|
|
|
|
export async function handleClaudeHook(req: Request): Promise<Response | null> {
|
|
if (req.method !== 'POST') return null
|
|
|
|
try {
|
|
const url = new URL(req.url)
|
|
const agent = url.searchParams.get('agent') || ''
|
|
const body = await req.json() as HookPayload
|
|
|
|
// On Stop events, extract last assistant response from transcript
|
|
if (body.hook_event_name === 'Stop' && body.transcript_path) {
|
|
try {
|
|
let tp = body.transcript_path as string
|
|
// Normalize path for Windows (handle both C:\ and /c/ formats)
|
|
tp = tp.replace(/\\/g, '/')
|
|
if (/^\/[a-zA-Z]\//.test(tp)) {
|
|
tp = tp[1].toUpperCase() + ':' + tp.slice(2)
|
|
}
|
|
if (existsSync(tp)) {
|
|
const lines = readFileSync(tp, 'utf8').trim().split('\n')
|
|
for (let i = lines.length - 1; i >= Math.max(0, lines.length - 30); i--) {
|
|
try {
|
|
const obj = JSON.parse(lines[i])
|
|
if (obj.type === 'assistant' && obj.message?.role === 'assistant') {
|
|
const content = obj.message.content
|
|
if (Array.isArray(content)) {
|
|
const text = content.filter((c: any) => c.type === 'text').map((c: any) => c.text).join('\n')
|
|
if (text) {
|
|
body.assistant_response = text.slice(0, 500)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
} catch { /* skip unparseable lines */ }
|
|
}
|
|
}
|
|
} catch (e) {
|
|
console.error('[claude-hook] Failed to read transcript:', e)
|
|
}
|
|
}
|
|
|
|
// Inject agent name into hook data for WS consumers
|
|
const hookData = { ...body, agent_name: agent || 'main' }
|
|
|
|
// 1. Broadcast full hook data via WebSocket (always, even for subagents)
|
|
try {
|
|
await fetch(`http://localhost:${PORT_TERMINAL}/claude-hook`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(hookData)
|
|
})
|
|
} catch (e) {
|
|
console.error('[claude-hook] Failed to forward hook to terminal server:', e)
|
|
}
|
|
|
|
// 2. Derive status and broadcast for backward compat (App.vue/AgentBar.vue)
|
|
const { status, tool } = deriveStatus(body)
|
|
try {
|
|
await fetch(`http://localhost:${PORT_TERMINAL}/claude-status`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ status, tool, agent: agent || 'main' })
|
|
})
|
|
} catch (e) {
|
|
console.error('[claude-hook] Failed to forward status to terminal server:', e)
|
|
}
|
|
|
|
return jsonResponse({ success: true, event: body.hook_event_name, agent: agent || 'main' })
|
|
} catch (e) {
|
|
return errorResponse('Invalid JSON body', 400)
|
|
}
|
|
}
|