Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ on:
pull_request:
workflow_dispatch:

permissions:
contents: read
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
Expand Down Expand Up @@ -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.
Expand Down
11 changes: 11 additions & 0 deletions CLI/CMUXCLI+AgentHookDefinitions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let home = ProcessInfo.processInfo.environment["HOME"].flatMap { value -> String? in
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
Expand Down Expand Up @@ -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: []
),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
AgentHookDef(
name: "amp", displayName: "Amp", statusKey: "amp",
configDir: ".config/amp", configFile: "plugins/cmux-session.ts",
Expand Down
305 changes: 305 additions & 0 deletions CLI/CMUXCLI+OmpExtension.swift
Original file line number Diff line number Diff line change
@@ -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;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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<string, unknown> = {}): 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<string, unknown> = {
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) });
});
}
Comment on lines +191 to +194

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 sendHookSync blocks the event loop for up to 5 s at agent teardown

api.on("agent_end", async ...) declares an async handler, but the body calls sendHookSync — a synchronous spawnSync with timeout: 5000 — without await. That means every OMP session end blocks Node's event loop for up to 5 seconds waiting for the cmux subprocess. The other two hooks (session_start, before_agent_start) correctly use await sendHook(...) which resolves as soon as stdin is flushed. If OMP's extension API honours the returned promise from an async handler, replacing the call here with await sendHook("stop", ...) gives the same delivery guarantee without a wall-clock block.

Rule Used: Flag fixed sleeps, delayed dispatch, timers, polli... (source)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in 795243c by removing spawnSync and awaiting the same detached stdin-flush sendHook path for agent_end. The Python regression now uses a slow fake cmux command so synchronous Stop dispatch would fail the timing assertion while still proving all three payloads arrive.

— Claude Code

"""#

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)")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}


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
))
}
}
12 changes: 11 additions & 1 deletion CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading