SPB Git

Repository Public

HookEvent.swift 7.0 KB 155 lines swift

1import Foundation23/// Loss-less JSON value for hook payloads we do not model explicitly.4public enum JSONValue: Codable, Sendable, Hashable {5    case null6    case bool(Bool)7    case number(Double)8    case string(String)9    case array([JSONValue])10    case object([String: JSONValue])1112    public init(from decoder: Decoder) throws {13        let c = try decoder.singleValueContainer()14        if c.decodeNil() { self = .null }15        else if let b = try? c.decode(Bool.self) { self = .bool(b) }16        else if let n = try? c.decode(Double.self) { self = .number(n) }17        else if let s = try? c.decode(String.self) { self = .string(s) }18        else if let a = try? c.decode([JSONValue].self) { self = .array(a) }19        else if let o = try? c.decode([String: JSONValue].self) { self = .object(o) }20        else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "unsupported JSON") }21    }2223    public func encode(to encoder: Encoder) throws {24        var c = encoder.singleValueContainer()25        switch self {26        case .null: try c.encodeNil()27        case .bool(let b): try c.encode(b)28        case .number(let n): try c.encode(n)29        case .string(let s): try c.encode(s)30        case .array(let a): try c.encode(a)31        case .object(let o): try c.encode(o)32        }33    }3435    public var stringValue: String? { if case .string(let s) = self { return s }; return nil }36    public var boolValue: Bool? { if case .bool(let b) = self { return b }; return nil }37    public var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o }; return nil }38    public subscript(key: String) -> JSONValue? { objectValue?[key] }3940    /// One-line human summary used for tool inputs (never executed, only displayed).41    public var summary: String {42        switch self {43        case .null: return "null"44        case .bool(let b): return b ? "true" : "false"45        case .number(let n): return n == n.rounded() ? String(Int(n)) : String(n)46        case .string(let s): return s47        case .array(let a): return "[" + a.prefix(5).map(\.summary).joined(separator: ", ") + (a.count > 5 ? ", …]" : "]")48        case .object(let o):49            let preferred = ["command", "file_path", "path", "pattern", "url", "query", "description"]50            if let key = preferred.first(where: { o[$0] != nil }), let v = o[key] { return "\(key): \(v.summary)" }51            return o.keys.sorted().prefix(4).map { "\($0): \(o[$0]!.summary)" }.joined(separator: ", ")52        }53    }54}5556/// Event names documented at https://code.claude.com/docs/en/hooks (read 2026-11-01).57public enum HookEventName: String, Codable, Sendable, CaseIterable {58    case sessionStart = "SessionStart"59    case sessionEnd = "SessionEnd"60    case userPromptSubmit = "UserPromptSubmit"61    case preToolUse = "PreToolUse"62    case postToolUse = "PostToolUse"63    case postToolUseFailure = "PostToolUseFailure"64    case permissionRequest = "PermissionRequest"65    case permissionDenied = "PermissionDenied"66    case notification = "Notification"67    case stop = "Stop"68    case stopFailure = "StopFailure"69    case subagentStart = "SubagentStart"70    case subagentStop = "SubagentStop"71    case preCompact = "PreCompact"72    case postCompact = "PostCompact"73    case cwdChanged = "CwdChanged"74    case elicitation = "Elicitation"7576    /// Events NEXTERM subscribes to. `PermissionRequest` is observed only — the hook never returns a decision.77    public static let subscribed: [HookEventName] = [.sessionStart, .sessionEnd, .userPromptSubmit, .preToolUse, .postToolUse, .postToolUseFailure, .permissionRequest, .notification, .stop, .subagentStart, .subagentStop, .preCompact, .cwdChanged]78}7980/// A hook payload as delivered on the hook's stdin / HTTP body. Common fields are typed; everything81/// else stays available in `raw`.82public struct HookEvent: Sendable, Hashable {83    public let name: String84    public let event: HookEventName?85    public let sessionID: String86    public let cwd: String?87    public let transcriptPath: String?88    public let permissionMode: String?89    public let toolName: String?90    public let toolInput: JSONValue?91    public let toolUseID: String?92    public let notificationType: String?93    public let message: String?94    public let title: String?95    public let source: String?96    public let reason: String?97    public let prompt: String?98    public let lastAssistantMessage: String?99    public let agentID: String?100    public let agentType: String?101    public let raw: [String: JSONValue]102    public let receivedAt: Date103104    public init(json: Data, receivedAt: Date = Date()) throws {105        let object = try JSONDecoder().decode([String: JSONValue].self, from: json)106        try self.init(object: object, receivedAt: receivedAt)107    }108109    public init(object: [String: JSONValue], receivedAt: Date = Date()) throws {110        guard let name = object["hook_event_name"]?.stringValue else { throw HookEventError.missingField("hook_event_name") }111        guard let session = object["session_id"]?.stringValue, !session.isEmpty else { throw HookEventError.missingField("session_id") }112        self.name = name113        self.event = HookEventName(rawValue: name)114        self.sessionID = session115        self.cwd = object["cwd"]?.stringValue116        self.transcriptPath = object["transcript_path"]?.stringValue117        self.permissionMode = object["permission_mode"]?.stringValue118        self.toolName = object["tool_name"]?.stringValue119        self.toolInput = object["tool_input"]120        self.toolUseID = object["tool_use_id"]?.stringValue121        self.notificationType = object["notification_type"]?.stringValue122        self.message = object["message"]?.stringValue123        self.title = object["title"]?.stringValue124        self.source = object["source"]?.stringValue125        self.reason = object["reason"]?.stringValue126        self.prompt = object["prompt"]?.stringValue127        self.lastAssistantMessage = object["last_assistant_message"]?.stringValue128        self.agentID = object["agent_id"]?.stringValue129        self.agentType = object["agent_type"]?.stringValue130        self.raw = object131        self.receivedAt = receivedAt132    }133134    /// Short description for logs and Mission Control ("PreToolUse Bash: npm test").135    public var headline: String {136        switch event {137        case .preToolUse, .postToolUse, .postToolUseFailure, .permissionRequest:138            let tool = toolName ?? "tool"139            let input = toolInput?.summary ?? ""140            return "\(name) \(tool)\(input.isEmpty ? "" : ": \(input.prefix(120))")"141        case .notification:142            return "Notification\(notificationType.map { " (\($0))" } ?? ""): \(message ?? title ?? "")"143        case .sessionStart: return "Session started\(source.map { " (\($0))" } ?? "")"144        case .sessionEnd: return "Session ended\(reason.map { " (\($0))" } ?? "")"145        case .userPromptSubmit: return "Prompt: \((prompt ?? "").prefix(120))"146        case .stop: return "Turn finished"147        default: return name148        }149    }150}151152public enum HookEventError: Error, Equatable, Sendable {153    case missingField(String)154}155
Files main
Menu

Theme