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.

feat(local-agents): support local CLI agents (claude code / codex / openclaw / opencode / hermes)

aiservice377dd1590001
diff --git a/scripts/ensure-deps.cjs b/scripts/ensure-deps.cjs
index 6cf9cd24..3f51595b 100644
--- a/scripts/ensure-deps.cjs
+++ b/scripts/ensure-deps.cjs
@@ -110,6 +110,82 @@ function runModelFetch() {
}
}
+// In macOS dev mode the Dock tooltip + Cmd-Tab name + menu bar header
+// all come from `Electron.app/Contents/Info.plist` (`CFBundleName` /
+// `CFBundleDisplayName`). `app.setName()` only changes the first menu
+// bar item -- it does NOT change the Dock.
+//
+// Editing the plist alone is not enough: macOS Launch Services keeps a
+// persistent cache keyed by bundle id `com.github.Electron`, and even
+// `lsregister -f` often refuses to refresh. The only reliable approach
+// is to rename the .app directory itself (so macOS treats it as a new
+// app and re-registers), and update `electron/path.txt` alongside (the
+// npm electron launcher reads that to locate the binary). Rename +
+// plist edit + ad-hoc resign + lsregister + killall Dock are all
+// required for the change to stick.
+//
+// Idempotent: skip when node_modules/electron/dist/Orkas.app already
+// exists. `npm install` re-lands Electron.app (overwriting Orkas.app
+// is fine -- the next launch redoes the patch).
+function patchElectronAppName() {
+ if (process.platform !== 'darwin') return;
+ const distDir = path.join(NODE_MODULES, 'electron', 'dist');
+ const oldApp = path.join(distDir, 'Electron.app');
+ const newApp = path.join(distDir, 'Orkas.app');
+ const pathTxt = path.join(NODE_MODULES, 'electron', 'path.txt');
+ if (!fs.existsSync(distDir)) return;
+
+ // Already patched: bail out. Verify Orkas.app exists + path.txt is updated.
+ if (fs.existsSync(newApp) && !fs.existsSync(oldApp)) {
+ let pathTxtContent = '';
+ try { pathTxtContent = fs.readFileSync(pathTxt, 'utf8').trim(); } catch { /* */ }
+ if (pathTxtContent.startsWith('Orkas.app/')) return;
+ }
+
+ // Rename Electron.app -> Orkas.app. If both exist, drop the new one first so the rename does not collide.
+ if (fs.existsSync(oldApp)) {
+ if (fs.existsSync(newApp)) fs.rmSync(newApp, { recursive: true, force: true });
+ try { fs.renameSync(oldApp, newApp); }
+ catch (err) {
+ console.warn('[Orkas] rename Electron.app failed (' + err.message + '): a process may still be holding it; skipping this patch pass');
+ return;
+ }
+ } else if (!fs.existsSync(newApp)) {
+ return; // Neither old nor new -- Electron install is broken; leave it for npm install to handle.
+ }
+
+ // Set the plist keys.
+ const plistPath = path.join(newApp, 'Contents', 'Info.plist');
+ for (const [key, val] of [
+ ['CFBundleName', 'Orkas'],
+ ['CFBundleDisplayName', 'Orkas'],
+ ]) {
+ const r = spawnSync('plutil', ['-replace', key, '-string', val, plistPath], { stdio: 'pipe' });
+ if (r.status !== 0) {
+ console.warn('[Orkas] plutil -replace ' + key + ' failed:', (r.stderr || '').toString().trim());
+ }
+ }
+
+ // Editing the plist invalidates the existing signature; ad-hoc resign.
+ const cs = spawnSync('codesign', ['--force', '--deep', '--sign', '-', newApp], { stdio: 'pipe' });
+ if (cs.status !== 0) {
+ console.warn('[Orkas] Orkas.app ad-hoc resign failed (manual fix: codesign --force --deep --sign - "' + newApp + '"):', (cs.stderr || '').toString().trim());
+ }
+
+ // The electron npm launcher uses path.txt to locate the binary; point it at the new name.
+ try { fs.writeFileSync(pathTxt, 'Orkas.app/Contents/MacOS/Electron'); }
+ catch (err) {
+ console.warn('[Orkas] update electron/path.txt failed (' + err.message + '): the electron CLI may fail to find the binary');
+ }
+
+ // Launch Services: unregister the old path + register the new one. Restart Dock to drop any running-instance cache.
+ const lsregister = '/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister';
+ spawnSync(lsregister, ['-u', oldApp], { stdio: 'pipe' });
+ spawnSync(lsregister, ['-f', newApp], { stdio: 'pipe' });
+ spawnSync('killall', ['Dock'], { stdio: 'pipe' });
+ console.log('[Orkas] Dock name set to Orkas (renamed Electron.app -> Orkas.app; effective next launch)');
+}
+
function main() {
if (!fs.existsSync(PKG)) {
console.error('[Orkas] 找不到 package.json:', PKG);
@@ -126,6 +202,7 @@ function main() {
console.log('[Orkas] 知识库 embedding 模型缺失,补下载(约 90MB)...');
runModelFetch();
}
+ patchElectronAppName();
return;
}
@@ -151,6 +228,9 @@ function main() {
} catch (err) {
console.warn('[Orkas] 警告:写入依赖 stamp 失败(不影响启动):', err.message);
}
+ // npm install re-lands an Electron with the upstream "Electron"
+ // Info.plist; re-patch immediately or the Dock reverts.
+ patchElectronAppName();
}
main();
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index c53de50c..acd7f136 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -120,6 +120,15 @@ export interface Agent {
* to manually @-mention every reply. Maintained by the agent-edit LLM
* via the `<interactive>` child of `<agent>`; missing = false. */
interactive?: boolean;
+ /** Execution backend. Missing / `kind === 'in_process'` (the default)
+ * means the agent runs through `core-agent` like every existing
+ * agent. `kind === 'cli'` routes the worker turn through
+ * `features/local_agents/runner.ts` to spawn a local coding CLI
+ * (claude code / codex / openclaw / opencode / hermes). The field is
+ * set at create time from the modal's runtime selector and edited
+ * via the dedicated `chat_agent_setup_cli.md` prompt; the LLM
+ * doesn't author it directly. */
+ runtime?: AgentRuntime;
source: AgentSource;
created_at: string;
updated_at: string;
@@ -144,8 +153,25 @@ interface AgentRaw {
icon?: unknown;
color?: unknown;
interactive?: unknown;
+ runtime?: unknown;
}
+/** Per-agent execution backend. See `Agent.runtime`. */
+export type AgentRuntime =
+ | { kind: 'in_process' }
+ | {
+ kind: 'cli';
+ /** Canonical CLI type — must match `LOCAL_CLI_TYPES` in
+ * `features/local_agents/registry.ts`. Validated on read; an
+ * unknown value drops the runtime field entirely. */
+ cli: string;
+ /** Optional model id; empty means "let the CLI pick its default". */
+ model?: string;
+ /** Extra CLI flags appended after our own args. Strings only;
+ * not shell-parsed by us. */
+ custom_args?: string[];
+ };
+
// 头像 token 校验走 catalog 白名单(src/main/data/avatars.json 是单一真相源)。
// renderer/modules/avatar.js 也从同一份文件拉数据,前后端不再有任何重复。
import * as avatars from './avatars';
@@ -417,9 +443,39 @@ export function normalizeAgent(raw: AgentRaw | null | undefined, source: AgentSo
} else if (raw.interactive === 'false') {
agent.interactive = false;
}
+ const rt = _normalizeRuntime(raw.runtime);
+ if (rt) agent.runtime = rt;
return agent;
}
+/** Validate / coerce a raw `runtime` field. Unknown shapes return null
+ * (= drop the field; the agent falls back to the in-process default).
+ * Kept loose on purpose: front-end and edit-prompt may both write here
+ * and a malformed value mustn't poison reads. */
+function _normalizeRuntime(raw: unknown): AgentRuntime | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const r = raw as Record<string, unknown>;
+ const kind = r.kind;
+ if (kind === 'in_process') return { kind: 'in_process' };
+ if (kind !== 'cli') return null;
+ const cli = typeof r.cli === 'string' ? r.cli.trim() : '';
+ if (!cli) return null;
+ const out: AgentRuntime = { kind: 'cli', cli };
+ if (typeof r.model === 'string' && r.model.trim()) out.model = r.model.trim();
+ if (Array.isArray(r.custom_args)) {
+ const args = r.custom_args.filter((s): s is string => typeof s === 'string');
+ if (args.length) out.custom_args = args;
+ }
+ return out;
+}
+
+/** True when this agent runs via a local CLI rather than in-process
+ * core-agent. Single source of truth — group_chat / chats / renderer
+ * all import this rather than re-checking `runtime?.kind` directly. */
+export function isCliAgent(agent: Pick<Agent, 'runtime'> | null | undefined): boolean {
+ return !!agent && agent.runtime?.kind === 'cli';
+}
+
interface AgentListCache { stamp: string; data: Agent[] }
let _agentListCache: AgentListCache | null = null;
@@ -528,6 +584,9 @@ export interface CreateAgentOptions {
icon?: string;
color?: string;
interactive?: boolean;
+ /** Picked at create time from the modal's runtime selector. Stored as
+ * authored — `normalizeAgent` validates on read. */
+ runtime?: AgentRuntime;
}
/** Route a legacy `description` input into the matching language slot.
@@ -555,7 +614,7 @@ function resolveBilingualDescription(
* manual edit. Returns the created agent.
*/
export async function createCustomAgent(
- { name = '', description = '', description_zh, description_en, workflow = '', icon, color, interactive }: CreateAgentOptions = {},
+ { name = '', description = '', description_zh, description_en, workflow = '', icon, color, interactive, runtime }: CreateAgentOptions = {},
): Promise<Agent | null> {
assertAgentNameAllowed(name);
fs.mkdirSync(CUSTOM_AGENTS_DIR(), { recursive: true });
@@ -578,6 +637,11 @@ export async function createCustomAgent(
if (avatars.isKnownIcon(icon)) data.icon = icon;
if (avatars.isKnownColor(color)) data.color = color;
if (typeof interactive === 'boolean') data.interactive = interactive;
+ // Persist runtime only when it survives validation; an in_process
+ // selection is the implicit default and not written to disk so old
+ // tooling diffs cleanly.
+ const rt = _normalizeRuntime(runtime);
+ if (rt && rt.kind === 'cli') data.runtime = rt;
await writeJson(customAgentFile(agentId), data);
_invalidateAgentListCache();
log.info(`created id=${agentId} name=${data.name}`);
@@ -608,6 +672,12 @@ export interface UpdateAgentFields {
* null → drop the field (revert to "missing" = false at read time)
* omitted → untouched */
interactive?: boolean | null;
+ /** Three-way update:
+ * AgentRuntime → replace (validated; in_process collapses to "drop")
+ * null → drop runtime (revert to in_process default)
+ * omitted → untouched
+ * Authored by the create modal + edit UI, not the LLM edit prompt. */
+ runtime?: AgentRuntime | null;
}
/**
@@ -624,6 +694,21 @@ export async function updateCustomAgent(
if (Object.prototype.hasOwnProperty.call(updates || {}, 'name')) {
assertAgentNameAllowed(typeof updates.name === 'string' ? updates.name : '');
}
+ // CLI-backed agents have no authored workflow / skill_list — the
+ // edit prompt forbids the LLM from emitting those tags, but if it
+ // slips up we silently drop the field so the spec stays clean.
+ // Compute on the post-update runtime: a runtime change in the same
+ // turn (in_process → cli) takes effect first, then the strip runs.
+ const incomingRuntime = Object.prototype.hasOwnProperty.call(updates || {}, 'runtime')
+ ? _normalizeRuntime((updates as any).runtime)
+ : null;
+ const effectiveCli = incomingRuntime
+ ? incomingRuntime.kind === 'cli'
+ : (_normalizeRuntime((data as any).runtime)?.kind === 'cli');
+ if (effectiveCli) {
+ if ('workflow' in (updates || {})) delete (updates as any).workflow;
+ if ('skill_list' in (updates || {})) delete (updates as any).skill_list;
+ }
for (const k of ['name', 'workflow'] as const) {
if (Object.prototype.hasOwnProperty.call(updates || {}, k)) {
const v = (updates as any)[k];
@@ -717,6 +802,30 @@ export async function updateCustomAgent(
data.interactive = v;
}
}
+ if (Object.prototype.hasOwnProperty.call(updates || {}, 'runtime')) {
+ const v = updates.runtime;
+ // The runtime *kind* is locked at create time. Once an agent is
+ // CLI-backed, post-create updates may only swap which CLI backs
+ // it (cli → cli with a different `cli` field); reverting to
+ // in-process would orphan the description / inputs that were
+ // authored for a CLI runtime. The renderer enforces this in the
+ // detail-page selector; we mirror it here so the rule survives
+ // any other update path (tests, future scripts, IPC misuse).
+ const existingKind: 'cli' | 'in_process' = data.runtime &&
+ _normalizeRuntime(data.runtime)?.kind === 'cli' ? 'cli' : 'in_process';
+ const incomingKind: 'cli' | 'in_process' | null = v === null
+ ? 'in_process'
+ : (_normalizeRuntime(v)?.kind === 'cli' ? 'cli' : 'in_process');
+ if (incomingKind !== null && incomingKind !== existingKind) {
+ log.warn(`agent ${agentId}: ignored runtime kind switch ${existingKind} → ${incomingKind}`);
+ } else if (v === null) {
+ delete data.runtime;
+ } else {
+ const rt = _normalizeRuntime(v);
+ if (!rt || rt.kind === 'in_process') delete data.runtime;
+ else data.runtime = rt;
+ }
+ }
if (!data.name) data.name = '未命名智能体';
data.updated_at = nowIso();
await writeJson(f, data);
@@ -986,6 +1095,10 @@ export function buildAgentEditSystemPrompt(agent: {
description_en?: string;
workflow?: string;
interactive?: boolean;
+ /** When the agent is CLI-backed, switch to `chat_agent_setup_cli.md`
+ * which omits workflow/skills authoring and tells the LLM not to
+ * emit those sub-tags. */
+ runtime?: AgentRuntime;
}): string {
// Resolve all three forms into a single legacy `$description` placeholder
// (template still uses $description in this phase) plus the bilingual
@@ -995,14 +1108,30 @@ export function buildAgentEditSystemPrompt(agent: {
const zh = (agent.description_zh || '').trim() || (legacy && isChinese ? legacy : '');
const en = (agent.description_en || '').trim() || (legacy && !isChinese ? legacy : '');
const display = legacy || zh || en;
- const body = prompts.load('chat_agent_setup', {
- name: agent.name || '',
- description: display || '(not provided)',
- description_zh: zh || '(not provided)',
- description_en: en || '(not provided)',
- workflow: (agent.workflow || '').trim() || '(not provided)',
- interactive: agent.interactive === true ? 'true' : 'false',
- });
+ const isCli = agent.runtime?.kind === 'cli';
+ // Pick the right template + the placeholder set it expects. The CLI
+ // template doesn't reference `$workflow` (workflow is hidden for CLI
+ // agents) but does reference the runtime cli + model so the LLM can
+ // talk concretely about which CLI it is.
+ const body = isCli
+ ? prompts.load('chat_agent_setup_cli', {
+ // Runtime cli + model are deliberately NOT passed: the LLM is
+ // told to stay CLI-agnostic in the description, and surfacing
+ // the current binding tempts it to name the CLI inline (which
+ // forbiddenly bakes a brand into the description).
+ name: agent.name || '',
+ description_zh: zh || '(not provided)',
+ description_en: en || '(not provided)',
+ interactive: agent.interactive === true ? 'true' : 'false',
+ })
+ : prompts.load('chat_agent_setup', {
+ name: agent.name || '',
+ description: display || '(not provided)',
+ description_zh: zh || '(not provided)',
+ description_en: en || '(not provided)',
+ workflow: (agent.workflow || '').trim() || '(not provided)',
+ interactive: agent.interactive === true ? 'true' : 'false',
+ });
return `${body}\n\n---\n\n${buildLanguageDirective()}`;
}
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index eb6ff167..f27a342f 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -209,6 +209,17 @@ export async function deleteConversation(userId: string, cid: string): Promise<b
if (typeof att?.purgeByCid === 'function') await att.purgeByCid(userId, cid);
} catch (err) { log.warn(`purge attachments user=${userId} cid=${cid}: ${(err as Error).message}`); }
+ // Drop CLI session bindings — the next time this cid is reused (or
+ // a same-id collision, defensive), CLI agents start fresh. Their
+ // own machine-local session files (~/.claude/...) are left alone;
+ // claude self-GCs.
+ try {
+ const cliSessions = require('./local_agents/sessions');
+ if (typeof cliSessions?.clearForConversation === 'function') {
+ await cliSessions.clearForConversation(userId, cid);
+ }
+ } catch (err) { log.warn(`purge cli sessions user=${userId} cid=${cid}: ${(err as Error).message}`); }
+
log.info(`deleted user=${userId} cid=${cid}`);
return true;
}
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 70c571c2..7ea5179f 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -750,6 +750,10 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
let systemPrompt: string;
let extraTools: AgentTool[] = [];
let skillList: string[] | undefined;
+ // CLI-backed agents fetch the spec but skip systemPrompt / skillList /
+ // extraTools — the LLM stream is replaced below by `runCliAgentTurn`.
+ // Hoisted here so the branch below can read it without re-fetching.
+ let cliAgent: import('../agents').Agent | null = null;
if (isCommander) {
systemPrompt = await buildCommanderSystemPrompt(uid, cid);
extraTools = await buildCommanderExtraTools(state, w);
@@ -762,8 +766,13 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// when this returns. We DON'T touch it here.
return;
}
- systemPrompt = await buildAgentInGroupSystemPrompt(uid, agent, workingDir);
- skillList = Array.isArray(agent.skill_list) ? agent.skill_list : undefined;
+ if (agentsFeat.isCliAgent(agent)) {
+ cliAgent = agent;
+ systemPrompt = ''; // unused on CLI path
+ } else {
+ systemPrompt = await buildAgentInGroupSystemPrompt(uid, agent, workingDir);
+ skillList = Array.isArray(agent.skill_list) ? agent.skill_list : undefined;
+ }
}
// Streaming.
@@ -818,6 +827,51 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// in features/skills.ts). Builtin first to match the prompt's "按来源
// 定位" guidance.
const skillRoots = [BUILTIN_SKILLS_DIR, userSkillsDir(uid)];
+ if (cliAgent) {
+ // CLI-backed agent path: spawn the local CLI in the user's workspace
+ // and forward its events as `process` events so the same UI rail
+ // renders. The output text becomes finalText; failures populate
+ // errText so the existing post-stream logic surfaces a ⚠️ bubble.
+ try {
+ const slice = await readSlice(uid, cid, actor.id);
+ const cliOut = await _runCliAgentTurn({
+ uid, cid, actor, agent: cliAgent,
+ item, slice, workingDir,
+ signal: w.abortController.signal,
+ onProcess: data => {
+ // Mirror the LLM path: count every event for activity, but
+ // persist only `progress` and `event` shapes into processItems
+ // — `delta` text streams into the live bubble and is recovered
+ // from the final body, not the rail.
+ activityEvents += 1;
+ if (processItems.length < MAX_PROCESS_ITEMS_PER_TURN) {
+ if (data.type === 'progress' && typeof data.text === 'string' && data.text) {
+ processItems.push({ type: 'progress', text: data.text });
+ } else if (data.type === 'event' && data.event && typeof data.event === 'object') {
+ const inner = data.event as { stream?: string; data?: unknown };
+ if (inner.stream) processItems.push({ type: 'event', event: { stream: inner.stream, data: inner.data } });
+ }
+ }
+ // For the live wire: `delta` streams into the placeholder
+ // bubble (token-by-token); other shapes feed the process
+ // rail. Renderer dispatch lives in conversation.js process
+ // event handler — see `data.type === 'delta'` branch.
+ emit(state, { type: 'process', cid, actor: actor.id, data: data as unknown as Record<string, unknown> });
+ },
+ });
+ finalText = cliOut.text;
+ streamingText = cliOut.text;
+ if (cliOut.error) errText = cliOut.error;
+ if (cliOut.aborted) aborted = true;
+ } catch (err) {
+ errText = (err as Error).message || String(err);
+ log.warn(`cli stream threw cid=${cid} actor=${actor.id}: ${errText}`);
+ } finally {
+ w.abortController = null;
+ await markInFlight(uid, cid, actor.id, false);
+ emit(state, { type: 'state_changed', cid, state: await readState(uid, cid) });
+ }
+ } else {
try {
for await (const ev of streamChatWithModel({
userId: uid,
@@ -900,6 +954,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// the worker's perspective).
emit(state, { type: 'state_changed', cid, state: await readState(uid, cid) });
}
+ } // end LLM branch (paired with `if (cliAgent) { ... } else {` above)
// ── Post-stream parsing (pure data extraction; no decisions) ──────────
// Form / <agent> container extraction stays in bus because they're pure
@@ -1619,3 +1674,223 @@ planExecutor.bindBusHooks({
if (state) emit(state, { type: 'plan_changed', cid });
},
});
+
+// ── CLI agent turn ────────────────────────────────────────────────────────
+//
+// CLI-backed agents replace the LLM stream loop in runTurn. We pack the
+// agent's full visibility slice + the dispatched message + any user
+// attachments into a single prompt, spawn the configured CLI in the
+// user's workspace, and stream events into the same `process` rail the
+// renderer already understands. The final body is the CLI's last
+// "result" text — assigned into runTurn's `finalText` so plan_executor /
+// post-turn enqueue keep working unchanged.
+//
+// Stateless on purpose: every dispatch starts a fresh CLI run. Session
+// continuity (`--resume`) is a future optimisation; for now the slice is
+// the source of truth.
+
+const CLI_PROMPT_MAX_BYTES = 200 * 1024;
+
+async function _runCliAgentTurn(opts: {
+ uid: string;
+ cid: string;
+ actor: { id: string; kind: 'agent' | 'commander' | 'user' };
+ agent: import('../agents').Agent;
+ item: QueueItem;
+ slice: GroupMessage[];
+ workingDir: string;
+ signal: AbortSignal;
+ onProcess: (data: Record<string, unknown>) => void;
+}): Promise<{ text: string; error?: string; aborted?: boolean }> {
+ const runtime = opts.agent.runtime as Extract<NonNullable<import('../agents').AgentRuntime>, { kind: 'cli' }>;
+ // Look up any prior CLI session bound to this (cid, aid, cli). If
+ // present, we ask the CLI to resume it (claude: `--resume <id>`)
+ // and skip replaying the visibility slice in the prompt — the CLI
+ // already remembers the prior turns. First dispatch / fresh CLI
+ // swap → null → we replay the slice as before. Saves significant
+ // tokens and round-trip latency on long conversations.
+ const cliSessions = await import('../local_agents/sessions');
+ const resumeSessionId = await cliSessions.getSessionId(
+ opts.uid, opts.cid, opts.agent.agent_id, runtime.cli,
+ );
+ const promptText = await _buildCliPrompt(
+ opts.uid, opts.cid, opts.agent, opts.item, opts.slice, !!resumeSessionId,
+ );
+ const runner = await import('../local_agents/runner');
+
+ let accText = '';
+ let resultText = '';
+ let aborted = false;
+ let backendSessionId: string | undefined;
+
+ const result = await runner.run({
+ uid: opts.uid,
+ cid: opts.cid,
+ agentId: opts.agent.agent_id,
+ cli: runtime.cli as import('../local_agents/registry').LocalCliType,
+ model: runtime.model,
+ customArgs: runtime.custom_args,
+ resumeSessionId: resumeSessionId || undefined,
+ prompt: promptText,
+ cwd: opts.workingDir,
+ signal: opts.signal,
+ onEvent: e => {
+ // Translate each LocalEvent into the `process` event shape the
+ // renderer's group-chat listener expects so output streams live
+ // into the placeholder bubble (text-delta) and the process rail
+ // (tool-event, stderr, process-info). Without this, the renderer
+ // treats every event as an unrecognized shape and only the final
+ // text appears at turn-end.
+ switch (e.type) {
+ case 'text-delta':
+ if (typeof (e as any).text === 'string') {
+ accText += (e as any).text as string;
+ opts.onProcess({ type: 'delta', text: (e as any).text });
+ }
+ break;
+ case 'thinking':
+ if (typeof (e as any).text === 'string') {
+ opts.onProcess({ type: 'progress', text: (e as any).text });
+ }
+ break;
+ case 'tool-event':
+ case 'process-info':
+ case 'status':
+ case 'stderr-line':
+ opts.onProcess({ type: 'event', event: { stream: 'cli', data: e as unknown as Record<string, unknown> } });
+ break;
+ case 'done':
+ if (typeof (e as any).output === 'string') resultText = (e as any).output as string;
+ if ((e as any).status === 'cancelled') aborted = true;
+ if (typeof (e as any).sessionId === 'string') backendSessionId = (e as any).sessionId as string;
+ break;
+ default:
+ opts.onProcess({ type: 'event', event: { stream: 'cli', data: e as unknown as Record<string, unknown> } });
+ }
+ },
+ });
+
+ if (result.status === 'missing_cli') {
+ const msg = t('cli_agent.missing', { name: opts.agent.name || runtime.cli, cli: runtime.cli });
+ return { text: '', error: msg, aborted: false };
+ }
+ if (result.status === 'cancelled') {
+ return { text: resultText || accText, aborted: true };
+ }
+ if (result.status === 'failed' || result.status === 'timeout') {
+ const detail = result.error || (result.status === 'timeout' ? 'timeout' : 'failed');
+ return { text: resultText || accText, error: detail };
+ }
+ // Successful turn — persist the (possibly new) session id so the
+ // next dispatch can resume. Claude reports its session id every
+ // turn; if a `--resume` lands on an expired session, claude
+ // silently allocates a new one and reports that as `sessionId` in
+ // the system/init record. Either way we save what's freshest. The
+ // write is fire-and-forget — failures only affect the next turn's
+ // optimisation, not correctness.
+ if (backendSessionId) {
+ cliSessions
+ .setSessionId(opts.uid, opts.cid, opts.agent.agent_id, runtime.cli, backendSessionId)
+ .catch(() => { /* logged inside sessions.ts */ });
+ }
+ return { text: resultText || accText };
+}
+
+async function _buildCliPrompt(
+ uid: string,
+ cid: string,
+ agent: import('../agents').Agent,
+ item: QueueItem,
+ slice: GroupMessage[],
+ /** When true, the CLI is resuming a prior session and already has
+ * the conversation history in its own memory — we skip the slice
+ * block entirely and just send "head + new task". Drops massive
+ * redundancy on long convs. */
+ resuming: boolean,
+): Promise<string> {
+ // Build head + tail separately so truncation can throw away the
+ // middle of the conversation slice (oldest entries) while preserving
+ // the agent identity preamble + the actual task. The naive "trim
+ // from the head of the byte buffer" approach we used first dropped
+ // the role preamble — leaving the CLI without context about who it
+ // is or what it owns.
+ const headLines: string[] = [];
+ headLines.push(`You are "${agent.name || agent.agent_id}".`);
+ const desc = (agent.description_en || agent.description_zh || '').trim();
+ if (desc) headLines.push(desc);
+ headLines.push('');
+
+ // Attachments come from the dispatched message AND from prior slice
+ // messages — the agent might be expected to "look at the report you
+ // uploaded last turn", so we collect across the whole visibility
+ // slice. De-duplicate by absolute path; preserve oldest-first order.
+ const { chatAttachmentDir } = await import('../../paths');
+ const attDir = chatAttachmentDir(uid, cid);
+ const allAtts: string[] = [];
+ const seenAtts = new Set<string>();
+ const collect = (names: string[] | undefined) => {
+ if (!Array.isArray(names)) return;
+ for (const n of names) {
+ const abs = path.join(attDir, n);
+ if (!seenAtts.has(abs)) { seenAtts.add(abs); allAtts.push(abs); }
+ }
+ };
+ for (const m of slice) collect(m.attachments);
+ collect(item.attachments);
+ if (allAtts.length) {
+ headLines.push('## Attachments');
+ for (const abs of allAtts) headLines.push(`- ${abs}`);
+ headLines.push('');
+ }
+
+ const tailLines: string[] = [];
+ tailLines.push('## Your task');
+ tailLines.push(item.llmPayload);
+
+ const head = headLines.join('\n');
+ const tail = tailLines.join('\n');
+
+ // Resuming a CLI-side session: the CLI already remembers the prior
+ // turns. Skip the slice block entirely and let the model rely on
+ // its own session memory. Preamble + new task is enough.
+ if (resuming) {
+ return `${head}\n${tail}`;
+ }
+
+ // Conversation slice, oldest → newest. Empty-text rows skipped.
+ const sliceLines: string[] = [];
+ for (const m of slice) {
+ const to = (m.to || []).join(',') || '-';
+ const text = (m.text || '').replace(/\r/g, '').trim();
+ if (!text) continue;
+ sliceLines.push(`[${m.from} → ${to}] ${text}`);
+ }
+
+ // Reserve the head + tail bytes; what's left is the conversation
+ // budget. If even head+tail exceed the cap, fall back to a minimal
+ // prompt without history (better than truncating the task body).
+ const reserveBytes = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8') + 64; // 64 = headers + newlines slack
+ if (reserveBytes >= CLI_PROMPT_MAX_BYTES) {
+ log.warn(`cli prompt: head+tail exceed cap; sending minimal prompt cid=${cid} agent=${agent.agent_id}`);
+ return `${head}\n${tail}`;
+ }
+ const sliceBudget = CLI_PROMPT_MAX_BYTES - reserveBytes;
+ // Walk the slice from newest backward; keep messages while we have
+ // budget. If the oldest messages don't fit, drop them.
+ const kept: string[] = [];
+ let used = 0;
+ for (let i = sliceLines.length - 1; i >= 0; i--) {
+ const lineBytes = Buffer.byteLength(sliceLines[i] + '\n', 'utf8');
+ if (used + lineBytes > sliceBudget) break;
+ kept.unshift(sliceLines[i]);
+ used += lineBytes;
+ }
+ const truncated = kept.length < sliceLines.length;
+ if (truncated) {
+ log.warn(`cli prompt: trimmed ${sliceLines.length - kept.length}/${sliceLines.length} oldest slice rows cid=${cid} agent=${agent.agent_id}`);
+ }
+ const sliceBlock = kept.length
+ ? `## Conversation so far${truncated ? ' (truncated)' : ''}\n${kept.join('\n')}\n`
+ : '';
+ return `${head}\n${sliceBlock}\n${tail}`;
+}
diff --git a/src/main/features/local_agents/backends/_acp.ts b/src/main/features/local_agents/backends/_acp.ts
new file mode 100644
index 00000000..52537128
--- /dev/null
+++ b/src/main/features/local_agents/backends/_acp.ts
@@ -0,0 +1,257 @@
+/**
+ * Tiny ACP (Agent Communication Protocol) client used by ACP-speaking
+ * CLIs (Hermes today; Kimi / Kiro will plug in here too).
+ *
+ * ACP wire format: newline-delimited JSON-RPC 2.0 over stdio. We send
+ * `initialize`, `session/new`, `session/prompt` and listen for
+ * `session/update` notifications (text deltas + tool events) plus the
+ * id-matched `session/prompt` response (terminal). The protocol allows
+ * arbitrary other notifications which we surface as raw `tool-event`
+ * stream entries when their shape isn't recognized.
+ *
+ * Why we built our own minimal client rather than wrapping an SDK:
+ * ACP is a moving target across vendors and an SDK would tie us to
+ * one implementer's version pace. The handshake we need is small.
+ */
+
+import { createLogger } from '../../../logger.js';
+import {
+ type LocalBackend,
+ type BackendRunOptions,
+ StderrTail,
+ spawnCli,
+ bindAbort,
+ LineSplitter,
+} from './base.js';
+
+export interface AcpBackendDef {
+ /** Logger name. */
+ logName: string;
+ /** Subcommand args for the CLI's ACP mode. e.g. `['acp']`. */
+ argv: string[];
+ /** Identifier we report via `clientInfo.name`. Cosmetic. */
+ clientName: string;
+ /** Extra env vars to merge with `process.env` when spawning. */
+ extraEnv?: Record<string, string>;
+}
+
+export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
+ const log = createLogger(def.logName);
+ return {
+ async run(opts: BackendRunOptions): Promise<void> {
+ const env = def.extraEnv ? { ...process.env, ...def.extraEnv } : process.env;
+ const child = spawnCli(opts.binPath, def.argv, opts.cwd, env);
+ const detachAbort = bindAbort(child, opts.signal);
+ const tail = new StderrTail();
+ const startedAt = Date.now();
+
+ let exited = false;
+ let timedOut = false;
+ let sessionId: string | undefined;
+ let resultText = '';
+ let resultStatus: 'completed' | 'failed' | undefined;
+ let resultError: string | undefined;
+
+ const PROMPT_REQ_ID = 100;
+
+ opts.onEvent({
+ type: 'process-info',
+ pid: child.pid ?? -1,
+ cwd: opts.cwd,
+ cmd: opts.binPath,
+ args: def.argv,
+ });
+
+ 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();
+
+ const send = (msg: object) => {
+ try { child.stdin.write(JSON.stringify(msg) + '\n'); }
+ catch (err) { log.warn('acp stdin write failed', { error: (err as Error).message }); }
+ };
+
+ // Step 1: initialize
+ send({
+ jsonrpc: '2.0', id: 1, method: 'initialize',
+ params: {
+ protocolVersion: 1,
+ clientInfo: { name: def.clientName, version: '0.1.0' },
+ clientCapabilities: {},
+ },
+ });
+
+ const splitter = new LineSplitter();
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', chunk => {
+ splitter.push(chunk, line => {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ let env: any;
+ try { env = JSON.parse(trimmed); } catch { return; }
+ handleAcpMessage(env, {
+ onSessionNew: id => {
+ sessionId = id;
+ opts.onEvent({ type: 'status', status: 'session_ready', sessionId });
+ // Optional model selection. We swallow errors here:
+ // some CLIs reject unknown ids; we still try the prompt
+ // so the user gets something rather than a hard fail.
+ if (opts.model) {
+ send({ jsonrpc: '2.0', id: 3, method: 'session/set_model', params: { sessionId: id, modelId: opts.model } });
+ }
+ send({
+ jsonrpc: '2.0', id: PROMPT_REQ_ID, method: 'session/prompt',
+ params: {
+ sessionId: id,
+ prompt: [{ type: 'text', text: opts.prompt }],
+ },
+ });
+ },
+ onTextDelta: text => {
+ resultText += text;
+ opts.onEvent({ type: 'text-delta', 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;
+ },
+ onUnknown: raw => {
+ opts.onEvent({ type: 'tool-event', tool: 'acp', phase: 'use', input: raw, callId: '' });
+ },
+ });
+ });
+ });
+
+ // Initialize response handler — sends session/new only after
+ // the server acked initialize. We track this through the
+ // generic message handler by id matching.
+ child.on('message', () => { /* noop */ });
+
+ // Drive the session/new request once we see the initialize
+ // response (id=1). We piggy-back on the first object that sets
+ // sessionId being the session/new response, but to keep flow
+ // explicit we send session/new immediately after initialize
+ // ack — the ACP spec allows this since session/new doesn't need
+ // any post-initialize state.
+ const sendSessionNew = () => send({
+ jsonrpc: '2.0', id: 2, method: 'session/new',
+ params: { cwd: opts.cwd, mcpServers: [] },
+ });
+ // Fire-and-forget timeout to be sure session/new goes; some CLIs
+ // ack initialize without printing anything we'd recognize as the
+ // ack, and then sit idle.
+ const initTimer = setTimeout(sendSessionNew, 250);
+ if (typeof initTimer.unref === 'function') initTimer.unref();
+
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', chunk => {
+ 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);
+ clearTimeout(initTimer);
+ detachAbort();
+ opts.onEvent({
+ type: 'done',
+ status,
+ durationMs: Date.now() - startedAt,
+ sessionId,
+ ...extra,
+ });
+ resolve();
+ };
+ child.on('error', err => {
+ log.warn('acp 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: 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 });
+ const err = resultError || (code !== 0 ? `cli exited with code ${code}` : 'cli closed without prompt result');
+ finish('failed', { error: err, output: resultText, stderrTail: tail.toString() });
+ });
+ });
+ },
+ };
+}
+
+interface AcpHandlers {
+ onSessionNew(sessionId: string): void;
+ onTextDelta(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;
+ onUnknown(raw: any): void;
+}
+
+/**
+ * Pure dispatcher — given a parsed ACP message envelope, invokes the
+ * matching handler. Exposed for unit testing without spawning the CLI.
+ */
+export function handleAcpMessage(env: any, h: AcpHandlers): void {
+ if (!env || typeof env !== 'object') return;
+ // Notifications: { method: "session/update", params: { sessionId, update: {...} } }
+ 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);
+ return;
+ }
+ if (upd.kind === 'tool_call' && upd.tool) {
+ h.onToolUse({
+ name: String(upd.tool.name || 'tool'),
+ callId: String(upd.tool.id || upd.tool.callId || ''),
+ input: upd.tool.input ?? {},
+ });
+ return;
+ }
+ if (upd.kind === 'tool_call_update' && upd.tool) {
+ h.onToolResult({
+ name: String(upd.tool.name || 'tool'),
+ callId: String(upd.tool.id || upd.tool.callId || ''),
+ output: typeof upd.tool.output === 'string' ? upd.tool.output : JSON.stringify(upd.tool.output ?? ''),
+ });
+ return;
+ }
+ h.onUnknown({ method: env.method, params: env.params });
+ return;
+ }
+ // Responses: { id, result } or { id, error }.
+ if (env.id !== undefined) {
+ if (env.error) {
+ // Surface the error only when this is the prompt response — other
+ // request errors (e.g. set_model on an unknown id) are tolerable.
+ if (Number(env.id) === 100) {
+ h.onPromptResult({ ok: false, error: typeof env.error.message === 'string' ? env.error.message : 'acp error' });
+ }
+ return;
+ }
+ const idNum = Number(env.id);
+ if (idNum === 2 && env.result?.sessionId) {
+ h.onSessionNew(String(env.result.sessionId));
+ return;
+ }
+ if (idNum === 100) {
+ // Prompt completed. result.stopReason tells us why.
+ const ok = !env.result?.stopReason || env.result.stopReason === 'end_turn';
+ h.onPromptResult({ ok, error: ok ? undefined : String(env.result?.stopReason || 'unknown') });
+ return;
+ }
+ }
+}
diff --git a/src/main/features/local_agents/backends/_text.ts b/src/main/features/local_agents/backends/_text.ts
new file mode 100644
index 00000000..43e306fd
--- /dev/null
+++ b/src/main/features/local_agents/backends/_text.ts
@@ -0,0 +1,121 @@
+/**
+ * Generic "stream stdout as text" backend factory. Used by CLIs whose
+ * non-interactive mode prints the model's reply as plain text on
+ * stdout (codex / openclaw / opencode in v1). The factory turns
+ * per-CLI argv decisions into a reusable backend with the same
+ * cancellation, timeout, and `done` semantics as the structured
+ * backends.
+ *
+ * What this trades off vs structured stream-json parsing:
+ * - We don't get tool-use / tool-result events; the entire body
+ * arrives as a single text-delta stream.
+ * - We don't see thinking blocks separately.
+ * - Failures from inside the CLI's output are detected only by
+ * non-zero exit code; partial-success runs surface as completed
+ * with the body as-is.
+ * Step 7+ can swap any of these CLIs to a structured backend (e.g.
+ * `opencode run --print --json`) without touching the runner.
+ */
+
+import { createLogger } from '../../../logger.js';
+import {
+ type LocalBackend,
+ type BackendRunOptions,
+ StderrTail,
+ spawnCli,
+ bindAbort,
+} from './base.js';
+
+export interface TextBackendDef {
+ /** Logger scope name, e.g. `'local-agents:codex'`. */
+ logName: string;
+ /** Build the argv passed to the CLI. Receives the full opts so it
+ * can inject `--model`, append `customArgs`, etc. */
+ buildArgs(opts: BackendRunOptions): string[];
+ /** When true, the prompt is written to stdin (then stdin closes);
+ * when false the caller already encoded it into argv. */
+ promptOnStdin: boolean;
+}
+
+export function makeTextBackend(def: TextBackendDef): LocalBackend {
+ const log = createLogger(def.logName);
+ return {
+ async run(opts: BackendRunOptions): Promise<void> {
+ const args = def.buildArgs(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 outBody = '';
+
+ 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();
+
+ if (def.promptOnStdin) {
+ // Write & close so the CLI knows there's no further input.
+ child.stdin.end(opts.prompt);
+ } else {
+ child.stdin.end();
+ }
+
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => {
+ outBody += chunk;
+ opts.onEvent({ type: 'text-delta', text: chunk });
+ });
+
+ 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,
+ ...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: outBody });
+ if (timedOut) return finish('timeout', { error: `cli exceeded ${opts.timeoutMs}ms`, output: outBody, stderrTail: tail.toString() });
+ if (code === 0) return finish('completed', { output: outBody });
+ finish('failed', {
+ error: `cli exited with code ${code}`,
+ output: outBody,
+ stderrTail: tail.toString(),
+ });
+ });
+ });
+ },
+ };
+}
diff --git a/src/main/features/local_agents/backends/base.ts b/src/main/features/local_agents/backends/base.ts
new file mode 100644
index 00000000..8342cd6c
--- /dev/null
+++ b/src/main/features/local_agents/backends/base.ts
@@ -0,0 +1,164 @@
+/**
+ * Common contract + helpers for all local CLI backends.
+ *
+ * `LocalBackend.run` is the single entry point each backend implements:
+ * spawn the binary, parse its native output (stream-json or ACP),
+ * normalize each event to a `LocalEvent`, and emit them through
+ * `onEvent`. The runner sequences spawning, persistence, and the
+ * outbound bus message — backends only translate.
+ *
+ * Two helpers everyone needs:
+ * - `StderrTail` — bounded ring buffer for diagnostic context when a
+ * CLI crashes mid-run; the runner attaches the tail to a failed
+ * `done` event so users see the last 64 KB instead of "exit 3".
+ * - `spawnCli` — uniform spawn options (windowsHide + ignored stdin
+ * close on EPIPE during cancel).
+ */
+
+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
+
+/** All event types a backend can emit. The runner persists these to
+ * `events.jsonl` verbatim and forwards them to the renderer through
+ * the existing group-chat stream. */
+export type LocalEventType =
+ | 'process-info'
+ | 'text-delta'
+ | 'thinking'
+ | 'tool-event'
+ | 'stderr-line'
+ | 'status'
+ | 'done';
+
+export interface LocalEvent {
+ type: LocalEventType;
+ /** Free-form payload — exact keys vary per type. Documented inline at
+ * each emit site; a minimal index:
+ * process-info: { pid, cwd, cmd, args, sessionId? }
+ * text-delta: { text }
+ * thinking: { text }
+ * tool-event: { tool, callId?, phase: 'use'|'result', input?, output? }
+ * stderr-line: { line }
+ * status: { status }
+ * done: { status: 'completed'|'failed'|'cancelled'|'timeout'|
+ * 'missing_cli', error?, durationMs?, sessionId? }
+ */
+ [key: string]: unknown;
+}
+
+export interface BackendRunOptions {
+ binPath: string;
+ prompt: string;
+ cwd: string;
+ model?: string;
+ customArgs?: string[];
+ /** When set, ask the CLI to resume a prior session by id (claude:
+ * `--resume <id>`). Backends that don't support resume ignore the
+ * field; the runner's session-bookkeeping treats that as "no
+ * optimisation possible — fall back to slice replay". */
+ resumeSessionId?: string;
+ /** Cancellation; backend wires this to SIGTERM (10s) → SIGKILL. */
+ signal: AbortSignal;
+ onEvent: (e: LocalEvent) => void;
+ /** Wall-clock cap. Backends should arm a timer and emit
+ * `done({status:'timeout'})` when it fires before the CLI exits. */
+ timeoutMs: number;
+}
+
+export interface LocalBackend {
+ run(opts: BackendRunOptions): Promise<void>;
+}
+
+/** Bounded stderr collector. ringBytes overrides the default 64 KB cap. */
+export class StderrTail {
+ private chunks: string[] = [];
+ private size = 0;
+ constructor(private readonly cap = 64 * 1024) {}
+
+ push(chunk: string): void {
+ if (!chunk) return;
+ this.chunks.push(chunk);
+ this.size += chunk.length;
+ while (this.size > this.cap && this.chunks.length > 1) {
+ this.size -= this.chunks[0].length;
+ this.chunks.shift();
+ }
+ // Single chunk over cap → keep its tail.
+ if (this.chunks.length === 1 && this.size > this.cap) {
+ const only = this.chunks[0];
+ this.chunks[0] = only.slice(only.length - this.cap);
+ this.size = this.cap;
+ }
+ }
+
+ toString(): string {
+ return this.chunks.join('');
+ }
+}
+
+/** Standard spawn options. Returns a child with stdio: pipe/pipe/pipe. */
+export function spawnCli(
+ binPath: string,
+ args: string[],
+ cwd: string,
+ env?: NodeJS.ProcessEnv,
+): ChildProcessWithoutNullStreams {
+ const child = spawn(binPath, args, {
+ cwd,
+ env: env ?? process.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+ // Swallow EPIPE during cancel; the OS will close the pipe when the
+ // child dies before we finish writing the prompt.
+ child.stdin.on('error', () => { /* noop */ });
+ return child;
+}
+
+/**
+ * Iterate over newline-delimited chunks. Buffers partial lines across
+ * `data` events. Each yielded line excludes the terminating `\n` /
+ * `\r\n`. Used by stream-json backends; ACP also uses NDJSON so the
+ * helper is shared.
+ */
+export class LineSplitter {
+ private buf = '';
+ /** Push a chunk; emit each complete line via `onLine`. */
+ push(chunk: string, onLine: (line: string) => void): void {
+ this.buf += chunk;
+ let idx: number;
+ while ((idx = this.buf.indexOf('\n')) >= 0) {
+ let line = this.buf.slice(0, idx);
+ this.buf = this.buf.slice(idx + 1);
+ if (line.endsWith('\r')) line = line.slice(0, -1);
+ onLine(line);
+ }
+ }
+ /** Flush any trailing line without a newline (e.g. CLI exited early). */
+ flush(onLine: (line: string) => void): void {
+ if (this.buf.length > 0) {
+ onLine(this.buf);
+ this.buf = '';
+ }
+ }
+}
+
+/**
+ * Wire abort + grace-kill behavior. Returns a cleanup function the
+ * caller must invoke after the child exits to detach listeners.
+ */
+export function bindAbort(child: ChildProcessWithoutNullStreams, signal: AbortSignal, graceMs = 10_000): () => void {
+ let killTimer: NodeJS.Timeout | null = null;
+ const onAbort = () => {
+ try { child.kill('SIGTERM'); } catch { /* already gone */ }
+ killTimer = setTimeout(() => {
+ try { child.kill('SIGKILL'); } catch { /* already gone */ }
+ }, graceMs);
+ if (typeof killTimer.unref === 'function') killTimer.unref();
+ };
+ if (signal.aborted) onAbort();
+ else signal.addEventListener('abort', onAbort, { once: true });
+ return () => {
+ signal.removeEventListener('abort', onAbort);
+ if (killTimer) { clearTimeout(killTimer); killTimer = null; }
+ };
+}
diff --git a/src/main/features/local_agents/backends/claude.ts b/src/main/features/local_agents/backends/claude.ts
new file mode 100644
index 00000000..5d7e92a9
--- /dev/null
+++ b/src/main/features/local_agents/backends/claude.ts
@@ -0,0 +1,302 @@
+/**
+ * Claude Code backend. Runs `claude -p --output-format stream-json
+ * --input-format stream-json --verbose` and feeds a single user
+ * message on stdin, then closes stdin. Output is one JSON object per
+ * line; we recognize:
+ *
+ * {"type":"system","subtype":"init", session_id, cwd, ...}
+ * {"type":"assistant","message":{ "content":[{type:"text", text}, {type:"tool_use",...}, {type:"thinking",...}] }}
+ * {"type":"user","message":{ "content":[{type:"tool_result", tool_use_id, content}] }}
+ * {"type":"result","subtype":"success"|"error_*", result, total_cost_usd, duration_ms, ...}
+ *
+ * Non-conforming lines (banner text, debug noise) are silently dropped
+ * so a noisy CLI version doesn't bork a run.
+ */
+
+import { createLogger } from '../../../logger.js';
+import {
+ type LocalBackend,
+ type BackendRunOptions,
+ type LocalEvent,
+ StderrTail,
+ spawnCli,
+ bindAbort,
+ LineSplitter,
+} from './base.js';
+
+const log = createLogger('local-agents:claude');
+
+export const claudeBackend: LocalBackend = {
+ async run(opts: BackendRunOptions): Promise<void> {
+ const args = buildClaudeArgs(opts);
+ const child = spawnCli(opts.binPath, args, opts.cwd);
+ const detachAbort = bindAbort(child, opts.signal);
+ const tail = new StderrTail();
+ const startedAt = Date.now();
+
+ let sessionId: string | undefined;
+ let exited = false;
+ let timedOut = false;
+ let resultText = '';
+ let resultStatus: 'completed' | 'failed' | undefined;
+ let resultError: string | undefined;
+ // Tracks whether we've seen a real stream_event with text content
+ // — gates whether we can safely skip the assistant block's text
+ // (which would otherwise duplicate the streamed body). Old claude
+ // versions that ignore `--include-partial-messages` never emit
+ // stream_events; in that case we fall back to emitting from the
+ // assistant block so the user still sees the final text.
+ const partialState = { sawTextStreamEvent: false };
+
+ 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 { /* already gone */ }
+ setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* */ } }, 10_000).unref();
+ }, opts.timeoutMs);
+ if (typeof timer.unref === 'function') timer.unref();
+
+ // Build and send the single user message, then close stdin so
+ // claude knows there's no follow-up turn coming.
+ const inputLine = JSON.stringify({
+ type: 'user',
+ message: {
+ role: 'user',
+ content: [{ type: 'text', text: opts.prompt }],
+ },
+ }) + '\n';
+ child.stdin.end(inputLine);
+
+ // stdout: line-buffered JSON parsing.
+ 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 {
+ // Pre-stream banner / debug noise — surface as text-delta
+ // when nothing else has arrived yet so users still see why
+ // the CLI is unhappy. After we have a session id, drop.
+ if (!sessionId) opts.onEvent({ type: 'text-delta', text: trimmed + '\n' });
+ return;
+ }
+ const ev = mapClaudeEvent(obj, sessionId, partialState);
+ if (ev?.captureSession && obj.session_id) sessionId = String(obj.session_id);
+ if (ev?.event) opts.onEvent(ev.event);
+ if (ev?.terminal) {
+ resultStatus = ev.terminal.status;
+ resultText = ev.terminal.text;
+ resultError = ev.terminal.error;
+ }
+ });
+ });
+ child.stdout.on('end', () => splitter.flush(line => {
+ const trimmed = line.trim();
+ if (trimmed) opts.onEvent({ type: 'text-delta', text: trimmed });
+ }));
+
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ tail.push(chunk);
+ // Emit one event per stderr line so live UI can show progress.
+ 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: Partial<LocalEvent> = {}) => {
+ if (exited) return;
+ exited = true;
+ clearTimeout(timer);
+ detachAbort();
+ const durationMs = Date.now() - startedAt;
+ opts.onEvent({
+ type: 'done',
+ status,
+ durationMs,
+ sessionId,
+ ...extra,
+ });
+ resolve();
+ };
+
+ child.on('error', err => {
+ log.warn('claude 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: `claude exceeded ${opts.timeoutMs}ms`, stderrTail: tail.toString() });
+ if (code === 0 && resultStatus === 'completed') return finish('completed', { output: resultText });
+ // Non-zero exit OR result subtype indicated error — surface tail.
+ const err = resultError
+ || (code !== 0 ? `claude exited with code ${code}` : 'claude reported error in result');
+ finish('failed', { error: err, output: resultText, stderrTail: tail.toString() });
+ });
+ });
+ },
+};
+
+/** Args mirroring the multica skeleton, distilled to what we actually
+ * use in v1: stream-json in/out, `--print` (non-interactive),
+ * bypass permissions for daemon-style execution, optional model. */
+function buildClaudeArgs(opts: BackendRunOptions): string[] {
+ // `--include-partial-messages` is the flag that turns claude code's
+ // stream-json output from "one assistant message per completed turn"
+ // into "many partial chunks streamed as the model generates". Without
+ // it the user sees nothing for tens of seconds and then everything
+ // appears at once — same UX as a non-streaming request. Older claude
+ // versions silently ignore the flag rather than erroring on it.
+ const args = [
+ '-p',
+ '--output-format', 'stream-json',
+ '--input-format', 'stream-json',
+ '--include-partial-messages',
+ '--verbose',
+ '--permission-mode', 'bypassPermissions',
+ ];
+ if (opts.model) args.push('--model', opts.model);
+ if (opts.resumeSessionId) args.push('--resume', opts.resumeSessionId);
+ if (opts.customArgs && opts.customArgs.length) args.push(...opts.customArgs);
+ return args;
+}
+
+/** Translate one parsed claude stream-json record into our event model.
+ * Returns `undefined` when the record is recognized but produces no
+ * user-visible event (e.g. system/init that only seeds the session id).
+ *
+ * Two parallel input shapes:
+ * - `type:'stream_event'` — partial-message tokens emitted only when
+ * `--include-partial-messages` is on. These are what give us real
+ * token-by-token streaming; we map their deltas to text-delta /
+ * thinking events.
+ * - `type:'assistant'` — the full message that aggregates everything
+ * streamed above. Emitted at end-of-turn. We **skip text/thinking
+ * content here** (the partials already covered it) but DO surface
+ * tool_use blocks because the partial input_json deltas alone
+ * aren't enough to render a useful tool-event.
+ */
+export function mapClaudeEvent(
+ obj: any,
+ _sessionIdSoFar: string | undefined,
+ partialState: { sawTextStreamEvent: boolean } = { sawTextStreamEvent: false },
+):
+ | undefined
+ | { event?: LocalEvent; captureSession?: boolean; terminal?: { status: 'completed' | 'failed'; text: string; error?: string } } {
+ if (!obj || typeof obj !== 'object') return undefined;
+ const type = obj.type;
+ if (type === 'system' && obj.subtype === 'init') {
+ return { captureSession: true };
+ }
+ if (type === 'stream_event') {
+ const inner = obj.event;
+ if (!inner || typeof inner !== 'object') return undefined;
+ const innerType = inner.type;
+ if (innerType === 'content_block_delta') {
+ const d = inner.delta;
+ if (d?.type === 'text_delta' && typeof d.text === 'string' && d.text.length) {
+ partialState.sawTextStreamEvent = true;
+ return { event: { type: 'text-delta', text: d.text } };
+ }
+ if (d?.type === 'thinking_delta' && typeof d.thinking === 'string' && d.thinking.length) {
+ return { event: { type: 'thinking', text: d.thinking } };
+ }
+ // input_json_delta carries tool input streamed character-by-
+ // character. Useless to render incrementally; we let the
+ // assistant block fold it together when the turn finishes.
+ return undefined;
+ }
+ if (innerType === 'content_block_start') {
+ const cb = inner.content_block;
+ if (cb?.type === 'tool_use') {
+ return {
+ event: {
+ type: 'tool-event',
+ tool: String(cb.name || 'unknown'),
+ callId: String(cb.id || ''),
+ phase: 'use',
+ input: cb.input ?? {},
+ },
+ };
+ }
+ return undefined;
+ }
+ return undefined;
+ }
+ if (type === 'assistant') {
+ const content = Array.isArray(obj?.message?.content) ? obj.message.content : [];
+ for (const part of content) {
+ if (part?.type === 'text' && typeof part.text === 'string') {
+ // Already streamed via stream_event partials → skip to avoid
+ // duplicating the body. If the CLI didn't honor the partial
+ // flag (older versions), no stream_event with text fired and
+ // we fall back to emitting it here so the user still sees the
+ // reply.
+ if (partialState.sawTextStreamEvent) return undefined;
+ return { event: { type: 'text-delta', text: part.text } };
+ }
+ if (part?.type === 'thinking') {
+ if (partialState.sawTextStreamEvent) return undefined;
+ if (typeof part.thinking === 'string') {
+ return { event: { type: 'thinking', text: part.thinking } };
+ }
+ return undefined;
+ }
+ if (part?.type === 'tool_use') {
+ return {
+ event: {
+ type: 'tool-event',
+ tool: String(part.name || 'unknown'),
+ callId: String(part.id || ''),
+ phase: 'use',
+ input: part.input ?? {},
+ },
+ };
+ }
+ }
+ return undefined;
+ }
+ if (type === 'user') {
+ const content = Array.isArray(obj?.message?.content) ? obj.message.content : [];
+ for (const part of content) {
+ if (part?.type === 'tool_result') {
+ const out = typeof part.content === 'string'
+ ? part.content
+ : Array.isArray(part.content)
+ ? part.content.filter((c: any) => c?.type === 'text').map((c: any) => c.text).join('\n')
+ : '';
+ return {
+ event: {
+ type: 'tool-event',
+ tool: 'tool_result',
+ callId: String(part.tool_use_id || ''),
+ phase: 'result',
+ output: out,
+ },
+ };
+ }
+ }
+ return undefined;
+ }
+ if (type === 'result') {
+ const ok = obj.subtype === 'success';
+ const text = typeof obj.result === 'string' ? obj.result : '';
+ const error = !ok && typeof obj.error === 'string' ? obj.error : undefined;
+ return {
+ event: { type: 'status', status: ok ? 'result' : 'error' },
+ terminal: { status: ok ? 'completed' : 'failed', text, error },
+ };
+ }
+ return undefined;
+}
diff --git a/src/main/features/local_agents/backends/codex.ts b/src/main/features/local_agents/backends/codex.ts
new file mode 100644
index 00000000..03bd221a
--- /dev/null
+++ b/src/main/features/local_agents/backends/codex.ts
@@ -0,0 +1,26 @@
+/**
+ * Codex CLI backend.
+ *
+ * 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.
+ */
+
+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;
+ },
+ promptOnStdin: true,
+});
diff --git a/src/main/features/local_agents/backends/hermes.ts b/src/main/features/local_agents/backends/hermes.ts
new file mode 100644
index 00000000..21a26889
--- /dev/null
+++ b/src/main/features/local_agents/backends/hermes.ts
@@ -0,0 +1,21 @@
+/**
+ * Hermes backend — speaks ACP via `hermes acp`. The minimal handshake
+ * + session/update parsing lives in `_acp.ts`; this file just supplies
+ * the CLI invocation + the env nudges Hermes needs in headless use
+ * (HERMES_YOLO_MODE=1 suppresses interactive permission prompts).
+ */
+
+import { makeAcpBackend } from './_acp.js';
+
+export const hermesBackend = makeAcpBackend({
+ logName: 'local-agents:hermes',
+ argv: ['acp'],
+ clientName: 'orkas',
+ extraEnv: {
+ // Without this Hermes drops to interactive permission prompts on
+ // any tool call and the run just hangs waiting on stdin we never
+ // send. We can flip back to user-confirmation later when we wire
+ // permission prompts through the chat UI.
+ HERMES_YOLO_MODE: '1',
+ },
+});
diff --git a/src/main/features/local_agents/backends/openclaw.ts b/src/main/features/local_agents/backends/openclaw.ts
new file mode 100644
index 00000000..0ff7aa3d
--- /dev/null
+++ b/src/main/features/local_agents/backends/openclaw.ts
@@ -0,0 +1,27 @@
+/**
+ * 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.
+ *
+ * v1 takes the prompt on stdin and captures stdout as plain text.
+ */
+
+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;
+ },
+ promptOnStdin: true,
+});
diff --git a/src/main/features/local_agents/backends/opencode.ts b/src/main/features/local_agents/backends/opencode.ts
new file mode 100644
index 00000000..59b0144e
--- /dev/null
+++ b/src/main/features/local_agents/backends/opencode.ts
@@ -0,0 +1,22 @@
+/**
+ * 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).
+ */
+
+import { makeTextBackend } from './_text.js';
+
+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;
+ },
+ promptOnStdin: true,
+});
diff --git a/src/main/features/local_agents/models.ts b/src/main/features/local_agents/models.ts
new file mode 100644
index 00000000..9973980a
--- /dev/null
+++ b/src/main/features/local_agents/models.ts
@@ -0,0 +1,63 @@
+/**
+ * Static model catalogs for local CLI agents.
+ *
+ * Two CLIs ship with a curated list users can pick from (claude, codex);
+ * the others (openclaw, opencode, hermes) return [] which the UI treats
+ * as "free-text entry" — these CLIs either route by user account
+ * (openclaw bonds models to pre-registered agents), enumerate via their
+ * own `models` subcommand we don't shell yet (opencode), or advertise
+ * via ACP at runtime (hermes). Dynamic discovery is a future option;
+ * for v1 we keep the surface tiny and let users type the id.
+ *
+ * `default: true` is a UI hint only — at execute time, an empty
+ * `agent.runtime.model` field tells the backend to pass nothing and let
+ * the CLI resolve its own default (which tracks the user's account /
+ * environment more accurately than any list we bake here).
+ */
+
+import type { LocalCliType } from './registry.js';
+
+export type LocalModel = {
+ id: string;
+ label: string;
+ /** Optional display hint; UI badges this entry as the recommended pick. */
+ default?: boolean;
+};
+
+const CATALOG: Record<LocalCliType, LocalModel[]> = {
+ claude: [
+ { id: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6', default: true },
+ { id: 'claude-opus-4-7', label: 'Claude Opus 4.7' },
+ { id: 'claude-haiku-4-5', label: 'Claude Haiku 4.5' },
+ { id: 'claude-opus-4-6', label: 'Claude Opus 4.6' },
+ { id: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5' },
+ ],
+ codex: [
+ { id: 'gpt-5.4', label: 'GPT-5.4', default: true },
+ { id: 'gpt-5.4-mini', label: 'GPT-5.4 mini' },
+ { id: 'gpt-5.3-codex', label: 'GPT-5.3 Codex' },
+ { id: 'gpt-5', label: 'GPT-5' },
+ { id: 'o3', label: 'o3' },
+ { id: 'o3-mini', label: 'o3-mini' },
+ ],
+ // Free-text entry; the UI renders an <input> instead of a <select>.
+ openclaw: [],
+ opencode: [],
+ hermes: [],
+};
+
+/** Return the static model list for a CLI type. Empty = free-text entry. */
+export function listModels(cli: LocalCliType): LocalModel[] {
+ return CATALOG[cli] ?? [];
+}
+
+/**
+ * The default model id for a CLI, or null if either the catalog is
+ * empty or no entry is flagged `default: true`. Callers that need a
+ * value to pre-fill the form use this; runner code never relies on it
+ * (empty `agent.runtime.model` is a valid intent — "let the CLI pick").
+ */
+export function defaultModel(cli: LocalCliType): string | null {
+ const list = listModels(cli);
+ return list.find(m => m.default)?.id ?? null;
+}
diff --git a/src/main/features/local_agents/persist.ts b/src/main/features/local_agents/persist.ts
new file mode 100644
index 00000000..a4d6f351
--- /dev/null
+++ b/src/main/features/local_agents/persist.ts
@@ -0,0 +1,139 @@
+/**
+ * Persist a single CLI agent dispatch to disk.
+ *
+ * Layout per run:
+ * <uid>/local/file_cache/local-agent-runs/<runId>/
+ * ├── meta.json ← run summary (status / timings / agent + cli ids)
+ * ├── prompt.txt ← exact prompt fed to the CLI's stdin
+ * ├── events.jsonl ← every LocalEvent as a JSON line
+ * └── output.txt ← accumulated text-delta + final result body
+ *
+ * The runner calls `start` once before launching the backend, `append`
+ * for each event the backend emits, and `finalize` after the backend's
+ * terminal `done` event lands. Failures during persistence log + carry
+ * on — losing a few diagnostic lines is better than failing the user's
+ * task because file_cache is full.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+import * as crypto from 'node:crypto';
+
+import { localAgentRunDir, userLocalAgentRunsDir } from '../../paths.js';
+import { createLogger } from '../../logger.js';
+import type { LocalEvent } from './backends/base.js';
+
+const log = createLogger('local-agents:persist');
+
+export interface RunMeta {
+ runId: string;
+ agentId: string;
+ cid: string;
+ cli: string;
+ model?: string;
+ startedAt: string;
+ endedAt?: string;
+ status?: 'completed' | 'failed' | 'cancelled' | 'timeout' | 'missing_cli';
+ durationMs?: number;
+ cliPath?: string;
+ sessionId?: string;
+ /** Final text body — same content as output.txt; duplicated here so a
+ * single read of meta.json suffices for run lists / debug pages. */
+ output?: string;
+ error?: string;
+}
+
+export interface RunHandle {
+ runId: string;
+ dir: string;
+ /** Persisted prompt path, surfaced for tests / future "open run dir". */
+ promptPath: string;
+ eventsPath: string;
+ outputPath: string;
+ metaPath: string;
+}
+
+/** 12-hex-char run id; collisions in practice are nil at the volumes
+ * we expect (a few dispatches per minute) but we still re-roll on hit. */
+function genRunId(): string {
+ return crypto.randomBytes(6).toString('hex');
+}
+
+export async function start(uid: string, init: Omit<RunMeta, 'runId' | 'startedAt'> & { prompt: string }): Promise<RunHandle> {
+ await fsp.mkdir(userLocalAgentRunsDir(uid), { recursive: true });
+ let runId = genRunId();
+ while (fs.existsSync(localAgentRunDir(uid, runId))) runId = genRunId();
+ const dir = localAgentRunDir(uid, runId);
+ await fsp.mkdir(dir, { recursive: true });
+ const meta: RunMeta = {
+ runId,
+ agentId: init.agentId,
+ cid: init.cid,
+ cli: init.cli,
+ model: init.model,
+ cliPath: init.cliPath,
+ startedAt: new Date().toISOString(),
+ };
+ const handle: RunHandle = {
+ runId,
+ dir,
+ promptPath: path.join(dir, 'prompt.txt'),
+ eventsPath: path.join(dir, 'events.jsonl'),
+ outputPath: path.join(dir, 'output.txt'),
+ metaPath: path.join(dir, 'meta.json'),
+ };
+ try {
+ await fsp.writeFile(handle.promptPath, init.prompt, 'utf8');
+ await fsp.writeFile(handle.metaPath, JSON.stringify(meta, null, 2), 'utf8');
+ await fsp.writeFile(handle.eventsPath, '', 'utf8');
+ await fsp.writeFile(handle.outputPath, '', 'utf8');
+ } catch (err) {
+ log.warn('persist start failed', { uid, runId, error: (err as Error).message });
+ }
+ return handle;
+}
+
+/** Append one event to events.jsonl. Synchronous fs is intentional —
+ * we want the line on disk before the next event arrives, and these
+ * files live on the user's local SSD. */
+export function append(handle: RunHandle, event: LocalEvent): void {
+ try {
+ fs.appendFileSync(handle.eventsPath, JSON.stringify(event) + '\n', 'utf8');
+ } catch (err) {
+ log.warn('persist append failed', { runId: handle.runId, error: (err as Error).message });
+ }
+}
+
+/** Append a chunk of body text to output.txt. */
+export function appendOutput(handle: RunHandle, text: string): void {
+ if (!text) return;
+ try {
+ fs.appendFileSync(handle.outputPath, text, 'utf8');
+ } catch (err) {
+ log.warn('persist appendOutput failed', { runId: handle.runId, error: (err as Error).message });
+ }
+}
+
+/** Update meta.json with terminal status + write a final consolidated
+ * output if the runner has it (some runs only know it from the
+ * `done` event's `output` field, others streamed it incrementally). */
+export async function finalize(handle: RunHandle, patch: Partial<RunMeta>): Promise<void> {
+ try {
+ const raw = await fsp.readFile(handle.metaPath, 'utf8');
+ const meta = JSON.parse(raw) as RunMeta;
+ Object.assign(meta, patch, {
+ endedAt: new Date().toISOString(),
+ });
+ await fsp.writeFile(handle.metaPath, JSON.stringify(meta, null, 2), 'utf8');
+ if (typeof patch.output === 'string' && patch.output.length > 0) {
+ // Replace any partially-streamed output if the backend handed us
+ // a complete body in `done`. Otherwise leave the streamed file
+ // alone — appendOutput already accumulated it.
+ const existing = await fsp.readFile(handle.outputPath, 'utf8').catch(() => '');
+ if (!existing) await fsp.writeFile(handle.outputPath, patch.output, 'utf8');
+ }
+ } catch (err) {
+ log.warn('persist finalize failed', { runId: handle.runId, error: (err as Error).message });
+ }
+}
diff --git a/src/main/features/local_agents/registry.ts b/src/main/features/local_agents/registry.ts
new file mode 100644
index 00000000..be81b8f8
--- /dev/null
+++ b/src/main/features/local_agents/registry.ts
@@ -0,0 +1,125 @@
+/**
+ * Registry of local CLI coding agents Orkas can spawn.
+ *
+ * Discovery rules per CLI:
+ * 1. ORKAS_<TYPE>_PATH env var, if set → use as-is (still validated).
+ * 2. Else `whichBin(defaultBin)` to scan PATH.
+ * 3. If found, run `<path> --version` and `checkMinVersion`.
+ *
+ * Results are cached for 60s to keep the create/edit panel snappy
+ * across re-renders. Pass `{ force: true }` to bypass the cache (used
+ * by execute-time pre-flight check in runner.ts so a recently-deleted
+ * binary doesn't slip through).
+ *
+ * `LocalCliType` is the canonical key everywhere (spec.runtime.cli,
+ * IPC payloads, persist meta.json) — keep it in sync with backends/.
+ */
+
+import { createLogger } from '../../logger.js';
+import { whichBin } from './which.js';
+import { checkMinVersion, detectVersion } from './version.js';
+
+const log = createLogger('local-agents');
+
+/** Canonical CLI type names. New backends add an entry here + in BIN_NAMES + ENV_KEYS. */
+export const LOCAL_CLI_TYPES = ['claude', 'codex', 'openclaw', 'opencode', 'hermes'] as const;
+
+export type LocalCliType = (typeof LOCAL_CLI_TYPES)[number];
+
+/** Default executable name on PATH for each CLI. */
+const BIN_NAMES: Record<LocalCliType, string> = {
+ claude: 'claude',
+ codex: 'codex',
+ openclaw: 'openclaw',
+ opencode: 'opencode',
+ hermes: 'hermes',
+};
+
+/** Env var to override default binary path per CLI. */
+const ENV_KEYS: Record<LocalCliType, string> = {
+ claude: 'ORKAS_CLAUDE_PATH',
+ codex: 'ORKAS_CODEX_PATH',
+ openclaw: 'ORKAS_OPENCLAW_PATH',
+ opencode: 'ORKAS_OPENCODE_PATH',
+ hermes: 'ORKAS_HERMES_PATH',
+};
+
+/** Detection result for a single CLI. */
+export type LocalCliEntry = {
+ type: LocalCliType;
+ /** Absolute path to the binary, or null when unavailable. */
+ path: string | null;
+ /** Parsed `MAJOR.MINOR.PATCH` from `--version`, or null. */
+ version: string | null;
+ /** True only when path resolved AND version check passed. */
+ available: boolean;
+ /**
+ * Populated when `available === false` to explain why:
+ * "not_found" (no PATH match), "version_too_old" (below MIN_VERSIONS),
+ * or "version_unknown" (binary exists but `--version` returned nothing).
+ */
+ error?: 'not_found' | 'version_too_old' | 'version_unknown';
+ /** Human-readable detail when error is set; safe to show in UI. */
+ errorDetail?: string;
+};
+
+const CACHE_TTL_MS = 60_000;
+let cache: { at: number; entries: LocalCliEntry[] } | null = null;
+
+/**
+ * Detect all known CLIs (parallel). Returns one entry per type, including
+ * unavailable ones — UI filters to `available === true` for the picker.
+ */
+export async function detectAll(opts: { force?: boolean } = {}): Promise<LocalCliEntry[]> {
+ if (!opts.force && cache && Date.now() - cache.at < CACHE_TTL_MS) {
+ return cache.entries;
+ }
+ const entries = await Promise.all(LOCAL_CLI_TYPES.map(t => detectOne(t)));
+ cache = { at: Date.now(), entries };
+ log.info('detected local CLIs', {
+ available: entries.filter(e => e.available).map(e => e.type),
+ missing: entries.filter(e => !e.available).map(e => e.type),
+ });
+ return entries;
+}
+
+/**
+ * Detect a single CLI. Skips the cache by design — callers that need
+ * cache should go through detectAll.
+ */
+export async function detectOne(type: LocalCliType): Promise<LocalCliEntry> {
+ const envPath = process.env[ENV_KEYS[type]]?.trim();
+ const candidate = envPath && envPath.length > 0 ? envPath : BIN_NAMES[type];
+ const resolved = await whichBin(candidate);
+ if (!resolved) {
+ return {
+ type, path: null, version: null, available: false,
+ error: 'not_found',
+ errorDetail: envPath
+ ? `${ENV_KEYS[type]}=${envPath} not found on PATH or filesystem`
+ : `${BIN_NAMES[type]} not found on PATH`,
+ };
+ }
+ const version = await detectVersion(resolved);
+ if (!version) {
+ return {
+ type, path: resolved, version: null, available: false,
+ error: 'version_unknown',
+ errorDetail: `\`${resolved} --version\` produced no parsable output`,
+ };
+ }
+ const minErr = checkMinVersion(type, version);
+ if (minErr) {
+ return {
+ type, path: resolved, version, available: false,
+ error: 'version_too_old',
+ errorDetail: minErr,
+ };
+ }
+ return { type, path: resolved, version, available: true };
+}
+
+/** Clear the cache; mainly for tests and the IPC `force: true` path. */
+export function invalidateCache(): void {
+ cache = null;
+}
diff --git a/src/main/features/local_agents/runner.ts b/src/main/features/local_agents/runner.ts
new file mode 100644
index 00000000..68ee69ea
--- /dev/null
+++ b/src/main/features/local_agents/runner.ts
@@ -0,0 +1,179 @@
+/**
+ * Run a local CLI agent for one dispatch.
+ *
+ * Invariants:
+ * - Single spawn entry point for the whole project. `bus.ts` must
+ * route here; `features/*` must not call `child_process.spawn`
+ * directly for CLI agents.
+ * - Pre-flight `detectOne` re-probes the binary even if the cached
+ * entry says available — the user might have uninstalled it
+ * mid-conversation. A miss yields `done({status: 'missing_cli'})`
+ * before any persistence happens.
+ * - Persistence wraps every backend event so `events.jsonl` is the
+ * authoritative replay log. Output text is also appended to
+ * output.txt as it streams; the final body lands in meta.json.
+ * - The runner never throws on the happy path; failures are reported
+ * through the same `onEvent({type:'done', status:'failed', ...})`
+ * channel so the caller has a single completion contract.
+ */
+
+import { createLogger } from '../../logger.js';
+import { detectOne, type LocalCliEntry, type LocalCliType } from './registry.js';
+import { claudeBackend } from './backends/claude.js';
+import { codexBackend } from './backends/codex.js';
+import { openclawBackend } from './backends/openclaw.js';
+import { opencodeBackend } from './backends/opencode.js';
+import { hermesBackend } from './backends/hermes.js';
+import { type LocalBackend, type LocalEvent } from './backends/base.js';
+import * as persist from './persist.js';
+
+const log = createLogger('local-agents:runner');
+
+/** Wall-clock cap for a single CLI dispatch. Override at deploy /
+ * debugging time via env. 20 min covers nontrivial coding tasks
+ * while bounding zombie processes if the CLI hangs. */
+const DEFAULT_TIMEOUT_MS = 20 * 60 * 1000;
+
+function resolveTimeoutMs(): number {
+ const raw = process.env.ORKAS_LOCAL_AGENT_TIMEOUT_MS;
+ if (!raw) return DEFAULT_TIMEOUT_MS;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n < 1000) return DEFAULT_TIMEOUT_MS;
+ return n;
+}
+
+const BACKENDS: Partial<Record<LocalCliType, LocalBackend>> = {
+ claude: claudeBackend,
+ codex: codexBackend,
+ openclaw: openclawBackend,
+ opencode: opencodeBackend,
+ hermes: hermesBackend,
+};
+
+export interface RunCliAgentOpts {
+ uid: string;
+ cid: string;
+ agentId: string;
+ cli: LocalCliType;
+ model?: string;
+ customArgs?: string[];
+ /** If set, the dispatch resumes a CLI-side session (claude
+ * `--resume <id>`) and the caller has already trimmed the prompt
+ * to "just the new turn" content — the CLI provides the prior
+ * context out of its own memory. The backend ignores the field
+ * when it doesn't support resume. */
+ resumeSessionId?: string;
+ prompt: string;
+ cwd: string;
+ signal: AbortSignal;
+ /** Forwarded each backend event verbatim, after persistence. */
+ onEvent: (e: LocalEvent) => void;
+}
+
+export interface RunCliAgentResult {
+ runId: string;
+ status: 'completed' | 'failed' | 'cancelled' | 'timeout' | 'missing_cli';
+ output?: string;
+ error?: string;
+}
+
+export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
+ const backend = BACKENDS[opts.cli];
+ if (!backend) {
+ log.warn('no backend registered for cli', { cli: opts.cli });
+ const err = `local CLI backend not implemented: ${opts.cli}`;
+ opts.onEvent({ type: 'done', status: 'failed', error: err });
+ return { runId: '', status: 'failed', error: err };
+ }
+
+ // Pre-flight probe (cache-busting). A user might have uninstalled
+ // the CLI between create-time detection and now.
+ const entry = await detectOne(opts.cli);
+ if (!entry.available || !entry.path) {
+ return _missing(opts, entry);
+ }
+
+ const handle = await persist.start(opts.uid, {
+ agentId: opts.agentId,
+ cid: opts.cid,
+ cli: opts.cli,
+ model: opts.model,
+ cliPath: entry.path,
+ prompt: opts.prompt,
+ });
+ log.info('start', { runId: handle.runId, cli: opts.cli, agentId: opts.agentId, cid: opts.cid, cwd: opts.cwd });
+ const startedAtMs = Date.now();
+
+ // Wrapper writes events to disk before forwarding upstream so that
+ // a renderer crash mid-run still leaves a complete jsonl trail.
+ let streamedOutput = '';
+ let terminal: { status: RunCliAgentResult['status']; output?: string; error?: string; sessionId?: string } | null = null;
+ const onEvent = (e: LocalEvent) => {
+ persist.append(handle, e);
+ if (e.type === 'text-delta' && typeof e.text === 'string') {
+ streamedOutput += e.text;
+ persist.appendOutput(handle, e.text);
+ }
+ if (e.type === 'done') {
+ terminal = {
+ status: (e.status as RunCliAgentResult['status']) || 'failed',
+ output: typeof e.output === 'string' ? e.output : undefined,
+ error: typeof e.error === 'string' ? e.error : undefined,
+ sessionId: typeof e.sessionId === 'string' ? e.sessionId : undefined,
+ };
+ }
+ opts.onEvent(e);
+ };
+
+ try {
+ await backend.run({
+ binPath: entry.path,
+ prompt: opts.prompt,
+ cwd: opts.cwd,
+ model: opts.model,
+ customArgs: opts.customArgs,
+ resumeSessionId: opts.resumeSessionId,
+ signal: opts.signal,
+ onEvent,
+ timeoutMs: resolveTimeoutMs(),
+ });
+ } catch (err) {
+ const msg = (err as Error).message || String(err);
+ log.error('backend threw', { runId: handle.runId, error: msg });
+ if (!terminal) {
+ onEvent({ type: 'done', status: 'failed', error: msg });
+ }
+ }
+
+ // Backends are required to emit a `done` — if missing, treat as
+ // failure so callers don't hang on an absent terminal event.
+ if (!terminal) {
+ onEvent({ type: 'done', status: 'failed', error: 'backend exited without terminal event' });
+ terminal = { status: 'failed', error: 'backend exited without terminal event' };
+ }
+
+ const finalOutput = terminal.output ?? streamedOutput;
+ const endedAtMs = Date.now();
+ await persist.finalize(handle, {
+ status: terminal.status,
+ output: finalOutput,
+ error: terminal.error,
+ sessionId: terminal.sessionId,
+ durationMs: endedAtMs - startedAtMs,
+ });
+ log.info('end', {
+ runId: handle.runId, cli: opts.cli, status: terminal.status, bytes: finalOutput?.length ?? 0,
+ });
+ // The PC build also archives the run into the in-app debug panel
+ // (`devtools.archiveLlmCall`); the open-source build has no debug
+ // panel, so the per-run jsonl under `local-agent-runs/<runId>/`
+ // (written by `persist`) is the only artifact.
+ return { runId: handle.runId, status: terminal.status, output: finalOutput, error: terminal.error };
+}
+
+async function _missing(opts: RunCliAgentOpts, entry: LocalCliEntry): Promise<RunCliAgentResult> {
+ const err = entry.errorDetail || `local CLI '${opts.cli}' is not installed or not on PATH`;
+ log.warn('missing cli', { cli: opts.cli, error: err });
+ opts.onEvent({ type: 'done', status: 'missing_cli', error: err });
+ return { runId: '', status: 'missing_cli', error: err };
+}
diff --git a/src/main/features/local_agents/sessions.ts b/src/main/features/local_agents/sessions.ts
new file mode 100644
index 00000000..23043437
--- /dev/null
+++ b/src/main/features/local_agents/sessions.ts
@@ -0,0 +1,138 @@
+/**
+ * Per-conversation CLI session bindings.
+ *
+ * Each (cid, aid, cli) tuple gets a CLI-reported session id so the
+ * next dispatch can pass `--resume <id>` instead of re-replaying the
+ * full visibility slice as prompt context. The CLI keeps its own
+ * conversation memory; we only persist the handle.
+ *
+ * Storage: `<uid>/local/cli-sessions/<cid>.json`, shape:
+ * { "<aid>": { "cli": "claude", "sessionId": "...", "updatedAt": "..." } }
+ *
+ * Why under `local/` instead of `cloud/`: session ids reference
+ * machine-local CLI state (e.g. `~/.claude/projects/...`); a synced
+ * id from another device wouldn't resolve and would fail-noisy.
+ *
+ * `cli` is captured alongside the id so a runtime swap (the user
+ * picks a different CLI from the detail page selector) treats the
+ * old binding as stale — fresh dispatch, fresh prompt. The runner
+ * persists a new id once the new CLI emits one.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import { localCliSessionsFile, userLocalCliSessionsDir } from '../../paths.js';
+import { createLogger } from '../../logger.js';
+
+const log = createLogger('local-agents:sessions');
+
+interface CliSessionRecord {
+ cli: string;
+ sessionId: string;
+ updatedAt: string;
+}
+
+interface CliSessionsFile {
+ [aid: string]: CliSessionRecord;
+}
+
+async function read(uid: string, cid: string): Promise<CliSessionsFile> {
+ const file = localCliSessionsFile(uid, cid);
+ try {
+ const raw = await fsp.readFile(file, 'utf8');
+ const data = JSON.parse(raw);
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return {};
+ return data as CliSessionsFile;
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT') {
+ log.warn('read failed', { uid, cid, error: (err as Error).message });
+ }
+ return {};
+ }
+}
+
+async function write(uid: string, cid: string, data: CliSessionsFile): Promise<void> {
+ const file = localCliSessionsFile(uid, cid);
+ await fsp.mkdir(path.dirname(file), { recursive: true });
+ await fsp.writeFile(file, JSON.stringify(data, null, 2), 'utf8');
+}
+
+/**
+ * Return the bound CLI session id for the (cid, aid, cli) tuple, or
+ * null if no binding exists OR the binding is for a different CLI
+ * (runtime swapped). Caller treats null as "fresh dispatch — replay
+ * the visibility slice".
+ */
+export async function getSessionId(uid: string, cid: string, aid: string, cli: string): Promise<string | null> {
+ const file = await read(uid, cid);
+ const r = file[aid];
+ if (!r || r.cli !== cli) return null;
+ return r.sessionId || null;
+}
+
+/** Persist the session id reported by the CLI after a successful run. */
+export async function setSessionId(uid: string, cid: string, aid: string, cli: string, sessionId: string): Promise<void> {
+ if (!sessionId) return;
+ const file = await read(uid, cid);
+ file[aid] = { cli, sessionId, updatedAt: new Date().toISOString() };
+ try { await write(uid, cid, file); }
+ catch (err) {
+ log.warn('setSessionId failed', { uid, cid, aid, error: (err as Error).message });
+ }
+}
+
+/** Drop the binding for a single (cid, aid). Used when the agent is
+ * removed from the conversation or the user explicitly resets it. */
+export async function clearForAgent(uid: string, cid: string, aid: string): Promise<void> {
+ const file = await read(uid, cid);
+ if (!(aid in file)) return;
+ delete file[aid];
+ try {
+ if (Object.keys(file).length === 0) {
+ await fsp.unlink(localCliSessionsFile(uid, cid)).catch(() => { /* */ });
+ } else {
+ await write(uid, cid, file);
+ }
+ } catch (err) {
+ log.warn('clearForAgent failed', { uid, cid, aid, error: (err as Error).message });
+ }
+}
+
+/** Drop ALL bindings for a conversation. Called from
+ * `chats.deleteConversation` so a hard reset of the chat also drops
+ * any CLI session pointers we'd otherwise keep dangling. The CLI's
+ * own session files (e.g. `~/.claude/...`) are NOT touched — we
+ * don't have a portable / safe way to invoke CLI-side cleanup, and
+ * the CLI is expected to GC stale sessions itself. */
+export async function clearForConversation(uid: string, cid: string): Promise<void> {
+ const file = localCliSessionsFile(uid, cid);
+ try { await fsp.unlink(file); }
+ catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT') {
+ log.warn('clearForConversation failed', { uid, cid, error: (err as Error).message });
+ }
+ }
+}
+
+/** Synchronous best-effort variant of clearForConversation for
+ * contexts where async isn't available (e.g. inside synchronous
+ * delete cascades). */
+export function clearForConversationSync(uid: string, cid: string): void {
+ const file = localCliSessionsFile(uid, cid);
+ try { fs.unlinkSync(file); }
+ catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT') {
+ log.warn('clearForConversationSync failed', { uid, cid, error: (err as Error).message });
+ }
+ }
+}
+
+/** Test helper — confirms the dir exists / is empty for assertions. */
+export function _sessionsDirForTest(uid: string): string {
+ return userLocalCliSessionsDir(uid);
+}
diff --git a/src/main/features/local_agents/version.ts b/src/main/features/local_agents/version.ts
new file mode 100644
index 00000000..92bc6185
--- /dev/null
+++ b/src/main/features/local_agents/version.ts
@@ -0,0 +1,113 @@
+/**
+ * Version probe + minimum-version gate for local CLI agents.
+ *
+ * Two pure functions (parseSemver / checkMinVersion) for unit-testing,
+ * and one subprocess call (detectVersion) that runs `<bin> --version`
+ * and extracts the first `[v]MAJOR.MINOR.PATCH` token from stdout/stderr.
+ *
+ * MIN_VERSIONS is intentionally narrow: only CLIs whose stream-json /
+ * ACP shape changed in a known-incompatible way before some version are
+ * gated here. Adding entries should be paired with a backend that
+ * actually relies on the new shape.
+ */
+
+import { spawn } from 'node:child_process';
+
+/** Minimum CLI versions; absent entry = no minimum. */
+export const MIN_VERSIONS: Record<string, string> = {
+ // claude --output-format stream-json + --print are stable from 2.x.
+ claude: '2.0.0',
+ // codex `app-server --listen stdio://` was added in 0.100.0.
+ codex: '0.100.0',
+};
+
+const VERSION_RE = /v?(\d+)\.(\d+)\.(\d+)/;
+
+export type Semver = { major: number; minor: number; patch: number };
+
+/** Parse the first MAJOR.MINOR.PATCH triple in `raw`; null if not found. */
+export function parseSemver(raw: string): Semver | null {
+ if (typeof raw !== 'string') return null;
+ const m = VERSION_RE.exec(raw);
+ if (!m) return null;
+ return {
+ major: Number(m[1]),
+ minor: Number(m[2]),
+ patch: Number(m[3]),
+ };
+}
+
+/** Lexicographic compare across major / minor / patch. Returns -1/0/1. */
+export function compareSemver(a: Semver, b: Semver): number {
+ if (a.major !== b.major) return a.major < b.major ? -1 : 1;
+ if (a.minor !== b.minor) return a.minor < b.minor ? -1 : 1;
+ if (a.patch !== b.patch) return a.patch < b.patch ? -1 : 1;
+ return 0;
+}
+
+/**
+ * Returns null when `detected` meets the minimum for `cli`, or an
+ * explanatory string otherwise. Unknown / unparsable inputs return
+ * null (no minimum / nothing to gate against) — the goal is to refuse
+ * obviously-old binaries, not to be a strict version policy engine.
+ */
+export function checkMinVersion(cli: string, detected: string | null): string | null {
+ const minRaw = MIN_VERSIONS[cli];
+ if (!minRaw) return null;
+ if (!detected) return null;
+ const min = parseSemver(minRaw);
+ const got = parseSemver(detected);
+ if (!min || !got) return null;
+ if (compareSemver(got, min) < 0) {
+ return `${cli} ${detected} is below required minimum ${minRaw}`;
+ }
+ return null;
+}
+
+/**
+ * Run `<binPath> --version`, return the parsed version string (the raw
+ * line we matched, not just the semver), or null on any failure.
+ *
+ * Timeout is 5s — `--version` should be sub-100ms; anything longer is
+ * a hung/wrong binary.
+ */
+export async function detectVersion(binPath: string, timeoutMs = 5000): Promise<string | null> {
+ return new Promise(resolve => {
+ let settled = false;
+ const finish = (v: string | null) => {
+ if (settled) return;
+ settled = true;
+ resolve(v);
+ };
+
+ let stdout = '';
+ let stderr = '';
+ const child = spawn(binPath, ['--version'], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+
+ child.stdout?.on('data', (c: Buffer) => { stdout += c.toString('utf8'); });
+ child.stderr?.on('data', (c: Buffer) => { stderr += c.toString('utf8'); });
+
+ const timer = setTimeout(() => {
+ try { child.kill('SIGTERM'); } catch { /* noop */ }
+ finish(null);
+ }, timeoutMs);
+
+ child.on('error', () => {
+ clearTimeout(timer);
+ finish(null);
+ });
+ child.on('close', () => {
+ clearTimeout(timer);
+ const text = (stdout || stderr || '').trim();
+ if (!text) return finish(null);
+ const sv = parseSemver(text);
+ if (!sv) return finish(null);
+ // Return the matched semver string so callers store a clean value
+ // (the raw line may carry product names / notes we don't want).
+ finish(`${sv.major}.${sv.minor}.${sv.patch}`);
+ });
+ });
+}
diff --git a/src/main/features/local_agents/which.ts b/src/main/features/local_agents/which.ts
new file mode 100644
index 00000000..7ba7b264
--- /dev/null
+++ b/src/main/features/local_agents/which.ts
@@ -0,0 +1,80 @@
+/**
+ * Cross-platform binary lookup. Mirrors `exec.LookPath` semantics.
+ *
+ * Why we don't use the `which` npm package: keeps the dep allow-list
+ * tight, and the logic is short. Single source of truth so registry.ts
+ * doesn't carry path-search code.
+ *
+ * POSIX: scan `process.env.PATH` (split by ':'), stat `<dir>/<name>`,
+ * accept if it's a regular file with any executable bit set.
+ *
+ * Windows: scan PATH (split by ';'), multiply each candidate by
+ * `process.env.PATHEXT` (e.g. `.COM;.EXE;.BAT;.CMD`); first stat hit
+ * wins. The empty extension is also tried first because some installs
+ * drop bare names (PowerShell shims, MinGW, etc.).
+ */
+
+import * as fs from 'node:fs/promises';
+import * as path from 'node:path';
+
+const isWindows = process.platform === 'win32';
+
+/** Scan PATH and return the first absolute path matching `name`, or null. */
+export async function whichBin(name: string): Promise<string | null> {
+ if (!name) return null;
+
+ // Absolute or relative path with separator → caller already resolved.
+ if (path.isAbsolute(name) || name.includes(path.sep) || (isWindows && name.includes('/'))) {
+ return (await isExecutableFile(name)) ? path.resolve(name) : null;
+ }
+
+ const pathEnv = process.env.PATH ?? '';
+ const dirs = pathEnv.split(path.delimiter).filter(Boolean);
+ if (dirs.length === 0) return null;
+
+ const exts = isWindows ? winExtCandidates() : [''];
+
+ for (const dir of dirs) {
+ for (const ext of exts) {
+ const candidate = path.join(dir, name + ext);
+ if (await isExecutableFile(candidate)) {
+ return candidate;
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Returns the candidate extensions to try on Windows, with the empty
+ * extension first so an exact-name hit (rare but possible) short-circuits.
+ */
+function winExtCandidates(): string[] {
+ const raw = process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD';
+ const exts = raw
+ .split(';')
+ .map(s => s.trim())
+ .filter(Boolean);
+ // Always try the bare name first.
+ return ['', ...exts];
+}
+
+/**
+ * stat-and-check; resolves to false on any error (ENOENT, EACCES, etc.)
+ * so callers don't need to wrap.
+ *
+ * On POSIX we additionally require the executable bit; on Windows the
+ * extension match is enough (NTFS doesn't carry a unix-style x bit and
+ * fs.stat's `mode` is synthesized).
+ */
+async function isExecutableFile(p: string): Promise<boolean> {
+ try {
+ const st = await fs.stat(p);
+ if (!st.isFile()) return false;
+ if (isWindows) return true;
+ // 0o111 = any of user/group/other execute.
+ return (st.mode & 0o111) !== 0;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index de4a8942..54ffab8d 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -23,6 +23,15 @@ import * as path from 'node:path';
import * as fs from 'node:fs';
import { app, BrowserWindow, Menu, ipcMain, nativeImage, protocol, shell } from 'electron';
+// Force the user-visible app name to "Orkas" before anything else
+// reads it. In dev (running `electron .`) Electron defaults to the
+// `name` field in package.json (lowercase "orkas") or — when launched
+// without that being effective — to literally "Electron", which leaks
+// to the macOS Dock tooltip and the menu bar. Packaged builds set this
+// via electron-builder's `productName`; this call covers dev + any
+// edge case where productName isn't picked up early.
+app.setName('Orkas');
+
// Register the KB file protocol BEFORE `app.whenReady()` — privileged
// schemes can't be added after. `kb-file:///<relpath>` serves a single
// file out of the current active user's `<uid>/cloud/contexts/`. Used by
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 6eee0793..95232a17 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -36,6 +36,7 @@ import * as appConfig from '../features/config';
import * as avatars from '../features/avatars';
import { getRendererTables, isLang, t } from '../i18n';
import * as userWorkspace from '../features/user_workspace';
+import { invokeHandlers as localAgentsHandlers } from './local_agents';
import { safeId } from '../storage';
import { createLogger, logFromRenderer } from '../logger';
import * as path from 'node:path';
@@ -176,8 +177,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { agent };
},
- 'agents.create': async ({ name = '', description = '', workflow = '', icon, color } = {}) => {
- return { agent: await agents.createCustomAgent({ name, description, workflow, icon, color }) };
+ 'agents.create': async ({ name = '', description = '', workflow = '', icon, color, runtime } = {}) => {
+ return { agent: await agents.createCustomAgent({ name, description, workflow, icon, color, runtime }) };
},
'agents.update': async ({ agent_id, updates }) => {
@@ -574,6 +575,11 @@ const invokeHandlers: Record<string, InvokeHandler> = {
shell.showItemInFolder(norm);
return { path: norm };
},
+
+ // Local CLI agent discovery (claude / codex / openclaw / opencode / hermes).
+ // Discovery + model catalogs only; actual spawning happens inside group_chat
+ // dispatch via `features/local_agents/runner.ts`, never as a standalone IPC.
+ ...localAgentsHandlers,
};
// ── Stream handlers ──────────────────────────────────────────────────────
diff --git a/src/main/ipc/local_agents.ts b/src/main/ipc/local_agents.ts
new file mode 100644
index 00000000..3ca7a284
--- /dev/null
+++ b/src/main/ipc/local_agents.ts
@@ -0,0 +1,53 @@
+/**
+ * IPC handlers for local CLI agent discovery.
+ *
+ * Three logical channels exposed to the renderer:
+ * - `localAgents.list` → all known CLI types with availability + version
+ * - `localAgents.detect` → single-CLI re-probe (bypasses cache)
+ * - `localAgents.listModels` → static model catalog for a CLI type
+ *
+ * No `run` channel here — the renderer doesn't spawn CLIs directly;
+ * dispatch goes through the existing `groupChat` channel and `bus.ts`
+ * 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 { 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);
+}
+
+export const invokeHandlers = {
+ /**
+ * List all known CLI types. Default uses the 60s cache; pass
+ * `{ force: true }` to invalidate first (settings page refresh button,
+ * for instance, would want a fresh probe).
+ */
+ 'localAgents.list': async ({ force = false }: { force?: boolean } = {}) => {
+ const entries = await detectAll({ force: !!force });
+ return { entries };
+ },
+
+ /**
+ * Re-probe a single CLI without the cache. Used at execute-time by
+ * the runner to make sure a recently-uninstalled binary doesn't slip
+ * through, and by the create-modal to refresh after the user changes
+ * the relevant `ORKAS_<TYPE>_PATH` env var.
+ */
+ 'localAgents.detect': async ({ type }: { type?: unknown }) => {
+ if (!isLocalCliType(type)) throw new Error('invalid CLI type');
+ invalidateCache();
+ const entry = await detectOne(type);
+ return { entry };
+ },
+
+ /**
+ * Static model catalog for a CLI. Empty array signals the UI to
+ * render a free-text input (openclaw / opencode / hermes for now).
+ */
+ 'localAgents.listModels': async ({ type }: { type?: unknown }) => {
+ if (!isLocalCliType(type)) throw new Error('invalid CLI type');
+ return { models: listModels(type) };
+ },
+};
diff --git a/src/main/locales/en.json b/src/main/locales/en.json
index 691539d2..fc546493 100644
--- a/src/main/locales/en.json
+++ b/src/main/locales/en.json
@@ -73,6 +73,7 @@
"model.retrying": "Retrying",
"model.retrying_n": "Retry attempt {attempt}",
"model.aborted": "(stopped)",
+ "cli_agent.missing": "⚠️ Agent “{name}” needs the local CLI “{cli}” which isn’t installed. Install it and retry, or switch the agent to another type.",
"plan.announcement.heading": "I'll proceed with the following steps:",
"plan.announcement.assignee_self": "me",
"plan.announcement.assignee_user": "you",
diff --git a/src/main/locales/zh.json b/src/main/locales/zh.json
index 220df122..9e556ed9 100644
--- a/src/main/locales/zh.json
+++ b/src/main/locales/zh.json
@@ -73,6 +73,7 @@
"model.retrying": "正在重试",
"model.retrying_n": "正在第 {attempt} 次重试",
"model.aborted": "(已中断)",
+ "cli_agent.missing": "⚠️ 智能体「{name}」依赖的本地 CLI「{cli}」未安装。请安装该 CLI 后重试,或在编辑面板换成其他类型。",
"plan.announcement.heading": "我准备按下面的步骤推进:",
"plan.announcement.assignee_self": "我自己",
"plan.announcement.assignee_user": "请你",
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 60504cce..eff1e3e1 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -170,6 +170,27 @@ export const sessionToolResultsDir = (uid: string, sessionId: string) =>
// 永不同步 —— 源路径是本机绝对路径。
export const userFileCacheDir = (uid: string) => path.join(userLocalRoot(uid), 'file_cache');
+// Run-history root for local CLI agent dispatches
+// (features/local_agents/runner.ts). One subdirectory per dispatch:
+// <uid>/local/file_cache/local-agent-runs/<runId>/{meta.json,
+// prompt.txt, events.jsonl, output.txt}. Lives under file_cache so the
+// existing local-domain GC sweep covers it (7-day default per plan).
+export const userLocalAgentRunsDir = (uid: string) =>
+ path.join(userFileCacheDir(uid), 'local-agent-runs');
+export const localAgentRunDir = (uid: string, runId: string) =>
+ path.join(userLocalAgentRunsDir(uid), runId);
+
+// CLI agent session bindings (features/local_agents/sessions.ts) —
+// per-conversation map `{aid → {cli, sessionId}}` so the next dispatch
+// can `--resume` instead of re-replaying the whole visibility slice.
+// Lives under `local/` (NOT cloud-synced) because the session id
+// references claude's machine-local session files (`~/.claude/...`)
+// which aren't valid on a different device.
+export const userLocalCliSessionsDir = (uid: string) =>
+ path.join(userLocalRoot(uid), 'cli-sessions');
+export const localCliSessionsFile = (uid: string, cid: string) =>
+ path.join(userLocalCliSessionsDir(uid), `${cid}.json`);
+
// 用户本机工作区选择(features/user_workspace.ts):用户挑的文件夹绝对路径 +
// 最近列表。绝对路径本机相关,不同步。
export const userWorkspaceConfigFile = (uid: string) => path.join(userLocalRoot(uid), 'workspace.json');
diff --git a/src/main/prompts/chat_agent_setup_cli.md b/src/main/prompts/chat_agent_setup_cli.md
new file mode 100644
index 00000000..626f432b
--- /dev/null
+++ b/src/main/prompts/chat_agent_setup_cli.md
@@ -0,0 +1,148 @@
+## Core task
+You are working with the user to refine a custom **CLI-backed agent** — polish its `name`, bilingual `description`, optional `inputs` form, and the `interactive` flag until they are clear and stable.
+
+This agent does **not** run inside this system. When dispatched, it spawns a local coding CLI which executes the task end-to-end on its own — so the agent has no workflow / skills / tools authored here. **Do not write `<workflow>` / `<skills>` for this agent.**
+
+**The runtime CLI is interchangeable.** The user can swap which CLI executes this agent (Claude Code / Codex / OpenClaw / OpenCode / Hermes) at any time from the detail page. Therefore the description, name, and inputs you author **must stay valid regardless of which CLI is bound today** — they describe the agent's role, not the runtime.
+
+---
+
+## Current agent
+- **Name**: $name
+- **Description (Chinese)**: $description_zh
+- **Description (English)**: $description_en
+- **Interactive mode**: $interactive
+
+---
+
+## What to focus on
+
+1. **Understand the user's intent**: what does the user want this agent to do? What kind of coding task does it own (review / scaffolding / migration / quick prototyping / debugging…)? Whose problem does it solve? When info is insufficient, list questions in one batch and have the user fill them — don't guess.
+
+2. **The description (`description_zh` + `description_en`) is the only signal for dispatch selection** — when the commander dispatches, it **only sees name + description**, and injects the version matching the user's current UI language. A poorly written description = the agent never gets dispatched, or gets mis-dispatched.
+
+ **The description must be detailed but CLI-agnostic.** Describe **the agent's responsibility + when to use it** — what task it owns, what deliverable it produces, what user phrasings should select it. **Never name a specific CLI / brand / model** (no "Claude Code", "Codex", "GPT-5", "Sonnet", "Anthropic" — see "Forbidden words" below). The runtime can be swapped on a whim; if the description hard-codes a CLI, the agent's selection signal goes stale the moment the user switches it.
+
+ **Each language is written independently** (don't direct-translate; appeal to real phrasings of users in each language) using the **three-part formula**, written generously with concrete details so the commander has plenty of signal:
+ - ① one-paragraph function: what task the agent owns, what inputs it consumes, what artifact it delivers, where the artifact ends up. Concrete verbs + concrete objects, **no CLI names**. 1–3 sentences is fine — be specific.
+ - ② `适合` / `For:` + 3–5 quoted **real user phrasings** that should trigger this agent.
+ - ③ `触发词:` / `Triggers:` + 6–10 keywords (separated by `、` / `,`).
+
+ Example (Chinese): "对当前工作目录里的代码做一次结构化审查:抓出逻辑漏洞、潜在安全问题、错误处理与边界条件遗漏;扫完以 Markdown 报告交付,按"问题 / 风险等级 / 复现路径 / 建议修法"四列罗列,便于直接拿去改代码。适合"提交前帮我看下代码""审查一下这个 PR 的实现""把把关,看看有没有遗漏的边界";触发词:审查、code review、把把关、看下代码、检查、安全、漏洞、回归、重构"
+
+ Example (English): "Do a structured review of the code in the current workspace: surface logic bugs, security risks, error-handling gaps, and missing edge cases. Delivers a Markdown report grouped by "issue / severity / repro / suggested fix" so the developer can act on it directly. For: 'review my code before commit', 'have another look at the PR implementation', 'check whether I missed any edge cases'; Triggers: review, audit, code review, security, bugs, regression, refactor, edge cases"
+
+3. **Decide if `inputs` is needed** (one-shot form before the agent runs). Most CLI agents need **zero or very few inputs** because the user's natural-language ask in the conversation already carries enough; only add inputs when there is a genuinely structured choice the user must always make (e.g. "review depth: quick / deep" / "target stack: Python / Go / TS"). When in doubt, leave it empty.
+
+4. **Decide `interactive`**: same rules as a normal agent — `true` only when the agent's workflow truly depends on multi-turn user replies (tutoring / Q&A / role-play). For most coding-CLI agents (review / scaffold / report) the right answer is `false`. Default to `false` if unsure.
+
+5. **Iterate gradually**: chat about one thing at a time; don't dump every detail up front.
+
+---
+
+## What you must NOT do
+
+- **Do not write a `<workflow>` sub-tag**. This agent's execution lives in the external CLI; we don't author workflow for it.
+- **Do not write a `<skills>` sub-tag**. CLI agents don't use Orkas skills.
+- **Do not write a `<runtime>` sub-tag**. The runtime (which CLI / which model / extra args) is configured by the user via the modal and the settings UI; the LLM never authors it. If you change `<runtime>`, the system ignores you.
+- **Do not write a `<system>` / `<persona>` sub-tag**. They don't apply here.
+
+---
+
+## User-perspective output (hard rule)
+
+The conversation prose to the user (content **outside** the `<agent>` container) only states three things from the **user's perspective**: what this agent does / when to use it / what substantive change you made this round. **Do NOT** expose internal field names / data-structure terms / this-session terminology to the user — those are contracts between the LLM and the system; the user only gets confused.
+
+**Forbidden words list** (never appear in conversation prose **or** in the description sub-tags):
+- Field names / XML tags: `interactive` / `inputs` / `description` / `description_zh` / `description_en` / `name` / `runtime` / `<agent>` / `<inputs>` / any `<xxx>` tag.
+- Data-structure terms: `schema` / `frontmatter` / `JSON` / `select` / `multiselect` / `options` / `default` / `required` / "field" / "sub-tag" / "container" / "config" / id.
+- **Specific CLI / brand / model names** in the description: `Claude Code` / `Claude` / `Codex` / `GPT-*` / `OpenClaw` / `OpenCode` / `Hermes` / `Anthropic` / `OpenAI` / `Sonnet` / `Opus` / `Haiku` / etc. The runtime is interchangeable; descriptions must stay valid across CLI swaps. Use neutral phrasings like "the agent reads…", "produces a report…", "in the working directory…".
+
+**Translation table** (use user-perspective wording for these concepts):
+- `interactive=true` → "It will chat with you back and forth."
+- `interactive=false` → "It runs autonomously and won't need you to reply midway."
+- Editing `inputs` → "Before running, it asks you these things: A, B, C."
+- Editing `description_zh` / `description_en` / `name` → "I updated its description / name to ..." (don't expose specific field names; don't say "the Chinese description was changed / the English description was changed" — the user does not need to know it's a bilingual field).
+
+---
+
+## How to write changes back to the agent config
+
+The CLI agent has these editable fields: `name` / `description_zh` + `description_en` / `inputs` / `interactive`. Whenever any field needs updating, you **must** include a **single `<agent>...</agent>` container block** in your reply, with each updated field as a sub-tag inside (**full replacement, not incremental**).
+
+**Field sync policy**: `<name>` / `<description_zh>` / `<description_en>` are emitted only if changed this turn; otherwise omit. When editing the description, **judge each language independently** — if you only changed one, only emit that one. `<inputs>` / `<interactive>` are emitted in full whenever they are discussed / adjusted / reviewed.
+
+**Don't emit a container at all when**: ① no field was adjusted this turn (pure discussion / restating); ② the user is asking something unrelated to the agent.
+
+Format:
+
+```
+<agent>
+<name>The new name (one line)</name>
+<description_zh>The new Chinese description (per the three-part formula in §2 of "What to focus on")</description_zh>
+<description_en>The new English description (same three-part formula)</description_en>
+<inputs>
+[
+ {"id":"focus","label":"Review focus","type":"select",
+ "options":[{"value":"logic","label":"Logic bugs"},{"value":"security","label":"Security"},{"value":"both","label":"Both"}],
+ "default":"both"}
+]
+</inputs>
+<interactive>false</interactive>
+</agent>
+```
+
+Rules:
+- **At most one `<agent>...</agent>` container per turn**. Put the fields to be changed inside as sub-tags; omit the sub-tags for fields that aren't changing.
+- Each sub-tag **overwrites** the field's prior content — if you want to keep old content, write the old content into the sub-tag.
+- The `<agent>` container is auto-hidden from the user-visible message.
+- **Do NOT** insert anything other than the listed sub-tags inside the `<agent>` container; user-facing text goes into the prose outside the container.
+- **Do NOT** put any `<workflow>` / `<skills>` / `<runtime>` / `<system>` / `<persona>` tags inside — see "What you must NOT do".
+
+---
+
+## `<inputs>` sub-tag design (the one-shot form before each run)
+
+> Same shape as a normal agent — keep it minimal for CLI agents.
+
+This field decides "when the user runs this agent, which parameters does the main conversation collect via a form first". When done well, the UX is very clean (dropdowns, defaults, multi-select all in one go); done poorly, the user keeps getting nagged.
+
+**Each input must have**:
+- `id`: snake_case, unique within the agent, regex `^[a-z_][a-z0-9_]{0,31}$`.
+- `label`: a short user-facing phrase ("Review focus" / "Target stack") — no pinyin, no English ids in the label.
+- `type`: one of `text` / `textarea` / `select` / `multiselect` / `number` / `boolean` / `file`.
+- `default`: **must be provided**. For options, pick the most common; for free text, `""`; for multiselect, `[]` or a reasonable subset; boolean follows the "default on/off" of the agent; `file` is always `""` (single) or `[]` (multi).
+- `select`/`multiselect` must include `options: [{value, label}, ...]`.
+
+**Optional fields**: `description`, `required`, `placeholder`, `min`, `max`, `multiple` (file), `accept` (file).
+
+**Prefer empty inputs for CLI agents** unless the user clearly needs structured choices. The user's natural-language ask in the conversation usually carries everything the CLI needs.
+
+**When to emit `<inputs>[]</inputs>`** (empty): the agent has no structured up-front parameters. An empty sub-tag is more explicit than omitting — it tells the system "this agent has confirmed zero inputs".
+
+**When to NOT emit the block at all**: this round, the user asks something unrelated to inputs (changing description, small talk, etc.). Don't rewrite the schema out of nowhere.
+
+---
+
+## `<interactive>` sub-tag design
+
+Decides whether, when the agent is dispatched, the input box auto-retargets to this agent so the user doesn't need to manually `@` it to reply.
+
+**Meaning**:
+- `true` — the agent depends on **multi-turn user replies** to advance. Rare for CLI coding agents.
+- `false` (**default**) — once dispatched, the agent runs to completion in the CLI and hands back a deliverable. The right default for review / scaffold / migration / report agents.
+
+**Decision rules**:
+1. Does the agent's natural workflow involve waiting on the user mid-run? → `true`.
+2. Otherwise → `false`.
+3. Unsure → conservatively `false` (wrongly setting `true` causes the user's words to be misrouted, a worse experience).
+
+**Output rules**:
+- Per the "Field sync policy" above — when the agent's positioning is re-discussed, re-evaluate and re-emit `<interactive>true|false</interactive>` in full.
+- Inside the tag, **only** `true` or `false` (lowercase).
+
+---
+
+## Other
+- If the user asks something unrelated to the agent, just answer normally; afterwards, ask if they want to keep refining.
+- Keep replies concise; advance step by step.
diff --git a/src/renderer/index.html b/src/renderer/index.html
index d59d58fe..e9d52f13 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -257,6 +257,7 @@
<div class="agents-detail-title-row">
<span class="agents-detail-avatar-slot" id="agents-detail-avatar"></span>
<div class="agents-detail-name" id="agents-detail-name" contenteditable="false"></div>
+ <span class="agents-detail-source" id="agents-detail-source"></span>
<div class="detail-actions" id="agents-detail-actions">
<button class="btn-icon-use" id="agent-use-btn" data-i18n-title="agents.use_tooltip" data-i18n-aria-label="agents.use_tooltip" aria-label="使用">
<svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
@@ -267,9 +268,12 @@
<button class="btn btn-sm btn-danger" id="agent-delete-btn" data-i18n="agents.delete">删除</button>
</div>
</div>
- <div class="agents-detail-source" id="agents-detail-source"></div>
</div>
<div class="agents-detail-body">
+ <div class="agents-detail-section" id="agents-detail-runtime-section" style="display:none">
+ <div class="agents-detail-label" data-i18n="agents.label_runtime">运行环境</div>
+ <div class="agents-detail-runtime" id="agents-detail-runtime"></div>
+ </div>
<div class="agents-detail-section">
<div class="agents-detail-label" data-i18n="agents.label_desc">简介</div>
<div class="agents-detail-desc" id="agents-detail-desc" contenteditable="false"></div>
@@ -500,6 +504,10 @@
<label><span data-i18n="agent_modal.desc">简介</span> <span class="form-hint" data-i18n="agent_modal.desc_hint">一句话说明用途,创建后 AI 会基于此生成工作流程</span></label>
<textarea id="agent-desc-input" rows="4" data-i18n-placeholder="agent_modal.desc_placeholder" placeholder="例如:帮我在提交前审查代码,重点看逻辑漏洞和安全问题..."></textarea>
</div>
+ <div class="form-row" id="agent-modal-runtime-row" style="display:none">
+ <label><span data-i18n="agent_modal.runtime_label">运行环境</span> <span class="form-hint" data-i18n="agent_modal.runtime_hint">选择本地 CLI 则由该 CLI 来运行智能体</span></label>
+ <div class="ai-select" id="agent-modal-runtime-select"></div>
+ </div>
<div class="form-msg" id="agent-form-msg"></div>
<div class="modal-actions">
<button class="btn" onclick="closeAgentModal()" data-i18n="common.cancel">取消</button>
@@ -699,6 +707,7 @@
<script src="./modules/kb-picker.js"></script>
<script src="./modules/search.js"></script>
<script src="./modules/user-workspace.js"></script>
+ <script src="./modules/local-agents.js"></script>
<script src="./modules/agents.js"></script>
<script src="./modules/utils.js"></script>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 99f21fcb..04f1a821 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -205,6 +205,7 @@
"agents.edit": "Edit",
"agents.delete": "Delete",
"agents.label_desc": "Summary",
+ "agents.label_runtime": "Runtime",
"agents.label_workflow": "Workflow",
"agents.clear_chat": "Clear",
"agents.clear_chat_title": "Clear the edit chat for this agent",
@@ -424,6 +425,20 @@
"agent_modal.desc": "Summary",
"agent_modal.desc_hint": "One line on what it does — the AI will generate a workflow from this",
"agent_modal.desc_placeholder": "e.g. Review my code before commit, focus on logic bugs and security issues...",
+ "agent_modal.runtime_label": "Runtime",
+ "agent_modal.runtime_hint": "Pick a local CLI and that CLI will run the agent",
+ "agent_modal.runtime_in_process": "Orkas",
+ "agent_modal.runtime_cli_claude": "Claude Code",
+ "agent_modal.runtime_cli_codex": "Codex",
+ "agent_modal.runtime_cli_openclaw": "OpenClaw",
+ "agent_modal.runtime_cli_opencode": "OpenCode",
+ "agent_modal.runtime_cli_hermes": "Hermes",
+ "agent.cli_badge.claude": "CLI · Claude Code",
+ "agent.cli_badge.codex": "CLI · Codex",
+ "agent.cli_badge.openclaw": "CLI · OpenClaw",
+ "agent.cli_badge.opencode": "CLI · OpenCode",
+ "agent.cli_badge.hermes": "CLI · Hermes",
+ "agent.cli_missing": "⚠ Local CLI not installed",
"skill_modal.title_create": "New skill",
"skill_modal.title_edit": "Edit skill",
"skill_modal.name": "Name (English)",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index f97513b1..351c6470 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -205,6 +205,7 @@
"agents.edit": "编辑",
"agents.delete": "删除",
"agents.label_desc": "简介",
+ "agents.label_runtime": "运行环境",
"agents.label_workflow": "工作流程",
"agents.clear_chat": "清空",
"agents.clear_chat_title": "清空当前智能体的对话记录",
@@ -424,6 +425,20 @@
"agent_modal.desc": "简介",
"agent_modal.desc_hint": "一句话说明用途,创建后 AI 会基于此生成工作流程",
"agent_modal.desc_placeholder": "例如:帮我在提交前审查代码,重点看逻辑漏洞和安全问题...",
+ "agent_modal.runtime_label": "运行环境",
+ "agent_modal.runtime_hint": "选择本地 CLI 则由该 CLI 来运行智能体",
+ "agent_modal.runtime_in_process": "Orkas",
+ "agent_modal.runtime_cli_claude": "Claude Code",
+ "agent_modal.runtime_cli_codex": "Codex",
+ "agent_modal.runtime_cli_openclaw": "OpenClaw",
+ "agent_modal.runtime_cli_opencode": "OpenCode",
+ "agent_modal.runtime_cli_hermes": "Hermes",
+ "agent.cli_badge.claude": "CLI · Claude Code",
+ "agent.cli_badge.codex": "CLI · Codex",
+ "agent.cli_badge.openclaw": "CLI · OpenClaw",
+ "agent.cli_badge.opencode": "CLI · OpenCode",
+ "agent.cli_badge.hermes": "CLI · Hermes",
+ "agent.cli_missing": "⚠ 本地 CLI 未安装",
"skill_modal.title_create": "新建技能",
"skill_modal.title_edit": "编辑技能",
"skill_modal.name": "名称(英文)",
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 4ae49dae..f3ee1e3f 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -9,6 +9,17 @@ let _agentFieldSaveTimer = null;
// Mirror of `agents.ts::RESERVED_AGENT_NAMES` so the renderer can fail fast
// without a round-trip. Server is still authoritative — this is just UX.
const _RESERVED_AGENT_NAMES = new Set(['指挥官', '总指挥', 'commander']);
+/** Look up the localized "CLI · <Brand>" label for an agent runtime
+ * type, with a guaranteed-readable fallback when the locale key is
+ * missing. Orkas's `t()` returns the key itself on miss (so a naive
+ * `t(key) || fallback` never falls back); we explicitly compare. */
+function _cliBadgeLabel(type) {
+ const key = 'agent.cli_badge.' + type;
+ const v = t(key);
+ if (!v || v === key) return 'CLI · ' + type;
+ return v;
+}
+
function _isReservedAgentName(name) {
const key = String(name || '').replace(/\s+/g, '').toLowerCase();
return _RESERVED_AGENT_NAMES.has(key);
@@ -94,6 +105,11 @@ function renderAgentsGrid(agents) {
// the grid cards stay clean and use the ⋯ menu for actions.
const moreBtn = `<button type="button" class="agent-card-more" data-agent-more title="${moreTitle}" aria-label="${moreTitle}">⋯</button>`;
const avatarHtml = renderAvatarHtml(a.icon, a.color, { size: 32, seed: a.agent_id, extraClass: 'agent-card-avatar' });
+ // Show a small "CLI · <Brand>" chip on the bottom row, left-aligned,
+ // sharing the line with the play button on the right.
+ const cliChip = (a.runtime && a.runtime.kind === 'cli')
+ ? `<span class="agent-card-chip is-cli is-cli-${escapeHtml(a.runtime.cli)}">${escapeHtml(_cliBadgeLabel(a.runtime.cli))}</span>`
+ : '';
return `
<div class="agent-card${enabled ? '' : ' is-disabled'}" data-id="${escapeHtml(a.agent_id)}" data-source="${a.source}">
<div class="agent-card-header">
@@ -103,6 +119,7 @@ function renderAgentsGrid(agents) {
</div>
<div class="${descClass}">${escapeHtml(descText)}</div>
<div class="agent-card-actions">
+ ${cliChip}
<button type="button" class="agent-card-use" data-agent-use title="${useTitle}" aria-label="${useTitle}">
<svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
</button>
@@ -379,11 +396,23 @@ function _renderAgentDetail(agent, editing) {
nameEl.textContent = agent.name || '';
sourceEl.textContent = agent.source === 'builtin' ? t('agents.source_builtin') : t('agents.source_custom');
sourceEl.className = 'agents-detail-source ' + (agent.source === 'builtin' ? 'is-builtin' : 'is-custom');
+ // Runtime slot lives at the top of the body now (not the header):
+ // an always-editable dropdown so the user can flip Orkas ↔ local CLI
+ // without entering edit mode. The header chip was removed because
+ // it duplicated information the dropdown already exposes.
+ _renderAgentDetailRuntime(agent);
const localizedDesc = pickDesc(agent, getLang()).trim();
descEl.textContent = localizedDesc;
_renderAgentDetailAvatar(agent);
+ // CLI-backed agents have no authored workflow / skill_list — the
+ // external CLI brings its own behavior. Hide the entire workflow
+ // section so the detail page doesn't show an empty editor block.
+ const workflowSection = document.querySelector('.agents-detail-section-workflow');
+ const isCliRuntime = !!(agent.runtime && agent.runtime.kind === 'cli');
+ if (workflowSection) workflowSection.style.display = isCliRuntime ? 'none' : '';
+
const unsetHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset'))}</span>`;
// Workflow renders markdown in readonly mode; raw text in edit mode so user
// can edit source directly.
@@ -416,6 +445,89 @@ function _renderAgentDetail(agent, editing) {
_toggleAgentFieldEditable(editing);
}
+/** Render the runtime control in the detail body.
+ *
+ * The runtime "kind" is locked at create time:
+ * - `in_process` (Orkas) agents → never show the selector here. The
+ * runtime row stays hidden; user has no need to see it.
+ * - `cli` agents → show a selector with **CLI options only** (no
+ * Orkas / in_process option). User can swap which CLI backs the
+ * agent at any time, but can't revert to Orkas — that would
+ * invalidate the description and inputs which were authored
+ * specifically for a CLI runtime.
+ *
+ * Reuses `_aiSelectMount` (see CLAUDE.md "Reuse UI components") and
+ * persists each change via `agents.update({ runtime })`. */
+async function _renderAgentDetailRuntime(agent) {
+ const section = document.getElementById('agents-detail-runtime-section');
+ const slot = document.getElementById('agents-detail-runtime');
+ if (!slot || !section) return;
+ slot.innerHTML = '';
+
+ // In-process agents: section stays hidden. No selector, no
+ // information to surface.
+ if (agent.runtime?.kind !== 'cli') {
+ section.style.display = 'none';
+ return;
+ }
+
+ const entries = (typeof loadLocalCliEntries === 'function') ? await loadLocalCliEntries() : [];
+ const available = entries.filter(e => e.available);
+ const seen = new Set(available.map(e => e.type));
+ const currentType = agent.runtime.cli;
+
+ // Build CLI-only options: every detected CLI + the bound one if it's
+ // missing (with a warning suffix so the user can flip away in one
+ // click). Orkas / in_process is intentionally absent — see fn doc.
+ const options = [];
+ for (const e of available) {
+ options.push({
+ value: `cli:${e.type}`,
+ label: `${t('agent_modal.runtime_cli_' + e.type)}${e.version ? ` (${e.version})` : ''}`,
+ });
+ }
+ if (!seen.has(currentType)) {
+ const baseLabel = t('agent_modal.runtime_cli_' + currentType);
+ const labelText = (baseLabel && baseLabel !== 'agent_modal.runtime_cli_' + currentType)
+ ? baseLabel : currentType;
+ options.push({
+ value: `cli:${currentType}`,
+ label: `${labelText} ${t('agent.cli_missing')}`,
+ });
+ }
+ if (options.length === 0) {
+ // Defensive — shouldn't happen since we always add the bound CLI
+ // above. Hide the row instead of rendering an empty dropdown.
+ section.style.display = 'none';
+ return;
+ }
+ section.style.display = '';
+
+ const mount = document.createElement('div');
+ mount.className = 'ai-select agents-detail-runtime-select';
+ slot.appendChild(mount);
+ _aiSelectMount(mount, {
+ options, value: `cli:${currentType}`,
+ onChange: async (next) => {
+ const m = /^cli:(.+)$/.exec(next);
+ if (!m) return;
+ try {
+ const res = await window.orkas.invoke('agents.update', {
+ agent_id: agent.agent_id, updates: { runtime: { kind: 'cli', cli: m[1] } },
+ });
+ if (res?.ok && res.agent) {
+ _agentsCache = null;
+ const fetched = await apiFetch(`/api/agents/${encodeURIComponent(agent.agent_id)}`);
+ const data = await fetched.json();
+ if (data.ok && data.agent) _renderAgentDetail(data.agent, _agentEditing);
+ }
+ } catch (err) {
+ _agentsLog.warn('agents.update runtime failed', err);
+ }
+ },
+ });
+}
+
/** Render the detail-page avatar slot. Custom agents get a clickable avatar
* that opens the picker; builtin agents just show theirs read-only. Each
* picker change is sent as an `agents.update` IPC and the local cache is
@@ -600,6 +712,11 @@ function openAgentModal() {
descInput.value = '';
msgEl.textContent = '';
msgEl.className = 'form-msg';
+ // Refresh runtime selector each open — local CLI install state can
+ // change between opens (user installs claude during the session).
+ if (typeof mountLocalAgentRuntimeRow === 'function') {
+ mountLocalAgentRuntimeRow().catch(() => { /* falls through to hidden row */ });
+ }
modal.classList.add('open');
setTimeout(() => nameInput.focus(), 50);
}
@@ -638,10 +755,13 @@ async function saveAgentModal() {
// 创建时本地随机一对头像,让每个新智能体一上来就有不同的视觉锚点。
// 不让 LLM 介入 —— 头像是 UI 元数据,不影响 prompt 行为。
const avatar = randomAgentAvatar();
+ const runtime = (typeof getRuntimeFormValue === 'function') ? getRuntimeFormValue() : null;
+ const body = { name, description, icon: avatar.icon, color: avatar.color };
+ if (runtime) body.runtime = runtime;
const res = await apiFetch('/api/agents/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name, description, icon: avatar.icon, color: avatar.color }),
+ body: JSON.stringify(body),
});
const data = await res.json();
if (!data.ok || !data.agent) {
diff --git a/src/renderer/modules/local-agents.js b/src/renderer/modules/local-agents.js
new file mode 100644
index 00000000..dbeb51a3
--- /dev/null
+++ b/src/renderer/modules/local-agents.js
@@ -0,0 +1,100 @@
+// ─── Local CLI agents (renderer side) ─────────────────────────────────
+//
+// One dropdown in the create-agent modal:
+// Orkas (default, in-process) | Claude Code | Codex | OpenClaw | OpenCode | Hermes
+// Anything not detected on this machine is omitted from the list.
+//
+// Model + custom_args are intentionally NOT exposed in the modal — the
+// CLI picks its own default model (closer to what the user's account
+// actually supports), and most users never need extra flags. The spec
+// still supports both fields; advanced users can hand-edit `agent.json`
+// or we add a "details" toggle later when there's real demand.
+//
+// Detection pre-warms 500ms after the first agents-page render so the
+// 60s registry cache is warm by the time the user opens the modal —
+// the first cold detection runs `which` + `--version` for each CLI in
+// parallel and can take ~200ms; this avoids the layout-shift flash
+// that comes from awaiting it inside `openAgentModal`.
+
+const _localAgentsLog = createLogger('local-agents');
+
+let _localCliEntries = null; // cached availability list
+
+async function loadLocalCliEntries({ force = false } = {}) {
+ if (_localCliEntries && !force) return _localCliEntries;
+ try {
+ const res = await window.orkas.invoke('localAgents.list', { force });
+ _localCliEntries = Array.isArray(res?.entries) ? res.entries : [];
+ } catch (e) {
+ _localAgentsLog.warn('localAgents.list failed', e);
+ _localCliEntries = [];
+ }
+ return _localCliEntries;
+}
+
+let _runtimeSelectApi = null;
+
+/**
+ * Render the runtime selector inside the create-agent modal.
+ * - No CLIs detected → row stays hidden, selector treated as Orkas.
+ * - At least one detected → fills with "Orkas" (default) + each
+ * available CLI; defaults to Orkas.
+ * Idempotent: calling again rebuilds the row from current detection.
+ */
+async function mountLocalAgentRuntimeRow() {
+ const row = document.getElementById('agent-modal-runtime-row');
+ const mount = document.getElementById('agent-modal-runtime-select');
+ if (!row || !mount) return false;
+
+ const entries = await loadLocalCliEntries();
+ const available = entries.filter(e => e.available);
+ if (available.length === 0) {
+ row.style.display = 'none';
+ if (_runtimeSelectApi) _runtimeSelectApi.setOptions([], { value: 'in_process' });
+ return false;
+ }
+
+ row.style.display = '';
+ const options = [
+ { value: 'in_process', label: t('agent_modal.runtime_in_process') },
+ ...available.map(e => ({
+ value: `cli:${e.type}`,
+ label: `${t('agent_modal.runtime_cli_' + e.type)}${e.version ? ` (${e.version})` : ''}`,
+ })),
+ ];
+ // Mount once, re-set options on subsequent opens. Keeps the API
+ // instance stable so `getRuntimeFormValue` reads the same widget.
+ if (!_runtimeSelectApi) {
+ _runtimeSelectApi = _aiSelectMount(mount, {
+ options, value: 'in_process',
+ placeholder: t('agent_modal.runtime_in_process'),
+ onChange: () => { /* read on save */ },
+ });
+ } else {
+ _runtimeSelectApi.setOptions(options, { value: 'in_process' });
+ }
+ return true;
+}
+
+/**
+ * Read the current selector state into a runtime spec, or null when
+ * the user kept "Orkas" (so the caller doesn't write a runtime field
+ * at all and the agent stays in-process by default). Model + custom
+ * args are not collected here — backends fall back to their own
+ * defaults, which is usually what users want.
+ */
+function getRuntimeFormValue() {
+ const v = _runtimeSelectApi ? _runtimeSelectApi.getValue() : 'in_process';
+ if (!v || v === 'in_process') return null;
+ const m = /^cli:(.+)$/.exec(v);
+ if (!m) return null;
+ return { kind: 'cli', cli: m[1] };
+}
+
+// Pre-warm the registry cache shortly after script load so the first
+// modal open doesn't pay the cold detection cost. Fire-and-forget.
+setTimeout(() => { loadLocalCliEntries().catch(() => { /* warm-up best-effort */ }); }, 500);
+
+window.mountLocalAgentRuntimeRow = mountLocalAgentRuntimeRow;
+window.getRuntimeFormValue = getRuntimeFormValue;
+window.loadLocalCliEntries = loadLocalCliEntries;
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index 9644b1f9..c062a47a 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -484,15 +484,43 @@ function _aiSelectMount(el, config) {
});
};
+ // Portal the popover to <body> while open so an ancestor with
+ // `overflow: auto / hidden` (modals, settings panes) can't clip it.
+ // We set `position: fixed` + viewport coords from the trigger's
+ // bounding rect; on scroll/resize we re-measure. This replaces the
+ // earlier "popover lives inside .ai-select" layout — the markup
+ // still renders the popover inside .ai-select for first paint, but
+ // open/close moves it back and forth.
+ let portalParent = null;
+ let portalNextSibling = null;
+ const reposition = () => {
+ if (!state.open) return;
+ const rect = trigger.getBoundingClientRect();
+ popover.style.position = 'fixed';
+ popover.style.left = rect.left + 'px';
+ popover.style.top = (rect.bottom + 4) + 'px';
+ popover.style.width = rect.width + 'px';
+ // Flip up if the popover would overflow the viewport bottom.
+ const popH = popover.offsetHeight || 260;
+ if (rect.bottom + 4 + popH > window.innerHeight - 8 && rect.top - 4 - popH > 8) {
+ popover.style.top = (rect.top - 4 - popH) + 'px';
+ }
+ };
const open = () => {
if (state.open) return;
state.open = true;
el.classList.add('open');
popover.hidden = false;
+ portalParent = popover.parentNode;
+ portalNextSibling = popover.nextSibling;
+ document.body.appendChild(popover);
state.activeIdx = Math.max(0, state.options.findIndex(o => o.value === state.value));
renderPopover();
+ reposition();
setTimeout(() => document.addEventListener('mousedown', onDocDown, true), 0);
document.addEventListener('keydown', onKey, true);
+ window.addEventListener('scroll', reposition, true);
+ window.addEventListener('resize', reposition, true);
};
const close = () => {
@@ -500,8 +528,27 @@ function _aiSelectMount(el, config) {
state.open = false;
el.classList.remove('open');
popover.hidden = true;
+ popover.style.position = '';
+ popover.style.left = '';
+ popover.style.top = '';
+ popover.style.width = '';
+ // Restore popover to its original parent if that parent is still
+ // attached to the document. If the host widget got removed mid-open
+ // (e.g., the detail page re-rendered and replaced our slot), just
+ // detach the popover so it doesn't dangle on document.body.
+ if (portalParent) {
+ if (portalParent.isConnected) {
+ portalParent.insertBefore(popover, portalNextSibling);
+ } else if (popover.parentNode) {
+ popover.parentNode.removeChild(popover);
+ }
+ portalParent = null;
+ portalNextSibling = null;
+ }
document.removeEventListener('mousedown', onDocDown, true);
document.removeEventListener('keydown', onKey, true);
+ window.removeEventListener('scroll', reposition, true);
+ window.removeEventListener('resize', reposition, true);
};
const onDocDown = (e) => { if (!el.contains(e.target)) close(); };
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 6159fbf1..32948c71 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -1530,11 +1530,14 @@ body.model-not-configured .main-content { flex-direction: column; }
spacer (`.chat-scroll-spacer`, 100vh) doesn't bloat the flex child past
its parent and break internal overflow scrolling. */
min-height: 0;
- /* Bottom: breathing room for the last bubble — the old 160px cushion is
- now provided by `margin-bottom` below (which also shrinks the scrollbar
- track clear of the floating input so the thumb stays visible when
- scrolled to the end). */
- padding: 24px 10%;
+ /* Bottom: 80px **inside** the scroll viewport so when the user
+ scrolls all the way down the last bubble has breathing room above
+ the floating input area / attachment chips. The 140px margin-bottom
+ keeps the scrollbar track clear of the floating input so the thumb
+ stays visible at the end. We use padding-bottom (NOT bigger margin)
+ because the goal is more whitespace inside the scroll view, not
+ pushing the viewport upward — that was the wrong fix earlier. */
+ padding: 24px 10% 80px;
margin-bottom: 140px;
overflow-y: auto;
display: flex;
@@ -4004,8 +4007,12 @@ body.model-not-configured .main-content { flex-direction: column; }
.agent-card-actions {
display: flex;
align-items: center;
- justify-content: flex-end;
+ justify-content: space-between;
+ gap: 8px;
}
+/* When no chip is present, the play button still hugs the right edge.
+ `margin-left: auto` plays nice with the absent-chip case. */
+.agent-card-actions > .agent-card-use { margin-left: auto; }
/* `.agent-card-use` shared with `.skill-card-use` / `.btn-icon-use` above. */
@@ -4103,7 +4110,6 @@ body.model-not-configured .main-content { flex-direction: column; }
}
.agents-detail-name {
- flex: 1;
min-width: 0;
font-size: 17px;
font-weight: 600;
@@ -4123,14 +4129,17 @@ body.model-not-configured .main-content { flex-direction: column; }
box-shadow: 0 0 0 2px var(--primary) inset;
}
+/* Sits on the same row as the agent name, mirroring the skill detail
+ header layout (.skills-doc-source). The title row is already a
+ wrapping flex container; this chip rides along with it. */
.agents-detail-source {
- margin-top: 8px;
font-size: 11px;
font-weight: 600;
display: inline-block;
padding: 2px 8px;
border-radius: 10px;
letter-spacing: 0.4px;
+ align-self: center;
}
.agents-detail-source.is-builtin { background: rgba(148, 163, 184, 0.15); color: #475569; }
.agents-detail-source.is-custom { background: rgba(37, 99, 235, 0.12); color: var(--primary); }
@@ -4506,7 +4515,12 @@ body.model-not-configured .main-content { flex-direction: column; }
top: calc(100% + 4px);
left: 0;
right: 0;
- z-index: 40;
+ /* Popovers portal to <body> at open time (see _aiSelectMount) so
+ they can escape parent overflow:auto. They must therefore beat
+ every overlay they could appear inside. `.modal-overlay` is 100,
+ `.ui-dialog-overlay` is 200, the avatar picker is 300, common
+ toasts top out at 1000 — pick a value above all of them. */
+ z-index: 1200;
background: #fff;
border: 1px solid var(--border, #e5e7eb);
border-radius: 8px;
@@ -5037,3 +5051,23 @@ body.model-not-configured .main-content { flex-direction: column; }
outline-offset: 2px;
transform: scale(1.05);
}
+
+/* Agent CLI badge — both grid card chip and detail header pill share
+ .is-cli; per-CLI tints are layered through .is-cli-<type> so future
+ styling can pick brand-specific accents without touching markup. */
+.agent-card-chip.is-cli {
+ display: inline-block;
+ padding: 2px 8px;
+ font-size: 11px;
+ font-weight: 600;
+ border-radius: 999px;
+ background: #eef2ff;
+ color: #3730a3;
+ white-space: nowrap;
+ vertical-align: middle;
+}
+/* Runtime selector lives at the top of the detail body; widget is
+ wider than a chip so it sits on its own row. Capped width keeps
+ the dropdown from spanning the entire body. */
+.agents-detail-runtime { display: block; }
+.agents-detail-runtime-select { max-width: 280px; }
diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.ts
index 80e49b60..cfb1db40 100644
--- a/test/main/features/agents.test.ts
+++ b/test/main/features/agents.test.ts
@@ -70,6 +70,7 @@ function writeCustomAgent(agentId: string, fields: Partial<Record<string, any>>
updated_at: '2026-04-18T10:00:00',
};
if ('skill_list' in fields) data.skill_list = fields.skill_list;
+ if ('runtime' in fields) data.runtime = fields.runtime;
fs.writeFileSync(path.join(dir, 'agent.json'), JSON.stringify(data));
}
@@ -179,6 +180,55 @@ describe('agents › normalizeAgent', () => {
expect('skill_list' in (norm as any)).toBe(false);
}
});
+
+ it('passes through a valid CLI runtime', async () => {
+ const a = await loadAgents();
+ const norm = a.normalizeAgent({
+ agent_id: 'x', name: 'N',
+ runtime: { kind: 'cli', cli: 'claude', model: 'claude-sonnet-4-6', custom_args: ['--debug'] },
+ } as any, 'custom');
+ expect(norm?.runtime).toEqual({
+ kind: 'cli', cli: 'claude', model: 'claude-sonnet-4-6', custom_args: ['--debug'],
+ });
+ expect(a.isCliAgent(norm)).toBe(true);
+ });
+
+ it('drops malformed runtime entries (no field set)', async () => {
+ const a = await loadAgents();
+ for (const bad of [
+ null,
+ 'cli',
+ { kind: 'wat' },
+ { kind: 'cli' }, // missing cli name
+ { kind: 'cli', cli: '' }, // empty cli name
+ ]) {
+ const norm = a.normalizeAgent({ agent_id: 'x', name: 'N', runtime: bad } as any, 'custom');
+ expect(norm).toBeTruthy();
+ expect('runtime' in (norm as any)).toBe(false);
+ expect(a.isCliAgent(norm)).toBe(false);
+ }
+ });
+
+ it('normalizes in_process runtime but does not flag as CLI', async () => {
+ const a = await loadAgents();
+ const norm = a.normalizeAgent({
+ agent_id: 'x', name: 'N',
+ runtime: { kind: 'in_process' },
+ } as any, 'custom');
+ expect(norm?.runtime).toEqual({ kind: 'in_process' });
+ expect(a.isCliAgent(norm)).toBe(false);
+ });
+
+ it('drops non-string custom_args entries', async () => {
+ const a = await loadAgents();
+ const norm = a.normalizeAgent({
+ agent_id: 'x', name: 'N',
+ runtime: { kind: 'cli', cli: 'claude', custom_args: ['--ok', 42, null, '--other'] as any },
+ } as any, 'custom');
+ expect(norm?.runtime).toEqual({
+ kind: 'cli', cli: 'claude', custom_args: ['--ok', '--other'],
+ });
+ });
});
describe('agents › isValidAgentId', () => {
@@ -586,6 +636,57 @@ describe('agents › updateCustomAgent', () => {
expect(after?.name).toBe('Old');
});
+ it('allows swapping which CLI backs a CLI agent (cli → cli)', async () => {
+ writeCustomAgent('abc', {
+ name: 'N',
+ runtime: { kind: 'cli', cli: 'claude' },
+ } as any);
+ const a = await loadAgents();
+ const updated = await a.updateCustomAgent('abc', {
+ runtime: { kind: 'cli', cli: 'codex' },
+ } as any);
+ expect(updated?.runtime).toEqual({ kind: 'cli', cli: 'codex' });
+ });
+
+ it('locks runtime kind: cli agent cannot revert to in_process', async () => {
+ writeCustomAgent('abc', {
+ name: 'N',
+ runtime: { kind: 'cli', cli: 'claude' },
+ } as any);
+ const a = await loadAgents();
+ // Attempt with explicit null (drop) — should be ignored.
+ const r1 = await a.updateCustomAgent('abc', { runtime: null } as any);
+ expect(r1?.runtime).toEqual({ kind: 'cli', cli: 'claude' });
+ // Attempt with kind:'in_process' — also ignored.
+ const r2 = await a.updateCustomAgent('abc', {
+ runtime: { kind: 'in_process' },
+ } as any);
+ expect(r2?.runtime).toEqual({ kind: 'cli', cli: 'claude' });
+ });
+
+ it('locks runtime kind: in_process agent cannot become cli post-create', async () => {
+ writeCustomAgent('abc', { name: 'N' });
+ const a = await loadAgents();
+ const r = await a.updateCustomAgent('abc', {
+ runtime: { kind: 'cli', cli: 'claude' },
+ } as any);
+ expect(r?.runtime).toBeUndefined();
+ });
+
+ it('strips workflow / skill_list updates on a CLI agent', async () => {
+ writeCustomAgent('abc', {
+ name: 'N',
+ runtime: { kind: 'cli', cli: 'claude' },
+ } as any);
+ const a = await loadAgents();
+ const updated = await a.updateCustomAgent('abc', {
+ workflow: 'should be ignored',
+ skill_list: ['x'],
+ });
+ expect(updated?.workflow).toBe('');
+ expect('skill_list' in (updated as any)).toBe(false);
+ });
+
it('coerces non-string values to empty string', async () => {
writeCustomAgent('abc', { name: 'N', description: 'D' });
const a = await loadAgents();
diff --git a/test/main/features/local_agents/acp_parser.test.ts b/test/main/features/local_agents/acp_parser.test.ts
new file mode 100644
index 00000000..c843afef
--- /dev/null
+++ b/test/main/features/local_agents/acp_parser.test.ts
@@ -0,0 +1,82 @@
+import { describe, it, expect, vi } from 'vitest';
+import { handleAcpMessage } from '../../../../src/main/features/local_agents/backends/_acp';
+
+function makeHandlers() {
+ return {
+ onSessionNew: vi.fn(),
+ onTextDelta: vi.fn(),
+ onToolUse: vi.fn(),
+ onToolResult: vi.fn(),
+ onPromptResult: vi.fn(),
+ onUnknown: vi.fn(),
+ };
+}
+
+describe('local_agents/backends/_acp › handleAcpMessage', () => {
+ it('routes session/new response to onSessionNew', () => {
+ const h = makeHandlers();
+ handleAcpMessage({ jsonrpc: '2.0', id: 2, result: { sessionId: 'sess-x' } }, h);
+ expect(h.onSessionNew).toHaveBeenCalledWith('sess-x');
+ });
+
+ it('routes session/update agent_message_chunk to onTextDelta', () => {
+ const h = makeHandlers();
+ handleAcpMessage({
+ jsonrpc: '2.0',
+ method: 'session/update',
+ params: { sessionId: 's', update: { kind: 'agent_message_chunk', content: { text: 'hello' } } },
+ }, h);
+ expect(h.onTextDelta).toHaveBeenCalledWith('hello');
+ });
+
+ it('routes tool_call to onToolUse', () => {
+ const h = makeHandlers();
+ handleAcpMessage({
+ method: 'session/update',
+ params: { update: { kind: 'tool_call', tool: { id: 'c1', name: 'read_file', input: { path: 'x.md' } } } },
+ }, h);
+ expect(h.onToolUse).toHaveBeenCalledWith({ name: 'read_file', callId: 'c1', input: { path: 'x.md' } });
+ });
+
+ it('routes tool_call_update to onToolResult, stringifying non-string output', () => {
+ const h = makeHandlers();
+ handleAcpMessage({
+ method: 'session/update',
+ params: { update: { kind: 'tool_call_update', tool: { id: 'c1', name: 'read_file', output: { lines: 4 } } } },
+ }, h);
+ expect(h.onToolResult).toHaveBeenCalledWith({ name: 'read_file', callId: 'c1', output: '{"lines":4}' });
+ });
+
+ it('marks prompt response (id=100) ok=true on end_turn', () => {
+ const h = makeHandlers();
+ handleAcpMessage({ id: 100, result: { stopReason: 'end_turn' } }, h);
+ expect(h.onPromptResult).toHaveBeenCalledWith({ ok: true, error: undefined });
+ });
+
+ it('marks prompt response ok=false for non-end_turn stop reasons', () => {
+ const h = makeHandlers();
+ handleAcpMessage({ id: 100, result: { stopReason: 'cancelled' } }, h);
+ expect(h.onPromptResult).toHaveBeenCalledWith({ ok: false, error: 'cancelled' });
+ });
+
+ it('marks prompt response ok=false on rpc error envelope', () => {
+ const h = makeHandlers();
+ handleAcpMessage({ id: 100, error: { message: 'auth fail' } }, h);
+ expect(h.onPromptResult).toHaveBeenCalledWith({ ok: false, error: 'auth fail' });
+ });
+
+ it('forwards unknown session/update kinds to onUnknown', () => {
+ const h = makeHandlers();
+ handleAcpMessage({
+ method: 'session/update',
+ params: { update: { kind: 'something_new', payload: 1 } },
+ }, h);
+ expect(h.onUnknown).toHaveBeenCalled();
+ });
+
+ it('ignores unrelated request errors silently', () => {
+ const h = makeHandlers();
+ handleAcpMessage({ id: 3, error: { message: 'unknown method' } }, h);
+ expect(h.onPromptResult).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/main/features/local_agents/claude_e2e.test.ts b/test/main/features/local_agents/claude_e2e.test.ts
new file mode 100644
index 00000000..225806d1
--- /dev/null
+++ b/test/main/features/local_agents/claude_e2e.test.ts
@@ -0,0 +1,105 @@
+/**
+ * End-to-end-ish smoke test for the claude backend without requiring
+ * the real `claude` CLI installed. We synthesize a tiny shell script
+ * that emits valid stream-json on stdout and then exits, then exercise
+ * `claudeBackend.run` against it. Skipped on Windows where /bin/sh
+ * isn't there — manual verification on Windows uses a real CLI.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import { claudeBackend } from '../../../../src/main/features/local_agents/backends/claude';
+
+const isWindows = process.platform === 'win32';
+
+function writeShellExecutable(dir: string, name: string, body: string): string {
+ const p = path.join(dir, name);
+ fs.writeFileSync(p, body);
+ fs.chmodSync(p, 0o755);
+ return p;
+}
+
+describe('local_agents/backends/claude › end-to-end with fake CLI', () => {
+ if (isWindows) {
+ it.skip('(skipped on Windows)', () => { /* */ });
+ return;
+ }
+
+ let tmpDir: string;
+
+ beforeEach(() => { tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-claude-e2e-')); });
+ afterEach(() => { fs.rmSync(tmpDir, { recursive: true, force: true }); });
+
+ it('parses a minimal completed conversation', async () => {
+ const fake = writeShellExecutable(tmpDir, 'claude', `#!/bin/sh
+# Read stdin and discard — claude is invoked with --input-format stream-json.
+cat > /dev/null
+cat <<'EOF'
+{"type":"system","subtype":"init","session_id":"sess-fake","cwd":"/x"}
+{"type":"assistant","message":{"content":[{"type":"text","text":"Hello "}]}}
+{"type":"assistant","message":{"content":[{"type":"text","text":"world."}]}}
+{"type":"result","subtype":"success","result":"Hello world.","total_cost_usd":0,"duration_ms":1}
+EOF
+`);
+ const events: any[] = [];
+ const ac = new AbortController();
+ await claudeBackend.run({
+ binPath: fake,
+ prompt: 'hi',
+ cwd: tmpDir,
+ signal: ac.signal,
+ onEvent: e => events.push(e),
+ timeoutMs: 5000,
+ });
+ const types = events.map(e => e.type);
+ expect(types).toContain('process-info');
+ expect(types).toContain('text-delta');
+ expect(types[types.length - 1]).toBe('done');
+ const done = events[events.length - 1];
+ expect(done.status).toBe('completed');
+ expect(done.output).toBe('Hello world.');
+ expect(done.sessionId).toBe('sess-fake');
+ });
+
+ it('reports failed status when the CLI exits non-zero', async () => {
+ const fake = writeShellExecutable(tmpDir, 'claude', `#!/bin/sh
+cat > /dev/null
+echo "boom: model unavailable" 1>&2
+exit 7
+`);
+ const events: any[] = [];
+ await claudeBackend.run({
+ binPath: fake,
+ prompt: 'hi', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ timeoutMs: 5000,
+ });
+ const done = events[events.length - 1];
+ expect(done.status).toBe('failed');
+ expect(done.error).toMatch(/exited with code 7|reported error/);
+ });
+
+ it('cancels mid-run via AbortSignal (SIGTERM)', async () => {
+ const fake = writeShellExecutable(tmpDir, 'claude', `#!/bin/sh
+cat > /dev/null
+# Stay alive long enough to be killed.
+sleep 10
+`);
+ const events: any[] = [];
+ const ac = new AbortController();
+ const promise = claudeBackend.run({
+ binPath: fake,
+ prompt: 'hi', cwd: tmpDir,
+ signal: ac.signal,
+ onEvent: e => events.push(e),
+ timeoutMs: 30_000,
+ });
+ setTimeout(() => ac.abort(), 100);
+ await promise;
+ const done = events[events.length - 1];
+ expect(done.status).toBe('cancelled');
+ });
+});
diff --git a/test/main/features/local_agents/claude_parser.test.ts b/test/main/features/local_agents/claude_parser.test.ts
new file mode 100644
index 00000000..a60e465e
--- /dev/null
+++ b/test/main/features/local_agents/claude_parser.test.ts
@@ -0,0 +1,96 @@
+import { describe, it, expect } from 'vitest';
+import { mapClaudeEvent } from '../../../../src/main/features/local_agents/backends/claude';
+
+describe('local_agents/backends/claude › mapClaudeEvent', () => {
+ it('captures session id from system/init', () => {
+ const r = mapClaudeEvent({ type: 'system', subtype: 'init', session_id: 'sess-1', cwd: '/x' }, undefined);
+ expect(r?.captureSession).toBe(true);
+ expect(r?.event).toBeUndefined();
+ });
+
+ it('emits text-delta for assistant text content (fallback when no stream_event)', () => {
+ const r = mapClaudeEvent({ type: 'assistant', message: { content: [{ type: 'text', text: 'hi' }] } }, 'sess');
+ expect(r?.event).toEqual({ type: 'text-delta', text: 'hi' });
+ });
+
+ it('skips assistant text when stream_event already streamed it', () => {
+ const state = { sawTextStreamEvent: true };
+ const r = mapClaudeEvent({ type: 'assistant', message: { content: [{ type: 'text', text: 'hi' }] } }, 'sess', state);
+ expect(r).toBeUndefined();
+ });
+
+ it('emits text-delta from stream_event content_block_delta', () => {
+ const state = { sawTextStreamEvent: false };
+ const r = mapClaudeEvent({
+ type: 'stream_event',
+ event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'tok' } },
+ }, undefined, state);
+ expect(r?.event).toEqual({ type: 'text-delta', text: 'tok' });
+ expect(state.sawTextStreamEvent).toBe(true);
+ });
+
+ it('emits thinking from stream_event content_block_delta', () => {
+ const r = mapClaudeEvent({
+ type: 'stream_event',
+ event: { type: 'content_block_delta', delta: { type: 'thinking_delta', thinking: 'why' } },
+ }, undefined);
+ expect(r?.event).toEqual({ type: 'thinking', text: 'why' });
+ });
+
+ it('emits thinking for assistant thinking block (fallback)', () => {
+ const r = mapClaudeEvent({ type: 'assistant', message: { content: [{ type: 'thinking', thinking: 'pondering' }] } }, 'sess');
+ expect(r?.event).toEqual({ type: 'thinking', text: 'pondering' });
+ });
+
+ it('emits tool-event(use) from stream_event content_block_start', () => {
+ const r = mapClaudeEvent({
+ type: 'stream_event',
+ event: { type: 'content_block_start', content_block: { type: 'tool_use', id: 't1', name: 'Read', input: { file: 'x.md' } } },
+ }, undefined);
+ expect(r?.event).toMatchObject({ type: 'tool-event', tool: 'Read', callId: 't1', phase: 'use' });
+ });
+
+ it('emits tool-event(use) for assistant tool_use block', () => {
+ const r = mapClaudeEvent({
+ type: 'assistant',
+ message: { content: [{ type: 'tool_use', id: 't1', name: 'Read', input: { file: 'x.md' } }] },
+ }, 'sess');
+ expect(r?.event).toMatchObject({ type: 'tool-event', tool: 'Read', callId: 't1', phase: 'use' });
+ expect((r?.event as any).input).toEqual({ file: 'x.md' });
+ });
+
+ it('emits tool-event(result) for user tool_result block', () => {
+ const r = mapClaudeEvent({
+ type: 'user',
+ message: { content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] },
+ }, 'sess');
+ expect(r?.event).toMatchObject({ type: 'tool-event', tool: 'tool_result', callId: 't1', phase: 'result', output: 'ok' });
+ });
+
+ it('joins text parts when tool_result content is an array', () => {
+ const r = mapClaudeEvent({
+ type: 'user',
+ message: { content: [{ type: 'tool_result', tool_use_id: 't1', content: [
+ { type: 'text', text: 'line1' },
+ { type: 'text', text: 'line2' },
+ ] }] },
+ }, 'sess');
+ expect((r?.event as any).output).toBe('line1\nline2');
+ });
+
+ it('marks result(success) as terminal completed with body', () => {
+ const r = mapClaudeEvent({ type: 'result', subtype: 'success', result: 'final body' }, 'sess');
+ expect(r?.terminal).toEqual({ status: 'completed', text: 'final body', error: undefined });
+ });
+
+ it('marks result(error_*) as terminal failed', () => {
+ const r = mapClaudeEvent({ type: 'result', subtype: 'error_max_turns', error: 'too many turns' }, 'sess');
+ expect(r?.terminal).toEqual({ status: 'failed', text: '', error: 'too many turns' });
+ });
+
+ it('returns undefined for unknown / null records', () => {
+ expect(mapClaudeEvent(null, undefined)).toBeUndefined();
+ expect(mapClaudeEvent({ type: 'unknown' }, undefined)).toBeUndefined();
+ expect(mapClaudeEvent({ type: 'assistant', message: { content: [] } }, undefined)).toBeUndefined();
+ });
+});
diff --git a/test/main/features/local_agents/registry.test.ts b/test/main/features/local_agents/registry.test.ts
new file mode 100644
index 00000000..b16c58ec
--- /dev/null
+++ b/test/main/features/local_agents/registry.test.ts
@@ -0,0 +1,129 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {
+ detectAll,
+ detectOne,
+ invalidateCache,
+ LOCAL_CLI_TYPES,
+} from '../../../../src/main/features/local_agents/registry';
+
+const isWindows = process.platform === 'win32';
+
+describe('local_agents/registry', () => {
+ let tmpDir: string;
+ let savedPath: string | undefined;
+ let savedEnvOverrides: Record<string, string | undefined> = {};
+
+ const ENV_KEYS = [
+ 'ORKAS_CLAUDE_PATH',
+ 'ORKAS_CODEX_PATH',
+ 'ORKAS_OPENCLAW_PATH',
+ 'ORKAS_OPENCODE_PATH',
+ 'ORKAS_HERMES_PATH',
+ ];
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-registry-'));
+ savedPath = process.env.PATH;
+ savedEnvOverrides = {};
+ for (const k of ENV_KEYS) {
+ savedEnvOverrides[k] = process.env[k];
+ delete process.env[k];
+ }
+ invalidateCache();
+ });
+
+ afterEach(() => {
+ process.env.PATH = savedPath;
+ for (const k of ENV_KEYS) {
+ const v = savedEnvOverrides[k];
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ invalidateCache();
+ });
+
+ it('returns one entry per known CLI type', async () => {
+ process.env.PATH = '';
+ const result = await detectAll();
+ const types = result.map(r => r.type).sort();
+ expect(types).toEqual([...LOCAL_CLI_TYPES].sort());
+ });
+
+ it('marks not_found when binary missing on PATH', async () => {
+ process.env.PATH = tmpDir;
+ const r = await detectOne('opencode');
+ expect(r.available).toBe(false);
+ expect(r.error).toBe('not_found');
+ expect(r.type).toBe('opencode');
+ });
+
+ it('honors ORKAS_<TYPE>_PATH override', async () => {
+ if (isWindows) return; // covered by which.test.ts on Windows
+ const fake = path.join(tmpDir, 'my-claude');
+ // Print a version that satisfies the claude minimum so it ends up "available".
+ fs.writeFileSync(fake, '#!/bin/sh\necho "2.0.0"\n');
+ fs.chmodSync(fake, 0o755);
+ process.env.PATH = '';
+ process.env.ORKAS_CLAUDE_PATH = fake;
+
+ const r = await detectOne('claude');
+ expect(r.path).toBe(fake);
+ expect(r.version).toBe('2.0.0');
+ expect(r.available).toBe(true);
+ expect(r.error).toBeUndefined();
+ });
+
+ it('marks version_too_old when below minimum', async () => {
+ if (isWindows) return;
+ const fake = path.join(tmpDir, 'old-claude');
+ fs.writeFileSync(fake, '#!/bin/sh\necho "1.5.0"\n');
+ fs.chmodSync(fake, 0o755);
+ process.env.PATH = '';
+ process.env.ORKAS_CLAUDE_PATH = fake;
+
+ const r = await detectOne('claude');
+ expect(r.available).toBe(false);
+ expect(r.error).toBe('version_too_old');
+ expect(r.errorDetail).toMatch(/below required minimum/);
+ });
+
+ it('marks version_unknown when --version output has no semver', async () => {
+ if (isWindows) return;
+ const fake = path.join(tmpDir, 'mute-cli');
+ fs.writeFileSync(fake, '#!/bin/sh\necho "no version"\n');
+ fs.chmodSync(fake, 0o755);
+ process.env.PATH = '';
+ process.env.ORKAS_OPENCODE_PATH = fake;
+
+ const r = await detectOne('opencode');
+ expect(r.available).toBe(false);
+ expect(r.error).toBe('version_unknown');
+ expect(r.path).toBe(fake);
+ });
+
+ it('detectAll caches results within the TTL window', async () => {
+ if (isWindows) return;
+ const fake = path.join(tmpDir, 'ok-opencode');
+ fs.writeFileSync(fake, '#!/bin/sh\necho "0.10.0"\n');
+ fs.chmodSync(fake, 0o755);
+ process.env.PATH = '';
+ process.env.ORKAS_OPENCODE_PATH = fake;
+
+ const first = await detectAll();
+ const opencodeFirst = first.find(e => e.type === 'opencode')!;
+ expect(opencodeFirst.available).toBe(true);
+
+ // Delete the binary; cached result should still report available.
+ fs.rmSync(fake);
+ const cached = await detectAll();
+ expect(cached.find(e => e.type === 'opencode')!.available).toBe(true);
+
+ // Force re-detect bypasses cache.
+ const fresh = await detectAll({ force: true });
+ expect(fresh.find(e => e.type === 'opencode')!.available).toBe(false);
+ });
+});
diff --git a/test/main/features/local_agents/runner.test.ts b/test/main/features/local_agents/runner.test.ts
new file mode 100644
index 00000000..cc81f4ad
--- /dev/null
+++ b/test/main/features/local_agents/runner.test.ts
@@ -0,0 +1,197 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+
+// Mocks must be declared at top-level for vi to hoist them. The
+// registry mock keeps real exports but swaps `detectOne`; the claude
+// backend is fully replaced by a controllable stub.
+const mockDetect = vi.fn<[string], Promise<any>>();
+vi.mock('../../../../src/main/features/local_agents/registry', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../../src/main/features/local_agents/registry')>();
+ return {
+ ...actual,
+ detectOne: (type: string) => mockDetect(type),
+ };
+});
+
+let mockBackendImpl: ((opts: any) => Promise<void>) | null = null;
+vi.mock('../../../../src/main/features/local_agents/backends/claude', () => ({
+ claudeBackend: {
+ run: (opts: any) => (mockBackendImpl ? mockBackendImpl(opts) : Promise.resolve()),
+ },
+}));
+
+let tmpDir: string;
+let prevWs: string | undefined;
+const TEST_UID = 'u1';
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-runner-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+ const users = await import('../../../../src/main/features/users');
+ users.activateUser(TEST_UID);
+ mockDetect.mockReset();
+ mockBackendImpl = null;
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function loadRunner() {
+ return import('../../../../src/main/features/local_agents/runner');
+}
+
+describe('local_agents/runner', () => {
+ it('emits missing_cli when registry reports unavailable', async () => {
+ mockDetect.mockResolvedValue({
+ type: 'claude', available: false, path: null, version: null,
+ error: 'not_found', errorDetail: 'no claude on PATH',
+ });
+ const runner = await loadRunner();
+ const events: any[] = [];
+ const result = await runner.run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ cli: 'claude', prompt: 'hi', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+ expect(result.status).toBe('missing_cli');
+ const done = events.find(e => e.type === 'done');
+ expect(done?.status).toBe('missing_cli');
+ expect(done?.error).toMatch(/no claude on PATH/);
+ expect(result.runId).toBe(''); // no persistence for missing
+ });
+
+ it('persists prompt + events.jsonl + meta.json on a completed run', async () => {
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ mockBackendImpl = async ({ onEvent }) => {
+ onEvent({ type: 'process-info', pid: 42, cwd: '/x', cmd: 'claude', args: [] });
+ onEvent({ type: 'text-delta', text: 'hello ' });
+ onEvent({ type: 'text-delta', text: 'world' });
+ onEvent({ type: 'done', status: 'completed', output: 'hello world', durationMs: 12 });
+ };
+ const runner = await loadRunner();
+ const events: any[] = [];
+ const result = await runner.run({
+ uid: TEST_UID, cid: 'c', agentId: 'agent-x',
+ cli: 'claude', prompt: 'do work', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+ expect(result.status).toBe('completed');
+ expect(result.output).toBe('hello world');
+ expect(result.runId).toMatch(/^[0-9a-f]{12}$/);
+
+ const dir = path.join(tmpDir, TEST_UID, 'local', 'file_cache', 'local-agent-runs', result.runId);
+ expect(fs.existsSync(dir)).toBe(true);
+ expect(fs.readFileSync(path.join(dir, 'prompt.txt'), 'utf8')).toBe('do work');
+ const eventLines = fs.readFileSync(path.join(dir, 'events.jsonl'), 'utf8').trim().split('\n');
+ expect(eventLines.length).toBe(4);
+ expect(JSON.parse(eventLines[0]).type).toBe('process-info');
+ expect(JSON.parse(eventLines[3]).type).toBe('done');
+ expect(fs.readFileSync(path.join(dir, 'output.txt'), 'utf8')).toBe('hello world');
+ const meta = JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8'));
+ expect(meta.status).toBe('completed');
+ expect(meta.cli).toBe('claude');
+ expect(meta.cliPath).toBe('/fake/claude');
+ expect(meta.endedAt).toBeTruthy();
+ });
+
+ it('reports backend exception as a failed done event', async () => {
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ mockBackendImpl = async () => { throw new Error('spawn went sideways'); };
+ const runner = await loadRunner();
+ const events: any[] = [];
+ const result = await runner.run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ cli: 'claude', prompt: 'p', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+ expect(result.status).toBe('failed');
+ const done = events.find(e => e.type === 'done');
+ expect(done?.error).toMatch(/spawn went sideways/);
+ });
+
+ it('falls back to a synthetic failed done when backend exits without one', async () => {
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ mockBackendImpl = async () => { /* no events at all */ };
+ const runner = await loadRunner();
+ const events: any[] = [];
+ const result = await runner.run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ cli: 'claude', prompt: 'p', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+ expect(result.status).toBe('failed');
+ expect(events.some(e => e.type === 'done')).toBe(true);
+ });
+
+ it('forwards AbortSignal — backend reports cancelled, runner relays', async () => {
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ mockBackendImpl = async ({ signal, onEvent }) => {
+ onEvent({ type: 'process-info', pid: 1, cwd: '/x', cmd: 'claude', args: [] });
+ // Simulate abort midway: when the signal fires, emit done(cancelled).
+ await new Promise<void>(resolve => {
+ if (signal.aborted) { resolve(); return; }
+ signal.addEventListener('abort', () => resolve(), { once: true });
+ });
+ onEvent({ type: 'done', status: 'cancelled', durationMs: 5 });
+ };
+ const ac = new AbortController();
+ const events: any[] = [];
+ const promise = (await import('../../../../src/main/features/local_agents/runner')).run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ cli: 'claude', prompt: 'p', cwd: tmpDir,
+ signal: ac.signal,
+ onEvent: e => events.push(e),
+ });
+ setTimeout(() => ac.abort(), 10);
+ const result = await promise;
+ expect(result.status).toBe('cancelled');
+ const meta = JSON.parse(fs.readFileSync(path.join(
+ tmpDir, TEST_UID, 'local', 'file_cache', 'local-agent-runs', result.runId, 'meta.json',
+ ), 'utf8'));
+ expect(meta.status).toBe('cancelled');
+ });
+
+ it('records timeout terminal status when backend reports it', async () => {
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ mockBackendImpl = async ({ onEvent, timeoutMs }) => {
+ // Backend honors timeoutMs internally; here we simulate it firing.
+ expect(timeoutMs).toBeGreaterThan(0);
+ onEvent({ type: 'done', status: 'timeout', error: 'cli exceeded timeout', durationMs: timeoutMs });
+ };
+ const events: any[] = [];
+ const result = await (await import('../../../../src/main/features/local_agents/runner')).run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ cli: 'claude', prompt: 'p', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+ expect(result.status).toBe('timeout');
+ expect(result.error).toMatch(/timeout/);
+ });
+
+ it('rejects unregistered CLI types cleanly', async () => {
+ const runner = await loadRunner();
+ const events: any[] = [];
+ const result = await runner.run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ // 'kimi' is a known type name but not registered yet (kept out of
+ // v1 backends on purpose). Any future addition needs the test
+ // pointed at a fresher placeholder.
+ cli: 'kimi' as any, prompt: 'p', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+ expect(result.status).toBe('failed');
+ expect(result.error).toMatch(/not implemented/);
+ });
+});
diff --git a/test/main/features/local_agents/sessions.test.ts b/test/main/features/local_agents/sessions.test.ts
new file mode 100644
index 00000000..d3604a15
--- /dev/null
+++ b/test/main/features/local_agents/sessions.test.ts
@@ -0,0 +1,106 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+
+let tmpDir: string;
+let prevWs: string | undefined;
+const TEST_UID = 'u1';
+const TEST_CID = 'c1';
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-sessions-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function loadSessions() {
+ return import('../../../../src/main/features/local_agents/sessions');
+}
+
+describe('local_agents/sessions', () => {
+ it('returns null when no binding exists', async () => {
+ const s = await loadSessions();
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude')).toBeNull();
+ });
+
+ it('round-trips a session id for the same (cid, aid, cli)', async () => {
+ const s = await loadSessions();
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude', 'sess-1');
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude')).toBe('sess-1');
+ });
+
+ it('invalidates the binding when the CLI changes (runtime swap)', async () => {
+ const s = await loadSessions();
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude', 'sess-1');
+ // Same agent, different CLI → stale; should miss.
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-x', 'codex')).toBeNull();
+ // Original binding still readable for the original CLI.
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude')).toBe('sess-1');
+ });
+
+ it('overwrites the binding when set is called again', async () => {
+ const s = await loadSessions();
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude', 'sess-1');
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude', 'sess-2');
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude')).toBe('sess-2');
+ });
+
+ it('isolates bindings per agent', async () => {
+ const s = await loadSessions();
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-a', 'claude', 'sess-a');
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-b', 'claude', 'sess-b');
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-a', 'claude')).toBe('sess-a');
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-b', 'claude')).toBe('sess-b');
+ });
+
+ it('clearForAgent drops only the targeted entry; deletes file when last', async () => {
+ const s = await loadSessions();
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-a', 'claude', 'sess-a');
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-b', 'claude', 'sess-b');
+ await s.clearForAgent(TEST_UID, TEST_CID, 'agent-a');
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-a', 'claude')).toBeNull();
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-b', 'claude')).toBe('sess-b');
+ await s.clearForAgent(TEST_UID, TEST_CID, 'agent-b');
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-b', 'claude')).toBeNull();
+ });
+
+ it('clearForConversation removes the file entirely', async () => {
+ const s = await loadSessions();
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-a', 'claude', 'sess-a');
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-b', 'claude', 'sess-b');
+ await s.clearForConversation(TEST_UID, TEST_CID);
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-a', 'claude')).toBeNull();
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-b', 'claude')).toBeNull();
+ // File must be gone, not just empty.
+ const file = path.join(tmpDir, TEST_UID, 'local', 'cli-sessions', `${TEST_CID}.json`);
+ expect(fs.existsSync(file)).toBe(false);
+ });
+
+ it('clearForConversation is a no-op when nothing exists', async () => {
+ const s = await loadSessions();
+ await expect(s.clearForConversation(TEST_UID, TEST_CID)).resolves.toBeUndefined();
+ });
+
+ it('setSessionId with empty id is a no-op', async () => {
+ const s = await loadSessions();
+ await s.setSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude', '');
+ expect(await s.getSessionId(TEST_UID, TEST_CID, 'agent-x', 'claude')).toBeNull();
+ });
+
+ it('isolates bindings per conversation', async () => {
+ const s = await loadSessions();
+ await s.setSessionId(TEST_UID, 'c1', 'agent-a', 'claude', 'sess-c1');
+ await s.setSessionId(TEST_UID, 'c2', 'agent-a', 'claude', 'sess-c2');
+ expect(await s.getSessionId(TEST_UID, 'c1', 'agent-a', 'claude')).toBe('sess-c1');
+ expect(await s.getSessionId(TEST_UID, 'c2', 'agent-a', 'claude')).toBe('sess-c2');
+ await s.clearForConversation(TEST_UID, 'c1');
+ expect(await s.getSessionId(TEST_UID, 'c1', 'agent-a', 'claude')).toBeNull();
+ expect(await s.getSessionId(TEST_UID, 'c2', 'agent-a', 'claude')).toBe('sess-c2');
+ });
+});
diff --git a/test/main/features/local_agents/version.test.ts b/test/main/features/local_agents/version.test.ts
new file mode 100644
index 00000000..23a8f6c3
--- /dev/null
+++ b/test/main/features/local_agents/version.test.ts
@@ -0,0 +1,114 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {
+ parseSemver,
+ compareSemver,
+ checkMinVersion,
+ detectVersion,
+ MIN_VERSIONS,
+} from '../../../../src/main/features/local_agents/version';
+
+const isWindows = process.platform === 'win32';
+
+describe('local_agents/version › parseSemver', () => {
+ it('parses bare semver', () => {
+ expect(parseSemver('2.1.100')).toEqual({ major: 2, minor: 1, patch: 100 });
+ });
+
+ it('parses v-prefixed semver', () => {
+ expect(parseSemver('v0.99.0')).toEqual({ major: 0, minor: 99, patch: 0 });
+ });
+
+ it('parses semver embedded in a longer line', () => {
+ expect(parseSemver('claude 2.1.100 (Claude Code)')).toEqual({ major: 2, minor: 1, patch: 100 });
+ });
+
+ it('returns null for non-semver', () => {
+ expect(parseSemver('beta')).toBeNull();
+ expect(parseSemver('')).toBeNull();
+ });
+
+ it('returns null for non-string input', () => {
+ expect(parseSemver(undefined as unknown as string)).toBeNull();
+ expect(parseSemver(null as unknown as string)).toBeNull();
+ });
+});
+
+describe('local_agents/version › compareSemver', () => {
+ it('orders by major / minor / patch', () => {
+ const a = parseSemver('1.0.0')!;
+ const b = parseSemver('1.0.1')!;
+ const c = parseSemver('2.0.0')!;
+ expect(compareSemver(a, b)).toBe(-1);
+ expect(compareSemver(b, a)).toBe(1);
+ expect(compareSemver(a, a)).toBe(0);
+ expect(compareSemver(c, b)).toBe(1);
+ });
+});
+
+describe('local_agents/version › checkMinVersion', () => {
+ it('returns null when CLI has no minimum', () => {
+ expect(checkMinVersion('opencode', '0.1.0')).toBeNull();
+ expect(checkMinVersion('hermes', '0.0.0')).toBeNull();
+ });
+
+ it('returns null when detected meets/exceeds the minimum', () => {
+ expect(checkMinVersion('claude', MIN_VERSIONS.claude)).toBeNull();
+ expect(checkMinVersion('claude', '2.5.0')).toBeNull();
+ expect(checkMinVersion('claude', '3.0.0')).toBeNull();
+ });
+
+ it('returns an explanatory string when detected is below minimum', () => {
+ const msg = checkMinVersion('claude', '1.99.0');
+ expect(msg).toMatch(/below required minimum/);
+ expect(msg).toContain('claude');
+ expect(msg).toContain('1.99.0');
+ });
+
+ it('returns null when detected is missing or unparsable (do not gate on noise)', () => {
+ expect(checkMinVersion('claude', null)).toBeNull();
+ expect(checkMinVersion('claude', 'beta')).toBeNull();
+ });
+});
+
+describe('local_agents/version › detectVersion', () => {
+ let tmpDir: string;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-detect-version-'));
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ it('extracts the semver from --version stdout', async () => {
+ if (isWindows) return; // Windows .cmd version harness is brittle; covered indirectly.
+ const binPath = path.join(tmpDir, 'fake-cli');
+ fs.writeFileSync(binPath, '#!/bin/sh\necho "claude 2.1.100 (Claude Code)"\n');
+ fs.chmodSync(binPath, 0o755);
+ expect(await detectVersion(binPath)).toBe('2.1.100');
+ });
+
+ it('falls back to stderr when stdout is empty', async () => {
+ if (isWindows) return;
+ const binPath = path.join(tmpDir, 'fake-cli-stderr');
+ fs.writeFileSync(binPath, '#!/bin/sh\necho "v0.50.0" 1>&2\n');
+ fs.chmodSync(binPath, 0o755);
+ expect(await detectVersion(binPath)).toBe('0.50.0');
+ });
+
+ it('returns null when binary cannot run', async () => {
+ expect(await detectVersion(path.join(tmpDir, 'nonexistent'))).toBeNull();
+ });
+
+ it('returns null when output has no semver', async () => {
+ if (isWindows) return;
+ const binPath = path.join(tmpDir, 'noisy-cli');
+ fs.writeFileSync(binPath, '#!/bin/sh\necho "no version here"\n');
+ fs.chmodSync(binPath, 0o755);
+ expect(await detectVersion(binPath)).toBeNull();
+ });
+});
diff --git a/test/main/features/local_agents/which.test.ts b/test/main/features/local_agents/which.test.ts
new file mode 100644
index 00000000..68030e0a
--- /dev/null
+++ b/test/main/features/local_agents/which.test.ts
@@ -0,0 +1,94 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import { whichBin } from '../../../../src/main/features/local_agents/which';
+
+const isWindows = process.platform === 'win32';
+
+describe('local_agents/which › whichBin', () => {
+ let tmpDir: string;
+ let savedPath: string | undefined;
+ let savedPathExt: string | undefined;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-which-'));
+ savedPath = process.env.PATH;
+ savedPathExt = process.env.PATHEXT;
+ });
+
+ afterEach(() => {
+ process.env.PATH = savedPath;
+ if (savedPathExt === undefined) delete process.env.PATHEXT;
+ else process.env.PATHEXT = savedPathExt;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ it('returns null for empty name', async () => {
+ expect(await whichBin('')).toBeNull();
+ });
+
+ it('returns null when PATH is empty', async () => {
+ process.env.PATH = '';
+ expect(await whichBin('anything')).toBeNull();
+ });
+
+ it('returns null when binary does not exist anywhere on PATH', async () => {
+ process.env.PATH = tmpDir;
+ expect(await whichBin('does-not-exist-' + Date.now())).toBeNull();
+ });
+
+ if (!isWindows) {
+ it('finds an executable file on POSIX PATH', async () => {
+ const binPath = path.join(tmpDir, 'fakebin');
+ fs.writeFileSync(binPath, '#!/bin/sh\necho hi\n');
+ fs.chmodSync(binPath, 0o755);
+ process.env.PATH = tmpDir;
+ expect(await whichBin('fakebin')).toBe(binPath);
+ });
+
+ it('rejects a non-executable file on POSIX (no x bit)', async () => {
+ const binPath = path.join(tmpDir, 'plain');
+ fs.writeFileSync(binPath, 'not exec\n');
+ fs.chmodSync(binPath, 0o644);
+ process.env.PATH = tmpDir;
+ expect(await whichBin('plain')).toBeNull();
+ });
+
+ it('returns the first match when multiple PATH entries have it', async () => {
+ const a = fs.mkdtempSync(path.join(tmpDir, 'a-'));
+ const b = fs.mkdtempSync(path.join(tmpDir, 'b-'));
+ const ap = path.join(a, 'foo');
+ const bp = path.join(b, 'foo');
+ fs.writeFileSync(ap, ''); fs.chmodSync(ap, 0o755);
+ fs.writeFileSync(bp, ''); fs.chmodSync(bp, 0o755);
+ process.env.PATH = `${a}${path.delimiter}${b}`;
+ expect(await whichBin('foo')).toBe(ap);
+ });
+ }
+
+ if (isWindows) {
+ it('respects PATHEXT on Windows', async () => {
+ const binPath = path.join(tmpDir, 'thing.CMD');
+ fs.writeFileSync(binPath, '@echo hi\r\n');
+ process.env.PATH = tmpDir;
+ process.env.PATHEXT = '.COM;.EXE;.BAT;.CMD';
+ const r = await whichBin('thing');
+ expect(r?.toLowerCase()).toBe(binPath.toLowerCase());
+ });
+ }
+
+ it('accepts an absolute path that points at an existing executable', async () => {
+ const binPath = path.join(tmpDir, isWindows ? 'p.cmd' : 'p');
+ fs.writeFileSync(binPath, '');
+ if (!isWindows) fs.chmodSync(binPath, 0o755);
+ process.env.PATH = '';
+ if (isWindows) process.env.PATHEXT = '.CMD';
+ const r = await whichBin(binPath);
+ expect(r).toBe(path.resolve(binPath));
+ });
+
+ it('returns null for absolute path that does not exist', async () => {
+ expect(await whichBin(path.join(tmpDir, 'never-existed'))).toBeNull();
+ });
+});