Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
5e0ceee
test: cover OpenCode lifecycle notification regressions
austinywang Oct 14, 2026
0d93f4f
fix: restore OpenCode lifecycle notifications
austinywang Oct 14, 2026
0b2bd4b
fix: finish OpenCode notification repair
austinywang Oct 14, 2026
353bac7
fix: share OpenCode failure detail extraction
austinywang Oct 14, 2026
e6ec9c5
test: wait for OpenCode failure hook
austinywang Oct 14, 2026
ea43016
test: cover OpenCode server entry notifications
austinywang Oct 14, 2026
7a30c27
fix: activate OpenCode server plugin entries
austinywang Oct 14, 2026
c9124c6
Merge main c77b533b4bb into the OpenCode notification fix
austinywang Oct 14, 2026
2e3ecf5
fix(opencode): publish one terminal stop per turn
austinywang Oct 14, 2026
dc19c3b
fix(opencode): redact credentials in upstream failure text
austinywang Oct 14, 2026
8c75b03
fix(opencode): record OpenCode's own launch for resume
austinywang Oct 14, 2026
c3198e3
fix(cmux-tui): keep shutdown-interrupted OpenCode turns running
austinywang Oct 14, 2026
19a62eb
test: register the OpenCode server-entry harness as manual
austinywang Oct 14, 2026
8a659bf
fix: resubscribe OpenCode server entries after scope reinit
austinywang Oct 14, 2026
f63c460
fix(opencode): open turns on run signals, not message updates
austinywang Oct 14, 2026
47911cb
test(opencode): cover queued prompts and shutdown interruptions
austinywang Oct 14, 2026
34dd634
fix: bind OpenCode hooks to this process and plugin scope
austinywang Oct 14, 2026
b4413bc
test: cover raw OpenCode failure events in Feed
austinywang Oct 14, 2026
60df02b
fix: share OpenCode failure classification with Feed
austinywang Oct 14, 2026
ddd84e0
test: cover OpenCode interrupts and concurrent plugin scopes
austinywang Oct 14, 2026
58f74d2
fix: keep OpenCode interrupts and concurrent scopes out of failures
austinywang Oct 14, 2026
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
24 changes: 24 additions & 0 deletions CLI/AgentHookNotificationPolicy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,30 @@ enum AgentHookNotificationPolicy {
return patternIndex == patternScalars.count
}

/// Redacts credentials in upstream error text before notifications or
/// Feed show it. Unlike commands, paths and long identifiers such as model
/// names stay readable because they are the useful part of the error.
static func redactSensitiveErrorDetail(_ value: String) -> String {
let boundedValue = value.utf8.count > 8_192
? String(decoding: value.utf8.prefix(8_191), as: UTF8.self) + "…"
: value
let patterns: [(pattern: String, replacement: String)] = [
(#"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}"#, "<email>"),
(#"\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16})\b"#, "<token>"),
(#"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{12,}"#, "Bearer <token>"),
(#"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"#, "<token>"),
(#"(?i)\b(?:x[-_])?(?:api[-_]?key|password|secret|token|authorization|cookie)\s*[:=]\s*(?:Bearer\s+)?(?:'[^']*'|\"[^\"]*\"|[^\s'\";&|,]+)"#, "<credential>:<token>"),
(#"\b(?:sk|rk|sess)-[A-Za-z0-9._:-]{8,}\b"#, "<token>"),
]
return patterns.reduce(boundedValue) { partial, entry in
partial.replacingOccurrences(
of: entry.pattern,
with: entry.replacement,
options: [.regularExpression, .caseInsensitive]
)
}
}

/// Redacts credentials before a command reaches durable hook state or UI.
static func redactSensitiveCommand(_ value: String) -> String {
let boundedValue = value.utf8.count > 8_192
Expand Down
1 change: 1 addition & 0 deletions CLI/CMUXCLI+AgentHookCatalog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ extension CMUXCLI {
AgentHookDef(
name: "opencode", displayName: "OpenCode", statusKey: "opencode",
configDir: ".config/opencode", configFile: "plugins/cmux-session.js", configDirEnvOverride: "OPENCODE_CONFIG_DIR",
configDirResolver: { OpenCodePaths(environment: ProcessInfo.processInfo.environment).configDirectory.path },
sessionStoreSuffix: "opencode", disableEnvVar: "CMUX_OPENCODE_HOOKS_DISABLED",
hookMarker: "cmux hooks opencode", format: .flat,
events: []
Expand Down
213 changes: 198 additions & 15 deletions CLI/cmux.swift

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,10 @@ public enum AgentLaunchSanitizer {
var tail = args
while let first = tail.first {
let normalized = first.replacingOccurrences(of: "\\", with: "/")
// Compiled OpenCode reports Bun's virtual entry (src/index.js on
// 1.x, the TUI worker on V2); it is never a user argument.
let isInternalArgument = first == "tui-settings" ||
(normalized.contains("/$bunfs/") && normalized.hasSuffix("/tui/worker.js"))
normalized.contains("/$bunfs/") || normalized.contains("/~BUN/")
guard isInternalArgument else { break }
tail.removeFirst()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ struct OpenCodeBunWorkerSanitizerTests {
@Test("Drops internal TUI worker paths", arguments: [
"/$bunfs/root/src/cli/cmd/tui/worker.js",
"/$bunfs/root/src/cli/tui/worker.js",
"/$bunfs/root/src/index.js",
"B:/~BUN/root/src/index.js",
])
func dropsInternalTUIWorkerPaths(workerPath: String) {
#expect(
Expand Down
119 changes: 110 additions & 9 deletions Resources/opencode-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,34 @@ const createCMUXFeed = async (ctx, options = {}) => {
return firstString(status.type, status.status, status.state)?.toLowerCase() === "idle";
};

const sessionStatusType = (status) => {
if (typeof status === "string") return status.trim().toLowerCase();
if (!isObject(status)) return null;
return firstString(status.type, status.status, status.state)?.toLowerCase() || null;
};

const failureMessage = (event) => {
const props = eventProperties(event);
const raw = props.error || props.failure || props.reason;
if (typeof raw === "string") return normalizeText(raw, 500);
if (isObject(raw)) {
const nestedData = isObject(raw.data) ? raw.data : {};
const nested = firstString(
raw.message,
raw.error,
raw.reason,
raw.description,
nestedData.message,
nestedData.error,
nestedData.reason,
nestedData.description,
raw.name
);
if (nested) return normalizeText(nested, 500);
}
return normalizeText(firstString(props.message, props.description), 500);
};

const normalizeText = (value, max = 1000) => {
if (typeof value !== "string") return null;
const normalized = value.replace(/\s+/g, " ").trim();
Expand All @@ -98,11 +126,26 @@ const createCMUXFeed = async (ctx, options = {}) => {
lastUserMessage: null,
assistantPreamble: null,
cwd: null,
lastStopKind: null,
turnKeys: new Set(),
});
}
return sessions.get(key);
};

// A turn publishes exactly one terminal stop. Only a turn identity this
// session has not seen clears it, so a repeated update for the same prompt
// cannot reopen a finished turn. A missing identity starts a new turn.
const beginTurn = (sessionId, turnKey) => {
const state = sessionState(sessionId);
if (turnKey) {
if (state.turnKeys.has(turnKey)) return;
state.turnKeys.add(turnKey);
if (state.turnKeys.size > 50) state.turnKeys.delete(state.turnKeys.values().next().value);
}
state.lastStopKind = null;
};

const contextForSession = (sessionId) => {
const state = sessionState(sessionId);
const context = {};
Expand Down Expand Up @@ -663,6 +706,7 @@ const createCMUXFeed = async (ctx, options = {}) => {
if (!sid || !text) return null;
const state = sessionState(sid);
state.lastUserMessage = text;
beginTurn(sid, firstString(item.id, props.id, event.id));
return base(sid, {
hook_event_name: "UserPromptSubmit",
tool_input: { prompt: text },
Expand All @@ -682,6 +726,7 @@ const createCMUXFeed = async (ctx, options = {}) => {
const role = info.role || props.role;
if (messageId && sessionId && role) {
messageRoles.set(messageId, { sessionId, role });
if (role === "user") beginTurn(sessionId, messageId);
if (messageRoles.size > 300) {
messageRoles.delete(messageRoles.keys().next().value);
}
Expand All @@ -699,6 +744,7 @@ const createCMUXFeed = async (ctx, options = {}) => {
const state = sessionState(meta.sessionId);
if (meta.role === "user") {
state.lastUserMessage = text;
beginTurn(meta.sessionId, part.messageID);
return base(meta.sessionId, {
hook_event_name: "UserPromptSubmit",
tool_input: { prompt: text },
Expand All @@ -711,6 +757,15 @@ const createCMUXFeed = async (ctx, options = {}) => {
return null;
};

const shouldEmitStop = (sessionId, kind) => {
// The first terminal event settles the turn. A published stop cannot be
// reclassified, so a later failure or idle for the same turn is dropped.
const state = sessionState(sessionId);
if (state.lastStopKind) return false;
state.lastStopKind = kind;
return true;
};

const pushBlocking = (event, requestId) => {
const reply = new Promise((resolve) => {
let timeout;
Expand Down Expand Up @@ -767,6 +822,7 @@ const createCMUXFeed = async (ctx, options = {}) => {
const props = eventProperties(event);
const info = props.info || {};
const sid = sessionIdFromProperties(props) || "unknown";
beginTurn(sid, null);
const state = sessionState(sid);
state.cwd = info.directory || props.location?.directory || event.location?.directory || ctx?.location?.directory || ctx?.directory || state.cwd;
pushTelemetry(base(sid, {
Expand All @@ -777,19 +833,34 @@ const createCMUXFeed = async (ctx, options = {}) => {
}
case "session.status": {
const props = eventProperties(event);
if (!sessionStatusIsIdle(props.status)) break;
const sid = sessionIdFromProperties(props);
if (!sid) break;
// Busy carries no turn identity; prompts and user messages own it.
if (sid && sessionStatusType(props.status) === "busy") break;
if (!sessionStatusIsIdle(props.status)) break;
if (!sid || !shouldEmitStop(sid, "success")) break;
pushTelemetry(base(sid, {
hook_event_name: "Stop",
}));
break;
}
case "session.execution.succeeded":
case "session.execution.failed":
case "session.execution.interrupted": {
const sid = sessionIdFromEvent(event);
if (sid) pushTelemetry(base(sid, { hook_event_name: "Stop" }));
if (sid && shouldEmitStop(sid, "success")) pushTelemetry(base(sid, { hook_event_name: "Stop" }));
break;
}
case "session.execution.failed":
case "session.next.step.failed":
case "session.error": {
const sid = sessionIdFromEvent(event);
if (sid && shouldEmitStop(sid, "failure")) {
const error = failureMessage(event);
pushTelemetry(base(sid, {
hook_event_name: "Stop",
is_error: true,
...(error ? { error } : {}),
}));
}
break;
}
case "session.updated": {
Expand All @@ -798,19 +869,24 @@ const createCMUXFeed = async (ctx, options = {}) => {
if (eventProperties(event).info?.time?.archived) {
pushTelemetry(base(sid, { hook_event_name: "SessionEnd" }));
sessions.delete(sid);
} else {
pushTelemetry(base(sid, { hook_event_name: "SessionStart" }));
}
break;
}
case "session.idle": {
const sid = sessionIdFromProperties(eventProperties(event));
if (!sid) break;
if (!sid || !shouldEmitStop(sid, "success")) break;
pushTelemetry(base(sid, {
hook_event_name: "Stop",
}));
break;
}
case "session.next.prompted":
case "session.next.prompt.admitted": {
const sid = sessionIdFromEvent(event);
const props = eventProperties(event);
if (sid) beginTurn(sid, firstString(props.messageID, props.promptID, props.id, event.id));
break;
}
case "session.deleted": {
const sid = sessionIdFromProperties(eventProperties(event));
if (!sid) break;
Expand Down Expand Up @@ -999,10 +1075,35 @@ const createCMUXFeed = async (ctx, options = {}) => {

export const CMUXFeed = createCMUXFeed;

const CMUX_FEED_SERVER_OWNER_KEY = Symbol.for("cmux.feed.server.owner");

// Released OpenCode calls `server(ctx)` inside each TUI process with the
// project server context. Old V2 snapshots called it from a shared service
// without that context, so only subscribe when it is present.
const isTUIProcessServerContext = (ctx) =>
Boolean(ctx && typeof ctx === "object" && ctx.client && ctx.serverUrl && ctx.directory);

export default {
id: "cmux.server",
// V2 uses the package's ./tui export; never subscribe in the shared service.
server() { return {}; },
async server(ctx) {
if (!isTUIProcessServerContext(ctx)) return {};
// cmux-feed.js and plugins/cmux/index.js both load this source. Every
// loader in one plugin scope receives the same ctx; a reinitialized scope
// receives a new one, which replaces the previous feed.
const owner = globalThis[CMUX_FEED_SERVER_OWNER_KEY] ||= { ctx: null, feed: null };
if (owner.ctx === ctx) return {};
const previous = owner.feed;
owner.ctx = ctx;
owner.feed = null;
previous?.dispose?.();
const feed = await createCMUXFeed(ctx);
if (owner.ctx !== ctx) {
feed.dispose();
return {};
}
owner.feed = feed;
return feed;
},
// Compatibility alias for older V2 snapshots that called setup().
setup() { return () => {}; },
};
Loading
Loading