diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index a52d7aa81379..02613081de76 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -1,7 +1,7 @@ # cmux-owned Swift file length budget. # Format: max_linesrelative path # Reduce counts as files shrink. CI fails if tracked files exceed this budget. -34658 CLI/cmux.swift +34447 CLI/cmux.swift 17908 Sources/AppDelegate.swift 16491 Sources/ContentView.swift 14239 Sources/TerminalController.swift @@ -29,7 +29,7 @@ 3926 cmuxTests/TabManagerUnitTests.swift 3896 cmuxTests/WindowAndDragTests.swift 3688 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift -3669 cmuxTests/CLIGenericHookPersistenceTests.swift +3668 cmuxTests/CLIGenericHookPersistenceTests.swift 3397 Sources/CmuxConfig.swift 3364 cmuxTests/TabManagerSessionSnapshotTests.swift 3053 Sources/Update/UpdateTitlebarAccessory.swift diff --git a/CLI/CMUXCLI+PiExtension.swift b/CLI/CMUXCLI+PiExtension.swift new file mode 100644 index 000000000000..9ea3d8d04b6e --- /dev/null +++ b/CLI/CMUXCLI+PiExtension.swift @@ -0,0 +1,114 @@ +import Foundation + +extension CMUXCLI { + private static let piExtensionMarker = "cmux-pi-session-extension-marker" + private static let piExtensionFilename = "cmux-session.ts" + + private func piExtensionURL(for def: AgentHookDef) -> URL { + URL(fileURLWithPath: def.resolvedConfigDir(), isDirectory: true) + .appendingPathComponent("extensions", isDirectory: true) + .appendingPathComponent(Self.piExtensionFilename, isDirectory: false) + } + + private func existingPiExtensionContents(at url: URL, fileManager: FileManager = .default) throws -> String { + guard fileManager.fileExists(atPath: url.path) else { return "" } + do { + return try String(contentsOf: url, encoding: .utf8) + } catch { + let message = String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.error.readFailed", + defaultValue: "Failed to read %@" + ), + url.path + ) + throw CLIError(message: message) + } + } + + func installPiExtensionHooks(_ def: AgentHookDef) throws { + let extensionURL = piExtensionURL(for: def) + let fileManager = FileManager.default + let skipConfirm = ProcessInfo.processInfo.arguments.contains("--yes") + || ProcessInfo.processInfo.arguments.contains("-y") + let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fileManager) + if existing == Self.piExtensionSource { + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.alreadyUpToDate", + defaultValue: "Pi hooks already up to date at %@" + ), + extensionURL.path + )) + return + } + if !existing.isEmpty, !existing.contains(Self.piExtensionMarker) { + throw CLIError(message: String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.error.notCmuxExtension", + defaultValue: "%@ exists and is not a cmux extension; leaving it alone" + ), + extensionURL.path + )) + } + if !skipConfirm { + Self.printInstallPreview( + path: extensionURL.path, + oldContent: existing, + newContent: Self.piExtensionSource, + fallbackContent: Self.piExtensionSource + ) + print(String(localized: "cli.hooks.pi.confirmProceed", defaultValue: "\nProceed? [y/N] "), terminator: "") + guard readLine()?.lowercased().hasPrefix("y") == true else { + print(String(localized: "cli.hooks.pi.aborted", defaultValue: "Aborted.")) + return + } + } + try fileManager.createDirectory( + at: extensionURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.installed", + defaultValue: "Pi hooks installed at %@" + ), + extensionURL.path + )) + } + + func uninstallPiExtensionHooks(_ def: AgentHookDef) throws { + let extensionURL = piExtensionURL(for: def) + let fm = FileManager.default + guard fm.fileExists(atPath: extensionURL.path) else { + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.noneFound", + defaultValue: "No Pi cmux extension found at %@" + ), + extensionURL.path + )) + return + } + let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fm) + guard existing.contains(Self.piExtensionMarker) else { + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.refuseRemoveMissingMarker", + defaultValue: "Refusing to remove %@: missing cmux marker" + ), + extensionURL.path + )) + return + } + try fm.removeItem(at: extensionURL) + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.removed", + defaultValue: "Removed Pi cmux extension from %@" + ), + extensionURL.path + )) + } +} diff --git a/CLI/CMUXCLI+PiExtensionSource.swift b/CLI/CMUXCLI+PiExtensionSource.swift new file mode 100644 index 000000000000..5432d5de2291 --- /dev/null +++ b/CLI/CMUXCLI+PiExtensionSource.swift @@ -0,0 +1,3 @@ +extension CMUXCLI { + static let piExtensionSource = piExtensionSourcePart1 + "\n" + piExtensionSourcePart2 +} diff --git a/CLI/CMUXCLI+PiExtensionSourcePart1.swift b/CLI/CMUXCLI+PiExtensionSourcePart1.swift new file mode 100644 index 000000000000..b169e3d8a468 --- /dev/null +++ b/CLI/CMUXCLI+PiExtensionSourcePart1.swift @@ -0,0 +1,293 @@ +extension CMUXCLI { + static let piExtensionSourcePart1 = #""" +// cmux-pi-session-extension-marker v2 +// Bridges Pi session lifecycle, tool telemetry, notifications, and resume bindings into cmux. +// Installed by `cmux hooks pi install` or `cmux hooks setup`. +// DO NOT EDIT MANUALLY. cmux upgrades this file in place. + +import { spawn, spawnSync } from "node:child_process"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; + +type HookExtra = Record; + +interface SessionState { + nextTurn: number; + activeTurnId?: string; + stopped: boolean; +} + +interface CommandResult { + ok: boolean; + status: number | null; + stdout: string; + stderr: string; + error?: unknown; +} + +const sessionStates = new Map(); + +function firstString(...values: unknown[]): string | null { + for (const value of values) { + if (typeof value === "string" && value.trim().length > 0) return value.trim(); + } + return null; +} + +function objectValue(value: unknown, keys: string[]): unknown { + if (!value || typeof value !== "object") return undefined; + const typed = value as Record; + for (const key of keys) { + if (typed[key] !== undefined && typed[key] !== null) return typed[key]; + } + return undefined; +} + +function resolveExecutable(name: string): string { + const pathEnv = process.env.PATH || ""; + for (const dir of pathEnv.split(path.delimiter)) { + if (!dir) continue; + const candidate = path.join(dir, name); + try { + fs.accessSync(candidate, fs.constants.X_OK); + if (fs.statSync(candidate).isFile()) return candidate; + } catch (_) {} + } + return name; +} + +function looksLikePiExecutable(value: string): boolean { + const base = path.basename(value).toLowerCase(); + return base === "pi" || base === "pi-coding-agent"; +} + +function looksLikePiScript(value: string): boolean { + const normalized = value.replaceAll("\\", "/").toLowerCase(); + const base = path.basename(normalized); + return ( + normalized.includes("/@earendil-works/pi-coding-agent/") || + normalized.includes("/@mariozechner/pi-coding-agent/") || + normalized.includes("/packages/coding-agent/") || + ((base === "cli.js" || base === "cli.ts") && + (normalized.includes("pi-coding-agent") || normalized.includes("coding-agent"))) + ); +} + +function normalizedLaunchArgv(): string[] { + const raw = Array.isArray(process.argv) ? process.argv.map((value) => String(value)) : []; + if (raw.length === 0) return [resolveExecutable("pi")]; + if (looksLikePiExecutable(raw[0])) return raw; + if (raw.length > 1 && looksLikePiScript(raw[1])) { + return [resolveExecutable("pi"), ...raw.slice(2)]; + } + return [resolveExecutable("pi"), ...raw.slice(1)]; +} + +function base64NulSeparated(values: string[]): string { + const bytes: Buffer[] = []; + for (const value of values) { + bytes.push(Buffer.from(String(value), "utf8")); + bytes.push(Buffer.from([0])); + } + return Buffer.concat(bytes).toString("base64"); +} + +function secretLikeEnvKey(key: string): boolean { + return /(TOKEN|SECRET|PASSWORD|PASSWD|API[_-]?KEY|ACCESS[_-]?KEY|PRIVATE[_-]?KEY|CREDENTIAL|AUTHORIZATION|COOKIE)/i.test(key); +} + +function safePiEnvKey(key: string): boolean { + return ( + key === "PI_CODING_AGENT_DIR" || + key === "PI_CONFIG_DIR" || + key === "PI_CODING_AGENT_SESSION_DIR" || + (key.startsWith("PI_CODING_AGENT_") && !secretLikeEnvKey(key)) + ); +} + +function safeNodeEnvKey(key: string): boolean { + return ( + key === "NODE_ENV" || + key === "NODE_OPTIONS" || + key === "NODE_PATH" || + key === "NODE_NO_WARNINGS" || + key === "NODE_EXTRA_CA_CERTS" + ); +} + +function safeCmuxEnvKey(key: string): boolean { + if (key.startsWith("CMUX_TEST_PI_")) return !secretLikeEnvKey(key); + if (key.startsWith("CMUX_AGENT_LAUNCH_")) return !secretLikeEnvKey(key); + if (key === "CMUX_AGENT_HOOK_STATE_DIR") return true; + if (key === "CMUX_PI_CMUX_BIN" || key === "CMUX_PI_HOOKS_DISABLED") return true; + if (key === "CMUX_SURFACE_ID" || key === "CMUX_WORKSPACE_ID" || key === "CMUX_WINDOW_ID") return true; + if (key === "CMUX_PANE_ID" || key === "CMUX_TAB_ID" || key === "CMUX_PANEL_ID") return true; + if (key === "CMUX_SOCKET" || key === "CMUX_SOCKET_PATH") return true; + if (key === "CMUX_BUNDLE_ID" || key === "CMUX_BUNDLED_CLI_PATH") return true; + if (key === "CMUX_CLI_SENTRY_DISABLED" || key === "CMUX_DEBUG_LOG") return true; + return false; +} + +function shouldPreserveEnvKey(key: string): boolean { + if (safeCmuxEnvKey(key)) return true; + if (safePiEnvKey(key)) return true; + if (safeNodeEnvKey(key)) return true; + if (key === "PATH" || key === "HOME" || key === "PWD" || key === "SHELL") return true; + if (key === "USER" || key === "LOGNAME" || key === "TMPDIR" || key === "TZ") return true; + if (key === "LANG" || key.startsWith("LC_")) return true; + if (key === "TERM" || key === "TERM_PROGRAM" || key === "TERM_PROGRAM_VERSION" || key === "COLORTERM") return true; + if (key === "SSH_AUTH_SOCK") return true; + if (key.startsWith("PI_") || key.startsWith("NODE_")) return !secretLikeEnvKey(key); + return false; +} + +function hookEnvironment(cwd: string, includeSocketPassword = false): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(process.env)) { + if (value === undefined) continue; + if (shouldPreserveEnvKey(key)) env[key] = value; + } + // Only cmux CLI children need the socket credential; keep it out of the generic allowlist. + if (includeSocketPassword) { + const socketPassword = process.env.CMUX_SOCKET_PASSWORD; + if (socketPassword) env.CMUX_SOCKET_PASSWORD = socketPassword; + } + if (!env.CMUX_AGENT_LAUNCH_ARGV_B64) { + const argv = normalizedLaunchArgv(); + env.CMUX_AGENT_LAUNCH_KIND = "pi"; + env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("pi"); + env.CMUX_AGENT_LAUNCH_ARGV_B64 = base64NulSeparated(argv); + env.CMUX_AGENT_LAUNCH_CWD = cwd || process.cwd(); + } + return env; +} + +function eventName(subcommand: string): string { + switch (subcommand) { + case "session-start": + return "SessionStart"; + case "prompt-submit": + return "UserPromptSubmit"; + case "stop": + return "Stop"; + case "notification": + return "Notification"; + default: + return subcommand; + } +} + +function textFromContent(content: unknown): string | null { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return null; + const parts: string[] = []; + for (const block of content) { + if (!block || typeof block !== "object") continue; + const typed = block as { type?: unknown; text?: unknown }; + if (typed.type === "text" && typeof typed.text === "string") parts.push(typed.text); + } + return parts.join("\n") || null; +} + +function lastAssistantMessage(event: unknown): string | undefined { + const messagesValue = objectValue(event, ["messages"]); + const messages = Array.isArray(messagesValue) ? messagesValue : []; + for (let index = messages.length - 1; index >= 0; index -= 1) { + const message = messages[index]; + if (!message || typeof message !== "object") continue; + const typed = message as { role?: unknown; content?: unknown }; + if (typed.role !== "assistant") continue; + const text = firstString(textFromContent(typed.content)); + if (text) return text; + } + return undefined; +} + +function sessionIdFrom(ctx: ExtensionContext): string | null { + return firstString(ctx.sessionManager.getSessionId()); +} + +function cwdFrom(ctx: ExtensionContext): string { + return firstString(ctx.cwd, process.cwd()) || process.cwd(); +} + +function stateFor(sessionId: string): SessionState { + let state = sessionStates.get(sessionId); + if (!state) { + state = { nextTurn: 0, stopped: false }; + sessionStates.set(sessionId, state); + } + return state; +} + +function eventTurnId(event: unknown): string | null { + return firstString( + objectValue(event, ["turn_id", "turnId", "turnID"]) + ); +} + +function beginTurn(sessionId: string, event: unknown): string { + const state = stateFor(sessionId); + const turnId = eventTurnId(event) || `${sessionId}:turn-${state.nextTurn + 1}`; + if (!eventTurnId(event)) state.nextTurn += 1; + state.activeTurnId = turnId; + state.stopped = false; + return turnId; +} + +function currentTurnId(sessionId: string, event: unknown): string { + const state = stateFor(sessionId); + const turnId = eventTurnId(event) || state.activeTurnId || `${sessionId}:turn-${state.nextTurn + 1}`; + if (!eventTurnId(event) && !state.activeTurnId) state.nextTurn += 1; + return turnId; +} + +function finishTurn(sessionId: string, event: unknown): string { + const state = stateFor(sessionId); + const turnId = eventTurnId(event) || state.activeTurnId || `${sessionId}:turn-${state.nextTurn + 1}`; + if (!eventTurnId(event) && !state.activeTurnId) state.nextTurn += 1; + state.activeTurnId = undefined; + state.stopped = true; + return turnId; +} + +function warn(ctx: ExtensionContext | null, message: string, details: Record = {}): void { + const payload = { source: "cmux-pi-extension", level: "warning", message, ...details }; + try { + console.warn(JSON.stringify(payload)); + } catch (_) { + console.warn(`[cmux-pi-extension] ${message}`); + } + const ui = (ctx as unknown as { ui?: { notify?: (message: string, type?: string) => void } } | null)?.ui; + try { + ui?.notify?.("cmux Pi integration warning - check the terminal for details", "warning"); + } catch (_) {} +} + +function cmuxExecutable(): string { + return process.env.CMUX_PI_CMUX_BIN || "cmux"; +} + +function runCmux(args: string[], cwd: string, input?: string): CommandResult { + try { + const result = spawnSync(cmuxExecutable(), args, { + input, + encoding: "utf8", + env: hookEnvironment(cwd, true), + stdio: ["pipe", "pipe", "pipe"], + timeout: 5000, + }); + const status = typeof result.status === "number" ? result.status : null; + return { + ok: status === 0 && !result.error, + status, + stdout: typeof result.stdout === "string" ? result.stdout : "", + stderr: typeof result.stderr === "string" ? result.stderr : "", + error: result.error, + }; + } catch (error) { + return { ok: false, status: null, stdout: "", stderr: "", error }; + } +"""# +} diff --git a/CLI/CMUXCLI+PiExtensionSourcePart2.swift b/CLI/CMUXCLI+PiExtensionSourcePart2.swift new file mode 100644 index 000000000000..45f274d2f62e --- /dev/null +++ b/CLI/CMUXCLI+PiExtensionSourcePart2.swift @@ -0,0 +1,288 @@ +extension CMUXCLI { + static let piExtensionSourcePart2 = #""" +} + +function sendHook(subcommand: string, ctx: ExtensionContext, extra: HookExtra = {}): boolean { + if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return true; + if (!process.env.CMUX_SURFACE_ID) return true; + + const sessionId = sessionIdFrom(ctx); + if (!sessionId) return true; + + const cwd = cwdFrom(ctx); + const payload: HookExtra = { + session_id: sessionId, + cwd, + hook_event_name: eventName(subcommand), + event: eventName(subcommand), + ...extra, + }; + const result = runCmux(["hooks", "pi", subcommand], cwd, JSON.stringify(payload)); + if (!result.ok) { + warn(ctx, "cmux hook command failed", { + subcommand, + status: result.status, + stderr_available: result.stderr.trim().length > 0, + error_available: result.error !== undefined, + }); + } + return result.ok; +} + +function surfaceTargetArgs(): string[] | null { + const surfaceId = firstString(process.env.CMUX_SURFACE_ID); + if (!surfaceId) return null; + const args: string[] = []; + const workspaceId = firstString(process.env.CMUX_WORKSPACE_ID); + if (workspaceId) args.push("--workspace", workspaceId); + args.push("--surface", surfaceId); + return args; +} + +function parseJSONOutput(result: CommandResult): Record | null { + if (!result.ok) return null; + try { + const parsed = JSON.parse(result.stdout); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record : null; + } catch (_) { + return null; + } +} + +function resumeBindingMatches(payload: Record | null, sessionId: string): boolean { + const binding = payload?.resume_binding; + if (!binding || typeof binding !== "object") return false; + const typed = binding as Record; + return firstString(typed.kind) === "pi" && + firstString(typed.checkpoint_id, typed.checkpointId) === sessionId; +} + +const piOptionsWithValue = new Set([ + "--model", + "-m", + "--thinking", + "--provider", + "--extension", + "-e", + "--skill", + "--mcp-config", + "--permission-mode", + "--session-dir", + "--config", + "--profile", + "--system-prompt", + "--append-system-prompt", + "--cwd", + "--dir", + "--trust", + "--sandbox", +]); + +const piOptionsWithoutValue = new Set([ + "--no-color", + "--dangerously-skip-permissions", + "--yolo", +]); + +const piSelectorsToDrop = new Set([ + "--session", + "-s", + "--resume", + "--fork", + "--api-key", + "--prompt", + "--print", +]); + +function sanitizedResumeArgv(sessionId: string): string[] { + const raw = normalizedLaunchArgv(); + const executable = raw[0] || resolveExecutable("pi"); + const out = [executable, "--session", sessionId]; + for (let index = 1; index < raw.length; index += 1) { + const arg = raw[index]; + if (!arg) continue; + if (piSelectorsToDrop.has(arg)) { + if (index + 1 < raw.length && !raw[index + 1].startsWith("-")) index += 1; + continue; + } + if ( + arg.startsWith("--session=") || + arg.startsWith("--resume=") || + arg.startsWith("--fork=") || + arg.startsWith("--api-key=") || + arg.startsWith("--prompt=") + ) { + continue; + } + if (piOptionsWithValue.has(arg)) { + out.push(arg); + if (index + 1 < raw.length) { + out.push(raw[index + 1]); + index += 1; + } + continue; + } + if ([...piOptionsWithValue].some((option) => arg.startsWith(`${option}=`)) || piOptionsWithoutValue.has(arg)) { + out.push(arg); + } + } + return out; +} + +function ensureResumeBinding(ctx: ExtensionContext, sessionId: string, cwd: string): void { + if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return; + const target = surfaceTargetArgs(); + if (!target) return; + + const resumeArgv = sanitizedResumeArgv(sessionId); + const set = runCmux([ + "--json", + "surface", + "resume", + "set", + ...target, + "--name", + "Pi", + "--kind", + "pi", + "--checkpoint-id", + sessionId, + "--source", + "agent-hook", + "--cwd", + cwd, + "--", + ...resumeArgv, + ], cwd); + if (!set.ok) { + warn(ctx, "failed to set Pi resume binding", { + status: set.status, + stderr_available: set.stderr.trim().length > 0, + error_available: set.error !== undefined, + }); + return; + } + + const verified = parseJSONOutput(runCmux(["--json", "surface", "resume", "get", ...target], cwd)); + if (!resumeBindingMatches(verified, sessionId)) { + warn(ctx, "Pi resume binding did not verify after write", { session_id: sessionId }); + } +} + +function clearResumeBinding(ctx: ExtensionContext, sessionId: string, cwd: string): boolean { + if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return true; + const target = surfaceTargetArgs(); + if (!target) return true; + const result = runCmux([ + "--json", + "surface", + "resume", + "clear", + ...target, + "--checkpoint-id", + sessionId, + "--source", + "agent-hook", + ], cwd); + if (!result.ok) { + warn(ctx, "failed to clear Pi resume binding", { + status: result.status, + stderr_available: result.stderr.trim().length > 0, + error_available: result.error !== undefined, + }); + } + return result.ok; +} + +function sendFeed(eventName: "PreToolUse" | "PostToolUse", ctx: ExtensionContext, event: unknown, extra: HookExtra = {}): void { + if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return; + if (!process.env.CMUX_SURFACE_ID) return; + const sessionId = sessionIdFrom(ctx); + if (!sessionId) return; + const cwd = cwdFrom(ctx); + const payload: HookExtra = { + session_id: sessionId, + cwd, + hook_event_name: eventName, + event: eventName, + turn_id: currentTurnId(sessionId, event), + tool_call_id: firstString(objectValue(event, ["toolCallId", "tool_call_id", "id"])), + tool_name: firstString(objectValue(event, ["toolName", "tool_name", "name"])), + tool_input: objectValue(event, ["args", "input"]), + ...extra, + }; + try { + const child = spawn(cmuxExecutable(), ["hooks", "feed", "--source", "pi", "--event", eventName], { + env: hookEnvironment(cwd, true), + stdio: ["pipe", "ignore", "ignore"], + detached: true, + }); + child.on("error", () => {}); + child.stdin.on("error", () => {}); + child.stdin.end(JSON.stringify(payload)); + child.unref(); + } catch (_) {} +} + +export default function cmuxPiSessionExtension(pi: ExtensionAPI) { + pi.on("session_start", async (_event, ctx) => { + const sessionId = sessionIdFrom(ctx); + const cwd = cwdFrom(ctx); + if (sessionId) stateFor(sessionId).stopped = false; + const ok = sendHook("session-start", ctx); + if (ok && sessionId) ensureResumeBinding(ctx, sessionId, cwd); + }); + + pi.on("before_agent_start", async (event, ctx) => { + const sessionId = sessionIdFrom(ctx); + const turnId = sessionId ? beginTurn(sessionId, event) : undefined; + sendHook("prompt-submit", ctx, { prompt: event.prompt, turn_id: turnId }); + }); + + pi.on("tool_execution_start", async (event, ctx) => { + sendFeed("PreToolUse", ctx, event); + }); + + pi.on("tool_execution_end", async (event, ctx) => { + sendFeed("PostToolUse", ctx, event, { + tool_result: objectValue(event, ["result", "details", "content"]), + is_error: objectValue(event, ["isError", "is_error"]), + }); + }); + + pi.on("agent_end", async (event, ctx) => { + const sessionId = sessionIdFrom(ctx); + const turnId = sessionId ? finishTurn(sessionId, event) : undefined; + const message = lastAssistantMessage(event); + const notificationRouted = sendHook("notification", ctx, { + message: message || "Task completed", + turn_id: turnId, + notification: { + type: firstString(objectValue(event, ["stopReason", "reason", "terminationReason"])) || "completed", + }, + }); + const stopPayload: HookExtra = { + last_assistant_message: message, + turn_id: turnId, + }; + if (notificationRouted) stopPayload.cmux_notification_routed = true; + sendHook("stop", ctx, stopPayload); + }); + + pi.on("session_shutdown", async (event, ctx) => { + const sessionId = sessionIdFrom(ctx); + if (!sessionId) return; + const state = stateFor(sessionId); + const cwd = cwdFrom(ctx); + if (!state.stopped) { + const turnId = finishTurn(sessionId, event); + sendHook("stop", ctx, { + turn_id: turnId, + terminationReason: firstString(objectValue(event, ["reason"])) || "session_shutdown", + }); + } + if (clearResumeBinding(ctx, sessionId, cwd)) sessionStates.delete(sessionId); + }); +} +"""# +} diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 6f908e970c56..d5656f250a24 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -27719,221 +27719,6 @@ export default CMUXSessionRestore; print("Removed OpenCode cmux plugin from \(pluginURL.path)") } - private static let piExtensionMarker = "cmux-pi-session-extension-marker" - private static let piExtensionFilename = "cmux-session.ts" - private static let piExtensionSource = #""" -// cmux-pi-session-extension-marker v1 -// Bridges Pi session lifecycle events into cmux's restorable session store. -// Installed by `cmux hooks pi install` or `cmux hooks setup`. -// DO NOT EDIT MANUALLY. cmux upgrades this file in place. - -import { spawnSync } from "node:child_process"; -import * as fs from "node:fs"; -import * as path from "node:path"; -import type { AgentEndEvent, ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent"; - -function firstString(...values: unknown[]): string | null { - for (const value of values) { - if (typeof value === "string" && value.trim().length > 0) return value.trim(); - } - return null; -} - -function resolveExecutable(name: string): string { - const pathEnv = process.env.PATH || ""; - for (const dir of pathEnv.split(path.delimiter)) { - if (!dir) continue; - const candidate = path.join(dir, name); - try { - fs.accessSync(candidate, fs.constants.X_OK); - return candidate; - } catch (_) {} - } - return name; -} - -function looksLikePiExecutable(value: string): boolean { - const base = path.basename(value).toLowerCase(); - return base === "pi" || base === "pi-coding-agent"; -} - -function looksLikePiScript(value: string): boolean { - const normalized = value.replaceAll("\\", "/"); - const base = path.basename(normalized).toLowerCase(); - return ( - normalized.includes("/@mariozechner/pi-coding-agent/") || - normalized.includes("/packages/coding-agent/") || - (base === "cli.js" && normalized.includes("pi-coding-agent")) || - (base === "cli.ts" && normalized.includes("coding-agent")) - ); -} - -function normalizedLaunchArgv(): string[] { - const raw = Array.isArray(process.argv) ? process.argv.map((value) => String(value)) : []; - if (raw.length === 0) return [resolveExecutable("pi")]; - if (looksLikePiExecutable(raw[0])) return raw; - if (raw.length > 1 && looksLikePiScript(raw[1])) { - return [resolveExecutable("pi"), ...raw.slice(2)]; - } - return [resolveExecutable("pi"), ...raw.slice(1)]; -} - -function base64NulSeparated(values: string[]): string { - const bytes: Buffer[] = []; - for (const value of values) { - bytes.push(Buffer.from(String(value), "utf8")); - bytes.push(Buffer.from([0])); - } - return Buffer.concat(bytes).toString("base64"); -} - -function hookEnvironment(cwd: string): NodeJS.ProcessEnv { - const env: NodeJS.ProcessEnv = { ...process.env }; - delete env.AMP_API_KEY; - if (!env.CMUX_AGENT_LAUNCH_ARGV_B64) { - const argv = normalizedLaunchArgv(); - env.CMUX_AGENT_LAUNCH_KIND = "pi"; - env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("pi"); - env.CMUX_AGENT_LAUNCH_ARGV_B64 = base64NulSeparated(argv); - env.CMUX_AGENT_LAUNCH_CWD = cwd || process.cwd(); - } - return env; -} - -function eventName(subcommand: string): string { - switch (subcommand) { - case "session-start": - return "SessionStart"; - case "prompt-submit": - return "UserPromptSubmit"; - case "stop": - return "Stop"; - default: - return subcommand; - } -} - -function textFromContent(content: unknown): string | null { - if (typeof content === "string") return content; - if (!Array.isArray(content)) return null; - const parts: string[] = []; - for (const block of content) { - if (!block || typeof block !== "object") continue; - const typed = block as { type?: unknown; text?: unknown }; - if (typed.type === "text" && typeof typed.text === "string") parts.push(typed.text); - } - return parts.join("\n") || null; -} - -function lastAssistantMessage(event: AgentEndEvent): string | undefined { - for (let index = event.messages.length - 1; index >= 0; index -= 1) { - const message = event.messages[index]; - if (!message || typeof message !== "object") continue; - const typed = message as { role?: unknown; content?: unknown }; - if (typed.role !== "assistant") continue; - const text = firstString(textFromContent(typed.content)); - if (text) return text; - } - return undefined; -} - -function sendHook(subcommand: string, ctx: ExtensionContext, extra: Record = {}): void { - if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return; - if (!process.env.CMUX_SURFACE_ID) return; - - const sessionId = firstString(ctx.sessionManager.getSessionId()); - if (!sessionId) return; - - const cwd = firstString(ctx.cwd, process.cwd()) || process.cwd(); - const payload: Record = { - session_id: sessionId, - cwd, - hook_event_name: eventName(subcommand), - event: eventName(subcommand), - ...extra, - }; - const cmux = process.env.CMUX_PI_CMUX_BIN || "cmux"; - try { - spawnSync(cmux, ["hooks", "pi", subcommand], { - input: JSON.stringify(payload), - encoding: "utf8", - env: hookEnvironment(cwd), - stdio: ["pipe", "ignore", "ignore"], - timeout: 5000, - }); - } catch (_) {} -} - -export default function cmuxPiSessionExtension(pi: ExtensionAPI) { - pi.on("session_start", async (_event, ctx) => { - sendHook("session-start", ctx); - }); - - pi.on("before_agent_start", async (event, ctx) => { - sendHook("prompt-submit", ctx, { prompt: event.prompt }); - }); - - pi.on("agent_end", async (event, ctx) => { - sendHook("stop", ctx, { last_assistant_message: lastAssistantMessage(event) }); - }); -} -"""# - - private func piExtensionURL(for def: AgentHookDef) -> URL { - URL(fileURLWithPath: def.resolvedConfigDir(), isDirectory: true) - .appendingPathComponent("extensions", isDirectory: true) - .appendingPathComponent(Self.piExtensionFilename, isDirectory: false) - } - - private func installPiExtensionHooks(_ def: AgentHookDef) throws { - let extensionURL = piExtensionURL(for: def) - let skipConfirm = ProcessInfo.processInfo.arguments.contains("--yes") - || ProcessInfo.processInfo.arguments.contains("-y") - let existing = (try? String(contentsOf: extensionURL, encoding: .utf8)) ?? "" - if existing == Self.piExtensionSource { - print("Pi hooks already up to date at \(extensionURL.path)") - return - } - if !existing.isEmpty, !existing.contains(Self.piExtensionMarker) { - throw CLIError(message: "\(extensionURL.path) exists and is not a cmux extension; leaving it alone") - } - if !skipConfirm { - Self.printInstallPreview( - path: extensionURL.path, - oldContent: existing, - newContent: Self.piExtensionSource, - fallbackContent: Self.piExtensionSource - ) - print("\nProceed? [y/N] ", terminator: "") - guard readLine()?.lowercased().hasPrefix("y") == true else { - print("Aborted.") - return - } - } - try FileManager.default.createDirectory( - at: extensionURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) - print("Pi hooks installed at \(extensionURL.path)") - } - - private func uninstallPiExtensionHooks(_ def: AgentHookDef) throws { - let extensionURL = piExtensionURL(for: def) - let fm = FileManager.default - guard fm.fileExists(atPath: extensionURL.path) else { - print("No Pi cmux extension found at \(extensionURL.path)") - return - } - let existing = (try? String(contentsOf: extensionURL, encoding: .utf8)) ?? "" - guard existing.contains(Self.piExtensionMarker) else { - print("Refusing to remove \(extensionURL.path): missing cmux marker") - return - } - try fm.removeItem(at: extensionURL) - print("Removed Pi cmux extension from \(extensionURL.path)") - } - private func installRovoDevHooks(_ def: AgentHookDef) throws { let fm = FileManager.default let configDir = def.resolvedConfigDir() @@ -30520,7 +30305,11 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { } let notificationFingerprint = notificationDedupeFingerprint(status: stopNotificationStatus) - let shouldPublishStopNotification = def.publishesStopNotification && (!antigravityHasActiveBackgroundWork || stopNotificationStatus == .error) + let stopNotificationAlreadyRouted = (input.rawObject?["cmux_notification_routed"] as? Bool) == true + || (input.object?["cmux_notification_routed"] as? Bool) == true + let shouldPublishStopNotification = def.publishesStopNotification + && !stopNotificationAlreadyRouted + && (!antigravityHasActiveBackgroundWork || stopNotificationStatus == .error) let hasGrokTranscriptContext = def.name == "grok" && normalizedHookValue(cwd) != nil let shouldPublishGrokStopFallbackNotification = def.name == "grok" && stopNotificationStatus == .idle diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index e1e5e9711c8b..52d8f6fb73b6 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -33342,6 +33342,1131 @@ } } }, + "cli.hooks.pi.aborted": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "أُلغيَت العملية." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Prekinuto." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Afbrudt." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Abgebrochen." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Aborted." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Operación cancelada." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Opération annulée." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Operazione annullata." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "中止しました。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បានបោះបង់។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "중단했습니다." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Avbrutt." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Przerwano." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Abortado." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Операция прервана." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ยกเลิกแล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "İptal edildi." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Операцію скасовано." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已中止。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已中止。" + } + } + } + }, + "cli.hooks.pi.alreadyUpToDate": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "خطافات Pi محدَّثة بالفعل في %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Pi hookovi su već ažurirani u %@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Pi-hooks er allerede opdaterede i %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Pi-Hooks sind in %@ bereits auf dem neuesten Stand" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Pi hooks already up to date at %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Los hooks de Pi ya están actualizados en %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les hooks Pi sont déjà à jour dans %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Gli hook di Pi sono già aggiornati in %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ の Pi フックはすでに最新です" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "hooks របស់ Pi នៅ %@ ទាន់សម័យរួចហើយ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@의 Pi 훅은 이미 최신 상태입니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Pi-hooks er allerede oppdatert i %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Hooki Pi są już aktualne w %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Os hooks do Pi já estão atualizados em %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Хуки Pi в %@ уже актуальны" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ฮุก Pi ที่ %@ เป็นเวอร์ชันล่าสุดอยู่แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Pi kancaları %@ konumunda zaten güncel" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Хуки Pi у %@ вже актуальні" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "%@ 中的 Pi hooks 已是最新" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "%@ 中的 Pi hooks 已是最新" + } + } + } + }, + "cli.hooks.pi.confirmProceed": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "\nهل تريد المتابعة؟ [y/N] " + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "\nNastaviti? [y/N] " + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "\nFortsæt? [y/N] " + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "\nFortfahren? [y/N] " + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "\nProceed? [y/N] " + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "\n¿Continuar? [y/N] " + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "\nContinuer ? [y/N] " + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "\nProcedere? [y/N] " + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "\n続行しますか? [y/N] " + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "\nបន្តឬ? [y/N] " + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "\n계속하시겠습니까? [y/N] " + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "\nFortsette? [y/N] " + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "\nKontynuować? [y/N] " + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "\nProsseguir? [y/N] " + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "\nПродолжить? [y/N] " + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "\nดำเนินการต่อหรือไม่? [y/N] " + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "\nDevam edilsin mi? [y/N] " + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "\nПродовжити? [y/N] " + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "\n是否继续? [y/N] " + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "\n是否繼續? [y/N] " + } + } + } + }, + "cli.hooks.pi.error.notCmuxExtension": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "%@ موجود وليس امتداد cmux؛ سيتم تركه كما هو" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "%@ postoji i nije cmux ekstenzija; ostavljam ga netaknutim" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "%@ findes og er ikke en cmux-udvidelse; lader den være" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%@ existiert und ist keine cmux-Erweiterung; wird unverändert belassen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ exists and is not a cmux extension; leaving it alone" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%@ existe y no es una extensión de cmux; se dejará intacto" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ existe et n’est pas une extension cmux ; aucun changement n’y sera apporté" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "%@ esiste e non è un'estensione cmux; verrà lasciato invariato" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ は存在しますが cmux 拡張ではありません。そのままにします" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "%@ មានរួចហើយ ហើយមិនមែនជា​ផ្នែកបន្ថែម cmux ទេ; ទុកវាដូចដើម" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@이(가) 존재하지만 cmux 확장이 아니므로 그대로 둡니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "%@ finnes og er ikke en cmux-utvidelse; lar den være i fred" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "%@ istnieje i nie jest rozszerzeniem cmux; pozostawiam bez zmian" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%@ existe e não é uma extensão do cmux; será deixado como está" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "%@ существует и не является расширением cmux; оставляем без изменений" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "%@ มีอยู่แล้วและไม่ใช่ส่วนขยาย cmux; จะปล่อยไว้ตามเดิม" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "%@ mevcut ve bir cmux uzantısı değil; olduğu gibi bırakılıyor" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "%@ існує і не є розширенням cmux; залишаємо без змін" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "%@ 已存在且不是 cmux 扩展;将保持不变" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "%@ 已存在且不是 cmux 擴充功能;將維持原樣" + } + } + } + }, + "cli.hooks.pi.error.readFailed": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "فشل في قراءة %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Čitanje %@ nije uspjelo" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Kunne ikke læse %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Fehler beim Lesen von %@" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Failed to read %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo leer %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Échec de la lecture de %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Impossibile leggere %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ の読み取りに失敗しました" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "អាន %@ មិនបានសម្រេច" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@을(를) 읽지 못했습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Klarte ikke å lese %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Nie udało się odczytać %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Falha ao ler %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Не удалось прочитать %@" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "อ่าน %@ ไม่สำเร็จ" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "%@ okunamadı" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Не вдалося прочитати %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "读取 %@ 失败" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "讀取 %@ 失敗" + } + } + } + }, + "cli.hooks.pi.installed": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم تثبيت خطافات Pi في %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Pi hookovi su instalirani u %@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Pi-hooks er installeret i %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Pi-Hooks wurden in %@ installiert" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Pi hooks installed at %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Hooks de Pi instalados en %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Hooks Pi installés dans %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Hook di Pi installati in %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Pi フックを %@ にインストールしました" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បានដំឡើង hooks របស់ Pi នៅ %@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@에 Pi 훅을 설치했습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Pi-hooks er installert i %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Zainstalowano hooki Pi w %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Hooks do Pi instalados em %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Хуки Pi установлены в %@" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ติดตั้งฮุก Pi ที่ %@ แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Pi kancaları %@ konumuna kuruldu" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Хуки Pi встановлено в %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已在 %@ 安装 Pi hooks" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已在 %@ 安裝 Pi hooks" + } + } + } + }, + "cli.hooks.pi.noneFound": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "لم يتم العثور على امتداد Pi cmux في %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Nijedna Pi cmux ekstenzija nije pronađena u %@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Ingen Pi cmux-udvidelse fundet i %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Keine Pi-cmux-Erweiterung in %@ gefunden" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No Pi cmux extension found at %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se encontró ninguna extensión Pi cmux en %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune extension Pi cmux trouvée dans %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nessuna estensione Pi cmux trovata in %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ に Pi cmux 拡張が見つかりません" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "រកមិនឃើញ​ផ្នែកបន្ថែម Pi cmux នៅ %@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@에서 Pi cmux 확장을 찾을 수 없습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Fant ingen Pi cmux-utvidelse i %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Nie znaleziono rozszerzenia Pi cmux w %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhuma extensão Pi cmux encontrada em %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение Pi cmux в %@ не найдено" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ไม่พบส่วนขยาย Pi cmux ที่ %@" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "%@ konumunda Pi cmux uzantısı bulunamadı" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення Pi cmux у %@ не знайдено" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "未在 %@ 找到 Pi cmux 扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "未在 %@ 找到 Pi cmux 擴充功能" + } + } + } + }, + "cli.hooks.pi.refuseRemoveMissingMarker": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم رفض إزالة %@: علامة cmux مفقودة" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Odbijam uklanjanje %@: nedostaje cmux oznaka" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Nægter at fjerne %@: manglende cmux-markør" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%@ wird nicht entfernt: cmux-Markierung fehlt" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Refusing to remove %@: missing cmux marker" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Se rechaza eliminar %@: falta el marcador de cmux" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Suppression de %@ refusée : marqueur cmux manquant" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Rimozione di %@ rifiutata: marcatore cmux mancante" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ の削除を拒否しました: cmux マーカーがありません" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បដិសេធមិនលុប %@៖ បាត់សញ្ញាសម្គាល់ cmux" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@ 삭제를 거부합니다: cmux 마커가 없습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Nekter å fjerne %@: manglende cmux-markør" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Odmowa usunięcia %@: brak znacznika cmux" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Recusando remover %@: marcador do cmux ausente" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Отказ в удалении %@: отсутствует маркер cmux" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ปฏิเสธที่จะลบ %@: ไม่มีเครื่องหมาย cmux" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "%@ kaldırılmayı reddediliyor: cmux işareti eksik" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Відмовлено у видаленні %@: відсутній маркер cmux" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "拒绝移除 %@:缺少 cmux 标记" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "拒絕移除 %@:缺少 cmux 標記" + } + } + } + }, + "cli.hooks.pi.removed": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تمت إزالة امتداد Pi cmux من %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Pi cmux ekstenzija je uklonjena iz %@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Pi cmux-udvidelse blev fjernet fra %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Pi-cmux-Erweiterung aus %@ entfernt" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Removed Pi cmux extension from %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Se eliminó la extensión Pi cmux de %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Extension Pi cmux supprimée de %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Estensione Pi cmux rimossa da %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ から Pi cmux 拡張を削除しました" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បានលុប​ផ្នែកបន្ថែម Pi cmux ចេញពី %@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@에서 Pi cmux 확장을 제거했습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Fjernet Pi cmux-utvidelse fra %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Usunięto rozszerzenie Pi cmux z %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensão Pi cmux removida de %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение Pi cmux удалено из %@" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ลบส่วนขยาย Pi cmux ออกจาก %@ แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Pi cmux uzantısı %@ konumundan kaldırıldı" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення Pi cmux видалено з %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已从 %@ 移除 Pi cmux 扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已從 %@ 移除 Pi cmux 擴充功能" + } + } + } + }, "cli.install.adminRequired": { "extractionState": "manual", "localizations": { diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 4faa09671967..9ef84d50d489 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -275,6 +275,10 @@ B9000071A1B2C3D4E5F60719 /* CMUXCLI+Memory.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000070A1B2C3D4E5F60719 /* CMUXCLI+Memory.swift */; }; D7AB0000000000000000000D /* CMUXCLI+MoveTabToNewWorkspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB0000000000000000000E /* CMUXCLI+MoveTabToNewWorkspace.swift */; }; B9000072A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000073A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift */; }; + C05555010000000000000001 /* CMUXCLI+PiExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05555010000000000000002 /* CMUXCLI+PiExtension.swift */; }; + C05555010000000000000003 /* CMUXCLI+PiExtensionSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05555010000000000000004 /* CMUXCLI+PiExtensionSource.swift */; }; + C05555010000000000000005 /* CMUXCLI+PiExtensionSourcePart1.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05555010000000000000006 /* CMUXCLI+PiExtensionSourcePart1.swift */; }; + C05555010000000000000007 /* CMUXCLI+PiExtensionSourcePart2.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05555010000000000000008 /* CMUXCLI+PiExtensionSourcePart2.swift */; }; B9000054A1B2C3D4E5F60719 /* CMUXCLI+Process.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000055A1B2C3D4E5F60719 /* CMUXCLI+Process.swift */; }; REE0CA0000000000000000C2 /* CMUXCLI+Remotes.swift in Sources */ = {isa = PBXBuildFile; fileRef = REE0CA0000000000000000C1 /* CMUXCLI+Remotes.swift */; }; C0DE64950000000000000001 /* CMUXCLI+SessionsList.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE64950000000000000002 /* CMUXCLI+SessionsList.swift */; }; @@ -1513,6 +1517,10 @@ B9000070A1B2C3D4E5F60719 /* CMUXCLI+Memory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Memory.swift"; sourceTree = ""; }; D7AB0000000000000000000E /* CMUXCLI+MoveTabToNewWorkspace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+MoveTabToNewWorkspace.swift"; sourceTree = ""; }; B9000073A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+OmpExtension.swift"; sourceTree = ""; }; + C05555010000000000000002 /* CMUXCLI+PiExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+PiExtension.swift"; sourceTree = ""; }; + C05555010000000000000004 /* CMUXCLI+PiExtensionSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+PiExtensionSource.swift"; sourceTree = ""; }; + C05555010000000000000006 /* CMUXCLI+PiExtensionSourcePart1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+PiExtensionSourcePart1.swift"; sourceTree = ""; }; + C05555010000000000000008 /* CMUXCLI+PiExtensionSourcePart2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+PiExtensionSourcePart2.swift"; sourceTree = ""; }; B9000055A1B2C3D4E5F60719 /* CMUXCLI+Process.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Process.swift"; sourceTree = ""; }; REE0CA0000000000000000C1 /* CMUXCLI+Remotes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Remotes.swift"; sourceTree = ""; }; C0DE64950000000000000002 /* CMUXCLI+SessionsList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+SessionsList.swift"; sourceTree = ""; }; @@ -3357,6 +3365,10 @@ B9000069A1B2C3D4E5F60719 /* CMUXCLI+AmpExtension.swift */, C0D3F1F00000000000000102 /* CMUXCLI+CodexFireAndForgetHooks.swift */, B9000073A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift */, + C05555010000000000000002 /* CMUXCLI+PiExtension.swift */, + C05555010000000000000004 /* CMUXCLI+PiExtensionSource.swift */, + C05555010000000000000006 /* CMUXCLI+PiExtensionSourcePart1.swift */, + C05555010000000000000008 /* CMUXCLI+PiExtensionSourcePart2.swift */, B9000070A1B2C3D4E5F60719 /* CMUXCLI+Memory.swift */, B9000031A1B2C3D4E5F60719 /* CMUXCLI+DocsSettings.swift */, B900002DA1B2C3D4E5F60719 /* CMUXCLI+ThemeSupport.swift */, @@ -4840,8 +4852,12 @@ B9000052A1B2C3D4E5F60719 /* CMUXCLI+InstallPreview.swift in Sources */, B9000071A1B2C3D4E5F60719 /* CMUXCLI+Memory.swift in Sources */, D7AB0000000000000000000D /* CMUXCLI+MoveTabToNewWorkspace.swift in Sources */, - B9000072A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift in Sources */, - B9000054A1B2C3D4E5F60719 /* CMUXCLI+Process.swift in Sources */, + B9000072A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift in Sources */, + C05555010000000000000001 /* CMUXCLI+PiExtension.swift in Sources */, + C05555010000000000000003 /* CMUXCLI+PiExtensionSource.swift in Sources */, + C05555010000000000000005 /* CMUXCLI+PiExtensionSourcePart1.swift in Sources */, + C05555010000000000000007 /* CMUXCLI+PiExtensionSourcePart2.swift in Sources */, + B9000054A1B2C3D4E5F60719 /* CMUXCLI+Process.swift in Sources */, REE0CA0000000000000000C2 /* CMUXCLI+Remotes.swift in Sources */, C0DE64950000000000000001 /* CMUXCLI+SessionsList.swift in Sources */, C12984000000000000000002 /* CMUXCLI+SIGPIPEProbes.swift in Sources */, diff --git a/cmuxTests/CLIGenericHookPersistenceTests.swift b/cmuxTests/CLIGenericHookPersistenceTests.swift index 33af444abcfb..c903975a5ba8 100644 --- a/cmuxTests/CLIGenericHookPersistenceTests.swift +++ b/cmuxTests/CLIGenericHookPersistenceTests.swift @@ -314,32 +314,31 @@ extension CLINotifyProcessIntegrationRegressionTests { "CMUX_CLI_SENTRY_DISABLED": "1", ] - func runAntigravityHook(_ subcommand: String, input: String) -> ProcessRunResult { - let serverHandled = startMockServer(listenerFD: listenerFD, state: state) { line in - guard let payload = self.jsonObject(line) else { - return "OK" - } - guard let id = payload["id"] as? String, let method = payload["method"] as? String else { - return self.malformedRequestResponse(id: payload["id"] as? String, raw: line) - } - switch method { - case "surface.list": - return self.surfaceListResponse(id: id, surfaceId: surfaceId) - case "feed.push": - return self.v2Response(id: id, ok: true, result: [:]) - default: - return self.v2Response(id: id, ok: false, error: ["code": "unrecognized_method", "message": "unexpected method: \(method)"]) - } + startDetachedMockServer(listenerFD: listenerFD, state: state, connectionCount: 128) { line in + guard let payload = self.jsonObject(line) else { + return "OK" } - let result = runProcess( + guard let id = payload["id"] as? String, let method = payload["method"] as? String else { + return self.malformedRequestResponse(id: payload["id"] as? String, raw: line) + } + switch method { + case "surface.list": + return self.surfaceListResponse(id: id, surfaceId: surfaceId) + case "feed.push": + return self.v2Response(id: id, ok: true, result: [:]) + default: + return self.v2Response(id: id, ok: false, error: ["code": "unrecognized_method", "message": "unexpected method: \(method)"]) + } + } + + func runAntigravityHook(_ subcommand: String, input: String) -> ProcessRunResult { + runProcess( executablePath: cliPath, arguments: ["hooks", "antigravity", subcommand], environment: environment, standardInput: input, timeout: 5 ) - wait(for: [serverHandled], timeout: 5) - return result } let start = runAntigravityHook( @@ -3088,21 +3087,21 @@ extension CLINotifyProcessIntegrationRegressionTests { .compactMap { $0["hooks"] as? [[String: Any]] } .flatMap { $0 } .compactMap { $0["command"] as? String } - + let commandBodies = allCommands + allCommands.compactMap { FileManager.default.fileExists(atPath: $0) ? try? String(contentsOf: URL(fileURLWithPath: $0), encoding: .utf8) : nil } XCTAssertTrue( - allCommands.contains { + commandBodies.contains { $0.contains("CMUX_BUNDLED_CLI_PATH") && $0.contains("\"$cmux_cli\" --socket \"$CMUX_SOCKET_PATH\" hooks codex prompt-submit") }, - "Codex hooks should route through the launching app's bundled CLI, saw \(allCommands)" + "Codex hooks should route through the launching app's bundled CLI, saw \(commandBodies)" ) XCTAssertFalse( - allCommands.contains { $0.contains("command -v cmux >/dev/null 2>&1 && cmux hooks codex") }, - "Codex hooks must not use the reload-global cmux shim directly, saw \(allCommands)" + commandBodies.contains { $0.contains("command -v cmux >/dev/null 2>&1 && cmux hooks codex") }, + "Codex hooks must not use the reload-global cmux shim directly, saw \(commandBodies)" ) XCTAssertFalse( - allCommands.contains { $0 == previousBundledHookCommand }, - "Codex setup should replace bundled-CLI hooks that did not pin CMUX_SOCKET_PATH, saw \(allCommands)" + commandBodies.contains { $0 == previousBundledHookCommand }, + "Codex setup should replace bundled-CLI hooks that did not pin CMUX_SOCKET_PATH, saw \(commandBodies)" ) XCTAssertEqual( allCommands.filter { $0.contains("hooks codex prompt-submit") }.count, @@ -3246,7 +3245,7 @@ extension CLINotifyProcessIntegrationRegressionTests { XCTAssertEqual(params["auto_resume"] as? Bool, true) XCTAssertEqual( params["command"] as? String, - "{ cd -- '\(workspace.path)' 2>/dev/null || [ ! -d '\(workspace.path)' ]; } && '\(scenario.executable)' 'chat' '--resume-id' '\(scenario.sessionId)' '--agent' 'cmux' '--trust-tools' 'fs_read,fs_write'" + "cd -- '\(workspace.path)' 2>/dev/null || [ ! -d '\(workspace.path)' ] && '\(scenario.executable)' 'chat' '--resume-id' '\(scenario.sessionId)' '--agent' 'cmux' '--trust-tools' 'fs_read,fs_write'" ) XCTAssertEqual(params["environment"] as? [String: String], scenario.expectedEnvironment) XCTAssertFalse( diff --git a/cmuxTests/CLINotifyProcessTestSupport.swift b/cmuxTests/CLINotifyProcessTestSupport.swift index c7e4e6002207..128820993c9a 100644 --- a/cmuxTests/CLINotifyProcessTestSupport.swift +++ b/cmuxTests/CLINotifyProcessTestSupport.swift @@ -38,9 +38,7 @@ extension CLINotifyProcessIntegrationRegressionTests { func makeSocketPath(_ name: String) -> String { let shortID = UUID().uuidString.replacingOccurrences(of: "-", with: "").prefix(8) - return URL(fileURLWithPath: NSTemporaryDirectory()) - .appendingPathComponent("cli-\(name.prefix(6))-\(shortID).sock") - .path + return "/tmp/cli-\(name.prefix(3))-\(shortID).sock" } func bindUnixSocket(at path: String) throws -> Int32 { @@ -333,10 +331,18 @@ extension CLINotifyProcessIntegrationRegressionTests { v2Response( id: id, ok: true, - result: ["surfaces": [["id": surfaceId, "ref": "surface:1", "focused": true]]] + result: ["surfaces": [["id": surfaceId, "ref": "surface:1", "index": 1, "focused": true]]] ) } + func processTimeout(_ requested: TimeInterval) -> TimeInterval { + let env = ProcessInfo.processInfo.environment + guard env["GITHUB_ACTIONS"] == "true" || env["CI"] == "true" else { + return requested + } + return max(requested, 20) + } + func jsonObject(_ line: String) -> [String: Any]? { guard let data = line.data(using: .utf8) else { return nil } return try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] @@ -379,13 +385,36 @@ extension CLINotifyProcessIntegrationRegressionTests { try? stdinPipe.fileHandleForWriting.close() } + let outputLock = NSLock() + var stdoutData = Data() + var stderrData = Data() + let outputGroup = DispatchGroup() + + outputGroup.enter() + DispatchQueue.global(qos: .utility).async { + let data = stdoutPipe.fileHandleForReading.readDataToEndOfFile() + outputLock.lock() + stdoutData = data + outputLock.unlock() + outputGroup.leave() + } + + outputGroup.enter() + DispatchQueue.global(qos: .utility).async { + let data = stderrPipe.fileHandleForReading.readDataToEndOfFile() + outputLock.lock() + stderrData = data + outputLock.unlock() + outputGroup.leave() + } + let exitSignal = DispatchSemaphore(value: 0) DispatchQueue.global(qos: .userInitiated).async { process.waitUntilExit() exitSignal.signal() } - let timedOut = exitSignal.wait(timeout: .now() + timeout) == .timedOut + let timedOut = exitSignal.wait(timeout: .now() + processTimeout(timeout)) == .timedOut if timedOut { process.terminate() if exitSignal.wait(timeout: .now() + 1) == .timedOut { @@ -393,9 +422,14 @@ extension CLINotifyProcessIntegrationRegressionTests { _ = exitSignal.wait(timeout: .now() + 1) } } - - let stdout = String(data: stdoutPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" - let stderr = String(data: stderrPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" + _ = outputGroup.wait(timeout: .now() + 2) + + outputLock.lock() + let finalStdoutData = stdoutData + let finalStderrData = stderrData + outputLock.unlock() + let stdout = String(data: finalStdoutData, encoding: .utf8) ?? "" + let stderr = String(data: finalStderrData, encoding: .utf8) ?? "" return ProcessRunResult( status: process.isRunning ? SIGKILL : process.terminationStatus, stdout: stdout, diff --git a/cmuxTests/VMSSHCommandTests.swift b/cmuxTests/VMSSHCommandTests.swift index b4991cf87844..81605dd2c8d4 100644 --- a/cmuxTests/VMSSHCommandTests.swift +++ b/cmuxTests/VMSSHCommandTests.swift @@ -131,6 +131,7 @@ extension CLINotifyProcessIntegrationRegressionTests { let windowID = "22222222-2222-2222-2222-222222222222" let callerWorkspaceID = "33333333-3333-3333-3333-333333333333" let callerSurfaceID = "44444444-4444-4444-4444-444444444444" + let surfaceID = "55555555-5555-5555-5555-555555555555" defer { Darwin.close(listenerFD) @@ -162,6 +163,10 @@ extension CLINotifyProcessIntegrationRegressionTests { "window_id": windowID, ] ) + case "surface.list": + let params = payload["params"] as? [String: Any] ?? [:] + XCTAssertEqual(params["workspace_id"] as? String, workspaceID) + return self.surfaceListResponse(id: id, surfaceId: surfaceID) case "workspace.remote.configure": return self.v2Response( id: id, @@ -175,6 +180,8 @@ extension CLINotifyProcessIntegrationRegressionTests { ], ] ) + case "workspace.close": + return self.v2Response(id: id, ok: true, result: ["workspace_id": workspaceID]) default: return self.v2Response( id: id, @@ -215,7 +222,7 @@ extension CLINotifyProcessIntegrationRegressionTests { } XCTAssertEqual( requests.compactMap { $0["method"] as? String }, - ["window.focus", "workspace.create", "workspace.remote.configure"] + ["window.focus", "workspace.create", "surface.list", "workspace.remote.configure"] ) } diff --git a/docs/agent-hooks.md b/docs/agent-hooks.md index e918800425cb..2d01bbcdc211 100644 --- a/docs/agent-hooks.md +++ b/docs/agent-hooks.md @@ -21,7 +21,7 @@ Supported agent names are `codex`, `grok`, `opencode`, `pi`, `omp`, `amp`, `curs | Codex | `codex` | `~/.codex/hooks.json`, `~/.codex/config.toml` | `codex resume ` | PreToolUse, PermissionRequest telemetry | | Grok | `grok` | `~/.grok/hooks/cmux-session.json` | `grok -r ` | PreToolUse | | OpenCode | `opencode` | `~/.config/opencode/plugins/cmux-session.js`, `~/.config/opencode/plugins/cmux-feed.js` | `opencode --session ` | plugin event bus | -| Pi | `pi` | `~/.pi/agent/extensions/cmux-session.ts` | `pi --session ` | none | +| Pi | `pi` | `~/.pi/agent/extensions/cmux-session.ts` | `pi --session ` | tool_execution_start / tool_execution_end telemetry | | OMP | `omp` | `~/.omp/agent/extensions/cmux-omp-session.ts` or `$PI_CODING_AGENT_DIR/extensions/cmux-omp-session.ts` | `omp --session ` | none | | Amp | `amp` | `~/.config/amp/plugins/cmux-session.ts` | `amp threads continue ` | none | | Cursor CLI | `cursor-agent` | `~/.cursor/hooks.json` | `cursor-agent --resume ` | beforeShellExecution | @@ -158,6 +158,6 @@ Kiro Feed verbosity follows **Settings > Automation > Kiro Notification Level** Run `cmux hooks install --yes` to reinstall one integration. Run `cmux hooks uninstall --yes` before editing generated files by hand. -If Feed shows nothing, confirm the terminal has `CMUX_SURFACE_ID` and the hook file contains a `cmux hooks feed --source ` command or OpenCode feed plugin. Pi, OMP, and Rovo Dev currently provide lifecycle and restore hooks only, so they do not create Feed approval cards. Amp's bundled plugin reports live tab-status updates (idle / thinking / running / reading / done / error / interrupted) and lifecycle restore but does not create Feed approval cards. +If Feed shows nothing, confirm the terminal has `CMUX_SURFACE_ID` and the hook file contains a `cmux hooks feed --source ` command, generated extension bridge, or OpenCode feed plugin. Pi reports non-blocking tool execution telemetry through its generated extension. OMP and Rovo Dev currently provide lifecycle and restore hooks only, so they do not create Feed approval cards. Amp's bundled plugin reports live tab-status updates (idle / thinking / running / reading / done / error / interrupted) and lifecycle restore but does not create Feed approval cards. If relaunch does not resume an agent, check `~/.cmuxterm/-hook-sessions.json` for the saved session and verify the agent's resume command still works outside cmux. diff --git a/docs/feed.md b/docs/feed.md index 43d77f1a87c2..3837b7a291fc 100644 --- a/docs/feed.md +++ b/docs/feed.md @@ -84,7 +84,7 @@ Installs supported agent hooks whose binaries are on `PATH`. See [Agent hook int | CodeBuddy | `~/.codebuddy/settings.json` | PreToolUse | | Factory | `~/.factory/settings.json` | PreToolUse | | Qoder | `~/.qoder/settings.json` | PreToolUse | -| Pi | `~/.pi/agent/extensions/cmux-session.ts` | lifecycle only | +| Pi | `~/.pi/agent/extensions/cmux-session.ts` | tool_execution_start / tool_execution_end telemetry | | OMP | `~/.omp/agent/extensions/cmux-omp-session.ts` or `$PI_CODING_AGENT_DIR/extensions/cmux-omp-session.ts` | lifecycle only | | Rovo Dev | `~/.rovodev/config.yml` | lifecycle only | @@ -99,7 +99,7 @@ cmux hooks uninstall Agents without a binary on `PATH` are skipped at install time, and `cmux hooks setup` prints a summary line naming the ones it skipped. Use `cmux hooks setup --agent ` or `cmux hooks setup ` to install one integration, and `cmux hooks uninstall --agent ` or `cmux hooks uninstall ` to remove one. Rovo Dev accepts either `rovodev` or `rovo`. -Pi, OMP, and Rovo Dev provide lifecycle and session-restore hooks only; they do not install a Feed permission bridge. +Pi provides lifecycle and session-restore hooks plus Feed telemetry for `tool_execution_start` and `tool_execution_end` events. OMP and Rovo Dev provide lifecycle and session-restore hooks only; they do not install a Feed permission bridge. ## Decision semantics diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index 1347ef8caaaa..635e882ae49a 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -6,10 +6,12 @@ from __future__ import annotations import base64 +import json import os import shutil import subprocess import tempfile +import time from pathlib import Path from claude_teams_test_utils import resolve_cmux_cli @@ -20,6 +22,32 @@ def make_executable(path: Path, content: str) -> None: path.chmod(0o755) +def wait_for_text(path: Path, expected_count: int, timeout: float = 5.0) -> str: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if path.exists(): + text = path.read_text(encoding="utf-8") + if len([line for line in text.splitlines() if line.strip()]) >= expected_count: + return text + time.sleep(0.05) + return path.read_text(encoding="utf-8") if path.exists() else "" + + +def payloads_from_log(text: str) -> list[dict[str, object]]: + payloads: list[dict[str, object]] = [] + for raw in text.split("\n---\n"): + raw = raw.strip() + if not raw: + continue + try: + payload = json.loads(raw) + except json.JSONDecodeError: + continue + if isinstance(payload, dict): + payloads.append(payload) + return payloads + + def main() -> int: bun = shutil.which("bun") if bun is None: @@ -62,32 +90,108 @@ def main() -> int: print(f"FAIL: expected cmux marker in {extension_path}") return 1 + if "@earendil-works/pi-coding-agent" not in extension_text: + print("FAIL: generated Pi extension does not import the current Pi package") + return 1 + + bin_dir = root / "bin" + bin_dir.mkdir() + fake_pi = bin_dir / "pi" + make_executable(fake_pi, "#!/usr/bin/env bash\nexit 0\n") + fake_cmux = root / "fake-cmux" fake_args_log = root / "fake-cmux-args.log" fake_stdin_log = root / "fake-cmux-stdin.log" fake_env_log = root / "fake-cmux-env.log" + fake_binding = root / "fake-surface-binding.json" make_executable( fake_cmux, """#!/usr/bin/env bash set -euo pipefail -printf '%s\n' "$*" >> "$FAKE_CMUX_ARGS_LOG" -cat >> "$FAKE_CMUX_STDIN_LOG" -printf '\n---\n' >> "$FAKE_CMUX_STDIN_LOG" +printf '%s\n' "$*" >> "$CMUX_TEST_PI_ARGS_LOG" +payload="$(cat)" +printf '%s' "$payload" >> "$CMUX_TEST_PI_STDIN_LOG" +printf '\n---\n' >> "$CMUX_TEST_PI_STDIN_LOG" { printf 'kind=%s\n' "${CMUX_AGENT_LAUNCH_KIND-}" printf 'cwd=%s\n' "${CMUX_AGENT_LAUNCH_CWD-}" printf 'argv=%s\n' "${CMUX_AGENT_LAUNCH_ARGV_B64-}" -} >> "$FAKE_CMUX_ENV_LOG" + if [ -n "${OPENAI_API_KEY-}" ]; then printf 'OPENAI_API_KEY=present\n'; fi + if [ -n "${ANTHROPIC_AUTH_TOKEN-}" ]; then printf 'ANTHROPIC_AUTH_TOKEN=present\n'; fi + if [ -n "${CUSTOM_PASSWORD-}" ]; then printf 'CUSTOM_PASSWORD=present\n'; fi + if [ -n "${AMP_API_KEY-}" ]; then printf 'AMP_API_KEY=present\n'; fi + if [ -n "${CMUX_LEAK_TOKEN-}" ]; then printf 'CMUX_LEAK_TOKEN=present\n'; fi + if [ -n "${DATABASE_URL-}" ]; then printf 'DATABASE_URL=present\n'; fi + if [ -n "${DB_PASS-}" ]; then printf 'DB_PASS=present\n'; fi + if [ -n "${SENTRY_DSN-}" ]; then printf 'SENTRY_DSN=present\n'; fi + if [ -n "${GH_PAT-}" ]; then printf 'GH_PAT=present\n'; fi + if [ -n "${CLOUDFLARE_AUTH_KEY-}" ]; then printf 'CLOUDFLARE_AUTH_KEY=present\n'; fi + if [ -n "${STRIPE_SK-}" ]; then printf 'STRIPE_SK=present\n'; fi + if [ -n "${SLACK_WEBHOOK_URL-}" ]; then printf 'SLACK_WEBHOOK_URL=present\n'; fi + if [ -n "${CMUX_TEST_PI_TOKEN-}" ]; then printf 'CMUX_TEST_PI_TOKEN=present\n'; fi +} >> "$CMUX_TEST_PI_ENV_LOG" +case "$*" in + *"hooks pi notification"*) + if printf '%s' "$payload" | grep -q 'pi-session-notification-fails'; then + printf 'forced notification failure\n' >&2 + exit 42 + fi + printf '{}\n' + ;; + *"surface resume get"*) + if [ -f "$CMUX_TEST_PI_BINDING_FILE" ]; then + cat "$CMUX_TEST_PI_BINDING_FILE" + else + printf '{"resume_binding":null}\n' + fi + ;; + *"surface resume set"*) + checkpoint_id="" + previous="" + for token in "$@"; do + if [ "$previous" = "--checkpoint-id" ]; then + checkpoint_id="$token" + break + fi + previous="$token" + done + printf '{"resume_binding":{"kind":"pi","checkpoint_id":"%s","source":"agent-hook","command":"pi --session %s"}}\n' "$checkpoint_id" "$checkpoint_id" > "$CMUX_TEST_PI_BINDING_FILE" + printf '{"ok":true}\n' + ;; + *"surface resume clear"*) + rm -f "$CMUX_TEST_PI_BINDING_FILE" + printf '{"ok":true}\n' + ;; + *) + printf '{}\n' + ;; +esac """, ) check_env = env.copy() + check_env["PATH"] = str(bin_dir) + os.pathsep + check_env.get("PATH", "") check_env["CMUX_TEST_PI_EXTENSION_PATH"] = str(extension_path) check_env["CMUX_SURFACE_ID"] = "surface-pi-test" + check_env["CMUX_WORKSPACE_ID"] = "workspace-pi-test" check_env["CMUX_PI_CMUX_BIN"] = str(fake_cmux) - check_env["FAKE_CMUX_ARGS_LOG"] = str(fake_args_log) - check_env["FAKE_CMUX_STDIN_LOG"] = str(fake_stdin_log) - check_env["FAKE_CMUX_ENV_LOG"] = str(fake_env_log) + check_env["CMUX_TEST_PI_ARGS_LOG"] = str(fake_args_log) + check_env["CMUX_TEST_PI_STDIN_LOG"] = str(fake_stdin_log) + check_env["CMUX_TEST_PI_ENV_LOG"] = str(fake_env_log) + check_env["CMUX_TEST_PI_BINDING_FILE"] = str(fake_binding) + check_env["OPENAI_API_KEY"] = "openai-secret-should-not-leak" + check_env["ANTHROPIC_AUTH_TOKEN"] = "anthropic-secret-should-not-leak" + check_env["CUSTOM_PASSWORD"] = "password-should-not-leak" + check_env["AMP_API_KEY"] = "amp-secret-should-not-leak" + check_env["CMUX_LEAK_TOKEN"] = "cmux-secret-should-not-leak" + check_env["DATABASE_URL"] = "postgres://user:password@example.invalid/db" + check_env["DB_PASS"] = "db-pass-should-not-leak" + check_env["SENTRY_DSN"] = "https://public:private@example.invalid/1" + check_env["GH_PAT"] = "github-pat-should-not-leak" + check_env["CLOUDFLARE_AUTH_KEY"] = "cloudflare-key-should-not-leak" + check_env["STRIPE_SK"] = "stripe-secret-should-not-leak" + check_env["SLACK_WEBHOOK_URL"] = "https://hooks.slack.invalid/secret" + check_env["CMUX_TEST_PI_TOKEN"] = "test-token-should-not-leak" check_source = """ const extensionPath = process.env.CMUX_TEST_PI_EXTENSION_PATH; const mod = await import(extensionPath); @@ -98,13 +202,21 @@ def main() -> int: handlers.set(name, handler); } }); -for (const name of ["session_start", "before_agent_start", "agent_end"]) { +for (const name of [ + "session_start", + "before_agent_start", + "agent_end", + "session_shutdown", + "tool_execution_start", + "tool_execution_end", +]) { if (typeof handlers.get(name) !== "function") throw new Error(`missing ${name}`); } process.argv.splice( 0, process.argv.length, - "/Users/example/.bun/bin/pi", + "/opt/homebrew/bin/node", + "/tmp/node_modules/@earendil-works/pi-coding-agent/dist/cli.js", "--model", "anthropic/claude-sonnet-4-5" ); @@ -116,6 +228,19 @@ def main() -> int: }; await handlers.get("session_start")({}, ctx); await handlers.get("before_agent_start")({ prompt: "hello pi" }, ctx); +await handlers.get("tool_execution_start")({ + id: "tool-event-start-should-not-be-turn-id", + toolCallId: "tool-call-1", + toolName: "bash", + args: { command: "echo ok" } +}, ctx); +await handlers.get("tool_execution_end")({ + id: "tool-event-end-should-not-be-turn-id", + toolCallId: "tool-call-1", + toolName: "bash", + result: { content: [{ type: "text", text: "ok" }] }, + isError: false +}, ctx); await handlers.get("agent_end")({ messages: [ { role: "user", content: "hello pi" }, @@ -123,6 +248,41 @@ def main() -> int: ], stopReason: "completed" }, ctx); +await handlers.get("session_shutdown")({ reason: "quit" }, ctx); +const interruptedCtx = { + cwd: "/tmp/pi-project", + sessionManager: { + getSessionId() { return "pi-session-interrupted"; } + } +}; +await handlers.get("session_start")({}, interruptedCtx); +await handlers.get("before_agent_start")({ prompt: "interrupt me" }, interruptedCtx); +await handlers.get("session_shutdown")({ reason: "terminated" }, interruptedCtx); +process.env.CMUX_PI_HOOKS_DISABLED = "1"; +const disabledCtx = { + cwd: "/tmp/pi-project", + sessionManager: { + getSessionId() { return "pi-session-disabled"; } + } +}; +await handlers.get("session_start")({}, disabledCtx); +await handlers.get("session_shutdown")({ reason: "disabled" }, disabledCtx); +delete process.env.CMUX_PI_HOOKS_DISABLED; +const notificationFailureCtx = { + cwd: "/tmp/pi-project", + sessionManager: { + getSessionId() { return "pi-session-notification-fails"; } + } +}; +await handlers.get("session_start")({}, notificationFailureCtx); +await handlers.get("before_agent_start")({ prompt: "finish without routed notification" }, notificationFailureCtx); +await handlers.get("agent_end")({ + messages: [ + { role: "user", content: "finish without routed notification" }, + { role: "assistant", content: "notification should fail" } + ], + stopReason: "completed" +}, notificationFailureCtx); """ check = subprocess.run( [bun, "--eval", check_source], @@ -140,26 +300,145 @@ def main() -> int: print(f"stderr={check.stderr.strip()}") return 1 - args_log = fake_args_log.read_text(encoding="utf-8") if fake_args_log.exists() else "" - stdin_log = fake_stdin_log.read_text(encoding="utf-8") if fake_stdin_log.exists() else "" - env_log = fake_env_log.read_text(encoding="utf-8") if fake_env_log.exists() else "" + args_log = wait_for_text(fake_args_log, 21, timeout=20.0) + stdin_log = wait_for_text(fake_stdin_log, 34, timeout=20.0) + env_log = wait_for_text(fake_env_log, 21 * 3, timeout=20.0) for expected in [ "hooks pi session-start", "hooks pi prompt-submit", "hooks pi stop", + "hooks pi notification", + "hooks feed --source pi --event PreToolUse", + "hooks feed --source pi --event PostToolUse", + "surface resume get", + "surface resume set", + "surface resume clear", ]: if expected not in args_log: print(f"FAIL: extension did not invoke {expected}, got {args_log!r}") return 1 - if '"session_id":"pi-session-test"' not in stdin_log: - print(f"FAIL: extension did not pass session id, got {stdin_log!r}") + + arg_lines = [line for line in args_log.splitlines() if line.strip()] + resume_ops = [] + for line in [line for line in arg_lines if "surface resume " in line]: + if "surface resume get" in line: + resume_ops.append("get") + elif "surface resume set" in line: + resume_ops.append("set") + elif "surface resume clear" in line: + resume_ops.append("clear") + expected_resume_ops = ["set", "get", "clear", "set", "get", "clear", "set", "get"] + if resume_ops != expected_resume_ops: + print(f"FAIL: extension did not verify resume binding after set, got {resume_ops!r}") + return 1 + stop_notification_ops = [] + for line in arg_lines: + if "hooks pi notification" in line: + stop_notification_ops.append("notification") + elif "hooks pi stop" in line: + stop_notification_ops.append("stop") + if stop_notification_ops[:2] != ["notification", "stop"]: + print( + "FAIL: Pi completion stop suppressed native fallback before custom notification, " + f"got {stop_notification_ops!r}" + ) + return 1 + if stop_notification_ops[-2:] != ["notification", "stop"]: + print( + "FAIL: Pi notification failure path did not attempt custom notification before stop, " + f"got {stop_notification_ops!r}" + ) + return 1 + + payloads = payloads_from_log(stdin_log) + if not any(payload.get("session_id") == "pi-session-test" for payload in payloads): + print(f"FAIL: extension did not pass session id, got {payloads!r}") + return 1 + prompt_payload = next((payload for payload in payloads if payload.get("prompt") == "hello pi"), None) + stop_payload = next((payload for payload in payloads if payload.get("last_assistant_message") == "done"), None) + if prompt_payload is None or stop_payload is None: + print(f"FAIL: extension did not pass prompt/assistant payload, got {payloads!r}") + return 1 + prompt_turn_id = prompt_payload.get("turn_id") + if not isinstance(prompt_turn_id, str) or not prompt_turn_id: + print(f"FAIL: prompt-submit payload did not include a fallback turn_id, got {prompt_payload!r}") return 1 - if '"prompt":"hello pi"' not in stdin_log or '"last_assistant_message":"done"' not in stdin_log: - print(f"FAIL: extension did not pass prompt/assistant payload, got {stdin_log!r}") + if stop_payload.get("turn_id") != prompt_turn_id: + print(f"FAIL: stop payload did not reuse prompt turn_id, prompt={prompt_payload!r}, stop={stop_payload!r}") + return 1 + if stop_payload.get("cmux_notification_routed") is not True: + print(f"FAIL: successful Pi completion notification did not mark stop as routed: {stop_payload!r}") + return 1 + fallback_stop_payload = next( + ( + payload + for payload in payloads + if payload.get("session_id") == "pi-session-notification-fails" + and payload.get("hook_event_name") == "Stop" + ), + None, + ) + if fallback_stop_payload is None: + print(f"FAIL: notification failure session did not send a stop payload, got {payloads!r}") + return 1 + if fallback_stop_payload.get("cmux_notification_routed") is True: + print( + "FAIL: failed Pi completion notification still suppressed native notification fallback, " + f"got {fallback_stop_payload!r}" + ) + return 1 + interrupted_stop_payload = next( + (payload for payload in payloads if payload.get("terminationReason") == "terminated"), + None, + ) + if interrupted_stop_payload is None: + print(f"FAIL: interrupted session shutdown did not send stop payload, got {payloads!r}") + return 1 + if interrupted_stop_payload.get("cmux_notification_routed") is True: + print( + "FAIL: interrupted session shutdown suppressed native notification fallback, " + f"got {interrupted_stop_payload!r}" + ) + return 1 + feed_events = [payload for payload in payloads if payload.get("hook_event_name") in {"PreToolUse", "PostToolUse"}] + if len(feed_events) != 2 or {payload.get("tool_name") for payload in feed_events} != {"bash"}: + print(f"FAIL: Pi Feed bridge payloads were incomplete: {feed_events!r}") + return 1 + if {payload.get("turn_id") for payload in feed_events} != {prompt_turn_id}: + print(f"FAIL: Pi Feed bridge did not use the active prompt turn id: {feed_events!r}") + return 1 + notification_payload = next( + (payload for payload in payloads if payload.get("hook_event_name") == "Notification"), + None, + ) + if notification_payload is None or notification_payload.get("message") != "done": + print(f"FAIL: Pi completion notification was not routed through hooks pi notification: {payloads!r}") return 1 if "kind=pi" not in env_log or "cwd=/tmp/pi-project" not in env_log or "argv=" not in env_log: print(f"FAIL: extension did not pass launch metadata environment, got {env_log!r}") return 1 + leaked = [ + name + for name in [ + "OPENAI_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "CUSTOM_PASSWORD", + "AMP_API_KEY", + "CMUX_LEAK_TOKEN", + "DATABASE_URL", + "DB_PASS", + "SENTRY_DSN", + "GH_PAT", + "CLOUDFLARE_AUTH_KEY", + "STRIPE_SK", + "SLACK_WEBHOOK_URL", + "CMUX_TEST_PI_TOKEN", + ] + if f"{name}=present" in env_log + ] + if leaked: + print(f"FAIL: extension leaked secret environment keys to hook subprocesses: {leaked}; env={env_log!r}") + return 1 argv_line = next((line for line in env_log.splitlines() if line.startswith("argv=")), "") try: decoded_argv = [ @@ -171,7 +450,7 @@ def main() -> int: print(f"FAIL: extension launch argv was not valid base64 NUL data: {exc}; env={env_log!r}") return 1 expected_argv = [ - "/Users/example/.bun/bin/pi", + str(fake_pi), "--model", "anthropic/claude-sonnet-4-5", ]