Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion CLI/CMUXCLI+AgentHookDefinitions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ extension CMUXCLI {
enum HookFormat {
case flat // Cursor: {"hooks": {"event": [{"command": "..."}]}, "version": 1}
case nested(timeoutMs: Int) // Codex/Gemini: nested with type/command/timeout
case kiroAgentJSON(timeoutMs: Int) // ~/.kiro/agents/*.json flat command entries with timeout_ms
case antigravityJSON(timeoutSeconds: Int) // ~/.gemini/config/hooks.json named hook groups
case rovoDevYAML
case hermesAgentYAML
Expand Down Expand Up @@ -198,6 +199,20 @@ extension CMUXCLI {
],
feedHookEvents: ["PreToolUse"]
),
AgentHookDef(
name: "kiro", displayName: "Kiro", statusKey: "kiro",
configDir: ".kiro/agents", configFile: "cmux.json",
configDirEnvOverride: "KIRO_HOME", configDirEnvOverrideSubpath: "agents",
createConfigDirIfMissing: true, binaryName: "kiro-cli",
sessionStoreSuffix: "kiro", disableEnvVar: "CMUX_KIRO_HOOKS_DISABLED",
hookMarker: "cmux hooks kiro", format: .kiroAgentJSON(timeoutMs: 5000),
events: [
.init(agentEvent: "agentSpawn", cmuxSubcommand: "session-start"),
.init(agentEvent: "userPromptSubmit", cmuxSubcommand: "prompt-submit"),
.init(agentEvent: "stop", cmuxSubcommand: "stop"),
],
feedHookEvents: ["preToolUse", "postToolUse"]
),
AgentHookDef(
name: "antigravity", displayName: "Antigravity", statusKey: "antigravity",
configDir: ".gemini/config", configFile: "hooks.json",
Expand Down Expand Up @@ -306,7 +321,10 @@ extension CMUXCLI {
}

static func feedHookCommandString(for def: AgentHookDef, agentEvent: String) -> String {
agentHookShellCommand("cmux hooks feed --source \(def.name) --event \(agentEvent)", for: def)
if def.name == "kiro" {
return kiroAgentHookShellCommand("cmux hooks feed --source \(def.name) --event \(agentEvent)", for: def)
}
return agentHookShellCommand("cmux hooks feed --source \(def.name) --event \(agentEvent)", for: def)
}

Comment thread
austinywang marked this conversation as resolved.
Resolved
private static let grokPinnedHookMarker = "cmux-grok-hook-v2"
Expand All @@ -320,6 +338,11 @@ extension CMUXCLI {
return "cmux_cli=\"${CMUX_BUNDLED_CLI_PATH:-}\"; if [ -z \"$cmux_cli\" ] || [ ! -x \"$cmux_cli\" ]; then cmux_cli=\"$(command -v cmux 2>/dev/null || true)\"; fi; if [ -n \"$CMUX_SURFACE_ID\" ] && [ \"$\(def.disableEnvVar)\" != \"1\" ] && [ -n \"$cmux_cli\" ]; then { if [ -n \"${CMUX_SOCKET_PATH:-}\" ]; then \"$cmux_cli\" --socket \"$CMUX_SOCKET_PATH\" \(routedArguments); else \"$cmux_cli\" \(routedArguments); fi; } || echo '{}'; else echo '{}'; fi"
}

private static func kiroAgentHookShellCommand(_ command: String, for def: AgentHookDef) -> String {
let routedArguments = command.hasPrefix("cmux ") ? String(command.dropFirst("cmux ".count)) : command
return "cmux_cli=\"${CMUX_BUNDLED_CLI_PATH:-}\"; if [ -z \"$cmux_cli\" ] || [ ! -x \"$cmux_cli\" ]; then cmux_cli=\"$(command -v cmux 2>/dev/null || true)\"; fi; if [ -n \"$CMUX_SURFACE_ID\" ] && [ \"$\(def.disableEnvVar)\" != \"1\" ] && [ -n \"$cmux_cli\" ]; then if [ -n \"${CMUX_SOCKET_PATH:-}\" ]; then \"$cmux_cli\" --socket \"$CMUX_SOCKET_PATH\" \(routedArguments); else \"$cmux_cli\" \(routedArguments); fi; else echo '{}'; fi"
}

private static func usesPinnedHookDispatch(_ def: AgentHookDef) -> Bool {
def.name == "grok" || def.name == "antigravity"
}
Expand Down
135 changes: 120 additions & 15 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11847,7 +11847,7 @@ struct CMUXCLI {
agent. Claude Code hooks are injected automatically by the cmux Claude wrapper.

Agents:
codex, grok, opencode, pi, amp, cursor, gemini, antigravity (alias: agy), rovodev (alias: rovo), hermes-agent, copilot, codebuddy, factory, qoder
codex, grok, opencode, pi, amp, cursor, gemini, kiro, antigravity (alias: agy), rovodev (alias: rovo), hermes-agent, copilot, codebuddy, factory, qoder

Hook targets:
setup Install hooks for all supported agents on PATH
Expand All @@ -11862,6 +11862,7 @@ struct CMUXCLI {
~/.config/opencode/plugins/cmux-feed.js
~/.pi/agent/extensions/cmux-session.ts
~/.config/amp/plugins/cmux-session.ts
~/.kiro/agents/cmux.json
See docs/agent-hooks.md for the full integration matrix.

Examples:
Expand Down Expand Up @@ -23401,6 +23402,13 @@ struct CMUXCLI {
var entries = result[event.agentEvent] as? [[String: Any]] ?? []
entries.append(["command": cmd])
result[event.agentEvent] = entries
case .kiroAgentJSON(let timeoutMs):
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
var entries = result[event.agentEvent] as? [[String: Any]] ?? []
entries.append([
"command": cmd,
"timeout_ms": max(timeoutMs, 1),
] as [String: Any])
result[event.agentEvent] = entries
case .nested(let timeoutMs):
var groups = result[event.agentEvent] as? [[String: Any]] ?? []
let timeout = nestedHookTimeout(timeoutMs, for: def)
Expand Down Expand Up @@ -23432,6 +23440,13 @@ struct CMUXCLI {
var entries = result[agentEvent] as? [[String: Any]] ?? []
entries.append(["command": feedCmd])
result[agentEvent] = entries
case .kiroAgentJSON:
var entries = result[agentEvent] as? [[String: Any]] ?? []
entries.append([
"command": feedCmd,
"timeout_ms": feedTimeoutMs,
] as [String: Any])
result[agentEvent] = entries
case .nested:
var groups = result[agentEvent] as? [[String: Any]] ?? []
let timeout = nestedHookTimeout(feedTimeoutMs, for: def)
Expand Down Expand Up @@ -24442,7 +24457,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
var cmuxInsertionIndexes: [String: [Int]] = [:]
for (event, value) in hooks {
switch def.format {
case .flat:
case .flat, .kiroAgentJSON:
guard let entries = value as? [[String: Any]] else { continue }
var rewrittenEntries: [[String: Any]] = []
for entry in entries {
Expand Down Expand Up @@ -24499,7 +24514,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
// Add new cmux entries
for (event, value) in newHooks {
switch def.format {
case .flat:
case .flat, .kiroAgentJSON:
var entries = hooks[event] as? [[String: Any]] ?? []
if let newEntries = value as? [[String: Any]] {
if let insertionIndexes = cmuxInsertionIndexes[event], !insertionIndexes.isEmpty {
Expand All @@ -24526,6 +24541,14 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {

existing["hooks"] = hooks
if case .flat = def.format { existing["version"] = 1 }
if case .kiroAgentJSON = def.format {
if existing["name"] == nil {
existing["name"] = "cmux"
}
if existing["description"] == nil {
existing["description"] = "CMUX notification and Feed bridge hooks for Kiro CLI."
}
}
let codexHookTrustEntries = Self.codexHookTrustEntries(
hooks: hooks,
hooksFilePath: filePath,
Expand Down Expand Up @@ -24754,7 +24777,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
}
for (event, value) in hooks {
switch def.format {
case .flat:
case .flat, .kiroAgentJSON:
guard var entries = value as? [[String: Any]] else { continue }
let before = entries.count
entries.removeAll { isCmuxOwnedCommand($0["command"] as? String ?? "") }
Expand Down Expand Up @@ -26840,6 +26863,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
case "rovodev": envKey = "CMUX_ROVODEV_PID"
case "hermes-agent": envKey = "CMUX_HERMES_AGENT_PID"
case "copilot": envKey = "CMUX_COPILOT_PID"
case "kiro": envKey = "CMUX_KIRO_PID"
default: envKey = ""
}
if !envKey.isEmpty,
Expand Down Expand Up @@ -27068,10 +27092,10 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
var summary: String?
if lower == "bash" {
summary = firstString(in: dict, keys: ["description", "command"])
} else if lower == "run_command" {
} else if lower == "run_command" || lower == "execute_bash" || lower == "shell" {
summary = firstString(in: dict, keys: ["CommandLine", "commandLine", "command", "Cwd", "cwd"])
} else if ["write", "edit", "multiedit", "read"].contains(lower) {
summary = firstString(in: dict, keys: ["file_path", "path"])
} else if ["write", "edit", "multiedit", "read", "fs_read", "fs_write"].contains(lower) {
summary = firstString(in: dict, keys: ["file_path", "path"]) ?? firstOperationPath(in: dict)
} else if ["view_file", "write_to_file", "replace_file_content", "multi_replace_file_content"].contains(lower) {
summary = firstString(in: dict, keys: ["AbsolutePath", "TargetFile", "SearchPath", "DirectoryPath", "path"])
} else if lower == "askuserquestion" || lower == "ask_question" {
Expand All @@ -27088,6 +27112,16 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
return context.isEmpty ? nil : context
}

private func firstOperationPath(in dict: [String: Any]) -> String? {
guard let operations = dict["operations"] as? [[String: Any]] else { return nil }
for operation in operations {
if let path = firstString(in: operation, keys: ["path", "file_path", "filePath"]) {
return path
}
}
return nil
}

private func feedToolInputDictionary(_ raw: Any?) -> [String: Any]? {
if let dict = raw as? [String: Any] {
return dict
Expand Down Expand Up @@ -28609,13 +28643,23 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
event: rawEvent,
toolName: toolName
)
let env = ProcessInfo.processInfo.environment
if Self.shouldSuppressKiroFeedEvent(
source: source,
hookEventName: hookEventName,
toolName: toolName,
isActionable: isActionable,
env: env
) {
print("{}")
return
}

// Capture the agent's PID (not our subprocess PID) so the
// Feed can auto-expire pending cards when the agent is
// killed/crashed. Agent wrappers export CMUX_<AGENT>_PID.
// Other agents fall back to getppid() which walks up one
// level — close enough to catch most kill scenarios.
let env = ProcessInfo.processInfo.environment
let agentPid = agentPidForFeedSource(source, env: env)
let sessionId = firstString(
in: stdinObj,
Expand Down Expand Up @@ -28707,6 +28751,9 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {

let status = result["status"] as? String ?? "acknowledged"
if status == "resolved", let decision = result["decision"] as? [String: Any] {
if source == "kiro", Self.emitKiroDecisionIfHandled(decision: decision) {
return
}
let out = Self.renderAgentDecision(
source: source,
hookEventName: hookEventName,
Expand Down Expand Up @@ -28764,7 +28811,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
if source == "hermes-agent" {
switch event {
case "pre_tool_call":
if Self.sideEffectingTools.contains(toolName) {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
if Self.isSideEffectingTool(toolName) {
return ("PermissionRequest", true)
}
return ("PreToolUse", false)
Expand All @@ -28788,7 +28835,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
}

switch event {
case "PreToolUse", "beforeShellExecution":
case "PreToolUse", "preToolUse", "beforeShellExecution":
if source == "codex" { return ("PreToolUse", false) }
switch toolName {
case "ExitPlanMode":
Expand All @@ -28801,22 +28848,22 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
// from the Feed sidebar. Read-only tools stay as
// non-actionable telemetry so we don't flood the
// Actionable view with every file read.
if Self.sideEffectingTools.contains(toolName) {
if Self.isSideEffectingTool(toolName) {
return ("PermissionRequest", true)
}
return ("PreToolUse", false)
}
case "PermissionRequest":
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return ("PermissionRequest", true)
case "PostToolUse":
case "PostToolUse", "postToolUse":
return ("PostToolUse", false)
case "UserPromptSubmit":
case "UserPromptSubmit", "userPromptSubmit":
return ("UserPromptSubmit", false)
case "SessionStart":
case "SessionStart", "agentSpawn":
return ("SessionStart", false)
case "SessionEnd":
return ("SessionEnd", false)
case "Stop":
case "Stop", "stop":
return ("Stop", false)
case "SubagentStop":
return ("SubagentStop", false)
Expand Down Expand Up @@ -28854,6 +28901,64 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) {
"generate_image",
]

private static func isSideEffectingTool(_ toolName: String) -> Bool {
guard !toolName.isEmpty else { return false }
if sideEffectingTools.contains(toolName) {
return true
}
switch toolName.lowercased() {
case "bash", "write", "edit", "multiedit", "notebookedit",
"apply_patch", "shell", "execute_bash", "fs_write", "use_aws", "aws",
"terminal", "run_command", "write_to_file", "replace_file_content",
"multi_replace_file_content", "manage_task", "schedule",
"ask_permission", "invoke_subagent", "define_subagent", "manage_subagents",
"generate_image":
return true
default:
return false
}
}

private static func shouldSuppressKiroFeedEvent(
source: String,
hookEventName: String,
toolName: String,
isActionable: Bool,
env: [String: String]
) -> Bool {
guard source == "kiro" else { return false }
guard env["CMUX_KIRO_NOTIFICATION_LEVEL"] != nil || hookEventName == "PreToolUse" || hookEventName == "PostToolUse" else {
return false
}
guard !isActionable else { return false }
let level = env["CMUX_KIRO_NOTIFICATION_LEVEL"]?
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased() ?? "standard"
switch level {
case "minimal":
return hookEventName == "PreToolUse" || hookEventName == "PostToolUse"
case "verbose":
return false
default:
if hookEventName == "PreToolUse" || hookEventName == "PostToolUse" {
return !isSideEffectingTool(toolName)
}
return false
}
}

private static func emitKiroDecisionIfHandled(decision: [String: Any]) -> Bool {
guard (decision["kind"] as? String) == "permission" else { return false }
let mode = (decision["mode"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
if mode == "deny" || mode == nil || mode?.isEmpty == true {
fputs("User denied permission via cmux Feed.\n", stderr)
fflush(stderr)
exit(2)
}
print("{}")
return true
}

private static let skipInterviewAndPlanAnswer = "Skip interview and plan immediately"
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

/// Encodes the user's decision in the agent's expected hook stdout
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ public enum AgentLaunchEnvironmentPolicy {
"GROK_HOME",
"GROK_SANDBOX",
"HERMES_HOME",
"KIRO_HOME",
"KIRO_LOG_LEVEL",
"KIRO_LOG_NO_COLOR",
"NODE_OPTIONS",
"OPENCODE_CONFIG_DIR",
"PI_CACHE_RETENTION",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,15 @@ public enum AgentLaunchSanitizer {
return preserveOptions(tail, policy: cursorPolicy)
case "gemini":
return preserveOptions(args, policy: geminiPolicy)
case "kiro":
var tail = args
if tail.first == "chat" {
tail.removeFirst()
} else if let command = tail.first,
!command.hasPrefix("-") {
return nil
}
return preserveOptions(tail, policy: kiroPolicy)
case "antigravity":
return preserveOptions(args, policy: antigravityPolicy)
case "opencode":
Expand Down
Loading
Loading