Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
283 changes: 265 additions & 18 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -311,8 +311,8 @@ struct NotificationInfo {
}

private struct ClaudeHookParsedInput {
let rawInput: String
let object: [String: Any]?
let rawFallback: String?
let sessionId: String?
let cwd: String?
let transcriptPath: String?
Expand Down Expand Up @@ -9575,6 +9575,17 @@ struct CMUXCLI {
}
}

private static let claudeNodeOptionsRestoreModule = """
const hadOriginalNodeOptions = process.env.CMUX_ORIGINAL_NODE_OPTIONS_PRESENT === "1";
if (hadOriginalNodeOptions) {
process.env.NODE_OPTIONS = process.env.CMUX_ORIGINAL_NODE_OPTIONS ?? "";
} else {
delete process.env.NODE_OPTIONS;
}
delete process.env.CMUX_ORIGINAL_NODE_OPTIONS;
delete process.env.CMUX_ORIGINAL_NODE_OPTIONS_PRESENT;
"""

private func configureClaudeTeamsEnvironment(
processEnvironment: [String: String],
shimDirectory: URL,
Expand All @@ -9597,6 +9608,26 @@ struct CMUXCLI {
(key: "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS", value: "1"),
]
)
guard let restoreModuleURL = try? createClaudeNodeOptionsRestoreModule() else {
unsetenv("CMUX_ORIGINAL_NODE_OPTIONS_PRESENT")
unsetenv("CMUX_ORIGINAL_NODE_OPTIONS")
return
}
Comment on lines +9611 to +9615

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Fail-open path skips OOM guard when restore module creation fails.

On Line 9611, the early return means NODE_OPTIONS is never updated if restore-module creation fails, so --max-old-space-size=4096 is not enforced in that path.

🔧 Suggested fix
-        guard let restoreModuleURL = try? createClaudeNodeOptionsRestoreModule() else {
-            unsetenv("CMUX_ORIGINAL_NODE_OPTIONS_PRESENT")
-            unsetenv("CMUX_ORIGINAL_NODE_OPTIONS")
-            return
-        }
-        if let existing = processEnvironment["NODE_OPTIONS"] {
+        let restoreModuleURL = try? createClaudeNodeOptionsRestoreModule()
+        if let existing = processEnvironment["NODE_OPTIONS"] {
             setenv("CMUX_ORIGINAL_NODE_OPTIONS_PRESENT", "1", 1)
             setenv("CMUX_ORIGINAL_NODE_OPTIONS", existing, 1)
         } else {
             setenv("CMUX_ORIGINAL_NODE_OPTIONS_PRESENT", "0", 1)
             unsetenv("CMUX_ORIGINAL_NODE_OPTIONS")
         }
-        setenv(
-            "NODE_OPTIONS",
-            mergedNodeOptions(
-                existing: processEnvironment["NODE_OPTIONS"],
-                restoreModulePath: restoreModuleURL.path
-            ),
-            1
-        )
+        let merged: String
+        if let restoreModuleURL {
+            merged = mergedNodeOptions(
+                existing: processEnvironment["NODE_OPTIONS"],
+                restoreModulePath: restoreModuleURL.path
+            )
+        } else {
+            // Keep heap cap even if restore shim cannot be created.
+            merged = "--max-old-space-size=4096 \(cleanedNodeOptions(processEnvironment["NODE_OPTIONS"]))"
+                .trimmingCharacters(in: .whitespacesAndNewlines)
+        }
+        setenv("NODE_OPTIONS", merged, 1)

Also applies to: 9623-9630

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CLI/cmux.swift` around lines 9611 - 9615, The early return when
createClaudeNodeOptionsRestoreModule() fails causes the OOM guard
(--max-old-space-size=4096) to be skipped; instead of returning after calling
unsetenv("CMUX_ORIGINAL_NODE_OPTIONS_PRESENT") and
unsetenv("CMUX_ORIGINAL_NODE_OPTIONS"), ensure NODE_OPTIONS is still set/updated
with the OOM flag and any necessary environment state is preserved or restored;
modify the failure branch in the createClaudeNodeOptionsRestoreModule() handling
to fall through to the same code path that enforces/merges in
"--max-old-space-size=4096" (the logic that updates NODE_OPTIONS) and apply the
same fix to the other identical block that handles restore-module creation
failure so both paths enforce the OOM guard.

if let existing = processEnvironment["NODE_OPTIONS"] {
setenv("CMUX_ORIGINAL_NODE_OPTIONS_PRESENT", "1", 1)
setenv("CMUX_ORIGINAL_NODE_OPTIONS", existing, 1)
} else {
setenv("CMUX_ORIGINAL_NODE_OPTIONS_PRESENT", "0", 1)
unsetenv("CMUX_ORIGINAL_NODE_OPTIONS")
}
setenv(
"NODE_OPTIONS",
mergedNodeOptions(
existing: processEnvironment["NODE_OPTIONS"],
restoreModulePath: restoreModuleURL.path
),
1
)
}

private func createTmuxCompatShimDirectory(
Expand Down Expand Up @@ -9625,6 +9656,15 @@ struct CMUXCLI {
)
}

private func createClaudeNodeOptionsRestoreModule() throws -> URL {
let root = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent("cmux-claude-node-options", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: nil)
let restoreModuleURL = root.appendingPathComponent("restore-node-options.cjs", isDirectory: false)
try writeShimIfChanged(Self.claudeNodeOptionsRestoreModule, to: restoreModuleURL)
return restoreModuleURL
}

private func runClaudeTeams(
commandArgs: [String],
socketPath: String,
Expand Down Expand Up @@ -9729,11 +9769,37 @@ struct CMUXCLI {

private func writeShimIfChanged(_ script: String, to url: URL) throws {
let normalized = script.trimmingCharacters(in: .whitespacesAndNewlines)
let fileManager = FileManager.default
let existing = try? String(contentsOf: url, encoding: .utf8)
if existing?.trimmingCharacters(in: .whitespacesAndNewlines) != normalized {
try script.write(to: url, atomically: false, encoding: .utf8)
guard existing?.trimmingCharacters(in: .whitespacesAndNewlines) != normalized else {
try fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path)
return
}
let directoryURL = url.deletingLastPathComponent()
let tempURL = directoryURL.appendingPathComponent(".\(url.lastPathComponent).\(UUID().uuidString).tmp")
try script.write(to: tempURL, atomically: false, encoding: .utf8)
try fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: tempURL.path)
do {
if fileManager.fileExists(atPath: url.path) {
_ = try fileManager.replaceItemAt(url, withItemAt: tempURL)
} else {
try fileManager.moveItem(at: tempURL, to: url)
}
} catch {
let current = try? String(contentsOf: url, encoding: .utf8)
if current?.trimmingCharacters(in: .whitespacesAndNewlines) == normalized {
try? fileManager.removeItem(at: tempURL)
return
}
if fileManager.fileExists(atPath: url.path) {
do {
_ = try fileManager.replaceItemAt(url, withItemAt: tempURL)
return
} catch {}
}
try? fileManager.removeItem(at: tempURL)
throw error
}
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path)
}

private static let omoPluginName = "oh-my-opencode"
Expand Down Expand Up @@ -11400,7 +11466,7 @@ struct CMUXCLI {

case "notification", "notify":
telemetry.breadcrumb("claude-hook.notification")
var summary = summarizeClaudeHookNotification(rawInput: rawInput)
var summary = summarizeClaudeHookNotification(parsedInput: parsedInput)

let mappedSession = parsedInput.sessionId.flatMap { try? sessionStore.lookup(sessionId: $0) }
let workspaceId = try resolvePreferredWorkspaceIdForClaudeHook(
Expand Down Expand Up @@ -11851,13 +11917,150 @@ struct CMUXCLI {
let data = trimmed.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let object = json as? [String: Any] else {
return ClaudeHookParsedInput(rawInput: rawInput, object: nil, sessionId: nil, cwd: nil, transcriptPath: nil)
let fallback = trimmed.isEmpty ? nil : truncate(
normalizedSingleLine(redactClaudeSensitiveSpans(trimmed)),
maxLength: 180
)
return ClaudeHookParsedInput(object: nil, rawFallback: fallback, sessionId: nil, cwd: nil, transcriptPath: nil)
}

let sessionId = extractClaudeHookSessionId(from: object)
let cwd = extractClaudeHookCWD(from: object)
let transcriptPath = firstString(in: object, keys: ["transcript_path", "transcriptPath"])
return ClaudeHookParsedInput(rawInput: rawInput, object: object, sessionId: sessionId, cwd: cwd, transcriptPath: transcriptPath)
let compactObject = compactClaudeHookObject(object)
return ClaudeHookParsedInput(
object: compactObject,
rawFallback: nil,
sessionId: sessionId,
cwd: cwd,
transcriptPath: transcriptPath
)
}

private func compactClaudeHookObject(_ object: [String: Any]) -> [String: Any] {
var compact: [String: Any] = [:]

for key in [
"tool_name",
"last_assistant_message",
"lastAssistantMessage",
"event",
"event_name",
"hook_event_name",
"type",
"kind",
"notification_type",
"matcher",
"reason",
"message",
"body",
"text",
"prompt",
"error",
"description",
] {
if let value = compactClaudeHookStringValue(
object[key],
maxLength: claudeHookCompactFieldLimit(for: key)
) {
compact[key] = value
}
}
Comment on lines +11943 to +11968

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 last_assistant_message retained without truncation

last_assistant_message / lastAssistantMessage is included in the compacted object as a raw string with no length cap. On long sessions this field can contain the full text of a multi-paragraph assistant turn — potentially several kilobytes — which offsets the memory savings the compact pass was designed to achieve.

All other message-like fields (message, body, text, prompt, description) are short by nature. Only this one is unbounded.

Consider capping it at the same 180-char limit used elsewhere for display purposes:

for key in [
    "tool_name",
    "last_assistant_message",
    "lastAssistantMessage",
    // ...
] {
    if var value = firstString(in: object, keys: [key]) {
        if key == "last_assistant_message" || key == "lastAssistantMessage" {
            value = truncate(normalizedSingleLine(value), maxLength: 180)
        }
        compact[key] = value
    }
}


if let toolInput = object["tool_input"] as? [String: Any] {
var compactToolInput: [String: Any] = [:]
for key in ["file_path", "command", "pattern", "description", "query"] {
if let value = compactClaudeHookToolInputValue(toolInput[key], key: key) {
compactToolInput[key] = value
}
}
if let questions = toolInput["questions"] as? [[String: Any]] {
compactToolInput["questions"] = questions.prefix(1).map { question in
var compactQuestion: [String: Any] = [:]
if let value = compactClaudeHookStringValue(question["question"], maxLength: 180) {
compactQuestion["question"] = value
}
if let value = compactClaudeHookStringValue(question["header"], maxLength: 80) {
compactQuestion["header"] = value
}
if let options = question["options"] as? [[String: Any]] {
let compactOptions: [[String: Any]] = options.compactMap { option in
guard let label = compactClaudeHookStringValue(option["label"], maxLength: 60) else {
return nil
}
return ["label": label] as [String: Any]
}
compactQuestion["options"] = compactOptions
}
return compactQuestion
}
}
if !compactToolInput.isEmpty {
compact["tool_input"] = compactToolInput
}
}

for key in ["notification", "data"] {
guard let nested = object[key] as? [String: Any] else { continue }
var compactNested: [String: Any] = [:]
for nestedKey in ["type", "kind", "reason", "message", "body", "text", "prompt", "error", "description"] {
if let value = compactClaudeHookStringValue(
nested[nestedKey],
maxLength: claudeHookCompactFieldLimit(for: nestedKey)
) {
compactNested[nestedKey] = value
}
}
if !compactNested.isEmpty {
compact[key] = compactNested
}
}

return compact
}

private func claudeHookCompactFieldLimit(for key: String) -> Int {
switch key {
case "tool_name", "event", "event_name", "hook_event_name", "type", "kind", "notification_type", "matcher", "reason":
return 80
case "last_assistant_message", "lastAssistantMessage", "message", "body", "text", "prompt", "error", "description":
return 240
default:
return 160
}
}

private func compactClaudeHookToolInputValue(_ rawValue: Any?, key: String) -> String? {
switch key {
case "file_path":
return compactClaudeHookStringValue(rawValue, maxLength: 240, keepSuffix: true)
case "command":
return compactClaudeHookStringValue(rawValue, maxLength: 120)
case "pattern", "query":
return compactClaudeHookStringValue(rawValue, maxLength: 120)
case "description":
return compactClaudeHookStringValue(rawValue, maxLength: 180)
default:
return compactClaudeHookStringValue(rawValue, maxLength: 160)
}
}

private func compactClaudeHookStringValue(
_ rawValue: Any?,
maxLength: Int,
keepSuffix: Bool = false
) -> String? {
guard let rawString = rawValue as? String else { return nil }
let previewLength = max(maxLength, min(maxLength * 4, 1024))
let preview = keepSuffix
? String(rawString.suffix(previewLength))
: String(rawString.prefix(previewLength))
let normalized = normalizedSingleLine(preview)
guard !normalized.isEmpty else { return nil }
if keepSuffix, normalized.count > maxLength {
return "…" + String(normalized.suffix(maxLength - 1))
}
return truncate(normalized, maxLength: maxLength)
}

private func extractClaudeHookSessionId(from object: [String: Any]) -> String? {
Expand Down Expand Up @@ -11995,19 +12198,14 @@ struct CMUXCLI {
return nil
}

private func summarizeClaudeHookNotification(rawInput: String) -> (subtitle: String, body: String) {
let trimmed = rawInput.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
private func summarizeClaudeHookNotification(parsedInput: ClaudeHookParsedInput) -> (subtitle: String, body: String) {
guard let object = parsedInput.object else {
if let fallback = parsedInput.rawFallback, !fallback.isEmpty {
return classifyClaudeNotification(signal: fallback, message: fallback)
}
return ("Waiting", "Claude is waiting for your input")
}

guard let data = trimmed.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let object = json as? [String: Any] else {
let fallback = truncate(normalizedSingleLine(trimmed), maxLength: 180)
return classifyClaudeNotification(signal: fallback, message: fallback)
}

let nested = (object["notification"] as? [String: Any]) ?? (object["data"] as? [String: Any]) ?? [:]
let signalParts = [
firstString(in: object, keys: ["event", "event_name", "hook_event_name", "type", "kind"]),
Expand All @@ -12018,7 +12216,6 @@ struct CMUXCLI {
firstString(in: object, keys: ["message", "body", "text", "prompt", "error", "description"]),
firstString(in: nested, keys: ["message", "body", "text", "prompt", "error", "description"])
]
let session = firstString(in: object, keys: ["session_id", "sessionId"])
let message = messageCandidates.compactMap { $0 }.first ?? "Claude needs your input"
let normalizedMessage = normalizedSingleLine(message)
let signal = signalParts.compactMap { $0 }.joined(separator: " ")
Expand Down Expand Up @@ -12082,6 +12279,56 @@ struct CMUXCLI {
.replacingOccurrences(of: "|", with: "¦")
}

private func redactClaudeSensitiveSpans(_ value: String) -> String {
let patterns: [(pattern: String, replacement: String)] = [
(#"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}"#, "<email>"),
(#"(?:~|/)[^\s\"']+"#, "<path>"),
(#"\b(?:sk|rk|sess|token|key|secret|api[_-]?key)[A-Za-z0-9._:-]{8,}\b"#, "<token>"),
(#"\b[A-Za-z0-9_-]{24,}\b"#, "<token>")
]
return patterns.reduce(value) { partial, entry in
partial.replacingOccurrences(
of: entry.pattern,
with: entry.replacement,
options: [.regularExpression, .caseInsensitive]
)
}
}

private func mergedNodeOptions(existing: String?, restoreModulePath: String) -> String {
let requireOption = "--require=\(restoreModulePath)"
let memoryOption = "--max-old-space-size=4096"
let cleanedExisting = cleanedNodeOptions(existing)
guard !cleanedExisting.isEmpty else {
return "\(requireOption) \(memoryOption)"
}
return "\(requireOption) \(memoryOption) \(cleanedExisting)"
}

private func cleanedNodeOptions(_ existing: String?) -> String {
let tokens = (existing ?? "")
.split(whereSeparator: \.isWhitespace)
.map(String.init)
guard !tokens.isEmpty else { return "" }

var filtered: [String] = []
var index = 0
while index < tokens.count {
let token = tokens[index]
if token == "--max-old-space-size" {
index += min(2, tokens.count - index)
continue
}
if token.hasPrefix("--max-old-space-size=") {
index += 1
continue
}
filtered.append(token)
index += 1
}
return filtered.joined(separator: " ")
}

// MARK: - Codex hooks

/// The hooks.json content that cmux installs into ~/.codex/.
Expand Down
Loading
Loading