Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(hetero): report missing gateway working directories (#18431)

AmAzing-9a95eb70b602
diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.ts
index f81147d0f9a..1b39d7e691d 100644
--- a/apps/cli/src/device/agentRun.test.ts
+++ b/apps/cli/src/device/agentRun.test.ts
@@ -1,12 +1,26 @@
import { EventEmitter } from 'node:events';
+import { statSync } from 'node:fs';
+import os from 'node:os';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { spawnHeteroAgentRun } from './agentRun';
const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));
vi.mock('node:child_process', () => ({ spawn: spawnMock }));
+// `resolveHeteroSpawnCwd` stats the candidate directories; treat every path as
+// an existing directory unless a test says otherwise.
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return { ...actual, statSync: vi.fn() };
+});
+
+const asDirectory = { isDirectory: () => true } as ReturnType<typeof statSync>;
+const mockMissingDir = (missing: string) =>
+ vi
+ .mocked(statSync)
+ .mockImplementation((candidate) => (candidate === missing ? undefined : asDirectory) as never);
const makeFakeChild = () => {
const child = new EventEmitter() as EventEmitter & {
@@ -27,6 +41,10 @@ const baseParams = {
};
describe('spawnHeteroAgentRun', () => {
+ beforeEach(() => {
+ vi.mocked(statSync).mockReturnValue(asDirectory);
+ });
+
afterEach(() => {
spawnMock.mockReset();
});
@@ -84,14 +102,34 @@ describe('spawnHeteroAgentRun', () => {
expect(child.stdin.end).toHaveBeenCalledTimes(1);
});
- it('rejects (no stuck run) when the child errors before spawning, e.g. bad cwd', async () => {
+ it('starts the wrapper from home so its inner preflight can report a missing cwd', async () => {
+ const missingCwd = '/missing';
+ const child = makeFakeChild();
+ spawnMock.mockReturnValue(child);
+ mockMissingDir(missingCwd);
+
+ const ackPromise = spawnHeteroAgentRun({ ...baseParams, cwd: missingCwd });
+
+ const [, args, options] = spawnMock.mock.calls[0];
+ const cwdArgIndex = args.indexOf('--cwd');
+ expect(options.cwd).toBe(os.homedir());
+ expect(args[cwdArgIndex + 1]).toBe(missingCwd);
+ child.emit('spawn');
+
+ await expect(ackPromise).resolves.toEqual({ status: 'accepted' });
+ expect(child.stdin.write).toHaveBeenCalledWith(JSON.stringify('hi'));
+ });
+
+ it('rejects when the wrapper process still fails to spawn from the fallback cwd', async () => {
+ const missingCwd = '/missing';
const child = makeFakeChild();
spawnMock.mockReturnValue(child);
+ mockMissingDir(missingCwd);
- const ackPromise = spawnHeteroAgentRun({ ...baseParams, cwd: '/missing' });
- child.emit('error', new Error('spawn ENOENT'));
+ const ackPromise = spawnHeteroAgentRun({ ...baseParams, cwd: missingCwd });
+ child.emit('error', new Error('spawn EACCES'));
- await expect(ackPromise).resolves.toEqual({ reason: 'spawn ENOENT', status: 'rejected' });
+ await expect(ackPromise).resolves.toEqual({ reason: 'spawn EACCES', status: 'rejected' });
expect(child.stdin.write).not.toHaveBeenCalled();
});
diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.ts
index 2476e364187..c42900a7069 100644
--- a/apps/cli/src/device/agentRun.ts
+++ b/apps/cli/src/device/agentRun.ts
@@ -4,6 +4,7 @@ import {
buildHeteroExecStdinPayload,
type HeteroExecImageRef,
} from '@lobechat/heterogeneous-agents/protocol';
+import { resolveHeteroSpawnCwd } from '@lobechat/heterogeneous-agents/workingDirectory';
export interface SpawnHeteroAgentRunParams {
agentType: string;
@@ -47,11 +48,9 @@ interface SpawnHeteroAgentRunLogger {
* detached `lh connect --daemon` child where `PATH` may be minimal.
*
* Resolves only once the child's outcome is known: `accepted` on the `spawn`
- * event, `rejected` on an early `error`. `spawn()` reports failures (missing or
- * inaccessible `cwd`, etc.) asynchronously via `error`, so acking eagerly would
- * report a false success and leave the run with no process to emit
- * `heteroFinish` β€” surfacing as a stuck assistant message. A rejected ack
- * instead flows back as a dispatch failure the user can see.
+ * event, `rejected` on an early wrapper-process `error`. A missing target cwd
+ * is handled inside `lh hetero exec`, which can classify it and emit
+ * `heteroFinish`; other wrapper spawn failures flow back as rejected dispatches.
*/
export function spawnHeteroAgentRun(
params: SpawnHeteroAgentRunParams,
@@ -74,6 +73,10 @@ export function spawnHeteroAgentRun(
workspaceId,
} = params;
const workDir = cwd ?? process.cwd();
+ // A stale project path must not prevent the wrapper CLI from starting: the
+ // inner spawnAgent preflight owns cwd classification and reports the
+ // structured working_directory_not_found error through heteroFinish.
+ const spawnCwd = resolveHeteroSpawnCwd(workDir);
// Server-ingest mode (--topic + --operation-id): events are batch-POSTed to
// the server, not rendered. `--input-json -` reads the prompt from stdin.
@@ -117,7 +120,7 @@ export function spawnHeteroAgentRun(
};
const child = spawn(process.execPath, [...process.execArgv, ...cliArgs], {
- cwd: workDir,
+ cwd: spawnCwd,
env: {
...process.env,
...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 89ca41f2c68..f11cd385531 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -71,6 +71,11 @@ import {
TraeAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
import { truncateTitle } from '@lobechat/heterogeneous-agents/transcript';
+import {
+ describeUnusableWorkingDirectory,
+ isSpawnableDirectory,
+ resolveHeteroSpawnCwd,
+} from '@lobechat/heterogeneous-agents/workingDirectory';
import type {
HeterogeneousAgentModelCatalog,
HeteroSessionImportMessage,
@@ -465,7 +470,7 @@ export default class HeterogeneousAgentCtr {
agentType: session.agentType,
code: HeterogeneousAgentSessionErrorCode.WorkingDirectoryNotFound,
command: this.resolveSessionCommand(session),
- message: `Working directory does not exist: ${workingDirectory}`,
+ message: describeUnusableWorkingDirectory(workingDirectory),
workingDirectory,
};
}
@@ -617,7 +622,7 @@ export default class HeterogeneousAgentCtr {
private getSessionErrorPayload(error: unknown, session: AgentSession): SessionErrorPayload {
if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {
const workingDirectory = this.resolveSessionWorkingDirectory(session);
- if (!existsSync(workingDirectory)) {
+ if (!isSpawnableDirectory(workingDirectory)) {
return this.buildWorkingDirectoryMissingError(session, workingDirectory);
}
@@ -684,7 +689,7 @@ export default class HeterogeneousAgentCtr {
session: AgentSession,
): Promise<HeterogeneousAgentSessionError | undefined> {
const workingDirectory = this.resolveSessionWorkingDirectory(session);
- if (!existsSync(workingDirectory)) {
+ if (!isSpawnableDirectory(workingDirectory)) {
return this.buildWorkingDirectoryMissingError(session, workingDirectory);
}
@@ -2641,14 +2646,22 @@ export default class HeterogeneousAgentCtr {
workspaceId,
} = params;
const workDir = cwd ?? process.cwd();
+ // Let the embedded CLI classify a stale project path and finish the
+ // operation through heteroFinish instead of failing this wrapper spawn as
+ // the misleading `spawn LobeHub.exe ENOENT`.
+ const workDirUsable = isSpawnableDirectory(workDir);
+ const spawnCwd = resolveHeteroSpawnCwd(workDir);
// When CLI tracing is enabled (dev builds, or the Help-menu toggle in
// packaged builds), have `lh hetero exec` persist the agent process's RAW
// stream-json (pre-adapter) on this device. The remote-device path
// otherwise leaves no local record β€” the CLI consumes stdout internally and
// only POSTs adapted events to the server β€” so without this there's nothing
- // to inspect when a remote run misbehaves.
- const rawDumpDir = this.shouldTraceCliOutput ? this.resolveTraceRootDir(workDir) : undefined;
+ // to inspect when a remote run misbehaves. Do not pass a cwd-relative dump
+ // path for a missing workDir: RawStreamDump would recreate the deleted
+ // directory before spawnAgent can report it.
+ const rawDumpDir =
+ this.shouldTraceCliOutput && workDirUsable ? this.resolveTraceRootDir(workDir) : undefined;
const args = [
'hetero',
@@ -2703,7 +2716,7 @@ export default class HeterogeneousAgentCtr {
// an older global install earlier on PATH, letting model discovery report a
// capability that the actual execution runtime does not support.
const child = spawn(process.execPath, [cliScript, ...args], {
- cwd: workDir,
+ cwd: spawnCwd,
env,
stdio: ['pipe', 'inherit', 'inherit'],
});
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index a9801dfce39..e9811468563 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -1,5 +1,5 @@
import { EventEmitter } from 'node:events';
-import { existsSync } from 'node:fs';
+import { existsSync, statSync } from 'node:fs';
import { access, mkdtemp, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises';
import * as os from 'node:os';
import path from 'node:path';
@@ -24,9 +24,17 @@ const platformMock = vi.mocked(os.platform);
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
- return { ...actual, existsSync: vi.fn(() => true) };
+ return { ...actual, existsSync: vi.fn(() => true), statSync: vi.fn() };
});
+// Working-directory checks go through `statSync`; treat every path as an
+// existing directory unless a test marks one as missing.
+const asDirectory = { isDirectory: () => true } as ReturnType<typeof statSync>;
+const mockMissingDir = (missing: string) =>
+ vi
+ .mocked(statSync)
+ .mockImplementation((candidate) => (candidate === missing ? undefined : asDirectory) as never);
+
const FAKE_DESKTOP_PATH = '/Users/fake/Desktop';
describe('redactPromptArgs', () => {
@@ -563,6 +571,7 @@ describe('HeterogeneousAgentCtr', () => {
mockGetAllWindows.mockReset();
platformMock.mockReturnValue('linux');
vi.mocked(existsSync).mockReturnValue(true);
+ vi.mocked(statSync).mockReturnValue(asDirectory);
delete process.env.LOBE_CLAUDE_CODE_SDK;
delete process.env.LOBE_CODEX_APP_SERVER;
});
@@ -1639,7 +1648,9 @@ describe('HeterogeneousAgentCtr', () => {
});
it('validates the default desktop directory when the session cwd is omitted', async () => {
- vi.mocked(existsSync).mockImplementation((candidate) => candidate === FAKE_DESKTOP_PATH);
+ vi.mocked(statSync).mockImplementation((candidate) =>
+ candidate === FAKE_DESKTOP_PATH ? asDirectory : (undefined as never),
+ );
const detect = vi.fn().mockResolvedValue({ available: false });
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
@@ -1655,13 +1666,13 @@ describe('HeterogeneousAgentCtr', () => {
ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
).rejects.toThrow('Codex CLI was not found');
- expect(existsSync).toHaveBeenCalledWith(FAKE_DESKTOP_PATH);
+ expect(statSync).toHaveBeenCalledWith(FAKE_DESKTOP_PATH, expect.anything());
expect(detect).toHaveBeenCalledWith('codex', true);
});
it('reports a missing working directory instead of claiming the Codex CLI is missing', async () => {
const missingCwd = '/tmp/lobehub-deleted-worktree';
- vi.mocked(existsSync).mockImplementation((candidate) => candidate !== missingCwd);
+ mockMissingDir(missingCwd);
const detect = vi.fn().mockResolvedValue({
available: true,
path: '/Applications/ChatGPT.app/Contents/Resources/codex',
@@ -2745,6 +2756,7 @@ describe('HeterogeneousAgentCtr', () => {
'--operation-id',
'op-gateway',
]);
+ expect(spawnCall.options.cwd).toBe(process.cwd());
expect(spawnCall.options.env).toEqual(
expect.objectContaining({
ELECTRON_RUN_AS_NODE: '1',
@@ -2826,8 +2838,34 @@ describe('HeterogeneousAgentCtr', () => {
expect(proc.stdin.write).not.toHaveBeenCalled();
});
+ it('starts the wrapper from home so its inner preflight can report a missing cwd', async () => {
+ const missingCwd = '/missing/project';
+ const proc = createGatewayCliProc();
+ nextFakeProc = proc;
+ mockMissingDir(missingCwd);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+
+ const ack = ctr.spawnLhHeteroExec({ ...params, cwd: missingCwd });
+
+ expect(spawnCalls).toHaveLength(1);
+ const [spawnCall] = spawnCalls;
+ const cwdArgIndex = spawnCall.args.indexOf('--cwd');
+ expect(spawnCall.options.cwd).toBe(os.homedir());
+ expect(spawnCall.args[cwdArgIndex + 1]).toBe(missingCwd);
+ expect(spawnCall.args).not.toContain('--raw-dump');
+ proc.emit('spawn');
+
+ await expect(ack).resolves.toEqual({ status: 'accepted' });
+ expect(proc.stdin.write).toHaveBeenCalledOnce();
+ });
+
it('rejects before spawn when the embedded CLI is missing', async () => {
- vi.mocked(existsSync).mockReturnValueOnce(false);
+ vi.mocked(existsSync).mockImplementation(
+ (candidate) => candidate !== '/fake/cli/dist/index.js',
+ );
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.json
index e536871e70c..1db9004768f 100644
--- a/packages/heterogeneous-agents/package.json
+++ b/packages/heterogeneous-agents/package.json
@@ -15,7 +15,8 @@
"./resolveCliCommand": "./src/spawn/resolveCliCommand.ts",
"./scanHost": "./src/scan/scanHost.ts",
"./spawn": "./src/spawn/index.ts",
- "./transcript": "./src/transcript/index.ts"
+ "./transcript": "./src/transcript/index.ts",
+ "./workingDirectory": "./src/spawn/workingDirectory.ts"
},
"main": "./src/index.ts",
"scripts": {
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index 9e640d13049..a83f182dbc1 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -1,6 +1,5 @@
import type { ChildProcess } from 'node:child_process';
import { spawn } from 'node:child_process';
-import { existsSync } from 'node:fs';
import path from 'node:path';
import { PassThrough } from 'node:stream';
@@ -9,7 +8,6 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import type { AskUserBridge } from '../askUser/AskUserBridge';
import { resolveHeterogeneousAgentCommand } from '../config';
import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';
-import { HETERO_WORKING_DIRECTORY_NOT_FOUND } from './classifyProcessFailure';
import { isPathLikeCommand, resolveCliSpawnPlan } from './cliSpawn';
import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';
import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';
@@ -17,6 +15,7 @@ import { buildGrokAcpPrompt, GrokAcpSession } from './grokAcpSession';
import type { AgentPromptInput, BuildAgentInputOptions } from './input';
import { buildAgentInput } from './input';
import { buildTraeAcpPrompt, TraeAcpSession } from './traeAcpSession';
+import { assertSpawnableWorkingDirectory } from './workingDirectory';
export interface SpawnAgentOptions {
/** Registered local heterogeneous-agent type key. */
@@ -582,12 +581,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
const command = resolveHeterogeneousAgentCommand(options.agentType, options.command);
const cwd = options.cwd || process.cwd();
- if (!existsSync(cwd)) {
- throw Object.assign(new Error(`Working directory does not exist: ${cwd}`), {
- code: HETERO_WORKING_DIRECTORY_NOT_FOUND,
- workingDirectory: cwd,
- });
- }
+ assertSpawnableWorkingDirectory(cwd);
if (options.agentType === 'grok-build') {
return spawnGrokAcpAgent(options, command, cwd);
}
@@ -783,12 +777,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentHandle> => {
const requestedCommand = resolveHeterogeneousAgentCommand('trae', options.command);
const cwd = options.cwd || process.cwd();
- if (!existsSync(cwd)) {
- throw Object.assign(new Error(`Working directory does not exist: ${cwd}`), {
- code: HETERO_WORKING_DIRECTORY_NOT_FOUND,
- workingDirectory: cwd,
- });
- }
+ assertSpawnableWorkingDirectory(cwd);
const command =
isPathLikeCommand(requestedCommand) && !path.isAbsolute(requestedCommand)
? path.resolve(cwd, requestedCommand)
diff --git a/packages/heterogeneous-agents/src/spawn/workingDirectory.test.ts b/packages/heterogeneous-agents/src/spawn/workingDirectory.test.ts
new file mode 100644
index 00000000000..0edf9c2e2a7
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/workingDirectory.test.ts
@@ -0,0 +1,102 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import type * as NodeOs from 'node:os';
+import { homedir, tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ assertSpawnableWorkingDirectory,
+ describeUnusableWorkingDirectory,
+ isSpawnableDirectory,
+ resolveHeteroSpawnCwd,
+} from './workingDirectory';
+
+// `homedir` / `tmpdir` are mocked so the fallback chain can be driven without
+// depending on the machine's real home and temp layout.
+vi.mock('node:os', async (importOriginal) => {
+ const actual = await importOriginal<typeof NodeOs>();
+ return {
+ ...actual,
+ homedir: vi.fn(() => actual.homedir()),
+ tmpdir: vi.fn(() => actual.tmpdir()),
+ };
+});
+
+const realOs = await vi.importActual<typeof NodeOs>('node:os');
+const realHomedir = realOs.homedir();
+const realTmpdir = realOs.tmpdir();
+
+const workDir = mkdtempSync(path.join(realTmpdir, 'hetero-workdir-'));
+const filePath = path.join(workDir, 'file.txt');
+writeFileSync(filePath, 'x');
+const missingDir = path.join(workDir, 'gone');
+
+afterAll(() => {
+ rmSync(workDir, { force: true, recursive: true });
+});
+
+beforeEach(() => {
+ vi.mocked(homedir).mockReturnValue(realHomedir);
+ vi.mocked(tmpdir).mockReturnValue(realTmpdir);
+});
+
+describe('isSpawnableDirectory', () => {
+ it('accepts a directory and rejects a missing path or a regular file', () => {
+ expect(isSpawnableDirectory(workDir)).toBe(true);
+ expect(isSpawnableDirectory(missingDir)).toBe(false);
+ expect(isSpawnableDirectory(filePath)).toBe(false);
+ });
+});
+
+describe('describeUnusableWorkingDirectory', () => {
+ it('distinguishes a missing path from a path that is not a directory', () => {
+ expect(describeUnusableWorkingDirectory(missingDir)).toBe(
+ `Working directory does not exist: ${missingDir}`,
+ );
+ expect(describeUnusableWorkingDirectory(filePath)).toBe(
+ `Working directory is not a directory: ${filePath}`,
+ );
+ });
+});
+
+describe('assertSpawnableWorkingDirectory', () => {
+ it('passes for a directory', () => {
+ expect(() => assertSpawnableWorkingDirectory(workDir)).not.toThrow();
+ });
+
+ it('throws the structured working-directory error for an unusable path', () => {
+ expect(() => assertSpawnableWorkingDirectory(filePath)).toThrow(
+ `Working directory is not a directory: ${filePath}`,
+ );
+ expect(() => assertSpawnableWorkingDirectory(missingDir)).toThrow(
+ expect.objectContaining({
+ code: 'HETERO_WORKING_DIRECTORY_NOT_FOUND',
+ workingDirectory: missingDir,
+ }),
+ );
+ });
+});
+
+describe('resolveHeteroSpawnCwd', () => {
+ it('keeps the configured working directory when it is usable', () => {
+ expect(resolveHeteroSpawnCwd(workDir)).toBe(workDir);
+ });
+
+ it('falls back to home when the working directory is gone', () => {
+ expect(resolveHeteroSpawnCwd(missingDir)).toBe(realHomedir);
+ });
+
+ it('falls back to temp when home is unavailable too', () => {
+ vi.mocked(homedir).mockReturnValue(path.join(missingDir, 'home'));
+
+ expect(resolveHeteroSpawnCwd(missingDir)).toBe(realTmpdir);
+ });
+
+ it('returns undefined so the caller inherits its own cwd when nothing is usable', () => {
+ vi.mocked(homedir).mockReturnValue(path.join(missingDir, 'home'));
+ vi.mocked(tmpdir).mockReturnValue(path.join(missingDir, 'tmp'));
+
+ expect(resolveHeteroSpawnCwd(missingDir)).toBeUndefined();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/workingDirectory.ts b/packages/heterogeneous-agents/src/spawn/workingDirectory.ts
new file mode 100644
index 00000000000..62cb2d0b98b
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/workingDirectory.ts
@@ -0,0 +1,72 @@
+import { type Stats, statSync } from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+
+import { HETERO_WORKING_DIRECTORY_NOT_FOUND } from './classifyProcessFailure';
+
+/**
+ * Working-directory checks shared by every heterogeneous-agent spawn site
+ * (desktop main, `lh connect` daemon, `lh hetero exec`).
+ *
+ * Exposed as its own package subpath rather than through the `./spawn` barrel:
+ * the connect daemon only needs these few lines, and the barrel pulls in the
+ * agent SDKs and stream pipeline behind it.
+ */
+
+/**
+ * `statSync` is the only filesystem primitive this module uses, so the
+ * predicate and the message it produces can never disagree.
+ */
+const statDirectory = (dir: string): Stats | undefined => {
+ try {
+ return statSync(dir, { throwIfNoEntry: false });
+ } catch {
+ // An unreadable path (EACCES on a parent, symlink loop) is unusable too.
+ return undefined;
+ }
+};
+
+/**
+ * Whether `dir` can be used as a child process `cwd`. An existence check alone
+ * also accepts a regular file, and spawning with a file as `cwd` fails with
+ * ENOTDIR β€” an errno no classifier maps to `working_directory_not_found`, so
+ * the run would surface the generic error card instead of the
+ * working-directory guide.
+ */
+export const isSpawnableDirectory = (dir: string): boolean =>
+ statDirectory(dir)?.isDirectory() ?? false;
+
+/** Single wording for the working-directory failure across CLI and desktop. */
+export const describeUnusableWorkingDirectory = (dir: string): string =>
+ statDirectory(dir)
+ ? `Working directory is not a directory: ${dir}`
+ : `Working directory does not exist: ${dir}`;
+
+/**
+ * Fail a run before spawn when its working directory is unusable, with the
+ * `code` that `classifyHeteroProcessFailure` maps onto the working-directory
+ * guide card.
+ */
+export const assertSpawnableWorkingDirectory = (dir: string): void => {
+ if (isSpawnableDirectory(dir)) return;
+
+ throw Object.assign(new Error(describeUnusableWorkingDirectory(dir)), {
+ code: HETERO_WORKING_DIRECTORY_NOT_FOUND,
+ workingDirectory: dir,
+ });
+};
+
+/**
+ * Pick the cwd to start the `lh hetero exec` wrapper process from. A stale
+ * project path must not prevent the wrapper from starting: its inner
+ * `spawnAgent` preflight owns cwd classification and reports the structured
+ * `working_directory_not_found` error through `heteroFinish`, which the bare
+ * `spawn ... ENOENT` of a failed wrapper spawn cannot.
+ *
+ * Falls through home and temp so the wrapper still starts when home itself is
+ * unavailable (a disconnected network home). `undefined` means "inherit this
+ * process's cwd", which stays valid as long as this process runs.
+ */
+export const resolveHeteroSpawnCwd = (workDir: string): string | undefined =>
+ [workDir, homedir(), tmpdir()].find(
+ (candidate) => !!candidate && isSpawnableDirectory(candidate),
+ );