From 5b31ba2f852da9e128660124c351274254ff92bb Mon Sep 17 00:00:00 2001 From: joshrzemien Date: Thu, 4 Jun 2026 12:56:00 -0400 Subject: [PATCH 1/6] Add OMP hook installation and session restore Detect OMP sessions from supported selector flags and session roots, restore OMP launches through CMUXAgentLaunch, and cover hook persistence plus direct process detection. --- .github/workflows/ci.yml | 4 + CLI/CMUXCLI+AgentHookDefinitions.swift | 11 + CLI/CMUXCLI+OmpExtension.swift | 305 +++++ CLI/cmux.swift | 12 +- .../AgentLaunchEnvironmentPolicy.swift | 1 + .../AgentLaunchSanitizer.swift | 2 +- .../AgentLaunchSanitizerPrimaryPolicies.swift | 1 + .../CMUXAgentLaunch/AgentResumeArgv.swift | 2 + .../AgentLaunchEnvironmentPolicyTests.swift | 22 + .../AgentLaunchSanitizerTests.swift | 43 + .../AgentResumeArgvTests.swift | 1 + .../AgentResumeWorkingDirectoryTests.swift | 2 +- Resources/Localizable.xcstrings | 1000 +++++++++++++++++ Sources/TaskManagerTypes.swift | 8 + Sources/VaultAgentProcessScanner.swift | 113 +- Sources/VaultAgentRegistry.swift | 30 +- cmux.xcodeproj/project.pbxproj | 8 + cmuxTests/OmpSupportTests.swift | 349 ++++++ cmuxTests/PiVaultAgentPersistenceTests.swift | 1 + cmuxTests/TaskManagerResourcesTests.swift | 1 + docs/agent-hooks.md | 8 +- docs/feed.md | 3 + docs/vault.md | 15 +- tests/test_omp_extension_install.py | 590 ++++++++++ .../[locale]/docs/session-restore/page.tsx | 7 + 25 files changed, 2519 insertions(+), 20 deletions(-) create mode 100644 CLI/CMUXCLI+OmpExtension.swift create mode 100644 Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchEnvironmentPolicyTests.swift create mode 100644 cmuxTests/OmpSupportTests.swift create mode 100755 tests/test_omp_extension_install.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 22b05f40d22d..fbdbbce06745 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,9 @@ on: pull_request: workflow_dispatch: +permissions: + contents: read + concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} @@ -463,6 +466,7 @@ jobs: CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_claude_hook_stop_last_assistant.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_claude_hook_clear_running_status.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_pi_extension_install.py + CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_omp_extension_install.py tests-build-and-lag: # Build the full cmux scheme and run the lag regression on macOS CI. diff --git a/CLI/CMUXCLI+AgentHookDefinitions.swift b/CLI/CMUXCLI+AgentHookDefinitions.swift index e5c82ff746e1..a4b9b48fdca9 100644 --- a/CLI/CMUXCLI+AgentHookDefinitions.swift +++ b/CLI/CMUXCLI+AgentHookDefinitions.swift @@ -70,6 +70,9 @@ extension CMUXCLI { /// Resolves the config directory, respecting env override if set. func resolvedConfigDir() -> String { + if name == "omp" { + return CMUXCLI.resolvedOmpAgentDirectory().path + } let home = ProcessInfo.processInfo.environment["HOME"].flatMap { value -> String? in let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.isEmpty ? nil : trimmed @@ -193,6 +196,14 @@ extension CMUXCLI { hookMarker: "cmux hooks pi", format: .flat, events: [] ), + AgentHookDef( + name: "omp", displayName: "OMP", statusKey: "omp", + configDir: ".omp/agent", configFile: "extensions/cmux-omp-session.ts", + createConfigDirIfMissing: true, + sessionStoreSuffix: "omp", disableEnvVar: "CMUX_OMP_HOOKS_DISABLED", + hookMarker: "cmux hooks omp", format: .flat, + events: [] + ), AgentHookDef( name: "amp", displayName: "Amp", statusKey: "amp", configDir: ".config/amp", configFile: "plugins/cmux-session.ts", diff --git a/CLI/CMUXCLI+OmpExtension.swift b/CLI/CMUXCLI+OmpExtension.swift new file mode 100644 index 000000000000..8b8995436c26 --- /dev/null +++ b/CLI/CMUXCLI+OmpExtension.swift @@ -0,0 +1,305 @@ +import Foundation + +extension CMUXCLI { + private static let ompExtensionMarker = "cmux-omp-session-extension-marker" + private static let ompExtensionFilename = "cmux-omp-session.ts" + private static let ompExtensionSource = #""" +// cmux-omp-session-extension-marker v1 +// Bridges OMP session lifecycle events into cmux's restorable session store. +// Installed by `cmux hooks omp install` or `cmux hooks setup`. +// DO NOT EDIT MANUALLY. cmux upgrades this file in place. + +import { spawn } from "node:child_process"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import type { AgentEndEvent, ExtensionAPI, ExtensionContext } from "@oh-my-pi/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 looksLikeOmpExecutable(value: string): boolean { + return path.basename(value).toLowerCase() === "omp"; +} + +function looksLikeOmpScript(value: string): boolean { + const normalized = value.replaceAll("\\", "/").toLowerCase(); + const base = path.basename(normalized); + return ( + normalized.includes("/@oh-my-pi/pi-coding-agent/") || + normalized.includes("/oh-my-pi/") || + ((base === "cli.js" || base === "cli.ts") && normalized.includes("pi-coding-agent")) + ); +} + +function looksLikeJavaScriptRuntime(value: string): boolean { + const base = path.basename(value).toLowerCase(); + return base === "node" || base === "bun" || base === "deno" || base === "tsx" || base === "ts-node"; +} + +function normalizedLaunchArgv(): string[] { + const raw = Array.isArray(process.argv) ? process.argv.map((value) => String(value)) : []; + if (raw.length === 0) return [resolveExecutable("omp")]; + if (looksLikeOmpExecutable(raw[0])) return raw; + if (raw.length > 1 && (looksLikeOmpScript(raw[1]) || looksLikeJavaScriptRuntime(raw[0]))) { + return [resolveExecutable("omp"), ...raw.slice(2)]; + } + return [resolveExecutable("omp"), ...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 }; + if (!env.CMUX_AGENT_LAUNCH_ARGV_B64) { + const argv = normalizedLaunchArgv(); + env.CMUX_AGENT_LAUNCH_KIND = "omp"; + env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("omp"); + 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_OMP_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_OMP_CMUX_BIN || "cmux"; + try { + const child = spawn(cmux, ["hooks", "omp", subcommand], { + env: hookEnvironment(cwd), + 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 cmuxOmpSessionExtension(api: ExtensionAPI) { + api.on("session_start", async (_event, ctx) => { + sendHook("session-start", ctx); + }); + + api.on("before_agent_start", async (event, ctx) => { + sendHook("prompt-submit", ctx, { prompt: event.prompt }); + }); + + api.on("agent_end", async (event, ctx) => { + sendHook("stop", ctx, { last_assistant_message: lastAssistantMessage(event) }); + }); +} +"""# + + static func resolvedOmpAgentDirectory(environment: [String: String] = ProcessInfo.processInfo.environment) -> URL { + if let agentRoot = nonEmptyEnvironmentValue("PI_CODING_AGENT_DIR", in: environment) { + return URL( + fileURLWithPath: NSString(string: agentRoot).expandingTildeInPath, + isDirectory: true + ) + } + + let home = nonEmptyEnvironmentValue("HOME", in: environment) ?? NSHomeDirectory() + let configDir = nonEmptyEnvironmentValue("PI_CONFIG_DIR", in: environment) ?? ".omp" + let expandedConfigDir = NSString(string: configDir).expandingTildeInPath + let configRoot: URL + if (expandedConfigDir as NSString).isAbsolutePath { + configRoot = URL(fileURLWithPath: expandedConfigDir, isDirectory: true) + } else { + configRoot = URL( + fileURLWithPath: NSString(string: home).expandingTildeInPath, + isDirectory: true + ) + .appendingPathComponent(configDir, isDirectory: true) + } + return configRoot.appendingPathComponent("agent", isDirectory: true) + } + + private static func nonEmptyEnvironmentValue(_ name: String, in environment: [String: String]) -> String? { + let trimmed = environment[name]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? nil : trimmed + } + + private func ompExtensionURL() -> URL { + return Self.resolvedOmpAgentDirectory() + .appendingPathComponent("extensions", isDirectory: true) + .appendingPathComponent(Self.ompExtensionFilename, isDirectory: false) + } + + private func existingOmpExtensionContents(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.omp.error.notCmuxExtension", + defaultValue: "%@ exists and is not a cmux extension; leaving it alone" + ), + url.path + ) + throw CLIError(message: "\(message): \(error.localizedDescription)") + } + } + + + func installOmpExtensionHooks(_ _: AgentHookDef) throws { + let extensionURL = ompExtensionURL() + let fileManager = FileManager.default + let skipConfirm = ProcessInfo.processInfo.arguments.contains("--yes") + || ProcessInfo.processInfo.arguments.contains("-y") + let existing = try existingOmpExtensionContents(at: extensionURL, fileManager: fileManager) + if existing == Self.ompExtensionSource { + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.omp.alreadyUpToDate", + defaultValue: "OMP hooks already up to date at %@" + ), + extensionURL.path + )) + return + } + if !existing.isEmpty, !existing.contains(Self.ompExtensionMarker) { + throw CLIError(message: String.localizedStringWithFormat( + String( + localized: "cli.hooks.omp.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.ompExtensionSource, + fallbackContent: Self.ompExtensionSource + ) + print(String(localized: "cli.hooks.omp.confirmProceed", defaultValue: "\nProceed? [y/N] "), terminator: "") + guard readLine()?.lowercased().hasPrefix("y") == true else { + print(String(localized: "cli.hooks.omp.aborted", defaultValue: "Aborted.")) + return + } + } + try fileManager.createDirectory( + at: extensionURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try Self.ompExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.omp.installed", + defaultValue: "OMP hooks installed at %@" + ), + extensionURL.path + )) + } + + func uninstallOmpExtensionHooks(_ _: AgentHookDef) throws { + let extensionURL = ompExtensionURL() + let fm = FileManager.default + guard fm.fileExists(atPath: extensionURL.path) else { + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.omp.noneFound", + defaultValue: "No OMP cmux extension found at %@" + ), + extensionURL.path + )) + return + } + let existing = try existingOmpExtensionContents(at: extensionURL, fileManager: fm) + guard existing.contains(Self.ompExtensionMarker) else { + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.omp.refuseRemoveMissingMarker", + defaultValue: "Refusing to remove %@: missing cmux marker" + ), + extensionURL.path + )) + return + } + try fm.removeItem(at: extensionURL) + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.omp.removed", + defaultValue: "Removed OMP cmux extension from %@" + ), + extensionURL.path + )) + } +} diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 410c18260f05..f3560fa6e6a9 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -12981,7 +12981,7 @@ struct CMUXCLI { agent. Claude Code hooks are injected automatically by the cmux Claude wrapper. Agents: - codex, grok, opencode, pi, amp, cursor, gemini, kiro, antigravity (alias: agy), rovodev (alias: rovo), hermes-agent, copilot, codebuddy, factory, qoder + codex, grok, opencode, pi, omp, amp, cursor, gemini, kiro, antigravity (alias: agy), rovodev (alias: rovo), hermes-agent, copilot, codebuddy, factory, qoder Hook targets: setup Install hooks for all supported agents on PATH @@ -12995,6 +12995,7 @@ struct CMUXCLI { ~/.config/opencode/plugins/cmux-session.js ~/.config/opencode/plugins/cmux-feed.js ~/.pi/agent/extensions/cmux-session.ts + ~/.omp/agent/extensions/cmux-omp-session.ts ~/.config/amp/plugins/cmux-session.ts ~/.kiro/agents/cmux.json See docs/agent-hooks.md for the full integration matrix. @@ -13003,6 +13004,7 @@ struct CMUXCLI { cmux hooks setup cmux hooks setup --agent codex cmux hooks setup rovo + cmux hooks setup omp cmux hooks uninstall rovo cmux hooks codex install cmux hooks opencode install --project @@ -26146,6 +26148,10 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { try installPiExtensionHooks(def) return } + if def.name == "omp" { + try installOmpExtensionHooks(def) + return + } if def.name == "amp" { try installAmpExtensionHooks(def) return @@ -26503,6 +26509,10 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { try uninstallPiExtensionHooks(def) return } + if def.name == "omp" { + try uninstallOmpExtensionHooks(def) + return + } if def.name == "amp" { try uninstallAmpExtensionHooks(def) return diff --git a/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchEnvironmentPolicy.swift b/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchEnvironmentPolicy.swift index 9f1a6a70cb23..41a0fb3c0ff9 100644 --- a/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchEnvironmentPolicy.swift +++ b/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchEnvironmentPolicy.swift @@ -72,6 +72,7 @@ public enum AgentLaunchEnvironmentPolicy { "NODE_OPTIONS", "OPENCODE_CONFIG_DIR", "PI_CACHE_RETENTION", + "PI_CONFIG_DIR", "PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "PI_OFFLINE", diff --git a/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift b/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift index 8e0bbc3e73a3..771d809a4bd8 100644 --- a/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift +++ b/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift @@ -75,7 +75,7 @@ public enum AgentLaunchSanitizer { return preserveOptions(args, policy: codexPolicy) case "grok": return preserveOptions(args, policy: grokPolicy) - case "pi": + case "pi", "omp": return preserveOptions(args, policy: piPolicy) case "amp": // Strip the `threads continue ` resume sub-subcommand if the diff --git a/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizerPrimaryPolicies.swift b/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizerPrimaryPolicies.swift index a16f64053cf3..ba903f9e4b04 100644 --- a/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizerPrimaryPolicies.swift +++ b/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizerPrimaryPolicies.swift @@ -258,6 +258,7 @@ extension AgentLaunchSanitizer { "--thinking", "--tools", "-e", + "-r", "-t" ], nonRestorableCommands: [ diff --git a/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentResumeArgv.swift b/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentResumeArgv.swift index 4c3dcfbe896c..6d7522736a40 100644 --- a/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentResumeArgv.swift +++ b/Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentResumeArgv.swift @@ -99,6 +99,8 @@ public struct AgentResumeArgv: Sendable, Equatable { return withOption("grok", executable: "grok", option: "-r", sessionId: sessionId, executablePath: executablePath, arguments: arguments) case "pi": return withOption("pi", executable: "pi", option: "--session", sessionId: sessionId, executablePath: executablePath, arguments: arguments) + case "omp": + return withOption("omp", executable: "omp", option: "--session", sessionId: sessionId, executablePath: executablePath, arguments: arguments) case "amp": let parts = commandParts(executablePath: executablePath, arguments: arguments, fallbackExecutable: "amp") guard let preserved = AgentLaunchSanitizer.preservedArguments(kind: "amp", args: parts.tail) else { return nil } diff --git a/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchEnvironmentPolicyTests.swift b/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchEnvironmentPolicyTests.swift new file mode 100644 index 000000000000..105fb02c1317 --- /dev/null +++ b/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchEnvironmentPolicyTests.swift @@ -0,0 +1,22 @@ +import CMUXAgentLaunch +import Testing + +@Suite("AgentLaunchEnvironmentPolicy") +struct AgentLaunchEnvironmentPolicyTests { + @Test("Preserves OMP config roots without persisting secrets") + func preservesOmpConfigRootsWithoutPersistingSecrets() { + let selected = AgentLaunchEnvironmentPolicy.selectedEnvironment( + from: [ + "OPENAI_API_KEY": "secret-should-not-persist", + "PI_CODING_AGENT_DIR": "/tmp/omp-agent", + "PI_CONFIG_DIR": ".custom-omp", + ], + kind: "omp" + ) + + #expect(selected == [ + "PI_CODING_AGENT_DIR": "/tmp/omp-agent", + "PI_CONFIG_DIR": ".custom-omp", + ]) + } +} diff --git a/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift b/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift index 6857a6da63b2..4870c028a243 100644 --- a/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift +++ b/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift @@ -413,6 +413,49 @@ struct AgentLaunchSanitizerTests { ) } + @Test("Drops OMP session selectors without replaying prompts") + func dropsOmpSessionSelectorsWithoutReplayingPrompts() { + #expect( + AgentLaunchSanitizer.sanitizedLaunchArguments( + [ + "omp", + "-r", + "old-session", + "--model", + "anthropic/claude-sonnet-4-5", + "initial prompt should not replay", + ], + launcher: "omp", + fallbackKind: "omp" + ) == [ + "omp", + "--model", + "anthropic/claude-sonnet-4-5", + ] + ) + #expect( + AgentLaunchSanitizer.sanitizedLaunchArguments( + ["omp", "--resume=old-session", "--theme", "dark"], + launcher: "omp", + fallbackKind: "omp" + ) == ["omp", "--theme", "dark"] + ) + #expect( + AgentLaunchSanitizer.sanitizedLaunchArguments( + ["omp", "--session", "old-session", "--model", "anthropic/claude-sonnet-4-5"], + launcher: "omp", + fallbackKind: "omp" + ) == ["omp", "--model", "anthropic/claude-sonnet-4-5"] + ) + #expect( + AgentLaunchSanitizer.sanitizedLaunchArguments( + ["omp", "--session=old-session", "--theme", "dark"], + launcher: "omp", + fallbackKind: "omp" + ) == ["omp", "--theme", "dark"] + ) + } + @Test("Rejects noninteractive Antigravity launches") func rejectsNoninteractiveAntigravityLaunches() { #expect( diff --git a/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentResumeArgvTests.swift b/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentResumeArgvTests.swift index fc9da8d73056..3c7720041e2a 100644 --- a/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentResumeArgvTests.swift +++ b/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentResumeArgvTests.swift @@ -7,6 +7,7 @@ struct AgentResumeArgvTests { ("claude", "claude", ["claude", "--resume", "SID"]), ("grok", "grok", ["grok", "-r", "SID"]), ("pi", "pi", ["pi", "--session", "SID"]), + ("omp", "omp", ["omp", "--session", "SID"]), ("cursor", "cursor-agent", ["cursor-agent", "--resume", "SID"]), ("gemini", "gemini", ["gemini", "--resume", "SID"]), ("antigravity", "agy", ["agy", "--conversation", "SID"]), diff --git a/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentResumeWorkingDirectoryTests.swift b/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentResumeWorkingDirectoryTests.swift index 1f133a08b06d..d121e071c55c 100644 --- a/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentResumeWorkingDirectoryTests.swift +++ b/Packages/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentResumeWorkingDirectoryTests.swift @@ -12,7 +12,7 @@ struct AgentResumeWorkingDirectoryTests { launchWorkingDirectory: "/Users/x/repo" ) == "/Users/x/repo" ) - for kind in ["gemini", "cursor", "grok", "pi", "qoder"] { + for kind in ["gemini", "cursor", "grok", "pi", "omp", "qoder"] { #expect(AgentResumeWorkingDirectory().cwdNamespacing(forKind: kind) == .byDirectory) #expect( AgentResumeWorkingDirectory().resolve( diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index fc43fa1c4229..7e59ef5b37aa 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -2,6 +2,1006 @@ "sourceLanguage": "en", "version": "1.0", "strings": { + "cli.hooks.omp.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.omp.alreadyUpToDate": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "خطافات OMP محدَّثة بالفعل في %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "OMP hookovi su već ažurirani u %@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "OMP-hooks er allerede opdaterede i %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "OMP-Hooks sind in %@ bereits auf dem neuesten Stand" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "OMP hooks already up to date at %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Los hooks de OMP ya están actualizados en %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les hooks OMP sont déjà à jour dans %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Gli hook di OMP sono già aggiornati in %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ の OMP フックはすでに最新です" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "hooks របស់ OMP នៅ %@ ទាន់សម័យរួចហើយ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@의 OMP 훅은 이미 최신 상태입니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "OMP-hooks er allerede oppdatert i %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Hooki OMP są już aktualne w %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Os hooks do OMP já estão atualizados em %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Хуки OMP в %@ уже актуальны" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ฮุก OMP ที่ %@ เป็นเวอร์ชันล่าสุดอยู่แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "OMP kancaları %@ konumunda zaten güncel" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Хуки OMP у %@ вже актуальні" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "%@ 中的 OMP hooks 已是最新" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "%@ 中的 OMP hooks 已是最新" + } + } + } + }, + "cli.hooks.omp.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.omp.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.omp.installed": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم تثبيت خطافات OMP في %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "OMP hookovi su instalirani u %@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "OMP-hooks er installeret i %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "OMP-Hooks wurden in %@ installiert" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "OMP hooks installed at %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Hooks de OMP instalados en %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Hooks OMP installés dans %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Hook di OMP installati in %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "OMP フックを %@ にインストールしました" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បានដំឡើង hooks របស់ OMP នៅ %@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@에 OMP 훅을 설치했습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "OMP-hooks er installert i %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Zainstalowano hooki OMP w %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Hooks do OMP instalados em %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Хуки OMP установлены в %@" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ติดตั้งฮุก OMP ที่ %@ แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "OMP kancaları %@ konumuna kuruldu" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Хуки OMP встановлено в %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已在 %@ 安装 OMP hooks" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已在 %@ 安裝 OMP hooks" + } + } + } + }, + "cli.hooks.omp.noneFound": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "لم يتم العثور على امتداد OMP cmux في %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Nijedna OMP cmux ekstenzija nije pronađena u %@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Ingen OMP cmux-udvidelse fundet i %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Keine OMP-cmux-Erweiterung in %@ gefunden" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No OMP cmux extension found at %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se encontró ninguna extensión OMP cmux en %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune extension OMP cmux trouvée dans %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nessuna estensione OMP cmux trovata in %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ に OMP cmux 拡張が見つかりません" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "រកមិនឃើញ​ផ្នែកបន្ថែម OMP cmux នៅ %@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@에서 OMP cmux 확장을 찾을 수 없습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Fant ingen OMP cmux-utvidelse i %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Nie znaleziono rozszerzenia OMP cmux w %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhuma extensão OMP cmux encontrada em %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение OMP cmux в %@ не найдено" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ไม่พบส่วนขยาย OMP cmux ที่ %@" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "%@ konumunda OMP cmux uzantısı bulunamadı" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення OMP cmux у %@ не знайдено" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "未在 %@ 找到 OMP cmux 扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "未在 %@ 找到 OMP cmux 擴充功能" + } + } + } + }, + "cli.hooks.omp.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.omp.removed": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تمت إزالة امتداد OMP cmux من %@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "OMP cmux ekstenzija je uklonjena iz %@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "OMP cmux-udvidelse blev fjernet fra %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "OMP-cmux-Erweiterung aus %@ entfernt" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Removed OMP cmux extension from %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Se eliminó la extensión OMP cmux de %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Extension OMP cmux supprimée de %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Estensione OMP cmux rimossa da %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ から OMP cmux 拡張を削除しました" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បានលុប​ផ្នែកបន្ថែម OMP cmux ចេញពី %@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@에서 OMP cmux 확장을 제거했습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Fjernet OMP cmux-utvidelse fra %@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Usunięto rozszerzenie OMP cmux z %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensão OMP cmux removida de %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение OMP cmux удалено из %@" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ลบส่วนขยาย OMP cmux ออกจาก %@ แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "OMP cmux uzantısı %@ konumundan kaldırıldı" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення OMP cmux видалено з %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已从 %@ 移除 OMP cmux 扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已從 %@ 移除 OMP cmux 擴充功能" + } + } + } + }, "markdown.typography.font": { "extractionState": "manual", "localizations": { diff --git a/Sources/TaskManagerTypes.swift b/Sources/TaskManagerTypes.swift index 72dffd0fc42f..f3818d4bc07c 100644 --- a/Sources/TaskManagerTypes.swift +++ b/Sources/TaskManagerTypes.swift @@ -579,6 +579,14 @@ struct CmuxTaskManagerCodingAgentDefinition: Equatable { directBasenames: ["opencode", "opencode-ai", "open-code", "omo"], argumentNeedles: ["opencode", "opencode-ai", "open-code", "oh-my-openagent"] ), + CmuxTaskManagerCodingAgentDefinition( + id: "omp", + displayName: "OMP", + assetName: nil, + launchKinds: ["omp"], + directBasenames: ["omp"], + argumentNeedles: ["@oh-my-pi/pi-coding-agent"] + ), CmuxTaskManagerCodingAgentDefinition( id: "pi", displayName: "Pi", diff --git a/Sources/VaultAgentProcessScanner.swift b/Sources/VaultAgentProcessScanner.swift index dffd3fe798c4..b9c48b6d1e7b 100644 --- a/Sources/VaultAgentProcessScanner.swift +++ b/Sources/VaultAgentProcessScanner.swift @@ -769,22 +769,33 @@ private extension CmuxVaultAgentDetectRule { if let processName { expectedNames.append(processName) } - guard !expectedNames.isEmpty || !argvContains.isEmpty else { return false } + guard !expectedNames.isEmpty || !argvContains.isEmpty || !alternateArgvContains.isEmpty else { + return false + } let processNameMatch = expectedNames.isEmpty || expectedNames.contains { expected in process.executableBasenames.contains { candidate in candidate.compare(expected, options: [.caseInsensitive, .literal]) == .orderedSame } } - let argvContainsMatch = argvContains.isEmpty || argvContains.allSatisfy { needle in + let argvContainsMatch = argvContains.isEmpty || process.argumentsContainAll(argvContains) + let alternateArgvContainsMatch = !alternateArgvContains.isEmpty + && process.argumentsContainAll(alternateArgvContains) + return (processNameMatch && argvContainsMatch) || alternateArgvContainsMatch + } +} + +private extension VaultObservedAgentProcess { + func argumentsContainAll(_ needles: [String]) -> Bool { + needles.allSatisfy { needle in if needle.contains(" ") { - let joinedArguments = process.arguments.joined(separator: " ") + let joinedArguments = arguments.joined(separator: " ") return joinedArguments.range(of: needle, options: [.caseInsensitive, .literal]) != nil } if needle.contains("/") { - let joinedArguments = process.arguments.joined(separator: "\u{0}") + let joinedArguments = arguments.joined(separator: "\u{0}") return joinedArguments.range(of: needle, options: [.caseInsensitive, .literal]) != nil } - return process.arguments.contains { argument in + return arguments.contains { argument in argument.range(of: needle, options: [.caseInsensitive, .literal]) != nil || (argument as NSString).lastPathComponent.range( of: needle, @@ -792,7 +803,6 @@ private extension CmuxVaultAgentDetectRule { ) != nil } } - return processNameMatch && argvContainsMatch } } @@ -806,7 +816,7 @@ private extension CmuxVaultAgentSessionIDSource { case .argvOption(let option): return process.arguments.nonOptionValue(afterOption: option) case .piSessionFile: - if let session = process.arguments.nonOptionValue(afterOption: "--session") { + if let session = process.arguments.piCompatibleSessionID { return PiSessionLocator.resolvedSessionPath( session, for: process, @@ -877,6 +887,38 @@ private extension Array where Element == String { return value } + var piCompatibleSessionID: String? { + for index in indices { + let argument = self[index] + if argument == "--session" || argument == "--resume" || argument == "-r" { + let nextIndex = self.index(after: index) + guard nextIndex < endIndex else { continue } + if let value = normalizedNonOptionValue(self[nextIndex]) { + return value + } + continue + } + if argument.hasPrefix("--session="), + let value = normalizedNonOptionValue(String(argument.dropFirst("--session=".count))) { + return value + } + if argument.hasPrefix("--resume="), + let value = normalizedNonOptionValue(String(argument.dropFirst("--resume=".count))) { + return value + } + if argument.hasPrefix("-r="), + let value = normalizedNonOptionValue(String(argument.dropFirst("-r=".count))) { + return value + } + } + return nil + } + + private func normalizedNonOptionValue(_ rawValue: String) -> String? { + let value = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) + return !value.isEmpty && !value.hasPrefix("-") ? value : nil + } + var grokResumeSessionID: String? { let options = ["-r", "--resume"] for index in indices { @@ -953,16 +995,22 @@ enum PiSessionLocator { return nil } - var newest: (url: URL, modified: Date)? + var exactNewest: (url: URL, modified: Date)? + var partialNewest: (url: URL, modified: Date)? for case let url as URL in enumerator where url.pathExtension == "jsonl" { - guard url.deletingPathExtension().lastPathComponent.contains(trimmed) else { continue } + let basename = url.deletingPathExtension().lastPathComponent + guard basename == trimmed || basename.contains(trimmed) else { continue } let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .isRegularFileKey]) guard values?.isRegularFile == true, let modified = values?.contentModificationDate else { continue } - if newest == nil || modified > newest!.modified { - newest = (url, modified) + if basename == trimmed { + if exactNewest == nil || modified > exactNewest!.modified { + exactNewest = (url, modified) + } + } else if partialNewest == nil || modified > partialNewest!.modified { + partialNewest = (url, modified) } } - return newest?.url.path + return exactNewest?.url.path ?? partialNewest?.url.path } private static func candidateSessionDirectory( @@ -971,6 +1019,8 @@ enum PiSessionLocator { ) -> String { let sessionRoot = process.arguments.value(afterOption: "--session-dir") ?? process.environment["PI_CODING_AGENT_SESSION_DIR"] + ?? configuredSessionDirectory(for: registration) + ?? ompAgentSessionsRoot(for: process, registration: registration) ?? registration.sessionDirectory ?? defaultSessionsRoot() let expandedRoot = (sessionRoot as NSString).expandingTildeInPath @@ -981,6 +1031,45 @@ enum PiSessionLocator { return expandedRoot } + private static func ompAgentSessionsRoot( + for process: VaultObservedAgentProcess, + registration: CmuxVaultAgentRegistration + ) -> String? { + guard registration.id == "omp" else { return nil } + if let agentRoot = nonEmptyEnvironmentValue("PI_CODING_AGENT_DIR", in: process.environment) { + let expandedAgentRoot = NSString(string: agentRoot).expandingTildeInPath + return (expandedAgentRoot as NSString).appendingPathComponent("sessions") + } + guard let configDir = nonEmptyEnvironmentValue("PI_CONFIG_DIR", in: process.environment) else { + return nil + } + let home = nonEmptyEnvironmentValue("HOME", in: process.environment) ?? NSHomeDirectory() + let expandedConfigDir = NSString(string: configDir).expandingTildeInPath + let configRoot: String + if (expandedConfigDir as NSString).isAbsolutePath { + configRoot = expandedConfigDir + } else { + configRoot = ((NSString(string: home).expandingTildeInPath) as NSString) + .appendingPathComponent(configDir) + } + let agentRoot = (configRoot as NSString).appendingPathComponent("agent") + return (agentRoot as NSString).appendingPathComponent("sessions") + } + + private static func configuredSessionDirectory(for registration: CmuxVaultAgentRegistration) -> String? { + guard let sessionDirectory = registration.sessionDirectory else { return nil } + if registration.id == "omp", + sessionDirectory == CmuxVaultAgentRegistration.builtInOmp.sessionDirectory { + return nil + } + return sessionDirectory + } + + private static func nonEmptyEnvironmentValue(_ name: String, in environment: [String: String]) -> String? { + let trimmed = environment[name]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? nil : trimmed + } + static func newestJSONLFile(in directory: String, fileManager: FileManager = .default) -> URL? { var isDirectory: ObjCBool = false guard fileManager.fileExists(atPath: directory, isDirectory: &isDirectory), diff --git a/Sources/VaultAgentRegistry.swift b/Sources/VaultAgentRegistry.swift index c093108b5b0d..95d31f489830 100644 --- a/Sources/VaultAgentRegistry.swift +++ b/Sources/VaultAgentRegistry.swift @@ -126,6 +126,21 @@ struct CmuxVaultAgentRegistration: Codable, Hashable, Sendable { ) } + static var builtInOmp: CmuxVaultAgentRegistration { + CmuxVaultAgentRegistration( + id: "omp", + name: "OMP", + detect: CmuxVaultAgentDetectRule( + processName: "omp", + alternateArgvContains: ["@oh-my-pi/pi-coding-agent"] + ), + sessionIdSource: .piSessionFile, + resumeCommand: "{{executable}} --session {{sessionId}}", + cwd: .preserve, + sessionDirectory: "~/.omp/agent/sessions" + ) + } + static var builtInAntigravity: CmuxVaultAgentRegistration { CmuxVaultAgentRegistration( id: "antigravity", @@ -156,12 +171,18 @@ struct CmuxVaultAgentDetectRule: Codable, Hashable, Sendable { var processName: String? var processNames: [String] var argvContains: [String] + var alternateArgvContains: [String] private enum CodingKeys: String, CodingKey { - case processName, processNames, argvContains + case processName, processNames, argvContains, alternateArgvContains } - init(processName: String? = nil, processNames: [String] = [], argvContains: [String] = []) { + init( + processName: String? = nil, + processNames: [String] = [], + argvContains: [String] = [], + alternateArgvContains: [String] = [] + ) { let name = processName?.trimmingCharacters(in: .whitespacesAndNewlines) self.processName = name?.isEmpty == true ? nil : name self.processNames = processNames @@ -170,6 +191,9 @@ struct CmuxVaultAgentDetectRule: Codable, Hashable, Sendable { self.argvContains = argvContains .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } + self.alternateArgvContains = alternateArgvContains + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } } init(from decoder: Decoder) throws { @@ -179,6 +203,7 @@ struct CmuxVaultAgentDetectRule: Codable, Hashable, Sendable { processName = name?.isEmpty == true ? nil : name processNames = try Self.decodeOneOrManyStrings(forKey: .processNames, in: container) argvContains = try Self.decodeOneOrManyStrings(forKey: .argvContains, in: container) + alternateArgvContains = try Self.decodeOneOrManyStrings(forKey: .alternateArgvContains, in: container) } private static func decodeOneOrManyStrings( @@ -354,6 +379,7 @@ struct CmuxVaultAgentRegistry: Sendable { ) -> CmuxVaultAgentRegistry { var registrations = [ CmuxVaultAgentRegistration.builtInPi, + CmuxVaultAgentRegistration.builtInOmp, CmuxVaultAgentRegistration.builtInAntigravity, CmuxVaultAgentRegistration.builtInGrok, ] diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 141acaec3311..68f719d73609 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -119,6 +119,7 @@ B9000052A1B2C3D4E5F60719 /* CMUXCLI+InstallPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000053A1B2C3D4E5F60719 /* CMUXCLI+InstallPreview.swift */; }; 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 */; }; B9000054A1B2C3D4E5F60719 /* CMUXCLI+Process.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000055A1B2C3D4E5F60719 /* CMUXCLI+Process.swift */; }; B9000041A1B2C3D4E5F60719 /* CMUXCLI+SSHCommandSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000040A1B2C3D4E5F60719 /* CMUXCLI+SSHCommandSupport.swift */; }; B900002EA1B2C3D4E5F60719 /* CMUXCLI+Themes.swift in Sources */ = {isa = PBXBuildFile; fileRef = B900002CA1B2C3D4E5F60719 /* CMUXCLI+Themes.swift */; }; @@ -368,6 +369,7 @@ A5001094 /* NotificationsPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001091 /* NotificationsPage.swift */; }; D36090020000000000000001 /* NSWindow+CmuxPeerWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = D36090020000000000000002 /* NSWindow+CmuxPeerWindow.swift */; }; 4378399A7C0245EF8186F306 /* OmnibarAndToolsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B09C007F42697761B5F1A2AB /* OmnibarAndToolsTests.swift */; }; + 0A0F00550000000000000001 /* OmpSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A0F00550000000000000002 /* OmpSupportTests.swift */; }; D1BEF00002A1B2C3D4E5F719 /* open in Copy CLI */ = {isa = PBXBuildFile; fileRef = D1BEF00001A1B2C3D4E5F719 /* open */; }; FEED0000000000000000F007 /* opencode-plugin.js in Resources */ = {isa = PBXBuildFile; fileRef = FEED0000000000000000F006 /* opencode-plugin.js */; }; A5E01203A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5E01204A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift */; }; @@ -802,6 +804,7 @@ B9000053A1B2C3D4E5F60719 /* CMUXCLI+InstallPreview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+InstallPreview.swift"; sourceTree = ""; }; 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 = ""; }; B9000055A1B2C3D4E5F60719 /* CMUXCLI+Process.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Process.swift"; sourceTree = ""; }; B9000040A1B2C3D4E5F60719 /* CMUXCLI+SSHCommandSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+SSHCommandSupport.swift"; sourceTree = ""; }; B900002CA1B2C3D4E5F60719 /* CMUXCLI+Themes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+Themes.swift"; sourceTree = ""; }; @@ -1021,6 +1024,7 @@ A5001091 /* NotificationsPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationsPage.swift; sourceTree = ""; }; D36090020000000000000002 /* NSWindow+CmuxPeerWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/NSWindow+CmuxPeerWindow.swift"; sourceTree = ""; }; B09C007F42697761B5F1A2AB /* OmnibarAndToolsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OmnibarAndToolsTests.swift; sourceTree = ""; }; + 0A0F00550000000000000002 /* OmpSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OmpSupportTests.swift; sourceTree = ""; }; D1BEF00001A1B2C3D4E5F719 /* open */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = Resources/bin/open; sourceTree = SOURCE_ROOT; }; FEED0000000000000000F006 /* opencode-plugin.js */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.javascript; path = "opencode-plugin.js"; sourceTree = ""; }; A5E01204A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenCodeHookRegressionTests.swift; sourceTree = ""; }; @@ -1834,6 +1838,7 @@ B9000060A1B2C3D4E5F60719 /* CMUXCLI+HermesAgentHooks.swift */, B9000062A1B2C3D4E5F60719 /* CMUXCLI+AgentHookDefinitions.swift */, B9000069A1B2C3D4E5F60719 /* CMUXCLI+AmpExtension.swift */, + B9000073A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift */, B9000070A1B2C3D4E5F60719 /* CMUXCLI+Memory.swift */, B9000031A1B2C3D4E5F60719 /* CMUXCLI+DocsSettings.swift */, B900002DA1B2C3D4E5F60719 /* CMUXCLI+ThemeSupport.swift */, @@ -1992,6 +1997,7 @@ A5D4120EA1B2C3D4E5F60718 /* CLIAuthAliasTests.swift */, C0DE35530000000000000102 /* BundledCLILinkageTests.swift */, C37800000000000000000002 /* VMSSHCommandTests.swift */, + 0A0F00550000000000000002 /* OmpSupportTests.swift */, A5E01204A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift */, 10D684CFFB8CDEF89CE2D9E1 /* TabManagerSessionSnapshotTests.swift */, C1A2B3C4D5E6F70800000002 /* CmuxConfigTests.swift */, @@ -2727,6 +2733,7 @@ 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 */, B9000041A1B2C3D4E5F60719 /* CMUXCLI+SSHCommandSupport.swift in Sources */, B900002EA1B2C3D4E5F60719 /* CMUXCLI+Themes.swift in Sources */, @@ -2882,6 +2889,7 @@ D3664002D3664002D3664002 /* MarkdownPanelTests.swift in Sources */, 734F49D37E543DD01C2F4FEF /* NotificationAndMenuBarTests.swift in Sources */, 4378399A7C0245EF8186F306 /* OmnibarAndToolsTests.swift in Sources */, + 0A0F00550000000000000001 /* OmpSupportTests.swift in Sources */, A5E01203A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift in Sources */, C44550000000000000000001 /* PanelOwnedNativeViewSessionTests.swift in Sources */, B3575000000000000000000A /* PiVaultAgentPersistenceTests.swift in Sources */, diff --git a/cmuxTests/OmpSupportTests.swift b/cmuxTests/OmpSupportTests.swift new file mode 100644 index 000000000000..0b8860e116b9 --- /dev/null +++ b/cmuxTests/OmpSupportTests.swift @@ -0,0 +1,349 @@ +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("OMP support") +struct OmpSupportTests { + @Test func directProcessDetectionUsesExplicitSessionSelectorsBeforeLatestFallback() throws { + struct Selector { + let name: String + let arguments: [String] + } + + let selectors = [ + Selector(name: "--session value", arguments: ["--session", "explicit-omp-session"]), + Selector(name: "--session=value", arguments: ["--session=explicit-omp-session"]), + Selector(name: "--resume value", arguments: ["--resume", "explicit-omp-session"]), + Selector(name: "--resume=value", arguments: ["--resume=explicit-omp-session"]), + Selector(name: "-r value", arguments: ["-r", "explicit-omp-session"]), + Selector(name: "-r=value", arguments: ["-r=explicit-omp-session"]), + ] + + for selector in selectors { + let root = try Self.makeTemporaryDirectory(prefix: "cmux-omp-explicit-") + defer { try? FileManager.default.removeItem(at: root) } + let workspace = root.appendingPathComponent("repo", isDirectory: true) + let sessionsRoot = root.appendingPathComponent("sessions", isDirectory: true) + let projectDirectory = try #require(PiSessionLocator.projectDirectoryName(for: workspace.path)) + let projectSessions = sessionsRoot.appendingPathComponent(projectDirectory, isDirectory: true) + try FileManager.default.createDirectory(at: projectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + + let explicit = try Self.writeSessionFile( + id: "explicit-omp-session", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 1_000) + ) + let latest = try Self.writeSessionFile( + id: "latest-omp-session", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 2_000) + ) + let partial = try Self.writeSessionFile( + id: "prefix-explicit-omp-session-suffix", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 3_000) + ) + + let selectorComment = Comment(rawValue: selector.name) + let detected = try #require(Self.detectedOmpSnapshot( + arguments: ["/Users/example/.bun/bin/omp"] + selector.arguments, + environment: [ + "PWD": workspace.path, + "PI_CODING_AGENT_SESSION_DIR": sessionsRoot.path, + ] + ), selectorComment) + + #expect(detected.kind == RestorableAgentKind.custom("omp"), selectorComment) + #expect(Self.normalizedPath(detected.sessionId) == Self.normalizedPath(explicit.path), selectorComment) + #expect(Self.normalizedPath(detected.sessionId) != Self.normalizedPath(latest.path), selectorComment) + #expect(Self.normalizedPath(detected.sessionId) != Self.normalizedPath(partial.path), selectorComment) + #expect(detected.workingDirectory == workspace.path, selectorComment) + } + } + + @Test func directProcessDetectionFallsBackToPartialSessionFileMatch() throws { + let root = try Self.makeTemporaryDirectory(prefix: "cmux-omp-partial-session-") + defer { try? FileManager.default.removeItem(at: root) } + let workspace = root.appendingPathComponent("repo", isDirectory: true) + let sessionsRoot = root.appendingPathComponent("sessions", isDirectory: true) + let projectDirectory = try #require(PiSessionLocator.projectDirectoryName(for: workspace.path)) + let projectSessions = sessionsRoot.appendingPathComponent(projectDirectory, isDirectory: true) + try FileManager.default.createDirectory(at: projectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + + let partial = try Self.writeSessionFile( + id: "prefix-partial-omp-session-suffix", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 2_000) + ) + + let detected = try #require(Self.detectedOmpSnapshot( + arguments: ["/Users/example/.bun/bin/omp", "--session", "partial-omp-session"], + environment: [ + "PWD": workspace.path, + "PI_CODING_AGENT_SESSION_DIR": sessionsRoot.path, + ] + )) + + #expect(detected.kind == RestorableAgentKind.custom("omp")) + #expect(Self.normalizedPath(detected.sessionId) == Self.normalizedPath(partial.path)) + #expect(detected.workingDirectory == workspace.path) + } + + @Test func directProcessDetectionUsesOmpAgentDirectorySessionsWhenNoSessionDirectoryIsSet() throws { + let root = try Self.makeTemporaryDirectory(prefix: "cmux-omp-agent-dir-") + defer { try? FileManager.default.removeItem(at: root) } + let workspace = root.appendingPathComponent("repo", isDirectory: true) + let agentRoot = root.appendingPathComponent("omp-agent", isDirectory: true) + let projectDirectory = try #require(PiSessionLocator.projectDirectoryName(for: workspace.path)) + let projectSessions = agentRoot + .appendingPathComponent("sessions", isDirectory: true) + .appendingPathComponent(projectDirectory, isDirectory: true) + try FileManager.default.createDirectory(at: projectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + + let latest = try Self.writeSessionFile( + id: "omp-agent-dir-session", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 2_000) + ) + + let detected = try #require(Self.detectedOmpSnapshot( + arguments: ["/Users/example/.bun/bin/omp"], + environment: [ + "PWD": workspace.path, + "PI_CODING_AGENT_DIR": agentRoot.path, + ] + )) + + #expect(detected.kind == RestorableAgentKind.custom("omp")) + #expect(Self.normalizedPath(detected.sessionId) == Self.normalizedPath(latest.path)) + #expect(detected.workingDirectory == workspace.path) + } + + @Test func directProcessDetectionUsesPiConfigDirectoryAgentSessionsWhenAgentDirectoryIsUnset() throws { + let root = try Self.makeTemporaryDirectory(prefix: "cmux-omp-config-dir-") + defer { try? FileManager.default.removeItem(at: root) } + let home = root.appendingPathComponent("home", isDirectory: true) + let workspace = root.appendingPathComponent("repo", isDirectory: true) + let projectDirectory = try #require(PiSessionLocator.projectDirectoryName(for: workspace.path)) + let projectSessions = home + .appendingPathComponent(".custom-omp", isDirectory: true) + .appendingPathComponent("agent", isDirectory: true) + .appendingPathComponent("sessions", isDirectory: true) + .appendingPathComponent(projectDirectory, isDirectory: true) + try FileManager.default.createDirectory(at: projectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + + let latest = try Self.writeSessionFile( + id: "omp-config-dir-session", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 2_000) + ) + + let detected = try #require(Self.detectedOmpSnapshot( + arguments: ["/Users/example/.bun/bin/omp"], + environment: [ + "HOME": home.path, + "PWD": workspace.path, + "PI_CONFIG_DIR": ".custom-omp", + ] + )) + + #expect(detected.kind == RestorableAgentKind.custom("omp")) + #expect(Self.normalizedPath(detected.sessionId) == Self.normalizedPath(latest.path)) + #expect(detected.workingDirectory == workspace.path) + } + + @Test func directProcessDetectionPreservesCustomSessionDirectoryBeforeOmpEnvironment() throws { + let root = try Self.makeTemporaryDirectory(prefix: "cmux-omp-custom-session-dir-") + defer { try? FileManager.default.removeItem(at: root) } + let workspace = root.appendingPathComponent("repo", isDirectory: true) + let customRoot = root.appendingPathComponent("custom-sessions", isDirectory: true) + let environmentRoot = root.appendingPathComponent("environment-sessions", isDirectory: true) + let projectDirectory = try #require(PiSessionLocator.projectDirectoryName(for: workspace.path)) + let customProjectSessions = customRoot.appendingPathComponent(projectDirectory, isDirectory: true) + let environmentProjectSessions = environmentRoot + .appendingPathComponent("sessions", isDirectory: true) + .appendingPathComponent(projectDirectory, isDirectory: true) + try FileManager.default.createDirectory(at: customProjectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: environmentProjectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + + let custom = try Self.writeSessionFile( + id: "omp-custom-session-dir-session", + in: customProjectSessions, + modifiedAt: Date(timeIntervalSince1970: 1_000) + ) + let environment = try Self.writeSessionFile( + id: "omp-environment-session", + in: environmentProjectSessions, + modifiedAt: Date(timeIntervalSince1970: 2_000) + ) + + let registration = CmuxVaultAgentRegistration( + id: "omp", + name: "OMP", + detect: CmuxVaultAgentDetectRule(processName: "omp"), + sessionIdSource: .piSessionFile, + resumeCommand: "{{executable}} --session {{sessionId}}", + sessionDirectory: customRoot.path + ) + let detected = try #require(Self.detectedOmpSnapshot( + arguments: ["/Users/example/.bun/bin/omp"], + environment: [ + "PWD": workspace.path, + "PI_CODING_AGENT_DIR": environmentRoot.path, + ], + registration: registration + )) + + #expect(detected.kind == RestorableAgentKind.custom("omp")) + #expect(Self.normalizedPath(detected.sessionId) == Self.normalizedPath(custom.path)) + #expect(Self.normalizedPath(detected.sessionId) != Self.normalizedPath(environment.path)) + #expect(detected.workingDirectory == workspace.path) + } + + @Test func vaultDetectsBunInvokedOmpPackage() throws { + let root = try Self.makeTemporaryDirectory(prefix: "cmux-omp-bun-vault-") + defer { try? FileManager.default.removeItem(at: root) } + let workspace = root.appendingPathComponent("repo", isDirectory: true) + let sessionsRoot = root.appendingPathComponent("sessions", isDirectory: true) + let projectDirectory = try #require(PiSessionLocator.projectDirectoryName(for: workspace.path)) + let projectSessions = sessionsRoot.appendingPathComponent(projectDirectory, isDirectory: true) + try FileManager.default.createDirectory(at: projectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + + let latest = try Self.writeSessionFile( + id: "omp-bun-session", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 2_000) + ) + + let detected = try #require(Self.detectedOmpSnapshot( + processName: "bun", + processPath: "/opt/homebrew/bin/bun", + arguments: [ + "/opt/homebrew/bin/bun", + "/Users/example/.bun/install/global/node_modules/@oh-my-pi/pi-coding-agent/src/main.ts", + "--model", + "anthropic/claude-sonnet-4-5", + ], + environment: [ + "PWD": workspace.path, + "PI_CODING_AGENT_SESSION_DIR": sessionsRoot.path, + ] + )) + + #expect(detected.kind == RestorableAgentKind.custom("omp")) + #expect(Self.normalizedPath(detected.sessionId) == Self.normalizedPath(latest.path)) + #expect(detected.workingDirectory == workspace.path) + } + + + + @Test func taskManagerClassifiesOmpBeforeLegacyPiPackageNeedles() throws { + let direct = try #require(CmuxTaskManagerCodingAgentDefinition.matchingDefinition( + processName: "omp", + processPath: "/Users/example/.bun/bin/omp", + arguments: ["/Users/example/.bun/bin/omp", "--model", "anthropic/claude-sonnet-4-5"], + environment: [:] + )) + #expect(direct.id == "omp") + + let hostedOmp = try #require(CmuxTaskManagerCodingAgentDefinition.matchingDefinition( + processName: "bun", + processPath: "/opt/homebrew/bin/bun", + arguments: [ + "/opt/homebrew/bin/bun", + "/Users/example/.bun/install/global/node_modules/@oh-my-pi/pi-coding-agent/src/main.ts", + "--model", + "anthropic/claude-sonnet-4-5", + ], + environment: [:] + )) + #expect(hostedOmp.id == "omp") + + let legacyPi = try #require(CmuxTaskManagerCodingAgentDefinition.matchingDefinition( + processName: "bun", + processPath: "/opt/homebrew/bin/bun", + arguments: [ + "/opt/homebrew/bin/bun", + "/Users/example/.bun/install/global/node_modules/@mariozechner/pi-coding-agent/src/main.ts", + "--model", + "anthropic/claude-sonnet-4-5", + ], + environment: [:] + )) + #expect(legacyPi.id == "pi") + } + + private static func detectedOmpSnapshot( + processName: String = "omp", + processPath: String? = "/Users/example/.bun/bin/omp", + arguments: [String], + environment: [String: String], + registration: CmuxVaultAgentRegistration = .builtInOmp + ) -> SessionRestorableAgentSnapshot? { + let workspaceId = UUID(uuidString: "11111111-1111-1111-1111-111111111111")! + let panelId = UUID(uuidString: "22222222-2222-2222-2222-222222222222")! + let processId = 4242 + let panelKey = RestorableAgentSessionIndex.PanelKey(workspaceId: workspaceId, panelId: panelId) + let processSnapshot = CmuxTopProcessSnapshot( + processes: [ + CmuxTopProcessInfo( + pid: processId, + parentPID: 1, + name: processName, + path: processPath, + ttyDevice: nil, + cmuxWorkspaceID: workspaceId, + cmuxSurfaceID: panelId, + cmuxAttributionReason: "cmux-test", + processGroupID: nil, + terminalProcessGroupID: nil, + cpuPercent: 0, + residentBytes: 0, + virtualBytes: 0, + threadCount: 1 + ) + ], + sampledAt: Date(timeIntervalSince1970: 0), + includesProcessDetails: true + ) + return RestorableAgentSessionIndex.processDetectedSnapshots( + registry: CmuxVaultAgentRegistry(registrations: [registration]), + fileManager: FileManager.default, + processSnapshot: processSnapshot, + capturedAt: 42, + processArgumentsProvider: { requestedProcessId in + guard requestedProcessId == processId else { return nil } + return CmuxTopProcessArguments(arguments: arguments, environment: environment) + } + )[panelKey]?.snapshot + } + + private static func normalizedPath(_ path: String) -> String { + URL(fileURLWithPath: path).resolvingSymlinksInPath().path + } + + private static func makeTemporaryDirectory(prefix: String) throws -> URL { + let url = FileManager.default.temporaryDirectory.resolvingSymlinksInPath() + .appendingPathComponent(prefix + UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + private static func writeSessionFile(id: String, in directory: URL, modifiedAt: Date) throws -> URL { + let url = directory.appendingPathComponent("\(id).jsonl", isDirectory: false) + try "{}\n".write(to: url, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.modificationDate: modifiedAt], ofItemAtPath: url.path) + return url + } +} diff --git a/cmuxTests/PiVaultAgentPersistenceTests.swift b/cmuxTests/PiVaultAgentPersistenceTests.swift index f7a2f64b84b6..671fb51adc0d 100644 --- a/cmuxTests/PiVaultAgentPersistenceTests.swift +++ b/cmuxTests/PiVaultAgentPersistenceTests.swift @@ -68,6 +68,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { XCTAssertEqual(SessionAgent.registered(agent).assetName, "AgentIcons/Pi") } + func testBuiltInAntigravityRegistrationUsesBrandedIconAsset() { let agent = RegisteredSessionAgent(registration: CmuxVaultAgentRegistration.builtInAntigravity) diff --git a/cmuxTests/TaskManagerResourcesTests.swift b/cmuxTests/TaskManagerResourcesTests.swift index bdc7708438f3..1578ea11db33 100644 --- a/cmuxTests/TaskManagerResourcesTests.swift +++ b/cmuxTests/TaskManagerResourcesTests.swift @@ -43,6 +43,7 @@ final class TaskManagerResourcesTests: XCTestCase { XCTAssertEqual(definition.assetName, "AgentIcons/Antigravity") } + func testAttributedPayloadProratesSharedResourceMeasurements() { let summary = resourceSummary() diff --git a/docs/agent-hooks.md b/docs/agent-hooks.md index af41f1574cbc..040d3245b6f8 100644 --- a/docs/agent-hooks.md +++ b/docs/agent-hooks.md @@ -11,7 +11,7 @@ cmux hooks setup --agent cmux hooks uninstall ``` -Supported agent names are `codex`, `grok`, `opencode`, `pi`, `amp`, `cursor`, `gemini`, `kiro`, `rovodev` (or `rovo`), `copilot`, `codebuddy`, `factory`, and `qoder`. `cmux hooks setup` skips agents whose binary is not on `PATH` and prints a summary. +Supported agent names are `codex`, `grok`, `opencode`, `pi`, `omp`, `amp`, `cursor`, `gemini`, `kiro`, `rovodev` (or `rovo`), `copilot`, `codebuddy`, `factory`, and `qoder`. `cmux hooks setup` skips agents whose binary is not on `PATH` and prints a summary. ## Integrations @@ -22,6 +22,7 @@ Supported agent names are `codex`, `grok`, `opencode`, `pi`, `amp`, `cursor`, `g | 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 | +| 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 | | Gemini | `gemini` | `~/.gemini/settings.json` | `gemini --resume ` | PreToolUse | @@ -114,6 +115,7 @@ and browser state. Restored agent terminals stay idle until you resume them manu | Grok | `GROK_HOME` | `CMUX_GROK_HOOKS_DISABLED=1` | | OpenCode | `OPENCODE_CONFIG_DIR` | `CMUX_OPENCODE_HOOKS_DISABLED=1` | | Pi | `PI_CODING_AGENT_DIR` | `CMUX_PI_HOOKS_DISABLED=1` | +| OMP | `PI_CODING_AGENT_DIR` for the full agent directory; otherwise `PI_CONFIG_DIR` for the config root | `CMUX_OMP_HOOKS_DISABLED=1` | | Amp | none | `CMUX_AMP_HOOKS_DISABLED=1` | | Cursor CLI | none | `CMUX_CURSOR_HOOKS_DISABLED=1` | | Gemini | none | `CMUX_GEMINI_HOOKS_DISABLED=1` | @@ -126,6 +128,8 @@ and browser state. Restored agent terminals stay idle until you resume them manu Pi uses Pi's extension system, not the legacy Pi hooks API. The installed extension is auto-discovered from `~/.pi/agent/extensions/` or `$PI_CODING_AGENT_DIR/extensions/`. +OMP uses OMP's native extension system. OMP native extension discovery scans `${PI_CODING_AGENT_DIR:-~/${PI_CONFIG_DIR:-.omp}/agent}/extensions/`, so cmux installs OMP's extension with a distinct `cmux-omp-session.ts` filename and does not reuse Pi's `cmux-session.ts`. + Kiro stores hooks inside agent configuration files. The cmux installer creates or updates a `cmux` agent config with lifecycle, tool, and completion hooks; merge the generated `hooks` block into another Kiro agent config if you want the same cmux notifications on that agent. Kiro Feed verbosity follows **Settings > Automation > Kiro Notification Level** or `automation.kiroNotificationLevel` in `cmux.json`. `minimal` keeps actionable approval cards only, `standard` also keeps mutating tool events, and `verbose` keeps every Kiro tool event. @@ -134,6 +138,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 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 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 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 7c7307d142bb..fe5175eaa9e1 100644 --- a/docs/feed.md +++ b/docs/feed.md @@ -85,6 +85,7 @@ Installs supported agent hooks whose binaries are on `PATH`. See [Agent hook int | Factory | `~/.factory/settings.json` | PreToolUse | | Qoder | `~/.qoder/settings.json` | PreToolUse | | Pi | `~/.pi/agent/extensions/cmux-session.ts` | lifecycle only | +| 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 | Individual agents: @@ -98,6 +99,8 @@ 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. + ## Decision semantics **Permission modes** diff --git a/docs/vault.md b/docs/vault.md index 308691a35bc5..9527d1e85c62 100644 --- a/docs/vault.md +++ b/docs/vault.md @@ -4,7 +4,7 @@ Vault restores built-in agent sessions and can also read custom agent registrati `cmux.json`. Registrations define how cmux detects a running terminal process, where the agent's native session id comes from, and which command resumes that session. -Pi Coding Agent is registered by default: +Pi Coding Agent and OMP are registered by default: ```jsonc { @@ -21,6 +21,17 @@ Pi Coding Agent is registered by default: "resumeCommand": "{{executable}} --session {{sessionId}}", "cwd": "preserve", "sessionDirectory": "~/.pi/agent/sessions" + }, + { + "id": "omp", + "name": "OMP", + "detect": { + "processName": "omp" + }, + "sessionIdSource": { "type": "piSessionFile" }, + "resumeCommand": "{{executable}} --session {{sessionId}}", + "cwd": "preserve", + "sessionDirectory": "~/.omp/agent/sessions" } ] } @@ -53,6 +64,8 @@ For a generic agent that exposes the current session as an argv option: Supported `resumeCommand` placeholders are `{{sessionId}}`, `{{sessionPath}}`, `{{executable}}`, `{{cwd}}`, and `{{sessionDir}}`. Pi uses `pi --session ` instead of `pi --continue` so Vault reopens the exact saved session. +OMP accepts `--session`, `--resume`, and `-r` for existing sessions; Vault emits `omp --session ` so relaunch reopens the exact saved OMP session. + `resumeCommand` must include either `{{sessionId}}` or `{{sessionPath}}`, for example `pi --session {{sessionId}}`. diff --git a/tests/test_omp_extension_install.py b/tests/test_omp_extension_install.py new file mode 100755 index 000000000000..4e5447a73d8d --- /dev/null +++ b/tests/test_omp_extension_install.py @@ -0,0 +1,590 @@ +#!/usr/bin/env python3 +""" +Regression test: the generated OMP extension is importable and emits cmux hook calls without blocking OMP handlers. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shutil +import subprocess +import socket +import tempfile +import time +import threading +from pathlib import Path + +from claude_teams_test_utils import resolve_cmux_cli + + +def make_executable(path: Path, content: str) -> None: + path.write_text(content, encoding="utf-8") + 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 "" + + +class MockCmuxSocket: + def __init__(self, path: Path, workspace_id: str, surface_id: str) -> None: + self.path = path + self.workspace_id = workspace_id + self.surface_id = surface_id + self._messages: list[str] = [] + self._lock = threading.Lock() + self._stop = threading.Event() + self._server: socket.socket | None = None + self._thread: threading.Thread | None = None + + def __enter__(self) -> "MockCmuxSocket": + try: + self.path.unlink() + except FileNotFoundError: + pass + server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + server.bind(str(self.path)) + server.listen(16) + server.settimeout(0.1) + self._server = server + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + return self + + def __exit__(self, *_exc: object) -> None: + self._stop.set() + try: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.connect(str(self.path)) + except OSError: + pass + if self._thread is not None: + self._thread.join(timeout=2) + if self._server is not None: + self._server.close() + try: + self.path.unlink() + except FileNotFoundError: + pass + + def messages(self) -> list[str]: + with self._lock: + return list(self._messages) + + def _serve(self) -> None: + assert self._server is not None + while not self._stop.is_set(): + try: + conn, _addr = self._server.accept() + except TimeoutError: + continue + except OSError: + return + self._handle(conn) + + def _handle(self, conn: socket.socket) -> None: + with conn: + reader = conn.makefile("rb") + while True: + line_bytes = reader.readline() + if not line_bytes: + return + line = line_bytes.decode("utf-8", errors="replace").rstrip("\n") + if line: + with self._lock: + self._messages.append(line) + response = self._response(line) + try: + conn.sendall(response.encode("utf-8") + b"\n") + except BrokenPipeError: + return + + def _response(self, line: str) -> str: + try: + payload = json.loads(line) + except json.JSONDecodeError: + return "OK" + request_id = payload.get("id") or "unknown" + method = payload.get("method") + if method == "surface.list": + result = { + "surfaces": [ + { + "id": self.surface_id, + "ref": "surface:1", + "focused": True, + } + ] + } + elif method == "surface.resume.set": + result = {"ok": True} + elif method == "feed.push": + result = {} + else: + result = {} + return json.dumps({"id": request_id, "ok": True, "result": result}, separators=(",", ":")) + + +def json_rpc_messages(messages: list[str], method: str) -> list[dict[str, object]]: + matches: list[dict[str, object]] = [] + for line in messages: + try: + payload = json.loads(line) + except json.JSONDecodeError: + continue + if payload.get("method") == method: + matches.append(payload) + return matches + + +def verify_hook_persistence(cli_path: str, root: Path, base_env: dict[str, str]) -> bool: + hook_state_dir = root / "hook-state" + workspace = root / "hook-workspace" + hook_state_dir.mkdir() + workspace.mkdir() + workspace_id = "11111111-1111-1111-1111-111111111111" + surface_id = "22222222-2222-2222-2222-222222222222" + session_id = "omp-hook-session-123" + socket_path = Path("/tmp") / f"cmux-omp-hook-{os.getpid()}-{time.monotonic_ns()}.sock" + launch_argv = [ + "/Users/example/.bun/bin/omp", + "--resume", + "old-session", + "--model", + "anthropic/claude-sonnet-4-5", + "initial prompt should not persist", + ] + hook_env = base_env.copy() + hook_env.pop("PI_CODING_AGENT_DIR", None) + hook_env.update( + { + "PWD": str(workspace), + "CMUX_SOCKET_PATH": str(socket_path), + "CMUX_WORKSPACE_ID": workspace_id, + "CMUX_SURFACE_ID": surface_id, + "CMUX_AGENT_HOOK_STATE_DIR": str(hook_state_dir), + "CMUX_AGENT_LAUNCH_KIND": "omp", + "CMUX_AGENT_LAUNCH_EXECUTABLE": launch_argv[0], + "CMUX_AGENT_LAUNCH_ARGV_B64": base64.b64encode( + b"".join(value.encode("utf-8") + b"\0" for value in launch_argv) + ).decode("ascii"), + "CMUX_AGENT_LAUNCH_CWD": str(workspace), + "CMUX_CLI_SENTRY_DISABLED": "1", + "PI_CONFIG_DIR": ".custom-omp", + "OPENAI_API_KEY": "secret-should-not-persist", + } + ) + hook_input = json.dumps( + { + "session_id": session_id, + "cwd": str(workspace), + "hook_event_name": "SessionStart", + }, + separators=(",", ":"), + ) + + with MockCmuxSocket(socket_path, workspace_id=workspace_id, surface_id=surface_id) as server: + result = subprocess.run( + [cli_path, "hooks", "omp", "session-start"], + input=hook_input, + capture_output=True, + text=True, + check=False, + env=hook_env, + timeout=20, + ) + if result.returncode != 0 or result.stdout != "{}\n": + print("FAIL: omp session-start hook persistence command failed") + print(f"exit={result.returncode}") + print(f"stdout={result.stdout.strip()}") + print(f"stderr={result.stderr.strip()}") + return False + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if json_rpc_messages(server.messages(), "surface.resume.set"): + break + time.sleep(0.05) + messages = server.messages() + + store_path = hook_state_dir / "omp-hook-sessions.json" + if not store_path.exists(): + print(f"FAIL: omp hook did not write {store_path}") + return False + try: + store = json.loads(store_path.read_text(encoding="utf-8")) + session = store["sessions"][session_id] + except Exception as exc: + print(f"FAIL: omp hook session store did not contain {session_id}: {exc}") + print(store_path.read_text(encoding="utf-8")) + return False + + expected_fields = { + "sessionId": session_id, + "workspaceId": workspace_id, + "surfaceId": surface_id, + "cwd": str(workspace), + } + for key, expected in expected_fields.items(): + if session.get(key) != expected: + print(f"FAIL: omp hook session {key} expected {expected!r}, got {session.get(key)!r}") + return False + + launch_command = session.get("launchCommand") + if not isinstance(launch_command, dict): + print(f"FAIL: omp hook did not persist launch metadata: {session!r}") + return False + expected_arguments = [ + "/Users/example/.bun/bin/omp", + "--model", + "anthropic/claude-sonnet-4-5", + ] + if launch_command.get("launcher") != "omp" or launch_command.get("executablePath") != launch_argv[0]: + print(f"FAIL: omp hook persisted wrong launcher metadata: {launch_command!r}") + return False + if launch_command.get("arguments") != expected_arguments: + print(f"FAIL: omp hook persisted unsanitized launch arguments: {launch_command!r}") + return False + if launch_command.get("workingDirectory") != str(workspace): + print(f"FAIL: omp hook persisted wrong working directory: {launch_command!r}") + return False + if launch_command.get("environment") != {"PI_CONFIG_DIR": ".custom-omp"}: + print(f"FAIL: omp hook did not persist PI_CONFIG_DIR for resume: {launch_command!r}") + return False + if "secret-should-not-persist" in json.dumps(session, sort_keys=True): + print(f"FAIL: omp hook persisted secret environment data: {session!r}") + return False + + resume_sets = json_rpc_messages(messages, "surface.resume.set") + if len(resume_sets) != 1: + print(f"FAIL: expected one surface.resume.set, saw {messages!r}") + return False + params = resume_sets[0].get("params") + if not isinstance(params, dict): + print(f"FAIL: surface.resume.set missing params: {resume_sets[0]!r}") + return False + if params.get("kind") != "omp" or params.get("checkpoint_id") != session_id or params.get("auto_resume") is not True: + print(f"FAIL: surface.resume.set had wrong OMP binding params: {params!r}") + return False + command = params.get("command") + if not isinstance(command, str) or "--session" not in command or session_id not in command: + print(f"FAIL: surface.resume.set command cannot resume OMP session: {params!r}") + return False + return True + + +def main() -> int: + bun = shutil.which("bun") + if bun is None: + print("SKIP: bun not found") + return 0 + + try: + cli_path = resolve_cmux_cli() + except Exception as exc: + print(f"FAIL: {exc}") + return 1 + + with tempfile.TemporaryDirectory(prefix="cmux-omp-extension-") as td: + root = Path(td) + home = root / "home" + home.mkdir() + shared_agent_dir = root / "shared-agent-dir" + shared_pi_extension = shared_agent_dir / "extensions" / "cmux-session.ts" + shared_pi_extension.parent.mkdir(parents=True) + shared_pi_extension.write_text("// cmux-pi-session-extension-marker v1\n", encoding="utf-8") + + env = os.environ.copy() + env["HOME"] = str(home) + # OMP treats PI_CODING_AGENT_DIR as the full agent directory override. + # Install the OMP extension there while proving it does not collide with + # Pi's different cmux-session.ts filename in the same extensions folder. + env["PI_CODING_AGENT_DIR"] = str(shared_agent_dir) + + install = subprocess.run( + [cli_path, "hooks", "omp", "install", "--yes"], + capture_output=True, + text=True, + check=False, + env=env, + timeout=20, + ) + if install.returncode != 0: + print("FAIL: omp extension install failed") + print(f"exit={install.returncode}") + print(f"stdout={install.stdout.strip()}") + print(f"stderr={install.stderr.strip()}") + return 1 + + extension_path = shared_agent_dir / "extensions" / "cmux-omp-session.ts" + if not extension_path.exists(): + print(f"FAIL: expected extension at {extension_path}") + return 1 + extension_text = extension_path.read_text(encoding="utf-8") + if "cmux-omp-session-extension-marker" not in extension_text: + print(f"FAIL: expected cmux marker in {extension_path}") + return 1 + if shared_pi_extension.read_text(encoding="utf-8") != "// cmux-pi-session-extension-marker v1\n": + print("FAIL: OMP install modified the Pi extension in PI_CODING_AGENT_DIR") + return 1 + + reinstall = subprocess.run( + [cli_path, "hooks", "omp", "install", "--yes"], + capture_output=True, + text=True, + check=False, + env=env, + timeout=20, + ) + if reinstall.returncode != 0 or "already up to date" not in reinstall.stdout: + print("FAIL: omp extension reinstall was not idempotent") + print(f"exit={reinstall.returncode}") + print(f"stdout={reinstall.stdout.strip()}") + print(f"stderr={reinstall.stderr.strip()}") + return 1 + + 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" + make_executable( + fake_cmux, + """#!/usr/bin/env bash +set -euo pipefail +sleep 1 +printf '%s\n' "$*" >> "$FAKE_CMUX_ARGS_LOG" +cat >> "$FAKE_CMUX_STDIN_LOG" +printf '\n---\n' >> "$FAKE_CMUX_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-}" + if [ "${AMP_API_KEY-}" = "amp-secret" ]; then + printf 'amp=present\n' + else + printf 'amp=missing\n' + fi +} >> "$FAKE_CMUX_ENV_LOG" +""", + ) + + check_env = env.copy() + check_env["CMUX_TEST_OMP_EXTENSION_PATH"] = str(extension_path) + check_env["CMUX_SURFACE_ID"] = "surface-omp-test" + check_env["CMUX_OMP_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["AMP_API_KEY"] = "amp-secret" + check_source = """ +const extensionPath = process.env.CMUX_TEST_OMP_EXTENSION_PATH; +const mod = await import(extensionPath); +if (typeof mod.default !== "function") throw new Error("missing default export"); +const handlers = new Map(); +mod.default({ + on(name, handler) { + handlers.set(name, handler); + } +}); +for (const name of ["session_start", "before_agent_start", "agent_end"]) { + if (typeof handlers.get(name) !== "function") throw new Error(`missing ${name}`); +} +process.argv.splice( + 0, + process.argv.length, + "/Users/example/.bun/bin/omp", + "--model", + "anthropic/claude-sonnet-4-5" +); +const ctx = { + cwd: "/tmp/omp-project", + sessionManager: { + getSessionId() { return "omp-session-test"; } + } +}; +const start = Date.now(); +await handlers.get("session_start")({}, ctx); +await handlers.get("before_agent_start")({ prompt: "hello omp" }, ctx); +await handlers.get("agent_end")({ + messages: [ + { role: "user", content: "hello omp" }, + { role: "assistant", content: [{ type: "text", text: "done" }] } + ], + stopReason: "completed" +}, ctx); +const elapsed = Date.now() - start; +if (elapsed > 800) throw new Error(`handlers blocked for ${elapsed}ms`); +""" + check = subprocess.run( + [bun, "--eval", check_source], + cwd=root, + capture_output=True, + text=True, + check=False, + env=check_env, + timeout=20, + ) + if check.returncode != 0: + print("FAIL: generated OMP extension is not importable or blocks handlers") + print(f"exit={check.returncode}") + print(f"stdout={check.stdout.strip()}") + print(f"stderr={check.stderr.strip()}") + return 1 + + args_log = wait_for_text(fake_args_log, 3) + stdin_log = wait_for_text(fake_stdin_log, 3) + env_log = wait_for_text(fake_env_log, 12) + for expected in [ + "hooks omp session-start", + "hooks omp prompt-submit", + "hooks omp stop", + ]: + if expected not in args_log: + print(f"FAIL: extension did not invoke {expected}, got {args_log!r}") + return 1 + if '"session_id":"omp-session-test"' not in stdin_log: + print(f"FAIL: extension did not pass session id, got {stdin_log!r}") + return 1 + if '"prompt":"hello omp"' 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}") + return 1 + if "kind=omp" not in env_log or "cwd=/tmp/omp-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 + if "amp=present" not in env_log: + print(f"FAIL: extension stripped unrelated AMP_API_KEY from hook environment, got {env_log!r}") + return 1 + argv_line = next((line for line in env_log.splitlines() if line.startswith("argv=")), "") + try: + decoded_argv = [ + value + for value in base64.b64decode(argv_line.removeprefix("argv=")).decode("utf-8").split("\0") + if value + ] + except Exception as exc: + 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/omp", + "--model", + "anthropic/claude-sonnet-4-5", + ] + if decoded_argv != expected_argv: + print(f"FAIL: extension captured wrong OMP launch argv; expected {expected_argv!r}, got {decoded_argv!r}") + return 1 + + if not verify_hook_persistence(cli_path, root, env): + return 1 + + uninstall = subprocess.run( + [cli_path, "hooks", "omp", "uninstall", "--yes"], + capture_output=True, + text=True, + check=False, + env=env, + timeout=20, + ) + if uninstall.returncode != 0 or extension_path.exists(): + print("FAIL: omp extension uninstall failed") + print(f"exit={uninstall.returncode}") + print(f"stdout={uninstall.stdout.strip()}") + print(f"stderr={uninstall.stderr.strip()}") + return 1 + foreign_path = extension_path + foreign_path.parent.mkdir(parents=True, exist_ok=True) + foreign_path.write_text("// user extension\n", encoding="utf-8") + uninstall_foreign = subprocess.run( + [cli_path, "hooks", "omp", "uninstall", "--yes"], + capture_output=True, + text=True, + check=False, + env=env, + timeout=20, + ) + if uninstall_foreign.returncode != 0 or not foreign_path.exists() or "Refusing to remove" not in uninstall_foreign.stdout: + print("FAIL: omp extension uninstall did not preserve non-cmux file") + print(f"exit={uninstall_foreign.returncode}") + print(f"stdout={uninstall_foreign.stdout.strip()}") + print(f"stderr={uninstall_foreign.stderr.strip()}") + return 1 + + invalid_extension_bytes = b"\xff\xfe\x00cmux-not-utf8" + foreign_path.write_bytes(invalid_extension_bytes) + install_invalid = subprocess.run( + [cli_path, "hooks", "omp", "install", "--yes"], + capture_output=True, + text=True, + check=False, + env=env, + timeout=20, + ) + if install_invalid.returncode == 0 or foreign_path.read_bytes() != invalid_extension_bytes: + print("FAIL: omp extension install overwrote unreadable existing file") + print(f"exit={install_invalid.returncode}") + print(f"stdout={install_invalid.stdout.strip()}") + print(f"stderr={install_invalid.stderr.strip()}") + return 1 + uninstall_invalid = subprocess.run( + [cli_path, "hooks", "omp", "uninstall", "--yes"], + capture_output=True, + text=True, + check=False, + env=env, + timeout=20, + ) + if uninstall_invalid.returncode == 0 or foreign_path.read_bytes() != invalid_extension_bytes: + print("FAIL: omp extension uninstall removed unreadable existing file") + print(f"exit={uninstall_invalid.returncode}") + print(f"stdout={uninstall_invalid.stdout.strip()}") + print(f"stderr={uninstall_invalid.stderr.strip()}") + return 1 + foreign_path.unlink() + + + config_override = root / "absolute-omp-config" + config_env = env.copy() + config_env.pop("PI_CODING_AGENT_DIR", None) + config_env["PI_CONFIG_DIR"] = str(config_override) + config_install = subprocess.run( + [cli_path, "hooks", "omp", "install", "--yes"], + capture_output=True, + text=True, + check=False, + env=config_env, + timeout=20, + ) + config_extension_path = config_override / "agent" / "extensions" / "cmux-omp-session.ts" + if config_install.returncode != 0 or not config_extension_path.exists(): + print("FAIL: omp extension install did not respect absolute PI_CONFIG_DIR") + print(f"exit={config_install.returncode}") + print(f"stdout={config_install.stdout.strip()}") + print(f"stderr={config_install.stderr.strip()}") + return 1 + config_uninstall = subprocess.run( + [cli_path, "hooks", "omp", "uninstall", "--yes"], + capture_output=True, + text=True, + check=False, + env=config_env, + timeout=20, + ) + if config_uninstall.returncode != 0 or config_extension_path.exists(): + print("FAIL: omp extension uninstall did not respect absolute PI_CONFIG_DIR") + print(f"exit={config_uninstall.returncode}") + print(f"stdout={config_uninstall.stdout.strip()}") + print(f"stderr={config_uninstall.stderr.strip()}") + return 1 + print("PASS: generated OMP extension installs, emits non-blocking cmux hooks, and persists hook sessions") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/web/app/[locale]/docs/session-restore/page.tsx b/web/app/[locale]/docs/session-restore/page.tsx index 3cc4b8c730b5..00d5fd61a935 100644 --- a/web/app/[locale]/docs/session-restore/page.tsx +++ b/web/app/[locale]/docs/session-restore/page.tsx @@ -44,6 +44,7 @@ export default function SessionRestorePage() { cmux hooks setup codex cmux hooks setup grok cmux hooks setup antigravity +cmux hooks setup omp cmux hooks setup --agent opencode`}

{t("setupBehavior")}

@@ -95,6 +96,12 @@ cmux surface resume clear --checkpoint work`} pi --session <id> {t("none")} + + OMP + omp + omp --session <id> + {t("none")} + Amp amp From 055f337cdaeb734d95b052acf5921dbb4d79eabb Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 4 Jun 2026 19:53:53 -0700 Subject: [PATCH 2/6] Address OMP review feedback --- CLI/CMUXCLI+AgentHookDefinitions.swift | 8 +- CLI/CMUXCLI+OmpExtension.swift | 15 ++- Resources/Localizable.xcstrings | 125 +++++++++++++++++++++++++ Sources/VaultAgentProcessScanner.swift | 55 ++++++++++- cmuxTests/OmpSupportTests.swift | 79 ++++++++++++++++ 5 files changed, 269 insertions(+), 13 deletions(-) diff --git a/CLI/CMUXCLI+AgentHookDefinitions.swift b/CLI/CMUXCLI+AgentHookDefinitions.swift index a4b9b48fdca9..47649cce960f 100644 --- a/CLI/CMUXCLI+AgentHookDefinitions.swift +++ b/CLI/CMUXCLI+AgentHookDefinitions.swift @@ -13,6 +13,7 @@ extension CMUXCLI { let configDirEnvOverride: String? // e.g. "CODEX_HOME" overrides configDir let configDirEnvOverrideSubpath: String? // e.g. "GROK_HOME" + "hooks" let createConfigDirIfMissing: Bool // for agents whose hook dir is created lazily + let configDirResolver: (() -> String)? let sessionStoreSuffix: String // e.g. "cursor" -> ~/.cmuxterm/cursor-hook-sessions.json let disableEnvVar: String // e.g. "CMUX_CURSOR_HOOKS_DISABLED" let hookMarker: String // Marker in commands: "cmux hooks cursor" @@ -70,8 +71,8 @@ extension CMUXCLI { /// Resolves the config directory, respecting env override if set. func resolvedConfigDir() -> String { - if name == "omp" { - return CMUXCLI.resolvedOmpAgentDirectory().path + if let configDirResolver { + return configDirResolver() } let home = ProcessInfo.processInfo.environment["HOME"].flatMap { value -> String? in let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) @@ -101,6 +102,7 @@ extension CMUXCLI { configDir: String, configFile: String, configDirEnvOverride: String? = nil, configDirEnvOverrideSubpath: String? = nil, createConfigDirIfMissing: Bool = false, + configDirResolver: (() -> String)? = nil, binaryName: String? = nil, sessionStoreSuffix: String, disableEnvVar: String, hookMarker: String, format: HookFormat, events: [HookEvent], @@ -115,6 +117,7 @@ extension CMUXCLI { self.configDirEnvOverride = configDirEnvOverride self.configDirEnvOverrideSubpath = configDirEnvOverrideSubpath self.createConfigDirIfMissing = createConfigDirIfMissing + self.configDirResolver = configDirResolver self.binaryName = binaryName ?? name self.sessionStoreSuffix = sessionStoreSuffix; self.disableEnvVar = disableEnvVar self.hookMarker = hookMarker; self.format = format; self.events = events @@ -200,6 +203,7 @@ extension CMUXCLI { name: "omp", displayName: "OMP", statusKey: "omp", configDir: ".omp/agent", configFile: "extensions/cmux-omp-session.ts", createConfigDirIfMissing: true, + configDirResolver: { CMUXCLI.resolvedOmpAgentDirectory().path }, sessionStoreSuffix: "omp", disableEnvVar: "CMUX_OMP_HOOKS_DISABLED", hookMarker: "cmux hooks omp", format: .flat, events: [] diff --git a/CLI/CMUXCLI+OmpExtension.swift b/CLI/CMUXCLI+OmpExtension.swift index 8b8995436c26..fcc5bc85693d 100644 --- a/CLI/CMUXCLI+OmpExtension.swift +++ b/CLI/CMUXCLI+OmpExtension.swift @@ -28,7 +28,7 @@ function resolveExecutable(name: string): string { const candidate = path.join(dir, name); try { fs.accessSync(candidate, fs.constants.X_OK); - return candidate; + if (fs.statSync(candidate).isFile()) return candidate; } catch (_) {} } return name; @@ -205,18 +205,17 @@ export default function cmuxOmpSessionExtension(api: ExtensionAPI) { do { return try String(contentsOf: url, encoding: .utf8) } catch { - let message = String.localizedStringWithFormat( + throw CLIError(message: String.localizedStringWithFormat( String( - localized: "cli.hooks.omp.error.notCmuxExtension", - defaultValue: "%@ exists and is not a cmux extension; leaving it alone" + localized: "cli.hooks.omp.error.readFailed", + defaultValue: "Failed to read %@: %@" ), - url.path - ) - throw CLIError(message: "\(message): \(error.localizedDescription)") + url.path, + String(describing: error) + )) } } - func installOmpExtensionHooks(_ _: AgentHookDef) throws { let extensionURL = ompExtensionURL() let fileManager = FileManager.default diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 7e59ef5b37aa..2618bedafbd0 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -502,6 +502,131 @@ } } }, + "cli.hooks.omp.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.omp.installed": { "extractionState": "manual", "localizations": { diff --git a/Sources/VaultAgentProcessScanner.swift b/Sources/VaultAgentProcessScanner.swift index b9c48b6d1e7b..019adaec36f0 100644 --- a/Sources/VaultAgentProcessScanner.swift +++ b/Sources/VaultAgentProcessScanner.swift @@ -659,6 +659,10 @@ private struct VaultObservedAgentProcess: Sendable { return arguments[index] } + var piCompatibleSessionID: String? { + arguments.piCompatibleSessionID(startingAt: piCompatibleSessionArgumentStartIndex) + } + var openCodeExecutableArgumentIndex: Int? { if let first = arguments.first, Self.argumentLooksLikeOpenCode(first) { @@ -673,6 +677,17 @@ private struct VaultObservedAgentProcess: Sendable { return Self.argumentLooksLikeOpenCode(arguments[scriptIndex]) ? scriptIndex : nil } + private var piCompatibleSessionArgumentStartIndex: Int { + guard !arguments.isEmpty else { return 0 } + if let scriptIndex = Self.javaScriptRuntimeScriptArgumentIndex(arguments) { + return min(scriptIndex + 1, arguments.endIndex) + } + if arguments[arguments.startIndex].hasPrefix("-") { + return arguments.startIndex + } + return min(arguments.startIndex + 1, arguments.endIndex) + } + private var processIdentityLooksLikeOpenCode: Bool { executableBasenames.contains { basename in let normalized = basename.lowercased() @@ -705,6 +720,15 @@ private struct VaultObservedAgentProcess: Sendable { TmuxResumeParser.argumentLooksLikeTmuxServerProcessTitle(argument) } + private static func wrapperLooksLikeJavaScriptRuntime(_ basename: String) -> Bool { + switch basename.lowercased() { + case "node", "bun", "deno", "tsx", "ts-node": + return true + default: + return false + } + } + private static func wrapperLooksLikeNodeRuntime(_ basename: String) -> Bool { switch basename.lowercased() { case "node": @@ -714,6 +738,30 @@ private struct VaultObservedAgentProcess: Sendable { } } + private static func javaScriptRuntimeScriptArgumentIndex(_ arguments: [String]) -> Int? { + guard let first = arguments.first else { return nil } + guard wrapperLooksLikeJavaScriptRuntime((first as NSString).lastPathComponent) else { + return nil + } + var index = 1 + while index < arguments.count { + let argument = arguments[index] + if argument == "--" { + let nextIndex = index + 1 + return nextIndex < arguments.count ? nextIndex : nil + } + if argument.hasPrefix("-") { + if nodeOptionConsumesScript(argument) { + return nil + } + index += 1 + nodeOptionValueCount(argument) + continue + } + return index + } + return nil + } + private static func nodeScriptArgumentIndex(_ arguments: [String]) -> Int? { guard !arguments.isEmpty else { return nil } var index = 0 @@ -816,7 +864,7 @@ private extension CmuxVaultAgentSessionIDSource { case .argvOption(let option): return process.arguments.nonOptionValue(afterOption: option) case .piSessionFile: - if let session = process.arguments.piCompatibleSessionID { + if let session = process.piCompatibleSessionID { return PiSessionLocator.resolvedSessionPath( session, for: process, @@ -887,8 +935,9 @@ private extension Array where Element == String { return value } - var piCompatibleSessionID: String? { - for index in indices { + func piCompatibleSessionID(startingAt startIndex: Int) -> String? { + guard startIndex < endIndex else { return nil } + for index in indices where index >= startIndex { let argument = self[index] if argument == "--session" || argument == "--resume" || argument == "-r" { let nextIndex = self.index(after: index) diff --git a/cmuxTests/OmpSupportTests.swift b/cmuxTests/OmpSupportTests.swift index 0b8860e116b9..292ff469a1c5 100644 --- a/cmuxTests/OmpSupportTests.swift +++ b/cmuxTests/OmpSupportTests.swift @@ -246,7 +246,86 @@ struct OmpSupportTests { #expect(detected.workingDirectory == workspace.path) } + @Test func hostedOmpIgnoresRuntimePreloadFlagsBeforeAgentScript() throws { + let root = try Self.makeTemporaryDirectory(prefix: "cmux-omp-hosted-runtime-preload-") + defer { try? FileManager.default.removeItem(at: root) } + let workspace = root.appendingPathComponent("repo", isDirectory: true) + let sessionsRoot = root.appendingPathComponent("sessions", isDirectory: true) + let projectDirectory = try #require(PiSessionLocator.projectDirectoryName(for: workspace.path)) + let projectSessions = sessionsRoot.appendingPathComponent(projectDirectory, isDirectory: true) + try FileManager.default.createDirectory(at: projectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + + let latest = try Self.writeSessionFile( + id: "omp-hosted-latest-session", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 2_000) + ) + + let detected = try #require(Self.detectedOmpSnapshot( + processName: "node", + processPath: "/opt/homebrew/bin/node", + arguments: [ + "/opt/homebrew/bin/node", + "-r", + "/tmp/preload-session-module.js", + "/Users/example/.bun/install/global/node_modules/@oh-my-pi/pi-coding-agent/src/main.ts", + ], + environment: [ + "PWD": workspace.path, + "PI_CODING_AGENT_SESSION_DIR": sessionsRoot.path, + ] + )) + + #expect(detected.kind == RestorableAgentKind.custom("omp")) + #expect(Self.normalizedPath(detected.sessionId) == Self.normalizedPath(latest.path)) + #expect(detected.sessionId != "/tmp/preload-session-module.js") + #expect(detected.workingDirectory == workspace.path) + } + + @Test func hostedOmpParsesSessionSelectorsAfterAgentScript() throws { + let root = try Self.makeTemporaryDirectory(prefix: "cmux-omp-hosted-runtime-session-") + defer { try? FileManager.default.removeItem(at: root) } + let workspace = root.appendingPathComponent("repo", isDirectory: true) + let sessionsRoot = root.appendingPathComponent("sessions", isDirectory: true) + let projectDirectory = try #require(PiSessionLocator.projectDirectoryName(for: workspace.path)) + let projectSessions = sessionsRoot.appendingPathComponent(projectDirectory, isDirectory: true) + try FileManager.default.createDirectory(at: projectSessions, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + + let explicit = try Self.writeSessionFile( + id: "omp-hosted-explicit-session", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 1_000) + ) + let latest = try Self.writeSessionFile( + id: "omp-hosted-latest-session", + in: projectSessions, + modifiedAt: Date(timeIntervalSince1970: 2_000) + ) + + let detected = try #require(Self.detectedOmpSnapshot( + processName: "node", + processPath: "/opt/homebrew/bin/node", + arguments: [ + "/opt/homebrew/bin/node", + "-r", + "/tmp/preload-session-module.js", + "/Users/example/.bun/install/global/node_modules/@oh-my-pi/pi-coding-agent/src/main.ts", + "--session", + "omp-hosted-explicit-session", + ], + environment: [ + "PWD": workspace.path, + "PI_CODING_AGENT_SESSION_DIR": sessionsRoot.path, + ] + )) + #expect(detected.kind == RestorableAgentKind.custom("omp")) + #expect(Self.normalizedPath(detected.sessionId) == Self.normalizedPath(explicit.path)) + #expect(Self.normalizedPath(detected.sessionId) != Self.normalizedPath(latest.path)) + #expect(detected.workingDirectory == workspace.path) + } @Test func taskManagerClassifiesOmpBeforeLegacyPiPackageNeedles() throws { let direct = try #require(CmuxTaskManagerCodingAgentDefinition.matchingDefinition( From 7930e1fe02190662d06bc0bad6ec08f385e09090 Mon Sep 17 00:00:00 2001 From: joshrzemien Date: Fri, 5 Jun 2026 00:19:30 -0400 Subject: [PATCH 3/6] Address remaining OMP review feedback --- .github/workflows/ci.yml | 1 + CLI/CMUXCLI+AgentHookDefinitions.swift | 4 +-- CLI/CMUXCLI+OmpExtension.swift | 5 ++-- Resources/Localizable.xcstrings | 40 +++++++++++++------------- tests/test_omp_extension_install.py | 7 +++-- 5 files changed, 29 insertions(+), 28 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fbdbbce06745..239790ace2ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,7 @@ on: permissions: contents: read + actions: write concurrency: group: ${{ github.workflow }}-${{ github.ref }} diff --git a/CLI/CMUXCLI+AgentHookDefinitions.swift b/CLI/CMUXCLI+AgentHookDefinitions.swift index 47649cce960f..71b5b7ff1099 100644 --- a/CLI/CMUXCLI+AgentHookDefinitions.swift +++ b/CLI/CMUXCLI+AgentHookDefinitions.swift @@ -13,7 +13,7 @@ extension CMUXCLI { let configDirEnvOverride: String? // e.g. "CODEX_HOME" overrides configDir let configDirEnvOverrideSubpath: String? // e.g. "GROK_HOME" + "hooks" let createConfigDirIfMissing: Bool // for agents whose hook dir is created lazily - let configDirResolver: (() -> String)? + let configDirResolver: (@Sendable () -> String)? let sessionStoreSuffix: String // e.g. "cursor" -> ~/.cmuxterm/cursor-hook-sessions.json let disableEnvVar: String // e.g. "CMUX_CURSOR_HOOKS_DISABLED" let hookMarker: String // Marker in commands: "cmux hooks cursor" @@ -102,7 +102,7 @@ extension CMUXCLI { configDir: String, configFile: String, configDirEnvOverride: String? = nil, configDirEnvOverrideSubpath: String? = nil, createConfigDirIfMissing: Bool = false, - configDirResolver: (() -> String)? = nil, + configDirResolver: (@Sendable () -> String)? = nil, binaryName: String? = nil, sessionStoreSuffix: String, disableEnvVar: String, hookMarker: String, format: HookFormat, events: [HookEvent], diff --git a/CLI/CMUXCLI+OmpExtension.swift b/CLI/CMUXCLI+OmpExtension.swift index fcc5bc85693d..ac21e282d63a 100644 --- a/CLI/CMUXCLI+OmpExtension.swift +++ b/CLI/CMUXCLI+OmpExtension.swift @@ -208,10 +208,9 @@ export default function cmuxOmpSessionExtension(api: ExtensionAPI) { throw CLIError(message: String.localizedStringWithFormat( String( localized: "cli.hooks.omp.error.readFailed", - defaultValue: "Failed to read %@: %@" + defaultValue: "Failed to read %@" ), - url.path, - String(describing: error) + url.path )) } } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 2618bedafbd0..60b1c38196b4 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -508,121 +508,121 @@ "ar": { "stringUnit": { "state": "translated", - "value": "فشل في قراءة %@: %@" + "value": "فشل في قراءة %@" } }, "bs": { "stringUnit": { "state": "translated", - "value": "Čitanje %@ nije uspjelo: %@" + "value": "Čitanje %@ nije uspjelo" } }, "da": { "stringUnit": { "state": "translated", - "value": "Kunne ikke læse %@: %@" + "value": "Kunne ikke læse %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "Fehler beim Lesen von %@: %@" + "value": "Fehler beim Lesen von %@" } }, "en": { "stringUnit": { "state": "translated", - "value": "Failed to read %@: %@" + "value": "Failed to read %@" } }, "es": { "stringUnit": { "state": "translated", - "value": "No se pudo leer %@: %@" + "value": "No se pudo leer %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Échec de la lecture de %@ : %@" + "value": "Échec de la lecture de %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "Impossibile leggere %@: %@" + "value": "Impossibile leggere %@" } }, "ja": { "stringUnit": { "state": "translated", - "value": "%@ の読み取りに失敗しました: %@" + "value": "%@ の読み取りに失敗しました" } }, "km": { "stringUnit": { "state": "translated", - "value": "អាន %@ មិនបានសម្រេច៖ %@" + "value": "អាន %@ មិនបានសម្រេច" } }, "ko": { "stringUnit": { "state": "translated", - "value": "%@을(를) 읽지 못했습니다: %@" + "value": "%@을(를) 읽지 못했습니다" } }, "nb": { "stringUnit": { "state": "translated", - "value": "Klarte ikke å lese %@: %@" + "value": "Klarte ikke å lese %@" } }, "pl": { "stringUnit": { "state": "translated", - "value": "Nie udało się odczytać %@: %@" + "value": "Nie udało się odczytać %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Falha ao ler %@: %@" + "value": "Falha ao ler %@" } }, "ru": { "stringUnit": { "state": "translated", - "value": "Не удалось прочитать %@: %@" + "value": "Не удалось прочитать %@" } }, "th": { "stringUnit": { "state": "translated", - "value": "อ่าน %@ ไม่สำเร็จ: %@" + "value": "อ่าน %@ ไม่สำเร็จ" } }, "tr": { "stringUnit": { "state": "translated", - "value": "%@ okunamadı: %@" + "value": "%@ okunamadı" } }, "uk": { "stringUnit": { "state": "translated", - "value": "Не вдалося прочитати %@: %@" + "value": "Не вдалося прочитати %@" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "读取 %@ 失败:%@" + "value": "读取 %@ 失败" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "讀取 %@ 失敗:%@" + "value": "讀取 %@ 失敗" } } } diff --git a/tests/test_omp_extension_install.py b/tests/test_omp_extension_install.py index 4e5447a73d8d..352e8fb42829 100755 --- a/tests/test_omp_extension_install.py +++ b/tests/test_omp_extension_install.py @@ -439,9 +439,10 @@ def main() -> int: print(f"stderr={check.stderr.strip()}") return 1 - args_log = wait_for_text(fake_args_log, 3) - stdin_log = wait_for_text(fake_stdin_log, 3) - env_log = wait_for_text(fake_env_log, 12) + expected_invocations = 3 + args_log = wait_for_text(fake_args_log, expected_invocations) + stdin_log = wait_for_text(fake_stdin_log, expected_invocations * 2) + env_log = wait_for_text(fake_env_log, expected_invocations * 4) for expected in [ "hooks omp session-start", "hooks omp prompt-submit", From 0eaa6603bf2535aa8a866039d8ef5e77afde166a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 4 Jun 2026 22:02:12 -0700 Subject: [PATCH 4/6] Fix OMP stop hook payload delivery --- CLI/CMUXCLI+OmpExtension.swift | 73 +++++++++++++++++++++++------ tests/test_omp_extension_install.py | 12 +++-- 2 files changed, 67 insertions(+), 18 deletions(-) diff --git a/CLI/CMUXCLI+OmpExtension.swift b/CLI/CMUXCLI+OmpExtension.swift index ac21e282d63a..7e8974ba4c63 100644 --- a/CLI/CMUXCLI+OmpExtension.swift +++ b/CLI/CMUXCLI+OmpExtension.swift @@ -9,7 +9,7 @@ extension CMUXCLI { // Installed by `cmux hooks omp install` or `cmux hooks setup`. // DO NOT EDIT MANUALLY. cmux upgrades this file in place. -import { spawn } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import * as fs from "node:fs"; import * as path from "node:path"; import type { AgentEndEvent, ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent"; @@ -84,6 +84,13 @@ function hookEnvironment(cwd: string): NodeJS.ProcessEnv { return env; } +interface HookInvocation { + cmux: string; + cwd: string; + payload: string; + env: NodeJS.ProcessEnv; +} + function eventName(subcommand: string): string { switch (subcommand) { case "session-start": @@ -121,12 +128,12 @@ function lastAssistantMessage(event: AgentEndEvent): string | undefined { return undefined; } -function sendHook(subcommand: string, ctx: ExtensionContext, extra: Record = {}): void { - if (process.env.CMUX_OMP_HOOKS_DISABLED === "1") return; - if (!process.env.CMUX_SURFACE_ID) return; +function hookInvocation(subcommand: string, ctx: ExtensionContext, extra: Record = {}): HookInvocation | null { + if (process.env.CMUX_OMP_HOOKS_DISABLED === "1") return null; + if (!process.env.CMUX_SURFACE_ID) return null; const sessionId = firstString(ctx.sessionManager.getSessionId()); - if (!sessionId) return; + if (!sessionId) return null; const cwd = firstString(ctx.cwd, process.cwd()) || process.cwd(); const payload: Record = { @@ -137,30 +144,66 @@ function sendHook(subcommand: string, ctx: ExtensionContext, extra: Record = {}): Promise { + const invocation = hookInvocation(subcommand, ctx, extra); + if (!invocation) return; + await new Promise((resolve) => { + let settled = false; + const settle = () => { + if (settled) return; + settled = true; + resolve(); + }; + try { + const child = spawn(invocation.cmux, ["hooks", "omp", subcommand], { + env: invocation.env, + stdio: ["pipe", "ignore", "ignore"], + detached: true, + }); + child.on("error", settle); + child.stdin.on("error", settle); + child.stdin.on("finish", settle); + child.unref(); + child.stdin.end(invocation.payload); + } catch (_) { + settle(); + } + }); +} + +function sendHookSync(subcommand: string, ctx: ExtensionContext, extra: Record = {}): void { + const invocation = hookInvocation(subcommand, ctx, extra); + if (!invocation) return; try { - const child = spawn(cmux, ["hooks", "omp", subcommand], { - env: hookEnvironment(cwd), + spawnSync(invocation.cmux, ["hooks", "omp", subcommand], { + input: invocation.payload, + encoding: "utf8", + env: invocation.env, stdio: ["pipe", "ignore", "ignore"], - detached: true, + timeout: 5000, }); - child.on("error", () => {}); - child.stdin.on("error", () => {}); - child.stdin.end(JSON.stringify(payload)); - child.unref(); } catch (_) {} } export default function cmuxOmpSessionExtension(api: ExtensionAPI) { api.on("session_start", async (_event, ctx) => { - sendHook("session-start", ctx); + await sendHook("session-start", ctx); }); api.on("before_agent_start", async (event, ctx) => { - sendHook("prompt-submit", ctx, { prompt: event.prompt }); + await sendHook("prompt-submit", ctx, { prompt: event.prompt }); }); api.on("agent_end", async (event, ctx) => { - sendHook("stop", ctx, { last_assistant_message: lastAssistantMessage(event) }); + sendHookSync("stop", ctx, { last_assistant_message: lastAssistantMessage(event) }); }); } """# diff --git a/tests/test_omp_extension_install.py b/tests/test_omp_extension_install.py index 352e8fb42829..62cb7914b619 100755 --- a/tests/test_omp_extension_install.py +++ b/tests/test_omp_extension_install.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """ -Regression test: the generated OMP extension is importable and emits cmux hook calls without blocking OMP handlers. +Regression test: the generated OMP extension is importable and emits cmux hook calls with complete payloads. """ from __future__ import annotations @@ -421,7 +421,7 @@ def main() -> int: stopReason: "completed" }, ctx); const elapsed = Date.now() - start; -if (elapsed > 800) throw new Error(`handlers blocked for ${elapsed}ms`); +if (elapsed > 2000) throw new Error(`handlers blocked for ${elapsed}ms`); """ check = subprocess.run( [bun, "--eval", check_source], @@ -454,6 +454,12 @@ def main() -> int: if '"session_id":"omp-session-test"' not in stdin_log: print(f"FAIL: extension did not pass session id, got {stdin_log!r}") return 1 + if stdin_log.count('"session_id":"omp-session-test"') != 3: + print(f"FAIL: expected 3 hook payloads carrying the session id, got {stdin_log!r}") + return 1 + if '"hook_event_name":"Stop"' not in stdin_log: + print(f"FAIL: stop hook payload was missing: {stdin_log!r}") + return 1 if '"prompt":"hello omp"' 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}") return 1 @@ -583,7 +589,7 @@ def main() -> int: print(f"stdout={config_uninstall.stdout.strip()}") print(f"stderr={config_uninstall.stderr.strip()}") return 1 - print("PASS: generated OMP extension installs, emits non-blocking cmux hooks, and persists hook sessions") + print("PASS: generated OMP extension installs, emits complete cmux hook payloads, and persists hook sessions") return 0 From e6fcbc3c850b0cb374de1a5ed0f58bc15adadd5c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 4 Jun 2026 22:43:49 -0700 Subject: [PATCH 5/6] fix: report OMP extension read failures --- CLI/CMUXCLI+OmpExtension.swift | 5 +++-- tests/test_omp_extension_install.py | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CLI/CMUXCLI+OmpExtension.swift b/CLI/CMUXCLI+OmpExtension.swift index 7e8974ba4c63..a5522faea5d7 100644 --- a/CLI/CMUXCLI+OmpExtension.swift +++ b/CLI/CMUXCLI+OmpExtension.swift @@ -248,13 +248,14 @@ export default function cmuxOmpSessionExtension(api: ExtensionAPI) { do { return try String(contentsOf: url, encoding: .utf8) } catch { - throw CLIError(message: String.localizedStringWithFormat( + let message = String.localizedStringWithFormat( String( localized: "cli.hooks.omp.error.readFailed", defaultValue: "Failed to read %@" ), url.path - )) + ) + throw CLIError(message: "\(message): \(String(describing: error))") } } diff --git a/tests/test_omp_extension_install.py b/tests/test_omp_extension_install.py index 62cb7914b619..bac9a81b7758 100755 --- a/tests/test_omp_extension_install.py +++ b/tests/test_omp_extension_install.py @@ -539,6 +539,12 @@ def main() -> int: print(f"stdout={install_invalid.stdout.strip()}") print(f"stderr={install_invalid.stderr.strip()}") return 1 + install_invalid_output = install_invalid.stdout + install_invalid.stderr + if "Failed to read" not in install_invalid_output or "not a cmux extension" in install_invalid_output: + print("FAIL: omp extension install did not report unreadable file distinctly") + print(f"stdout={install_invalid.stdout.strip()}") + print(f"stderr={install_invalid.stderr.strip()}") + return 1 uninstall_invalid = subprocess.run( [cli_path, "hooks", "omp", "uninstall", "--yes"], capture_output=True, @@ -553,6 +559,12 @@ def main() -> int: print(f"stdout={uninstall_invalid.stdout.strip()}") print(f"stderr={uninstall_invalid.stderr.strip()}") return 1 + uninstall_invalid_output = uninstall_invalid.stdout + uninstall_invalid.stderr + if "Failed to read" not in uninstall_invalid_output or "not a cmux extension" in uninstall_invalid_output: + print("FAIL: omp extension uninstall did not report unreadable file distinctly") + print(f"stdout={uninstall_invalid.stdout.strip()}") + print(f"stderr={uninstall_invalid.stderr.strip()}") + return 1 foreign_path.unlink() From 795243c9de4c36a78997ee24d7b6e8ec11668ae0 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 4 Jun 2026 22:49:10 -0700 Subject: [PATCH 6/6] fix: avoid blocking OMP stop hook dispatch --- CLI/CMUXCLI+OmpExtension.swift | 18 ++---------------- tests/test_omp_extension_install.py | 2 +- 2 files changed, 3 insertions(+), 17 deletions(-) diff --git a/CLI/CMUXCLI+OmpExtension.swift b/CLI/CMUXCLI+OmpExtension.swift index a5522faea5d7..e01583b747de 100644 --- a/CLI/CMUXCLI+OmpExtension.swift +++ b/CLI/CMUXCLI+OmpExtension.swift @@ -9,7 +9,7 @@ extension CMUXCLI { // Installed by `cmux hooks omp install` or `cmux hooks setup`. // DO NOT EDIT MANUALLY. cmux upgrades this file in place. -import { spawn, spawnSync } from "node:child_process"; +import { spawn } from "node:child_process"; import * as fs from "node:fs"; import * as path from "node:path"; import type { AgentEndEvent, ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent"; @@ -179,20 +179,6 @@ async function sendHook(subcommand: string, ctx: ExtensionContext, extra: Record }); } -function sendHookSync(subcommand: string, ctx: ExtensionContext, extra: Record = {}): void { - const invocation = hookInvocation(subcommand, ctx, extra); - if (!invocation) return; - try { - spawnSync(invocation.cmux, ["hooks", "omp", subcommand], { - input: invocation.payload, - encoding: "utf8", - env: invocation.env, - stdio: ["pipe", "ignore", "ignore"], - timeout: 5000, - }); - } catch (_) {} -} - export default function cmuxOmpSessionExtension(api: ExtensionAPI) { api.on("session_start", async (_event, ctx) => { await sendHook("session-start", ctx); @@ -203,7 +189,7 @@ export default function cmuxOmpSessionExtension(api: ExtensionAPI) { }); api.on("agent_end", async (event, ctx) => { - sendHookSync("stop", ctx, { last_assistant_message: lastAssistantMessage(event) }); + await sendHook("stop", ctx, { last_assistant_message: lastAssistantMessage(event) }); }); } """# diff --git a/tests/test_omp_extension_install.py b/tests/test_omp_extension_install.py index bac9a81b7758..c7e6f5c553f3 100755 --- a/tests/test_omp_extension_install.py +++ b/tests/test_omp_extension_install.py @@ -359,7 +359,7 @@ def main() -> int: fake_cmux, """#!/usr/bin/env bash set -euo pipefail -sleep 1 +sleep 3 printf '%s\n' "$*" >> "$FAKE_CMUX_ARGS_LOG" cat >> "$FAKE_CMUX_STDIN_LOG" printf '\n---\n' >> "$FAKE_CMUX_STDIN_LOG"