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): classify remote CC/Codex process-level failures into status-guide errors (#17248)

Arvin Xu3ee09416e114
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index f0b76c35e80..62596faccb4 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -537,7 +537,7 @@ describe('hetero exec command', () => {
});
it('finishes server-ingest runs with error when spawnAgent rejects before streaming', async () => {
- mockSpawnAgent.mockRejectedValue(new Error('spawn claude ENOENT'));
+ mockSpawnAgent.mockRejectedValue(new Error('image fetch failed: 404'));
await runCmd([
'hetero',
@@ -557,17 +557,18 @@ describe('hetero exec command', () => {
expect(mockHeteroFinishMutate).toHaveBeenCalledTimes(1);
expect(mockHeteroFinishMutate.mock.calls[0][0]).toMatchObject({
agentType: 'claude-code',
- error: { message: 'spawn claude ENOENT', type: 'AgentRuntimeError' },
+ error: { message: 'image fetch failed: 404', type: 'AgentRuntimeError' },
operationId: 'op-server',
result: 'error',
topicId: 'topic-1',
});
+ expect(mockHeteroFinishMutate.mock.calls[0][0].error.body).toBeUndefined();
expect(exitSpy).toHaveBeenCalledWith(1);
});
it('finishes server-ingest runs with error when the agent event stream fails', async () => {
mockSpawnAgent.mockReturnValue(
- createFakeHandle({ eventsError: new Error('spawn claude ENOENT') }),
+ createFakeHandle({ eventsError: new Error('adapter choked on malformed JSONL') }),
);
await runCmd([
@@ -587,7 +588,89 @@ describe('hetero exec command', () => {
expect(mockHeteroFinishMutate).toHaveBeenCalledTimes(1);
expect(mockHeteroFinishMutate.mock.calls[0][0]).toMatchObject({
- error: { message: 'Error: spawn claude ENOENT', type: 'stream_error' },
+ error: { message: 'Error: adapter choked on malformed JSONL', type: 'stream_error' },
+ operationId: 'op-server',
+ result: 'error',
+ topicId: 'topic-1',
+ });
+ expect(mockHeteroFinishMutate.mock.calls[0][0].error.body).toBeUndefined();
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('classifies a spawn ENOENT stream failure as a structured cli_not_found error', async () => {
+ // `spawnAgent` surfaces a missing CLI binary by failing the event stream
+ // with the child's ErrnoException (see `failStream` in spawnAgent.ts).
+ const enoent = new Error('spawn claude ENOENT') as NodeJS.ErrnoException;
+ enoent.code = 'ENOENT';
+ mockSpawnAgent.mockReturnValue(createFakeHandle({ eventsError: enoent }));
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-server',
+ '--render',
+ 'none',
+ ]);
+
+ expect(mockHeteroFinishMutate).toHaveBeenCalledTimes(1);
+ expect(mockHeteroFinishMutate.mock.calls[0][0]).toMatchObject({
+ error: {
+ body: {
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ stderr: 'Error: spawn claude ENOENT',
+ },
+ // Classified errors are normalized to AgentRuntimeError β€” the
+ // transport-internal `stream_error` label must not leak into the
+ // persisted error type.
+ type: 'AgentRuntimeError',
+ },
+ operationId: 'op-server',
+ result: 'error',
+ topicId: 'topic-1',
+ });
+ expect(mockHeteroFinishMutate.mock.calls[0][0].error.message).toContain('was not found');
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('classifies an auth failure on stderr as a structured auth_required error', async () => {
+ // CLI exits non-zero after printing an auth error to stderr, without ever
+ // emitting a structured error event.
+ mockSpawnAgent.mockReturnValue(
+ createFakeHandle({
+ exitCode: 1,
+ stderrChunks: ['Error: not authenticated. Run `claude login` first.\n'],
+ }),
+ );
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-server',
+ '--render',
+ 'none',
+ ]);
+
+ expect(mockHeteroFinishMutate).toHaveBeenCalledTimes(1);
+ expect(mockHeteroFinishMutate.mock.calls[0][0]).toMatchObject({
+ error: {
+ body: { agentType: 'claude-code', code: 'auth_required' },
+ type: 'AgentRuntimeError',
+ },
operationId: 'op-server',
result: 'error',
topicId: 'topic-1',
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index e8a5cfe1066..25aedce4bae 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -15,7 +15,11 @@ import type {
AgentStreamEvent,
UploadHeterogeneousImage,
} from '@lobechat/heterogeneous-agents/spawn';
-import { createFileStoreImageUploader, spawnAgent } from '@lobechat/heterogeneous-agents/spawn';
+import {
+ classifyHeteroProcessFailure,
+ createFileStoreImageUploader,
+ spawnAgent,
+} from '@lobechat/heterogeneous-agents/spawn';
import type { Command } from 'commander';
import { getTrpcClient } from '../api/client';
@@ -596,6 +600,31 @@ const exec = async (options: ExecOptions): Promise<void> => {
})();
}
+ /**
+ * Build the `finish` error payload. Process-level failures the agent CLI
+ * never got to report in-stream (spawn ENOENT because the CLI isn't
+ * installed, an auth failure printed straight to stderr) are classified into
+ * the structured status-guide shape and attached as `body`, so the client
+ * renders the dedicated install/sign-in guide instead of the generic error
+ * card. Unclassifiable failures keep the flat `{ message, type }` everything
+ * downstream already handles.
+ *
+ * A classified error is always typed `AgentRuntimeError` β€” matching how the
+ * adapters' in-stream classified errors (overloaded / rate_limit) persist β€”
+ * instead of leaking the transport-internal `type` the failure happened to
+ * surface through (`stream_error` for a spawn ENOENT reads wrong on a
+ * "CLI not installed" error).
+ */
+ const buildFinishError = (
+ message: string,
+ type: string,
+ errnoCode?: string,
+ ): { body?: Record<string, unknown>; message: string; type: string } => {
+ const classified = classifyHeteroProcessFailure({ agentType, detail: message, errnoCode });
+ if (!classified) return { message, type };
+ return { body: { ...classified }, message: classified.message, type: 'AgentRuntimeError' };
+ };
+
/**
* Spawn one agent process and stream all its events into the server ingester.
*
@@ -649,7 +678,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
try {
await serverIngester.drain();
await sink.finish({
- error: { message, type: 'AgentRuntimeError' },
+ error: buildFinishError(message, 'AgentRuntimeError'),
result: 'error',
});
} catch {
@@ -756,8 +785,16 @@ const exec = async (options: ExecOptions): Promise<void> => {
if (serverIngester && sink) {
try {
await serverIngester.drain();
+ // A spawn failure (missing CLI binary / cwd) surfaces HERE, not via
+ // `exit`: `spawnAgent` fails the event stream on the child's `error`
+ // event, so this catch runs and exits before the finish block below.
+ // Pass the raw errno code along for precise classification.
await sink.finish({
- error: { message: String(err), type: 'stream_error' },
+ error: buildFinishError(
+ String(err),
+ 'stream_error',
+ (err as NodeJS.ErrnoException | null)?.code,
+ ),
result: 'error',
});
} catch {
@@ -894,7 +931,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
const errorDetail = result.terminalErrorMessage || stderrTail;
const finishError =
!exitedClean && errorDetail
- ? { message: errorDetail.slice(-1024), type: 'AgentRuntimeError' }
+ ? buildFinishError(errorDetail.slice(-1024), 'AgentRuntimeError')
: undefined;
try {
diff --git a/apps/cli/src/utils/BatchIngester.ts b/apps/cli/src/utils/BatchIngester.ts
index 52d1452cc7e..3b7d9307bc8 100644
--- a/apps/cli/src/utils/BatchIngester.ts
+++ b/apps/cli/src/utils/BatchIngester.ts
@@ -2,7 +2,17 @@ import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
export interface IngestSink {
finish: (params: {
- error?: { message: string; type: string };
+ error?: {
+ /**
+ * Structured status-guide error (`classifyHeteroProcessFailure` output:
+ * `agentType` + `code` + details). Persisted verbatim as the
+ * `ChatMessageError.body` so the client renders the dedicated
+ * install/sign-in guide instead of the generic error card.
+ */
+ body?: Record<string, unknown>;
+ message: string;
+ type: string;
+ };
result: 'cancelled' | 'error' | 'success';
sessionId?: string;
}) => Promise<void>;
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 39a7182894d..94f4f832ef3 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -475,6 +475,13 @@ const HeteroFinishSchema = z.object({
agentType: z.enum(['amp', 'claude-code', 'codex']),
error: z
.object({
+ /**
+ * Structured status-guide error for process-level failures (CLI not
+ * installed, auth required) β€” the CLI's `classifyHeteroProcessFailure`
+ * output. Persisted verbatim as the `ChatMessageError.body` so the
+ * client renders the dedicated guide.
+ */
+ body: z.record(z.string(), z.unknown()).optional(),
message: z.string(),
type: z.string(),
})
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index ad070928446..5e5094b0c41 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -263,12 +263,34 @@ export class HeterogeneousPersistenceHandler {
* this topic can include `--resume <id>`.
*/
async finish(params: {
- error?: { message: string; type: string };
+ error?: { body?: Record<string, unknown>; message: string; type: string };
operationId: string;
result: 'success' | 'error' | 'cancelled';
sessionId?: string;
+ /**
+ * Needed to bootstrap state for a failed run that never ingested: a
+ * process-level failure (spawn ENOENT, auth printed straight to stderr)
+ * produces ZERO stream events, so no ingest ever created an
+ * `OperationState` for this op.
+ */
+ topicId?: string;
}): Promise<void> {
- const state = operationStates.get(params.operationId);
+ let state = operationStates.get(params.operationId);
+
+ // A run that died before producing any stream event has no state β€” but its
+ // terminal error must still land on the assistant message HERE, before the
+ // caller publishes `agent_runtime_end`. The client refetches messages on
+ // that event, so deferring the write to CompletionLifecycle (which runs
+ // after the publish) races the refetch and the error card doesn't render
+ // live. Bootstrap from topic.metadata.runningOperation like ingest does;
+ // a stale/mismatched operation stays a no-op.
+ if (!state && params.result === 'error' && params.error && params.topicId) {
+ try {
+ state = await this.loadOrCreateState(params.operationId, params.topicId);
+ } catch {
+ return;
+ }
+ }
if (!state) return;
try {
@@ -974,7 +996,7 @@ export class HeterogeneousPersistenceHandler {
/** Final safety flush triggered by `heteroFinish`. */
private async flushFinalState(
state: OperationState,
- error: { message: string; type: string } | undefined,
+ error: { body?: Record<string, unknown>; message: string; type: string } | undefined,
result: 'success' | 'error' | 'cancelled',
) {
if (!state.main.accContent && !state.main.accReasoning && !error && result !== 'error') {
@@ -989,6 +1011,8 @@ export class HeterogeneousPersistenceHandler {
// Same canonical normalization as the in-stream `setError` path β€” the CLI's
// free-form `{ message, type }` runs through formatErrorForState so the
// terminal flush and the in-stream write produce one classified error shape.
+ // A structured `body` (status-guide error: agentType + code) passes
+ // through untouched β€” the client's guide UI gates on it.
updateValue.error = formatErrorForState(error);
}
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index 13e593ec7a1..c6d07acfb27 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -1248,6 +1248,115 @@ describe('HeterogeneousPersistenceHandler', () => {
expect(asst.content).toBe('partial');
});
+ it('finish() preserves a structured status-guide error body on the assistant', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Register op state without any in-stream error β€” the process-level
+ // failure (spawn ENOENT) only arrives via the finish payload.
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: '' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.finish({
+ error: {
+ body: {
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ stderr: 'Error: spawn claude ENOENT',
+ },
+ message: 'Claude Code CLI was not found on the machine running this agent.',
+ type: 'stream_error',
+ },
+ operationId: 'op-1',
+ result: 'error',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.error).toBeDefined();
+ // `body` must survive formatErrorForState untouched β€” the client's
+ // status-guide UI gates on `body.agentType` + `body.code`.
+ expect(asst.error.body).toMatchObject({
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ stderr: 'Error: spawn claude ENOENT',
+ });
+ expect(asst.error.message).toContain('was not found');
+ });
+
+ it('finish() with NO prior ingest bootstraps state and writes the error (spawn-fail path)', async () => {
+ // The real process-level failure shape: spawn ENOENT produces ZERO
+ // stream events, so no ingest ever created an OperationState. finish()
+ // must bootstrap from topic.metadata.runningOperation and write the
+ // error itself β€” deferring it to CompletionLifecycle (which runs AFTER
+ // the agent_runtime_end publish) races the client's message refetch.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.finish({
+ error: {
+ body: {
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ stderr: 'Error: spawn claude ENOENT',
+ },
+ message: 'Claude Code CLI was not found on the machine running this agent.',
+ type: 'AgentRuntimeError',
+ },
+ operationId: 'op-1',
+ result: 'error',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.error).toBeDefined();
+ expect(asst.error.body).toMatchObject({
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ });
+ expect(asst.error.message).toContain('was not found');
+ });
+
+ it('finish() with no state stays a no-op for a stale operation (mismatched runningOperation)', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ // The topic's runningOperation belongs to a DIFFERENT operation β€” a late
+ // finish from a superseded run must not touch the current turn.
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'asst-other',
+ operationId: 'op-OTHER',
+ },
+ },
+ });
+
+ await expect(
+ h.handler.finish({
+ error: { message: 'boom', type: 'AgentRuntimeError' },
+ operationId: 'op-1',
+ result: 'error',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(h.messages.get('asst-1')!.error).toBeUndefined();
+ expect(h.messageModel.update).not.toHaveBeenCalled();
+ });
+
it('finish() drops the per-operation state so a retry starts fresh', async () => {
const h = createHarness({
assistantMessageId: 'asst-1',
@@ -1612,7 +1721,13 @@ describe('HeterogeneousPersistenceHandler', () => {
chunkType: 'tools_calling',
subagent: subagentCtx,
toolsCalling: [
- { apiName: 'Read', arguments: '{}', id: 'inner-tc', identifier: 'read', type: 'default' },
+ {
+ apiName: 'Read',
+ arguments: '{}',
+ id: 'inner-tc',
+ identifier: 'read',
+ type: 'default',
+ },
],
}),
buildEvent('step_complete', 2, {
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 098c5adffc7..437cd39f05f 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -39,7 +39,12 @@ export interface HeterogeneousIngestParams {
export interface HeterogeneousFinishParams {
agentType: HeterogeneousAgentType;
- error?: { message: string; type: string };
+ /**
+ * CLI-reported failure. `body`, when present, is the structured status-guide
+ * error (`agentType` + `code` + details) persisted verbatim as the
+ * `ChatMessageError.body`.
+ */
+ error?: { body?: Record<string, unknown>; message: string; type: string };
operationId: string;
result: HeterogeneousFinishResult;
/**
@@ -184,7 +189,11 @@ export class HeterogeneousAgentService {
// accumulated content / reasoning that the in-stream `agent_runtime_end`
// already wrote (no-op when state is clean), persists the CLI's native
// session id for next-turn resume, and frees the per-operation memory.
- await this.persistenceHandler.finish({ error, operationId, result, sessionId });
+ // `topicId` lets finish() bootstrap state for a run that failed before
+ // producing any stream event (spawn ENOENT / auth-on-stderr): the terminal
+ // error must be written HERE, before the `agent_runtime_end` publish below
+ // triggers the client's message refetch.
+ await this.persistenceHandler.finish({ error, operationId, result, sessionId, topicId });
// Always emit a terminal `agent_runtime_end` so renderer subscribers shut
// down even if the CLI stream missed it (process killed mid-flight,
diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
new file mode 100644
index 00000000000..fccd9f6ebb8
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+
+import { classifyHeteroProcessFailure } from './classifyProcessFailure';
+
+describe('classifyHeteroProcessFailure', () => {
+ it('classifies a raw spawn ErrnoException code as cli_not_found', () => {
+ const result = classifyHeteroProcessFailure({
+ agentType: 'claude-code',
+ detail: 'Error: spawn claude ENOENT',
+ errnoCode: 'ENOENT',
+ });
+
+ expect(result).toMatchObject({
+ agentType: 'claude-code',
+ code: 'cli_not_found',
+ stderr: 'Error: spawn claude ENOENT',
+ });
+ expect(result?.message).toContain('`claude`');
+ });
+
+ it('classifies a flattened "spawn <cmd> ENOENT" stderr tail as cli_not_found', () => {
+ const result = classifyHeteroProcessFailure({
+ agentType: 'codex',
+ detail: 'some earlier output\nError: spawn codex ENOENT',
+ });
+
+ expect(result).toMatchObject({ agentType: 'codex', code: 'cli_not_found' });
+ expect(result?.message).toContain('`codex`');
+ });
+
+ it('does NOT treat an in-run ENOENT (no spawn context) as cli_not_found', () => {
+ const result = classifyHeteroProcessFailure({
+ agentType: 'claude-code',
+ detail: "ENOENT: no such file or directory, open '/tmp/foo.txt'",
+ });
+
+ expect(result).toBeUndefined();
+ });
+
+ it.each([
+ 'Failed to authenticate with the API',
+ 'Invalid authentication credentials',
+ 'authentication_error: OAuth token expired',
+ 'Error: not authenticated. Run `claude login` first.',
+ 'Request failed: 401 Unauthorized',
+ ])('classifies auth failure %j as auth_required', (detail) => {
+ const result = classifyHeteroProcessFailure({ agentType: 'claude-code', detail });
+
+ expect(result).toMatchObject({
+ agentType: 'claude-code',
+ code: 'auth_required',
+ stderr: detail,
+ });
+ });
+
+ it('prefers cli_not_found over auth patterns when both would match', () => {
+ const result = classifyHeteroProcessFailure({
+ agentType: 'claude-code',
+ detail: 'unauthorized junk\nError: spawn claude ENOENT',
+ errnoCode: 'ENOENT',
+ });
+
+ expect(result?.code).toBe('cli_not_found');
+ });
+
+ it('returns undefined for unsupported agent types', () => {
+ expect(
+ classifyHeteroProcessFailure({
+ agentType: 'amp',
+ detail: 'Error: spawn amp ENOENT',
+ errnoCode: 'ENOENT',
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for unclassifiable failures', () => {
+ expect(
+ classifyHeteroProcessFailure({
+ agentType: 'claude-code',
+ detail: 'Agent exited with code 1',
+ }),
+ ).toBeUndefined();
+ expect(classifyHeteroProcessFailure({ agentType: 'claude-code' })).toBeUndefined();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
new file mode 100644
index 00000000000..53f2371b435
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
@@ -0,0 +1,100 @@
+import type { HeterogeneousTerminalErrorData } from '../types';
+
+/**
+ * Process-level failure classification for `lh hetero exec` runs.
+ *
+ * The stream adapters (`adapters/claudeCode.ts`, `adapters/codex.ts`) classify
+ * failures the CLI reports in-stream (overloaded / rate-limit / auth relayed
+ * via a `result` event), but a run that dies BEFORE the agent CLI produces any
+ * stream β€” `spawn claude ENOENT`, an auth failure printed straight to stderr β€”
+ * never reaches an adapter. Without classification those runs land on the
+ * server as a bare `{ message }` error, so the client renders the generic JSON
+ * error card instead of the heterogeneous status guide (install CLI / sign in).
+ *
+ * This helper mirrors the desktop in-process classifier
+ * (`HeterogeneousAgentCtr.getSessionErrorPayload`) for the two guide codes a
+ * process-level failure can produce: `cli_not_found` and `auth_required`.
+ * The returned shape is persisted verbatim as the `ChatMessageError.body`, so
+ * it must carry `agentType` + `code` β€” that pair is what
+ * `isHeterogeneousAgentStatusGuideError` gates the dedicated UI on.
+ */
+
+/**
+ * Node reports a missing executable as an `ErrnoException` with
+ * `code: 'ENOENT'` and message `spawn <command> ENOENT`. When only stderr text
+ * is available (the raw error object was already flattened into the stderr
+ * tail), match the message shape instead. Note ENOENT is also raised for a
+ * missing `cwd` β€” same behavior as the desktop classifier; both mean "this
+ * machine can't start the CLI as configured".
+ */
+const SPAWN_ENOENT_PATTERN = /\bspawn .+ ENOENT\b/;
+
+/** Mirrors `CLI_AUTH_REQUIRED_PATTERNS` in the desktop `HeterogeneousAgentCtr`. */
+const CLI_AUTH_REQUIRED_PATTERNS = [
+ /failed to authenticate/i,
+ /invalid authentication credentials/i,
+ /authentication[_ ]error/i,
+ /not authenticated/i,
+ /\bunauthorized\b/i,
+ /\b401\b/,
+];
+
+const CLI_NOT_FOUND_MESSAGES: Record<string, string> = {
+ 'claude-code':
+ 'Claude Code CLI was not found on the machine running this agent. Install it and make sure `claude` can be executed.',
+ 'codex':
+ 'Codex CLI was not found on the machine running this agent. Install it and make sure `codex` can be executed.',
+};
+
+const AUTH_REQUIRED_MESSAGES: Record<string, string> = {
+ 'claude-code':
+ 'Claude Code could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',
+ 'codex':
+ 'Codex could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',
+};
+
+export interface ClassifyHeteroProcessFailureParams {
+ /** Adapter type key β€” only `claude-code` / `codex` have a status guide. */
+ agentType: string;
+ /** Stderr tail / flattened error message to pattern-match. */
+ detail?: string;
+ /**
+ * `err.code` from the raw Node `ErrnoException`, when the caller still has
+ * the error object (more precise than matching the message text).
+ */
+ errnoCode?: string;
+}
+
+/**
+ * Classify a process-level run failure into a structured status-guide error,
+ * or `undefined` when the failure isn't one the guide UI can act on (the
+ * caller should then keep its flat `{ message }` error).
+ */
+export const classifyHeteroProcessFailure = (
+ params: ClassifyHeteroProcessFailureParams,
+): HeterogeneousTerminalErrorData | undefined => {
+ const { agentType, errnoCode } = params;
+ const detail = params.detail?.trim();
+
+ const cliNotFoundMessage = CLI_NOT_FOUND_MESSAGES[agentType];
+ // Unknown agent type β†’ the client guide can't render it; don't classify.
+ if (!cliNotFoundMessage) return;
+
+ if (errnoCode === 'ENOENT' || (detail && SPAWN_ENOENT_PATTERN.test(detail))) {
+ return {
+ agentType,
+ code: 'cli_not_found',
+ message: cliNotFoundMessage,
+ ...(detail ? { stderr: detail } : {}),
+ };
+ }
+
+ if (detail && CLI_AUTH_REQUIRED_PATTERNS.some((pattern) => pattern.test(detail))) {
+ return {
+ agentType,
+ code: 'auth_required',
+ message: AUTH_REQUIRED_MESSAGES[agentType],
+ stderr: detail,
+ };
+ }
+};
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 88c17e169b8..70a42227b28 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -18,6 +18,10 @@ export {
type AgentStreamPipelineOptions,
type UploadHeterogeneousImage,
} from './agentStreamPipeline';
+export {
+ classifyHeteroProcessFailure,
+ type ClassifyHeteroProcessFailureParams,
+} from './classifyProcessFailure';
export {
buildClaudeSdkUserMessageFromStreamJson,
ClaudeAgentSdkSession,