Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

fix(local-agents): rewrite CLI backends against real protocols + ACP close

aiservice5193b148617e
diff --git a/src/main/features/local_agents/backends/_acp.ts b/src/main/features/local_agents/backends/_acp.ts
index 52537128..c139b80e 100644
--- a/src/main/features/local_agents/backends/_acp.ts
+++ b/src/main/features/local_agents/backends/_acp.ts
@@ -51,6 +51,13 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
let resultText = '';
let resultStatus: 'completed' | 'failed' | undefined;
let resultError: string | undefined;
+ // Captured upstream-provider error text from stderr. ACP servers
+ // (notably hermes 0.9) treat upstream HTTP 400/auth errors as
+ // "non-retryable" and still return `stopReason: end_turn` with
+ // an empty body — looking only at the JSON-RPC envelope makes a
+ // failed turn look successful. We sniff stderr for these and
+ // promote them to the run-level error if no text streamed.
+ let stderrErrorHint: string | undefined;
const PROMPT_REQ_ID = 100;
@@ -84,6 +91,16 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
},
});
+ // Pre-build session/new params: include model up front (Hermes
+ // accepts it; CLIs that don't honor model in session/new ignore
+ // it). The set_model fallback below covers servers that need
+ // an explicit setter.
+ const sessionNewParams: Record<string, unknown> = {
+ cwd: opts.cwd,
+ mcpServers: [],
+ };
+ if (opts.model) sessionNewParams.model = opts.model;
+
const splitter = new LineSplitter();
child.stdout.setEncoding('utf8');
child.stdout.on('data', chunk => {
@@ -114,12 +131,21 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
resultText += text;
opts.onEvent({ type: 'text-delta', text });
},
+ onThinking: text => opts.onEvent({ type: 'thinking', text }),
onToolUse: tool => opts.onEvent({ type: 'tool-event', tool: tool.name, callId: tool.callId, phase: 'use', input: tool.input }),
onToolResult: tool => opts.onEvent({ type: 'tool-event', tool: tool.name, callId: tool.callId, phase: 'result', output: tool.output }),
onPromptResult: r => {
resultStatus = r.ok ? 'completed' : 'failed';
if (r.ok && r.text) resultText = r.text;
if (!r.ok) resultError = r.error;
+ // ACP servers (hermes / kimi / kiro) keep stdin open
+ // ready for the next prompt — they're long-running.
+ // We're a one-shot dispatcher; closing stdin signals
+ // them to shut down so the close handler below fires
+ // and the outer Promise resolves. Without this we hang
+ // forever waiting on a child that's perfectly happy to
+ // sit idle.
+ try { child.stdin.end(); } catch { /* */ }
},
onUnknown: raw => {
opts.onEvent({ type: 'tool-event', tool: 'acp', phase: 'use', input: raw, callId: '' });
@@ -141,7 +167,7 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
// any post-initialize state.
const sendSessionNew = () => send({
jsonrpc: '2.0', id: 2, method: 'session/new',
- params: { cwd: opts.cwd, mcpServers: [] },
+ params: sessionNewParams,
});
// Fire-and-forget timeout to be sure session/new goes; some CLIs
// ack initialize without printing anything we'd recognize as the
@@ -154,6 +180,16 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
tail.push(chunk);
for (const line of chunk.split(/\r?\n/)) {
if (line) opts.onEvent({ type: 'stderr-line', line });
+ // Sniff for upstream-provider failures hermes prints just
+ // before silently returning end_turn. The most useful line
+ // is the "Error: HTTP 400: ..." one with the API's message;
+ // we keep the FIRST hit so retries don't overwrite the root
+ // cause. Pattern is intentionally loose because hermes log
+ // formatting drifts version-to-version.
+ if (!stderrErrorHint) {
+ const m = /(HTTP\s+\d{3}[^\n]*|Non-retryable[^\n]*|Error code:\s+\d{3}[^\n]*)/.exec(line);
+ if (m) stderrErrorHint = m[1].trim();
+ }
}
});
@@ -180,7 +216,22 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
child.on('close', code => {
if (opts.signal.aborted) return finish('cancelled', { output: resultText });
if (timedOut) return finish('timeout', { error: `cli exceeded ${opts.timeoutMs}ms`, output: resultText, stderrTail: tail.toString() });
- if (code === 0 && resultStatus === 'completed') return finish('completed', { output: resultText });
+ if (code === 0 && resultStatus === 'completed') {
+ // Demote silent failure: server claimed success via
+ // stopReason=end_turn but never streamed any text AND
+ // stderr contained an upstream-provider error. Hermes
+ // does this on auth/model misconfig (HTTP 400). Surface
+ // the captured error so the chat shows a real reason
+ // instead of an empty bubble.
+ if (!resultText && stderrErrorHint) {
+ return finish('failed', {
+ error: `${def.logName.replace('local-agents:', '')} reported success but produced no text — upstream: ${stderrErrorHint}`,
+ output: '',
+ stderrTail: tail.toString(),
+ });
+ }
+ return finish('completed', { output: resultText });
+ }
const err = resultError || (code !== 0 ? `cli exited with code ${code}` : 'cli closed without prompt result');
finish('failed', { error: err, output: resultText, stderrTail: tail.toString() });
});
@@ -192,6 +243,7 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
interface AcpHandlers {
onSessionNew(sessionId: string): void;
onTextDelta(text: string): void;
+ onThinking(text: string): void;
onToolUse(tool: { name: string; callId: string; input: unknown }): void;
onToolResult(tool: { name: string; callId: string; output: string }): void;
onPromptResult(r: { ok: boolean; text?: string; error?: string }): void;
@@ -201,6 +253,14 @@ interface AcpHandlers {
/**
* Pure dispatcher — given a parsed ACP message envelope, invokes the
* matching handler. Exposed for unit testing without spawning the CLI.
+ *
+ * Field-name reality check (vs ACP spec drafts):
+ * - Hermes 0.9 uses `update.sessionUpdate` as the discriminator
+ * (string like `agent_message_chunk` / `agent_thought_chunk` /
+ * `tool_call` / `tool_call_update` / `available_commands_update`),
+ * and puts text under `update.content.text`.
+ * - Some older / draft variants use `update.kind` instead.
+ * We check `sessionUpdate` first, then `kind` so both work.
*/
export function handleAcpMessage(env: any, h: AcpHandlers): void {
if (!env || typeof env !== 'object') return;
@@ -208,12 +268,24 @@ export function handleAcpMessage(env: any, h: AcpHandlers): void {
if (env.method === 'session/update') {
const upd = env.params?.update;
if (!upd || typeof upd !== 'object') return;
- // Common kinds (per ACP spec): agent_message_chunk, tool_call, tool_call_update, finished.
- if (upd.kind === 'agent_message_chunk' && typeof upd.content?.text === 'string') {
- h.onTextDelta(upd.content.text);
+ const kind: string = (typeof upd.sessionUpdate === 'string' && upd.sessionUpdate)
+ || (typeof upd.kind === 'string' && upd.kind)
+ || '';
+ if (!kind) return;
+ if (kind === 'agent_message_chunk') {
+ const text = upd.content?.text;
+ if (typeof text === 'string' && text.length) h.onTextDelta(text);
return;
}
- if (upd.kind === 'tool_call' && upd.tool) {
+ if (kind === 'agent_thought_chunk') {
+ // Thinking/internal monologue — hermes uses these for its
+ // "(◔_◔) mulling..." status messages and any planning the
+ // model emits before the actual reply.
+ const text = upd.content?.text;
+ if (typeof text === 'string' && text.length) h.onThinking(text);
+ return;
+ }
+ if (kind === 'tool_call' && upd.tool) {
h.onToolUse({
name: String(upd.tool.name || 'tool'),
callId: String(upd.tool.id || upd.tool.callId || ''),
@@ -221,7 +293,7 @@ export function handleAcpMessage(env: any, h: AcpHandlers): void {
});
return;
}
- if (upd.kind === 'tool_call_update' && upd.tool) {
+ if (kind === 'tool_call_update' && upd.tool) {
h.onToolResult({
name: String(upd.tool.name || 'tool'),
callId: String(upd.tool.id || upd.tool.callId || ''),
@@ -229,6 +301,13 @@ export function handleAcpMessage(env: any, h: AcpHandlers): void {
});
return;
}
+ if (kind === 'available_commands_update') {
+ // Hermes broadcasts its slash-command list right after session
+ // creation. Surface as unknown so it lands in the debug rail
+ // but doesn't pretend to be a tool/result event.
+ h.onUnknown({ method: env.method, params: env.params });
+ return;
+ }
h.onUnknown({ method: env.method, params: env.params });
return;
}
diff --git a/src/main/features/local_agents/backends/codex.ts b/src/main/features/local_agents/backends/codex.ts
index 03bd221a..b5a433dc 100644
--- a/src/main/features/local_agents/backends/codex.ts
+++ b/src/main/features/local_agents/backends/codex.ts
@@ -1,26 +1,444 @@
/**
- * Codex CLI backend.
+ * Codex CLI backend — talks the `codex app-server --listen stdio://`
+ * JSON-RPC 2.0 protocol. Modelled after multica's `codex.go`, distilled
+ * to what we need for one-shot agent dispatch:
*
- * v1 keeps it simple: `codex exec` reads the prompt from stdin and
- * prints the assistant reply to stdout. We skip `app-server` mode
- * (which speaks JSON-RPC over stdio) for now — it's significantly more
- * complex and the simple text body is enough to round-trip a dispatch
- * back into the group chat. Step 7+ can swap to app-server when we
- * want tool-use visibility on the timeline.
+ * 1. Spawn `codex app-server --listen stdio://`.
+ * 2. RPC `initialize` (clientInfo + experimentalApi capability).
+ * 3. Notify `initialized`.
+ * 4. RPC `thread/start` (or `thread/resume` if we have a prior thread)
+ * → `result.threadId`.
+ * 5. RPC `turn/start` with `{threadId, input:[{type:"text", text:prompt}]}`.
+ * 6. Listen for notifications until the turn ends:
+ * - `codex/event` (params is an event object with `type`):
+ * task_started / agent_message / exec_command_begin/end /
+ * patch_apply_begin/end / task_complete / turn_aborted
+ * - `turn/started` / `turn/completed` (top-level v2 lifecycle)
+ * - `error` (top-level transport error; non-retry → terminal)
+ * 7. Close stdin → codex exits cleanly.
+ *
+ * Notifications carry `threadId`; codex multiplexes subagent threads
+ * (memory consolidation, etc.) on the same stdio pipe. We filter to
+ * our own threadId to avoid surfacing unrelated chatter.
+ *
+ * Resume: when `opts.resumeSessionId` is set, we attempt
+ * `thread/resume` first; on any failure we fall back to a fresh
+ * `thread/start` so the user's task still runs (matching multica).
*/
-import { makeTextBackend } from './_text.js';
-
-export const codexBackend = makeTextBackend({
- logName: 'local-agents:codex',
- // `codex exec -` reads the prompt from stdin (no model selector here
- // unless the user installed an account that requires it via login).
- // Model is appended only when the user explicitly picked one.
- buildArgs(opts) {
- const args = ['exec', '-'];
- if (opts.model) args.push('--model', opts.model);
- if (opts.customArgs && opts.customArgs.length) args.push(...opts.customArgs);
- return args;
+import { createLogger } from '../../../logger.js';
+import {
+ type LocalBackend,
+ type BackendRunOptions,
+ type LocalEvent,
+ StderrTail,
+ spawnCli,
+ bindAbort,
+ LineSplitter,
+} from './base.js';
+
+const log = createLogger('local-agents:codex');
+
+export const codexBackend: LocalBackend = {
+ async run(opts: BackendRunOptions): Promise<void> {
+ const args = buildCodexArgs(opts);
+ const child = spawnCli(opts.binPath, args, opts.cwd);
+ const detachAbort = bindAbort(child, opts.signal);
+ const tail = new StderrTail();
+ const startedAt = Date.now();
+
+ let exited = false;
+ let timedOut = false;
+ let resolveOuter!: () => void;
+ const outerPromise = new Promise<void>(resolve => { resolveOuter = resolve; });
+
+ opts.onEvent({
+ type: 'process-info',
+ pid: child.pid ?? -1,
+ cwd: opts.cwd,
+ cmd: opts.binPath,
+ args,
+ });
+
+ const timer = setTimeout(() => {
+ timedOut = true;
+ try { child.kill('SIGTERM'); } catch { /* */ }
+ setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* */ } }, 10_000).unref();
+ }, opts.timeoutMs);
+ if (typeof timer.unref === 'function') timer.unref();
+
+ // ─── JSON-RPC client state ────────────────────────────────────────
+ let nextRpcId = 1;
+ const pending = new Map<number, { method: string; resolve: (r: any) => void; reject: (e: Error) => void }>();
+ let threadId: string | undefined;
+ let turnStarted = false;
+ let turnAborted = false;
+ let turnCompleted = false;
+ const seenTurnIds = new Set<string>();
+ let collectedText = '';
+ let turnError: string | undefined;
+
+ const sendLine = (msg: object) => {
+ try { child.stdin.write(JSON.stringify(msg) + '\n'); }
+ catch (err) { log.warn('codex stdin write failed', { error: (err as Error).message }); }
+ };
+
+ const rpc = (method: string, params: Record<string, unknown>): Promise<any> =>
+ new Promise<any>((resolve, reject) => {
+ const id = nextRpcId++;
+ pending.set(id, { method, resolve, reject });
+ sendLine({ jsonrpc: '2.0', id, method, params });
+ });
+
+ const notify = (method: string, params?: Record<string, unknown>) => {
+ sendLine({ jsonrpc: '2.0', method, ...(params ? { params } : {}) });
+ };
+
+ const closePending = (err: Error) => {
+ for (const { reject } of pending.values()) reject(err);
+ pending.clear();
+ };
+
+ // ─── stdout JSON-RPC framing ─────────────────────────────────────
+ const splitter = new LineSplitter();
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => {
+ splitter.push(chunk, line => {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ let env: any;
+ try { env = JSON.parse(trimmed); } catch { return; }
+ // Response (matches a pending request by id).
+ if (env && typeof env.id === 'number' && pending.has(env.id)) {
+ const p = pending.get(env.id)!;
+ pending.delete(env.id);
+ if (env.error) {
+ p.reject(new Error(`${p.method}: ${env.error.message || 'rpc error'} (code=${env.error.code ?? 0})`));
+ } else {
+ p.resolve(env.result);
+ }
+ return;
+ }
+ // Notification (no id, has method).
+ if (env && typeof env.method === 'string') {
+ handleNotification(env.method, env.params || {});
+ }
+ });
+ });
+
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ tail.push(chunk);
+ for (const line of chunk.split(/\r?\n/)) {
+ if (line) opts.onEvent({ type: 'stderr-line', line });
+ }
+ });
+
+ function emitTextDelta(text: string) {
+ if (!text) return;
+ collectedText += text;
+ opts.onEvent({ type: 'text-delta', text });
+ }
+
+ // Codex 0.125+ uses fine-grained notifications:
+ // thread/started, thread/status/changed, thread/tokenUsage/updated
+ // turn/started, turn/completed
+ // item/started, item/completed (with item.type: userMessage,
+ // agentMessage, agentReasoning, commandExecution, ...)
+ // item/agentMessage/delta (params.delta is the streamed text chunk)
+ // account/rateLimits/updated, mcpServer/startupStatus/updated (noise)
+ // Older codex (per multica) used `codex/event` notifications wrapping
+ // events with type:task_started/agent_message/etc — we keep a
+ // best-effort handler for that shape too in case older codex builds
+ // are encountered.
+ function handleNotification(method: string, params: Record<string, any>) {
+ const eventThreadId = typeof params.threadId === 'string' ? params.threadId : '';
+ if (threadId && eventThreadId && eventThreadId !== threadId) return;
+
+ // ── Streaming agent text (the important one) ─────────────────
+ if (method === 'item/agentMessage/delta') {
+ const delta = typeof params.delta === 'string' ? params.delta : '';
+ if (delta) emitTextDelta(delta);
+ return;
+ }
+
+ // ── Lifecycle ────────────────────────────────────────────────
+ if (method === 'turn/started') {
+ turnStarted = true;
+ opts.onEvent({ type: 'status', status: 'running' });
+ return;
+ }
+ if (method === 'turn/completed') {
+ const turn = params?.turn || {};
+ const turnId: string = typeof turn?.id === 'string' ? turn.id : '';
+ const status: string = typeof turn?.status === 'string' ? turn.status : '';
+ if (turnId && seenTurnIds.has(turnId)) return;
+ if (turnId) seenTurnIds.add(turnId);
+ if (status === 'failed') {
+ turnError = (turn?.error?.message && String(turn.error.message)) || 'codex turn failed';
+ }
+ const aborted = status === 'cancelled' || status === 'canceled'
+ || status === 'aborted' || status === 'interrupted';
+ finishTurn(aborted);
+ return;
+ }
+
+ // ── item/* — surface tool-equivalent events; fallback final text ──
+ if (method === 'item/started') {
+ const item = params.item || {};
+ if (item.type === 'commandExecution') {
+ opts.onEvent({
+ type: 'tool-event',
+ tool: 'exec_command',
+ callId: String(item.id || ''),
+ phase: 'use',
+ input: { command: item.command || item.script || '' },
+ });
+ } else if (item.type === 'fileChange' || item.type === 'patchApply') {
+ opts.onEvent({
+ type: 'tool-event',
+ tool: 'patch_apply',
+ callId: String(item.id || ''),
+ phase: 'use',
+ });
+ } else if (item.type === 'agentReasoning') {
+ // Reasoning chunks — surface as thinking. Some codex versions
+ // include text directly on item.text, others stream via a
+ // dedicated reasoning/delta we don't see today.
+ const text = typeof item.text === 'string' ? item.text : '';
+ if (text) opts.onEvent({ type: 'thinking', text });
+ }
+ return;
+ }
+ if (method === 'item/completed') {
+ const item = params.item || {};
+ if (item.type === 'commandExecution') {
+ opts.onEvent({
+ type: 'tool-event',
+ tool: 'exec_command',
+ callId: String(item.id || ''),
+ phase: 'result',
+ output: typeof item.output === 'string' ? item.output : (item.aggregatedOutput ?? ''),
+ });
+ } else if (item.type === 'fileChange' || item.type === 'patchApply') {
+ opts.onEvent({
+ type: 'tool-event',
+ tool: 'patch_apply',
+ callId: String(item.id || ''),
+ phase: 'result',
+ });
+ } else if (item.type === 'agentMessage') {
+ // Fallback when delta-streaming didn't fire: emit the final
+ // text once. We compare against what we already collected
+ // to avoid duplication.
+ const text = typeof item.text === 'string' ? item.text : '';
+ if (text && !collectedText.includes(text)) emitTextDelta(text);
+ }
+ return;
+ }
+
+ // ── Top-level error ──────────────────────────────────────────
+ if (method === 'error') {
+ const willRetry = !!params.willRetry;
+ const errMsg = (params.error?.message && String(params.error.message))
+ || (typeof params.message === 'string' ? params.message : '');
+ if (errMsg && !willRetry) turnError = errMsg;
+ return;
+ }
+
+ // ── Idle fallback when turn/completed never arrives ─────────
+ if (method === 'thread/status/changed') {
+ const statusType = params?.status?.type;
+ if (statusType === 'idle' && turnStarted) finishTurn(false);
+ return;
+ }
+
+ // ── Legacy codex/event protocol (older codex builds) ─────────
+ if (method === 'codex/event' || method.startsWith('codex/event/')) {
+ const ev = (params && typeof params === 'object' && typeof params.type === 'string')
+ ? params
+ : (params?.msg && typeof params.msg === 'object' ? params.msg : null);
+ if (ev) handleLegacyCodexEvent(ev);
+ return;
+ }
+
+ // Noise we explicitly drop without surfacing:
+ // thread/started, thread/tokenUsage/updated,
+ // account/rateLimits/updated, mcpServer/startupStatus/updated
+ }
+
+ function handleLegacyCodexEvent(ev: Record<string, any>) {
+ switch (ev.type) {
+ case 'task_started':
+ turnStarted = true;
+ opts.onEvent({ type: 'status', status: 'running' });
+ return;
+ case 'agent_message': {
+ const text = typeof ev.message === 'string' ? ev.message : '';
+ emitTextDelta(text);
+ return;
+ }
+ case 'agent_message_delta': {
+ const text = typeof ev.delta === 'string' ? ev.delta
+ : (typeof ev.message === 'string' ? ev.message : '');
+ emitTextDelta(text);
+ return;
+ }
+ case 'exec_command_begin':
+ opts.onEvent({
+ type: 'tool-event', tool: 'exec_command',
+ callId: String(ev.call_id || ev.callId || ''),
+ phase: 'use', input: { command: ev.command },
+ });
+ return;
+ case 'exec_command_end':
+ opts.onEvent({
+ type: 'tool-event', tool: 'exec_command',
+ callId: String(ev.call_id || ev.callId || ''),
+ phase: 'result', output: typeof ev.output === 'string' ? ev.output : '',
+ });
+ return;
+ case 'patch_apply_begin':
+ opts.onEvent({ type: 'tool-event', tool: 'patch_apply', callId: String(ev.call_id || ev.callId || ''), phase: 'use' });
+ return;
+ case 'patch_apply_end':
+ opts.onEvent({ type: 'tool-event', tool: 'patch_apply', callId: String(ev.call_id || ev.callId || ''), phase: 'result' });
+ return;
+ case 'task_complete':
+ finishTurn(false);
+ return;
+ case 'turn_aborted':
+ turnAborted = true;
+ finishTurn(true);
+ return;
+ }
+ }
+
+ function finishTurn(aborted: boolean) {
+ if (turnCompleted) return;
+ turnCompleted = true;
+ if (aborted) turnAborted = true;
+ // Close stdin so codex shuts down cleanly. The `close` handler
+ // below resolves the outer promise once the process exits.
+ try { child.stdin.end(); } catch { /* */ }
+ }
+
+ function finish(status: 'completed' | 'failed' | 'cancelled' | 'timeout', extra: Record<string, unknown> = {}) {
+ if (exited) return;
+ exited = true;
+ clearTimeout(timer);
+ detachAbort();
+ closePending(new Error('codex shutting down'));
+ opts.onEvent({
+ type: 'done', status,
+ durationMs: Date.now() - startedAt,
+ sessionId: threadId,
+ ...extra,
+ });
+ resolveOuter();
+ }
+
+ child.on('error', err => {
+ log.warn('codex spawn error', { error: (err as Error).message });
+ finish('failed', { error: (err as Error).message, stderrTail: tail.toString() });
+ });
+ child.on('close', code => {
+ if (opts.signal.aborted) return finish('cancelled', { output: collectedText });
+ if (timedOut) return finish('timeout', { error: `cli exceeded ${opts.timeoutMs}ms`, output: collectedText, stderrTail: tail.toString() });
+ if (turnAborted) return finish('cancelled', { output: collectedText });
+ if (turnError) return finish('failed', { error: turnError, output: collectedText, stderrTail: tail.toString() });
+ if (code === 0 && (turnCompleted || collectedText)) {
+ return finish('completed', { output: collectedText });
+ }
+ finish('failed', {
+ error: `codex exited with code ${code}` + (turnCompleted ? '' : ' (turn never completed)'),
+ output: collectedText,
+ stderrTail: tail.toString(),
+ });
+ });
+
+ // ─── Drive the protocol ──────────────────────────────────────────
+ (async () => {
+ try {
+ await rpc('initialize', {
+ clientInfo: { name: 'orkas', title: 'Orkas', version: '0.1.0' },
+ capabilities: { experimentalApi: true },
+ });
+ notify('initialized');
+
+ threadId = await startOrResumeThread(opts);
+ if (!threadId) {
+ finish('failed', { error: 'codex thread/start returned no thread id', stderrTail: tail.toString() });
+ return;
+ }
+
+ await rpc('turn/start', {
+ threadId,
+ input: [{ type: 'text', text: opts.prompt }],
+ });
+ // After turn/start succeeds we wait passively — turn end is
+ // driven by `turn/completed` / `task_complete` notifications,
+ // which call finishTurn → child.stdin.end → process exits →
+ // close handler resolves outerPromise.
+ } catch (err) {
+ const msg = (err as Error).message || String(err);
+ log.warn('codex protocol error', { error: msg });
+ if (!exited) finish('failed', { error: msg, stderrTail: tail.toString() });
+ }
+ })();
+
+ async function startOrResumeThread(o: BackendRunOptions): Promise<string | undefined> {
+ if (o.resumeSessionId) {
+ try {
+ const r = await rpc('thread/resume', {
+ threadId: o.resumeSessionId,
+ cwd: o.cwd,
+ model: o.model || null,
+ developerInstructions: null,
+ });
+ const tid = extractThreadId(r);
+ if (tid) return tid;
+ log.warn('codex thread/resume returned no thread id; falling back to thread/start');
+ } catch (err) {
+ log.warn('codex thread/resume failed; falling back to thread/start', { error: (err as Error).message });
+ }
+ }
+ const r = await rpc('thread/start', {
+ model: o.model || null,
+ modelProvider: null,
+ profile: null,
+ cwd: o.cwd,
+ approvalPolicy: null,
+ sandbox: null,
+ config: null,
+ baseInstructions: null,
+ developerInstructions: null,
+ compactPrompt: null,
+ includeApplyPatchTool: null,
+ experimentalRawEvents: false,
+ persistExtendedHistory: true,
+ });
+ return extractThreadId(r);
+ }
+
+ return outerPromise;
},
- promptOnStdin: true,
-});
+};
+
+function buildCodexArgs(opts: BackendRunOptions): string[] {
+ // Per multica: `codex app-server --listen stdio://` is the entry
+ // point for the JSON-RPC protocol. customArgs trail.
+ const args = ['app-server', '--listen', 'stdio://'];
+ if (opts.customArgs && opts.customArgs.length) args.push(...opts.customArgs);
+ return args;
+}
+
+/** Pull the `threadId` out of a `thread/start` or `thread/resume`
+ * response. Codex puts it at the top level of the result; older
+ * stubs sometimes wrap it under `thread`. Exposed for unit tests. */
+export function extractThreadId(result: any): string | undefined {
+ if (!result || typeof result !== 'object') return undefined;
+ if (typeof result.threadId === 'string' && result.threadId) return result.threadId;
+ if (result.thread && typeof result.thread.id === 'string' && result.thread.id) return result.thread.id;
+ return undefined;
+}
diff --git a/src/main/features/local_agents/backends/openclaw.ts b/src/main/features/local_agents/backends/openclaw.ts
index 0ff7aa3d..7a330f9e 100644
--- a/src/main/features/local_agents/backends/openclaw.ts
+++ b/src/main/features/local_agents/backends/openclaw.ts
@@ -1,27 +1,251 @@
/**
* OpenClaw backend.
*
- * In OpenClaw the model is bound to a pre-registered "agent" via
- * `openclaw agents add`; the run command picks the agent by name. We
- * pass `agent.runtime.model` (which is actually the agent name in the
- * OpenClaw world — see registry.listModels for openclaw) as the
- * positional argument when present.
+ * Empirically verified against `openclaw 2026.4.11`:
*
- * v1 takes the prompt on stdin and captures stdout as plain text.
+ * openclaw agent --local --json --session-id <id> [--agent <name>]
+ * [--timeout <seconds>] --message <prompt>
+ *
+ * — but unlike multica's older reference, this version emits its reply
+ * NOT as NDJSON-on-stdout. Instead **all output goes to stderr**:
+ * - Skill / tool warnings prefixed with `[skills]` / `[tools]` …
+ * - At the end, a single pretty-printed JSON object:
+ *
+ * {
+ * "payloads": [{ "text": "...", "mediaUrl": null }, ...],
+ * "meta": {
+ * "durationMs": 17149,
+ * "agentMeta": { "sessionId": "...", "provider": "...",
+ * "model": "...", "usage": {...} }
+ * }
+ * }
+ *
+ * stdout is empty. So we collect stderr, scan for the trailing JSON
+ * block, parse it, and surface `payloads[*].text` as the agent reply +
+ * `meta.agentMeta.sessionId` as the resume key. Earlier stderr lines
+ * (warnings, tool errors) are still forwarded as `stderr-line` events
+ * for visibility in the debug rail.
+ *
+ * Streaming: openclaw doesn't push partial tokens. The user sees a
+ * spinner / process rail until the run ends, then the full reply
+ * lands at once. Token-streaming would require openclaw to support
+ * NDJSON output mode; not available today.
*/
-import { makeTextBackend } from './_text.js';
-
-export const openclawBackend = makeTextBackend({
- logName: 'local-agents:openclaw',
- buildArgs(opts) {
- const args = ['run', '--prompt-stdin'];
- // openclaw uses `--agent <name>`; we re-use the model field as the
- // agent name when the user supplied one. Empty = let openclaw use
- // its current default.
- if (opts.model) args.push('--agent', opts.model);
- if (opts.customArgs && opts.customArgs.length) args.push(...opts.customArgs);
- return args;
+import * as crypto from 'node:crypto';
+import { createLogger } from '../../../logger.js';
+import {
+ type LocalBackend,
+ type BackendRunOptions,
+ type LocalEvent,
+ StderrTail,
+ spawnCli,
+ bindAbort,
+} from './base.js';
+
+const log = createLogger('local-agents:openclaw');
+
+export const openclawBackend: LocalBackend = {
+ async run(opts: BackendRunOptions): Promise<void> {
+ const sessionId = opts.resumeSessionId || crypto.randomUUID();
+ const args = buildOpenclawArgs(opts, sessionId);
+ const child = spawnCli(opts.binPath, args, opts.cwd);
+ const detachAbort = bindAbort(child, opts.signal);
+ const tail = new StderrTail();
+ const startedAt = Date.now();
+
+ let exited = false;
+ let timedOut = false;
+ // openclaw writes everything to stderr; we accumulate the FULL
+ // stderr (no cap — the trailing JSON blob we need to parse can
+ // run several KB) AND keep a separate StderrTail for the
+ // diagnostic snippet on failure.
+ let fullStderr = '';
+
+ opts.onEvent({
+ type: 'process-info',
+ pid: child.pid ?? -1,
+ cwd: opts.cwd,
+ cmd: opts.binPath,
+ args,
+ });
+
+ const timer = setTimeout(() => {
+ timedOut = true;
+ try { child.kill('SIGTERM'); } catch { /* */ }
+ setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* */ } }, 10_000).unref();
+ }, opts.timeoutMs);
+ if (typeof timer.unref === 'function') timer.unref();
+
+ // openclaw doesn't read stdin; close so it doesn't wait.
+ child.stdin.end();
+
+ // stdout is currently always empty for openclaw 2026.4.11 — keep a
+ // best-effort listener anyway in case future versions start using
+ // it (we'd surface the line as text-delta).
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => {
+ if (chunk) opts.onEvent({ type: 'text-delta', text: chunk });
+ });
+
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ fullStderr += chunk;
+ tail.push(chunk);
+ // Forward each line for the process rail. Strip ANSI escapes
+ // so colored log prefixes don't leak into the UI.
+ for (const line of chunk.split(/\r?\n/)) {
+ if (line) opts.onEvent({ type: 'stderr-line', line: stripAnsi(line) });
+ }
+ });
+
+ return new Promise<void>(resolve => {
+ const finish = (status: 'completed' | 'failed' | 'cancelled' | 'timeout', extra: Record<string, unknown> = {}) => {
+ if (exited) return;
+ exited = true;
+ clearTimeout(timer);
+ detachAbort();
+ opts.onEvent({
+ type: 'done', status,
+ durationMs: Date.now() - startedAt,
+ ...extra,
+ });
+ resolve();
+ };
+ child.on('error', err => {
+ log.warn('spawn error', { error: (err as Error).message });
+ finish('failed', { error: (err as Error).message, stderrTail: tail.toString() });
+ });
+ child.on('close', code => {
+ if (opts.signal.aborted) return finish('cancelled');
+ if (timedOut) return finish('timeout', { error: `cli exceeded ${opts.timeoutMs}ms`, stderrTail: tail.toString() });
+
+ const parsed = parseOpenclawReply(fullStderr);
+ const replyText = parsed?.text || '';
+ const sid = parsed?.sessionId || sessionId;
+
+ if (replyText) {
+ // Surface the reply as a single text-delta so the standard
+ // delta-streaming path in bus.ts populates the bubble. (It
+ // arrives at end-of-run, not token-by-token — see file header.)
+ opts.onEvent({ type: 'text-delta', text: replyText });
+ }
+
+ if (code === 0 && replyText) {
+ return finish('completed', { output: replyText, sessionId: sid });
+ }
+ if (code === 0 && !replyText) {
+ // Exit clean but no parseable reply → treat as failed so
+ // the user sees an error bubble instead of an empty turn.
+ return finish('failed', {
+ error: 'openclaw exited cleanly but produced no agent reply (check stderr tail)',
+ output: '',
+ sessionId: sid,
+ stderrTail: tail.toString(),
+ });
+ }
+ finish('failed', {
+ error: parsed?.error || `openclaw exited with code ${code}`,
+ output: replyText,
+ sessionId: sid,
+ stderrTail: tail.toString(),
+ });
+ });
+ });
},
- promptOnStdin: true,
-});
+};
+
+function buildOpenclawArgs(opts: BackendRunOptions, sessionId: string): string[] {
+ // Per `openclaw agent --help` (2026.4.11):
+ // --local run embedded agent (no gateway daemon needed)
+ // --json structured output (lands on stderr in this version)
+ // --session-id required for any deterministic session
+ // --message prompt body (argv, NOT stdin)
+ // Optional: --agent <name> selects a pre-registered agent; --timeout
+ // overrides the 600s default.
+ const args = ['agent', '--local', '--json', '--session-id', sessionId];
+ if (opts.model) args.push('--agent', opts.model);
+ if (opts.customArgs && opts.customArgs.length) args.push(...opts.customArgs);
+ args.push('--message', opts.prompt);
+ return args;
+}
+
+/** Strip ANSI color escape sequences. openclaw's `[skills]` /
+ * `[tools]` log lines are colorized; without this every stderr-line
+ * shows up in the UI with raw ESC[36m noise. */
+function stripAnsi(s: string): string {
+ // eslint-disable-next-line no-control-regex
+ return s.replace(/\[[0-9;]*m/g, '');
+}
+
+/**
+ * Find the trailing pretty-printed JSON object in openclaw's stderr
+ * and pull out the user-facing reply + session id. The JSON lands AT
+ * THE END of the stream, but earlier output (warnings, tool errors,
+ * partial JSON from interrupted tools) means we can't just take the
+ * first `{`. Strategy: walk backward from the end of the buffer
+ * looking for a `{` whose matching `}` (counting balanced braces)
+ * runs through to (or near) the end of the stream — that's the final
+ * envelope object. Validate by parsing.
+ *
+ * Exposed for unit testing.
+ */
+export function parseOpenclawReply(stderrText: string):
+ | null
+ | { text: string; sessionId?: string; error?: string } {
+ if (!stderrText) return null;
+ const clean = stripAnsi(stderrText);
+
+ // Walk backward through `{` candidates. The final `{` line in the
+ // stream is highly likely to be the start of the reply envelope.
+ // We try each candidate from latest to earliest until JSON.parse
+ // succeeds AND the result has the shape we expect.
+ const opens: number[] = [];
+ for (let i = 0; i < clean.length; i++) {
+ if (clean[i] === '{') opens.push(i);
+ }
+ for (let i = opens.length - 1; i >= 0; i--) {
+ const start = opens[i];
+ const end = findMatchingBrace(clean, start);
+ if (end < 0) continue;
+ const candidate = clean.slice(start, end + 1);
+ let obj: any;
+ try { obj = JSON.parse(candidate); } catch { continue; }
+ if (obj && typeof obj === 'object' && Array.isArray(obj.payloads)) {
+ const text = (obj.payloads as any[])
+ .map(p => (p && typeof p.text === 'string') ? p.text : '')
+ .filter(s => s.length)
+ .join('\n');
+ const sessionId = obj.meta?.agentMeta?.sessionId
+ || obj.meta?.sessionId
+ || undefined;
+ return { text, sessionId };
+ }
+ if (obj && typeof obj === 'object' && typeof obj.error === 'string') {
+ return { text: '', error: String(obj.error) };
+ }
+ }
+ return null;
+}
+
+function findMatchingBrace(s: string, openIdx: number): number {
+ let depth = 0;
+ let inStr = false;
+ let escape = false;
+ for (let i = openIdx; i < s.length; i++) {
+ const ch = s[i];
+ if (escape) { escape = false; continue; }
+ if (inStr) {
+ if (ch === '\\') escape = true;
+ else if (ch === '"') inStr = false;
+ continue;
+ }
+ if (ch === '"') { inStr = true; continue; }
+ if (ch === '{') depth++;
+ else if (ch === '}') {
+ depth--;
+ if (depth === 0) return i;
+ }
+ }
+ return -1;
+}
diff --git a/src/main/features/local_agents/backends/opencode.ts b/src/main/features/local_agents/backends/opencode.ts
index 59b0144e..44198a8d 100644
--- a/src/main/features/local_agents/backends/opencode.ts
+++ b/src/main/features/local_agents/backends/opencode.ts
@@ -1,22 +1,205 @@
/**
* OpenCode CLI backend.
*
- * `opencode run --print` runs non-interactively and prints the model
- * reply to stdout. The prompt is read from stdin. Model is selected
- * via `--model provider/name` when supplied (matches the format the
- * `opencode models` subcommand prints — same shape we'd surface in
- * future dynamic-discovery support).
+ * Correct invocation (per multica `opencode.go`; my earlier
+ * `_text.ts` template was wrong — opencode doesn't take stdin and
+ * `--print` isn't a flag):
+ *
+ * opencode run --format json [--model <provider/model>]
+ * [--session <id>] <prompt>
+ *
+ * Notes:
+ * - Prompt is passed as the LAST positional argv (NOT stdin).
+ * - Resume: `--session <id>` (different flag name from claude).
+ * - Output: NDJSON events on stdout. We care about:
+ * step_start, text (part.text), tool_use (part.tool/callID/state),
+ * error (error.data.message), step_finish (token usage; ignored).
+ * - sessionID may appear at top-level event or under part.
*/
-import { makeTextBackend } from './_text.js';
+import { createLogger } from '../../../logger.js';
+import {
+ type LocalBackend,
+ type BackendRunOptions,
+ type LocalEvent,
+ StderrTail,
+ spawnCli,
+ bindAbort,
+ LineSplitter,
+} from './base.js';
+
+const log = createLogger('local-agents:opencode');
+
+export const opencodeBackend: LocalBackend = {
+ async run(opts: BackendRunOptions): Promise<void> {
+ const args = buildOpencodeArgs(opts);
+ const child = spawnCli(opts.binPath, args, opts.cwd);
+ const detachAbort = bindAbort(child, opts.signal);
+ const tail = new StderrTail();
+ const startedAt = Date.now();
+
+ let exited = false;
+ let timedOut = false;
+ let textOut = '';
+ let resultStatus: 'completed' | 'failed' | undefined;
+ let resultError: string | undefined;
+ let observedSessionId: string | undefined;
+
+ opts.onEvent({
+ type: 'process-info',
+ pid: child.pid ?? -1,
+ cwd: opts.cwd,
+ cmd: opts.binPath,
+ args,
+ });
-export const opencodeBackend = makeTextBackend({
- logName: 'local-agents:opencode',
- buildArgs(opts) {
- const args = ['run', '--print'];
- if (opts.model) args.push('--model', opts.model);
- if (opts.customArgs && opts.customArgs.length) args.push(...opts.customArgs);
- return args;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ try { child.kill('SIGTERM'); } catch { /* */ }
+ setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* */ } }, 10_000).unref();
+ }, opts.timeoutMs);
+ if (typeof timer.unref === 'function') timer.unref();
+
+ // opencode reads prompt from argv; close stdin so it doesn't wait.
+ child.stdin.end();
+
+ const splitter = new LineSplitter();
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => {
+ splitter.push(chunk, line => {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ let obj: any;
+ try { obj = JSON.parse(trimmed); } catch { return; }
+ const ev = mapOpencodeEvent(obj);
+ if (ev?.captureSessionId) observedSessionId = ev.captureSessionId;
+ if (ev?.event) {
+ opts.onEvent(ev.event);
+ if (ev.event.type === 'text-delta' && typeof (ev.event as any).text === 'string') {
+ textOut += (ev.event as any).text as string;
+ }
+ }
+ if (ev?.terminal) {
+ resultStatus = ev.terminal.status;
+ resultError = ev.terminal.error;
+ }
+ });
+ });
+
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ tail.push(chunk);
+ for (const line of chunk.split(/\r?\n/)) {
+ if (line) opts.onEvent({ type: 'stderr-line', line });
+ }
+ });
+
+ return new Promise<void>(resolve => {
+ const finish = (status: 'completed' | 'failed' | 'cancelled' | 'timeout', extra: Record<string, unknown> = {}) => {
+ if (exited) return;
+ exited = true;
+ clearTimeout(timer);
+ detachAbort();
+ opts.onEvent({
+ type: 'done', status,
+ durationMs: Date.now() - startedAt,
+ sessionId: observedSessionId,
+ ...extra,
+ });
+ resolve();
+ };
+ child.on('error', err => {
+ log.warn('spawn error', { error: (err as Error).message });
+ finish('failed', { error: (err as Error).message, stderrTail: tail.toString() });
+ });
+ child.on('close', code => {
+ if (opts.signal.aborted) return finish('cancelled', { output: textOut });
+ if (timedOut) return finish('timeout', { error: `cli exceeded ${opts.timeoutMs}ms`, output: textOut, stderrTail: tail.toString() });
+ if (code === 0 && (resultStatus === 'completed' || resultStatus === undefined)) {
+ return finish('completed', { output: textOut });
+ }
+ const err = resultError
+ || (code !== 0 ? `opencode exited with code ${code}` : 'opencode closed without final event');
+ finish('failed', { error: err, output: textOut, stderrTail: tail.toString() });
+ });
+ });
},
- promptOnStdin: true,
-});
+};
+
+function buildOpencodeArgs(opts: BackendRunOptions): string[] {
+ const args = ['run', '--format', 'json'];
+ if (opts.model) args.push('--model', opts.model);
+ if (opts.resumeSessionId) args.push('--session', opts.resumeSessionId);
+ if (opts.customArgs && opts.customArgs.length) args.push(...opts.customArgs);
+ args.push(opts.prompt);
+ return args;
+}
+
+/** Pure mapper for opencode NDJSON events. Exposed for unit testing. */
+export function mapOpencodeEvent(obj: any):
+ | undefined
+ | {
+ event?: LocalEvent;
+ captureSessionId?: string;
+ terminal?: { status: 'completed' | 'failed'; error?: string };
+ } {
+ if (!obj || typeof obj !== 'object') return undefined;
+ const out: ReturnType<typeof mapOpencodeEvent> = {};
+ // SessionID can sit at top level or inside .part — accept either.
+ const sid = (typeof obj.sessionID === 'string' && obj.sessionID)
+ || (obj.part && typeof obj.part.sessionID === 'string' ? obj.part.sessionID : '');
+ if (sid) out!.captureSessionId = sid;
+ switch (obj.type) {
+ case 'text': {
+ const text = obj.part?.text;
+ if (typeof text === 'string' && text.length) {
+ out!.event = { type: 'text-delta', text };
+ }
+ return out;
+ }
+ case 'tool_use': {
+ const part = obj.part || {};
+ const state = part.state || {};
+ const status = String(state.status || '');
+ // Two visible phases: when the tool is just invoked vs when its
+ // output landed. Map to phase 'use' / 'result' so the renderer
+ // shows a use → result transition.
+ if (status === 'completed' || status === 'success' || status === 'done') {
+ const output = typeof state.output === 'string'
+ ? state.output
+ : (state.output != null ? JSON.stringify(state.output) : '');
+ out!.event = {
+ type: 'tool-event',
+ tool: String(part.tool || 'tool'),
+ callId: String(part.callID || part.id || ''),
+ phase: 'result',
+ output,
+ };
+ } else {
+ out!.event = {
+ type: 'tool-event',
+ tool: String(part.tool || 'tool'),
+ callId: String(part.callID || part.id || ''),
+ phase: 'use',
+ input: state.input ?? {},
+ };
+ }
+ return out;
+ }
+ case 'error': {
+ const errObj = obj.error || {};
+ const msg = errObj.data?.message || errObj.name || 'opencode reported error';
+ out!.terminal = { status: 'failed', error: String(msg) };
+ return out;
+ }
+ case 'step_finish':
+ // Token usage event; nothing to surface (we don't track usage
+ // for CLI calls in archive context yet).
+ return out;
+ case 'step_start':
+ out!.event = { type: 'status', status: 'running' };
+ return out;
+ default:
+ return out!.captureSessionId ? out : undefined;
+ }
+}
diff --git a/src/main/ipc/local_agents.ts b/src/main/ipc/local_agents.ts
index 3ca7a284..b368d852 100644
--- a/src/main/ipc/local_agents.ts
+++ b/src/main/ipc/local_agents.ts
@@ -11,13 +11,35 @@
* routes CLI agents into `features/local_agents/runner.ts` (Step 6).
*/
-import { detectAll, detectOne, invalidateCache, LOCAL_CLI_TYPES, type LocalCliType } from '../features/local_agents/registry.js';
+import { detectAll, detectOne, invalidateCache, LOCAL_CLI_TYPES, type LocalCliType, type LocalCliEntry } from '../features/local_agents/registry.js';
import { listModels } from '../features/local_agents/models.js';
function isLocalCliType(v: unknown): v is LocalCliType {
return typeof v === 'string' && (LOCAL_CLI_TYPES as readonly string[]).includes(v);
}
+// Set of CLI types we have a working dispatch backend for. Detection
+// is independent (registry probes PATH + --version regardless), but
+// the create-modal / detail-page selectors shouldn't let users pick a
+// CLI we can't actually dispatch through. As of today every detected
+// CLI has a backend — left as a guard for future additions where the
+// dispatch path lags detection.
+const DISPATCHABLE: ReadonlySet<LocalCliType> = new Set<LocalCliType>(
+ ['claude', 'codex', 'openclaw', 'opencode', 'hermes'],
+);
+
+function maskUnsupported(entries: LocalCliEntry[]): LocalCliEntry[] {
+ return entries.map(e => {
+ if (DISPATCHABLE.has(e.type)) return e;
+ return {
+ ...e,
+ available: false,
+ error: e.error ?? 'version_unknown',
+ errorDetail: 'backend not yet implemented in Orkas',
+ };
+ });
+}
+
export const invokeHandlers = {
/**
* List all known CLI types. Default uses the 60s cache; pass
@@ -26,7 +48,7 @@ export const invokeHandlers = {
*/
'localAgents.list': async ({ force = false }: { force?: boolean } = {}) => {
const entries = await detectAll({ force: !!force });
- return { entries };
+ return { entries: maskUnsupported(entries) };
},
/**
@@ -39,7 +61,7 @@ export const invokeHandlers = {
if (!isLocalCliType(type)) throw new Error('invalid CLI type');
invalidateCache();
const entry = await detectOne(type);
- return { entry };
+ return { entry: maskUnsupported([entry])[0] };
},
/**
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 12a18207..47fac7ae 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -695,6 +695,13 @@ async function _flushAgentFieldSave() {
// the next picker open means freshly-typed `@<multi-word-name>` only
// gets the fallback char class, which stops at the first whitespace.
await loadAgents(true);
+ // Repaint the input-box recipient chip if it's bound to this agent —
+ // its `name` field is a localStorage snapshot taken at picker time, so
+ // without an explicit re-render the chip keeps showing the old name
+ // until the next view switch.
+ if (field === 'name' && typeof _renderRecipientChip === 'function') {
+ try { _renderRecipientChip(); } catch (_) { /* non-fatal */ }
+ }
} catch (e) {
_agentsLog.warn('save agent field failed', e);
if (field === 'name') {
@@ -853,6 +860,11 @@ function _ensureAgentChatController() {
_renderAgentDetail(freshData.agent, true);
_agentsCache = null;
await loadAgents(true);
+ // Repaint the chat input recipient chip in case its bound
+ // agent was the one just renamed by the edit chat.
+ if (typeof _renderRecipientChip === 'function') {
+ try { _renderRecipientChip(); } catch (_) { /* non-fatal */ }
+ }
}
} catch (e) {
_agentsLog.warn('refresh after updated fields failed', e);
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 079121cd..e042cd10 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -245,8 +245,18 @@ function _renderRecipientChip(target) {
const nameEl = document.getElementById(id);
if (!nameEl) continue;
const r = _activeRecipient(tg);
- if (r.kind === 'agent' && r.name) {
- nameEl.textContent = '@' + r.name;
+ if (r.kind === 'agent' && r.id) {
+ // Resolve name from the live registry first — the `r.name` field is
+ // a snapshot taken at picker time and stays stale after rename. Fall
+ // back to the snapshot only when the registry doesn't know the agent
+ // (e.g. it was deleted), then to the id as a last resort.
+ let display = '';
+ if (typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache)) {
+ const a = _agentsCache.find((x) => x && x.agent_id === r.id);
+ if (a && a.name) display = a.name;
+ }
+ if (!display) display = r.name || r.id;
+ nameEl.textContent = '@' + display;
nameEl.removeAttribute('data-i18n');
} else {
nameEl.setAttribute('data-i18n', 'chat.recipient_commander');
@@ -441,10 +451,21 @@ const _LEADING_MENTION_RE = /^@([A-Za-z0-9_一-鿿-]+)\s?/u;
function applyRecipientPrefix(raw, target) {
const r = _activeRecipient(target || 'conversation');
- if (r.kind !== 'agent' || !r.name) return raw;
+ if (r.kind !== 'agent' || !r.id) return raw;
const text = String(raw || '');
if (_LEADING_MENTION_RE.exec(text)) return text;
- const tag = '@' + String(r.name).replace(/\s+/g, '');
+ // Resolve from the live registry by id — `r.name` is a localStorage
+ // snapshot taken at picker time, so a rename leaves it stale and the
+ // outgoing `@<token>` would still carry the old name. Fall back to the
+ // snapshot when the registry doesn't know the agent (deleted), then to
+ // the id as last resort.
+ let display = '';
+ if (typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache)) {
+ const a = _agentsCache.find((x) => x && x.agent_id === r.id);
+ if (a && a.name) display = a.name;
+ }
+ if (!display) display = r.name || r.id;
+ const tag = '@' + String(display).replace(/\s+/g, '');
return tag + ' ' + text;
}
diff --git a/test/main/features/local_agents/acp_parser.test.ts b/test/main/features/local_agents/acp_parser.test.ts
index c843afef..58ce46f8 100644
--- a/test/main/features/local_agents/acp_parser.test.ts
+++ b/test/main/features/local_agents/acp_parser.test.ts
@@ -5,6 +5,7 @@ function makeHandlers() {
return {
onSessionNew: vi.fn(),
onTextDelta: vi.fn(),
+ onThinking: vi.fn(),
onToolUse: vi.fn(),
onToolResult: vi.fn(),
onPromptResult: vi.fn(),
@@ -19,7 +20,7 @@ describe('local_agents/backends/_acp › handleAcpMessage', () => {
expect(h.onSessionNew).toHaveBeenCalledWith('sess-x');
});
- it('routes session/update agent_message_chunk to onTextDelta', () => {
+ it('routes session/update agent_message_chunk to onTextDelta (kind field)', () => {
const h = makeHandlers();
handleAcpMessage({
jsonrpc: '2.0',
@@ -29,6 +30,34 @@ describe('local_agents/backends/_acp › handleAcpMessage', () => {
expect(h.onTextDelta).toHaveBeenCalledWith('hello');
});
+ it('routes session/update agent_message_chunk via sessionUpdate field (Hermes wire format)', () => {
+ const h = makeHandlers();
+ handleAcpMessage({
+ method: 'session/update',
+ params: { sessionId: 's', update: { sessionUpdate: 'agent_message_chunk', content: { text: 'hi' } } },
+ }, h);
+ expect(h.onTextDelta).toHaveBeenCalledWith('hi');
+ });
+
+ it('routes agent_thought_chunk to onThinking', () => {
+ const h = makeHandlers();
+ handleAcpMessage({
+ method: 'session/update',
+ params: { update: { sessionUpdate: 'agent_thought_chunk', content: { text: '(◔_◔) mulling' } } },
+ }, h);
+ expect(h.onThinking).toHaveBeenCalledWith('(◔_◔) mulling');
+ });
+
+ it('available_commands_update goes to onUnknown (not pretending to be a tool)', () => {
+ const h = makeHandlers();
+ handleAcpMessage({
+ method: 'session/update',
+ params: { update: { sessionUpdate: 'available_commands_update', availableCommands: [{ name: 'help' }] } },
+ }, h);
+ expect(h.onToolUse).not.toHaveBeenCalled();
+ expect(h.onUnknown).toHaveBeenCalled();
+ });
+
it('routes tool_call to onToolUse', () => {
const h = makeHandlers();
handleAcpMessage({