π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import { randomUUID } from 'node:crypto';
import { once } from 'node:events';
import { createWriteStream } from 'node:fs';
import { mkdir, unlink, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import {
HETEROGENEOUS_AGENT_CONFIGS,
isLocalHeterogeneousType,
LOCAL_HETEROGENEOUS_AGENT_TYPES,
type LocalHeterogeneousAgentType,
usesHeterogeneousSessionInitialModel,
} from '@lobechat/heterogeneous-agents';
import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
import { LobeBuiltinMcpServer } from '@lobechat/heterogeneous-agents/builtinMcp';
import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';
import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';
import {
createPiRpcAgentHandle,
type PiRpcStartupControl,
preparePiRpcInput,
} from '@lobechat/heterogeneous-agents/rpc';
import type {
AgentStreamEvent,
UploadHeterogeneousImage,
} from '@lobechat/heterogeneous-agents/spawn';
import {
classifyHeteroProcessFailure,
createCodexAgentHandle,
createFileStoreImageUploader,
isHeteroStatusGuideErrorData,
resolveDshSpawnCommand,
spawnAgent,
spawnDshAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
import { isRecord } from '@lobechat/utils/object';
import type { Command } from 'commander';
import { getTrpcClient } from '../../api/client';
import { cliVersion } from '../../pkg';
import { CoalescingBatchIngester } from '../../utils/CoalescingBatchIngester';
import { withHeteroSteer } from '../../utils/heteroSteer';
import { HeteroTraceRecorder } from '../../utils/HeteroTraceRecorder';
import { log } from '../../utils/logger';
import { createOperationHeartbeat } from '../../utils/OperationHeartbeat';
import { createOperationTokenRenewal } from '../../utils/OperationTokenRenewal';
import { createLocalTraceStore } from '../../utils/traceStore';
import { TrpcIngestSink } from '../../utils/TrpcIngestSink';
import type { HeteroCliArgumentOptions } from './buildExtraArgs';
import { buildExtraArgs } from './buildExtraArgs';
import { dispatchedModeSpawnOptions } from './dispatchedModes';
import { type ResolvedPrompt, resolvePrompt } from './prompt';
const DSH_AGENT_TYPE = 'deepseek-harness';
export const SUPPORTED_AGENT_TYPES = new Set<string>([
...LOCAL_HETEROGENEOUS_AGENT_TYPES,
DSH_AGENT_TYPE,
]);
/**
* Extra env for the spawned agent process.
*
* In server-ingest mode the run's operation and conversation arrive as CLI
* arguments, not env, so the agent's own shell could not name them. Commands it
* runs on behalf of this conversation β `lh goal create --conversation` for
* `/goal`, evidence ingests β read `LOBEHUB_OPERATION_ID` / `LOBEHUB_TOPIC_ID`,
* so they are echoed into the child. A standalone run has no server identity
* and passes none.
*/
export const buildAgentProcessEnv = ({
operationId,
pathEnv,
topicId,
}: {
operationId?: string;
pathEnv?: string;
topicId?: string;
}): Record<string, string> | undefined => {
const env: Record<string, string> = {
...(pathEnv ? { PATH: pathEnv } : {}),
...(operationId ? { LOBEHUB_OPERATION_ID: operationId } : {}),
...(topicId ? { LOBEHUB_TOPIC_ID: topicId } : {}),
};
return Object.keys(env).length > 0 ? env : undefined;
};
const SUPPORTED_AGENT_TITLES = [
...HETEROGENEOUS_AGENT_CONFIGS.map(({ title }) => title),
'DeepSeek Harness',
].join(' / ');
const SUPPORTED_AGENT_COMMANDS = HETEROGENEOUS_AGENT_CONFIGS.map(
({ defaultCommand }) => `\`${defaultCommand}\``,
).join(', ');
/**
* Runtime factories for `lh hetero exec`. Pi uses RPC; other agents fall
* through to the generic one-shot `spawnAgent`.
*/
const spawnRuntimeRegistry: Partial<
Record<
LocalHeterogeneousAgentType,
(
spawnOpts: Parameters<typeof spawnAgent>[0],
lifecycle?: {
onRawStdout?: (chunk: Buffer) => void;
onStartupControl?: (control: PiRpcStartupControl) => void;
},
) => Promise<Awaited<ReturnType<typeof spawnAgent>>>
>
> = {
pi: async (spawnOpts, lifecycle) =>
createPiRpcAgentHandle({
...(await preparePiRpcInput(spawnOpts.prompt, {
args: spawnOpts.extraArgs ?? [],
lobeHubContext: !!spawnOpts.env?.LOBEHUB_TOPIC_ID,
})),
commandPath: spawnOpts.command!,
cwd: spawnOpts.cwd ?? process.cwd(),
detached: spawnOpts.detached,
env: { ...process.env, ...spawnOpts.env },
operationId: spawnOpts.operationId,
onRawStdout: lifecycle?.onRawStdout,
onStartupControl: lifecycle?.onStartupControl,
resumeSessionId: spawnOpts.resumeSessionId,
uploadImage: spawnOpts.uploadImage,
}),
};
/**
* Spawn via the registered runtime factory, or the generic one-shot spawn.
* `onRawStdout` (raw-dump tee) reaches both generic and registered runtimes;
* RPC runtimes must install it before their eager handshake.
*/
const spawnAgentOrRuntime = (
spawnOpts: Parameters<typeof spawnAgent>[0],
onRawStdout?: (chunk: Buffer) => void,
onStartupControl?: (control: PiRpcStartupControl) => void,
nativeCodex?: boolean,
): Promise<Awaited<ReturnType<typeof spawnAgent>>> => {
if (nativeCodex)
return createCodexAgentHandle({
askUserBridge: spawnOpts.askUserBridge,
clientVersion: cliVersion,
args: spawnOpts.extraArgs ?? [],
collaborationMode: spawnOpts.collaborationMode,
commandPath: spawnOpts.command!,
cwd: spawnOpts.cwd ?? process.cwd(),
env: { ...process.env, ...spawnOpts.env },
onRawStdout,
onStartupControl,
operationId: spawnOpts.operationId,
prompt: spawnOpts.prompt,
resumeSessionId: spawnOpts.resumeSessionId,
});
const runtimeFactory = spawnRuntimeRegistry[spawnOpts.agentType as LocalHeterogeneousAgentType];
if (runtimeFactory) return runtimeFactory(spawnOpts, { onRawStdout, onStartupControl });
return spawnAgent({ ...spawnOpts, onRawStdout });
};
/**
* Patterns that indicate a `--resume <sessionId>` run should be retried
* without `--resume`. Two classes of failure:
* 1. Session file missing (sandbox recycled): the container is ephemeral
* (~1 h idle TTL), so a new sandbox has an empty `~/.claude/projects/`
* and the stored session id is stale.
* 2. Context overflow (long conversation): the resumed session carries all
* accumulated history past the model's context window, so the API rejects
* the request right after CC initialises. Starting fresh (no `--resume`)
* drops the old history and lets CC respond to the new prompt alone.
*
* Checked against `error` stream events (from CC's result event) and, when CC
* exits without a result event, the accumulated stderr output.
*/
const RESUME_RETRY_PATTERNS = [
// Session file missing β sandbox was recycled
/no conversation found/i,
/session.*not found/i,
/conversation.*not found/i,
/resume.*not found/i,
// Codex reports a missing saved thread (exec and app-server alike) as
// "thread/resume failed: no rollout found for thread id <id>".
/no rollout found/i,
// Context overflow β API rejected the resumed session's accumulated history
/prompt.*too long/i,
/context.*too long/i,
/context window.*exceed/i,
/maximum.*context.*length/i,
] as const;
const looksLikeNeedsRetryWithoutResume = (text: string): boolean =>
RESUME_RETRY_PATTERNS.some((p) => p.test(text));
const isMissingGrokResumeSession = (data: Record<string, unknown> | undefined): boolean => {
if (data?.agentType !== 'grok-build' || !isRecord(data.details)) return false;
const { details } = data;
const rpcData = details.data;
return details.method === 'session/load' && isRecord(rpcData) && rpcData.code === 'FS_NOT_FOUND';
};
interface ExecOptions extends HeteroCliArgumentOptions {
/** Explicit device protocol capability; unsupported native options fail closed. */
codexAppServer?: boolean;
command?: string;
cwd?: string;
image?: string[];
inputJson?: string;
operationId?: string;
prompt?: string;
/**
* When set, persist the agent process's RAW stdout/stderr (pre-adapter
* stream-json) under `<rawDump>/<timestamp>-<operationId>/` for debugging.
* Independent of `--render` and the server ingest path.
*/
rawDump?: string;
/**
* Output rendering mode.
* jsonl β emit each `AgentStreamEvent` as a JSONL line on stdout (default
* when no --topic is set, or when explicitly requested).
* none β suppress JSONL stdout; only server-ingest mode is active.
* Default when --topic is set and running non-interactively.
*/
render?: 'jsonl' | 'none';
resume?: string;
/**
* Server topic id. When set, enables server-ingest mode: events are
* batch-POSTed to `aiAgent.heteroIngest` in addition to (or instead of)
* being written to stdout. Requires `--operation-id` to be a valid
* server-allocated operation id.
*/
topic?: string;
}
const collectImage = (value: string, previous: string[] = []): string[] => [...previous, value];
const collectAgentArg = (value: string, previous: string[] = []): string[] => [...previous, value];
interface RawStreamDumpAttempt {
/** Flush + close both file streams. Resolves once the bytes are on disk. */
close: () => Promise<void>;
writeStderr: (chunk: Buffer) => void;
writeStdout: (chunk: Buffer) => void;
}
/**
* Persists the agent process's RAW stdout/stderr β the untouched stream-json,
* BEFORE the adapter β to disk for post-hoc debugging. The adapted/ingested
* view can't tell a CC-side empty `tool_result` apart from an adapter
* extraction bug; the raw dump can.
*
* Enabled via `lh hetero exec --raw-dump <dir>`. Each exec gets its own
* `<dir>/<timestamp>-<operationId>/` session folder; each spawn attempt (the
* resume retry is a second attempt) writes `<label>.stdout.jsonl` /
* `<label>.stderr.log`. Fully best-effort: any dump failure is logged and
* swallowed so it never affects the run or its exit code.
*
* Future: the server-side sandbox runner (`spawnHeteroSandbox`) and the
* desktop device path (`spawnLhHeteroExec`) can pass `--raw-dump` pointing at
* a collectable location to capture remote runs the same way.
*/
class RawStreamDump {
private constructor(private readonly dir: string) {}
static async create(
root: string,
operationId: string,
meta: Record<string, unknown>,
): Promise<RawStreamDump | undefined> {
try {
const safeTs = new Date().toISOString().replaceAll(/[.:]/g, '-');
const dir = path.join(path.resolve(root), `${safeTs}-${operationId}`);
await mkdir(dir, { recursive: true });
await writeFile(
path.join(dir, 'meta.json'),
`${JSON.stringify({ ...meta, operationId, startedAt: new Date().toISOString() }, null, 2)}\n`,
);
log.info(`Raw stream dump enabled β ${dir}`);
return new RawStreamDump(dir);
} catch (err) {
log.warn(
`Failed to initialize raw stream dump: ${err instanceof Error ? err.message : String(err)}`,
);
return undefined;
}
}
openAttempt(label: string): RawStreamDumpAttempt {
const stdout = createWriteStream(path.join(this.dir, `${label}.stdout.jsonl`));
const stderr = createWriteStream(path.join(this.dir, `${label}.stderr.log`));
// A failed dump write must never crash the run β drop write errors.
stdout.on('error', () => {});
stderr.on('error', () => {});
return {
close: () =>
Promise.all([
new Promise<void>((resolve) => stdout.end(() => resolve())),
new Promise<void>((resolve) => stderr.end(() => resolve())),
]).then(() => undefined),
writeStderr: (chunk: Buffer) => {
stderr.write(chunk);
},
writeStdout: (chunk: Buffer) => {
stdout.write(chunk);
},
};
}
}
const exec = async (options: ExecOptions): Promise<void> => {
if (!SUPPORTED_AGENT_TYPES.has(options.type)) {
log.error(
`Unsupported --type "${options.type}". Supported: ${[...SUPPORTED_AGENT_TYPES].join(', ')}`,
);
process.exit(2);
}
if (options.codexAppServer && options.type !== 'codex') {
throw new Error('Native Codex options require --type codex');
}
let resolved: ResolvedPrompt;
try {
resolved = await resolvePrompt(options);
} catch (err) {
log.error(err instanceof Error ? err.message : String(err));
process.exit(2);
}
if (!resolved.describe()) {
log.error(
'Empty prompt. Pass --prompt <text>, --image <path>, --input-json <file|->, or pipe content via stdin.',
);
process.exit(2);
}
// Server-ingest mode is active when --topic is provided.
// --operation-id must be a server-allocated id in this mode (the server
// generates it before spawning the process and passes it via CLI args).
const serverIngest = !!options.topic;
if (serverIngest && !options.operationId) {
log.error('--operation-id is required when --topic is set (server-ingest mode).');
process.exit(2);
}
const operationId = options.operationId || randomUUID();
// Optional raw stream dump (pre-adapter stdout/stderr) for debugging.
let rawDump: RawStreamDump | undefined;
if (options.rawDump) {
rawDump = await RawStreamDump.create(options.rawDump, operationId, {
agentType: options.type,
cwd: options.cwd || process.cwd(),
resume: options.resume ?? null,
topicId: options.topic ?? null,
});
}
// Local execution trace. Recorded for EVERY run, not just server-ingest ones:
// a standalone `lh hetero exec` is exactly the case where nothing else keeps
// a record of what the agent did, and it is the same snapshot format a native
// agent run produces, so `lh trace op inspect` reads both.
const traceRecorder = new HeteroTraceRecorder({
agentType: options.type,
operationId,
onError: (message) => log.warn(`Trace: ${message}`),
store: createLocalTraceStore(),
topicId: options.topic,
});
// Determine JSONL output mode.
// Explicit --render flag always wins. Otherwise: emit JSONL in standalone
// mode; suppress in server-ingest mode (sink handles the data path).
const emitJsonl = options.render === 'jsonl' || (options.render === undefined && !serverIngest);
// Build the ingest sink β no-op for standalone mode, real tRPC sink for
// server-ingest mode. The tRPC client reads LOBEHUB_JWT (operation-scoped
// JWT injected by the server) for authentication.
const agentType = options.type;
let sink: TrpcIngestSink | undefined;
let serverIngester: CoalescingBatchIngester | undefined;
// Set for the duration of each spawn attempt (see `runOneAgent`): stops the
// running agent when the server tells us its output is being discarded.
let abortForIngestLoss: ((error: Error) => void) | undefined;
// Uploader for tool_result images (CC `Read` on an image file). Reuses the
// CLI's authenticated lambda client so the persisted event carries a
// `{ fileId, url }` reference instead of heavy base64. Only wired in
// server-ingest mode β standalone runs don't persist events, so there is
// nothing to echo. The pipeline degrades a throw/undefined to the
// `[Image: β¦]` text placeholder, so this never fails the run.
let uploadImage: UploadHeterogeneousImage | undefined;
if (serverIngest) {
const client = await getTrpcClient();
sink = new TrpcIngestSink(
client,
agentType,
operationId,
options.topic!,
process.env.LOBEHUB_ASSISTANT_MESSAGE_ID,
);
serverIngester = new CoalescingBatchIngester(sink, undefined, (error) => {
// The server has stopped storing this run's events (its topic marker was
// settled underneath it, or the operation is already terminal) and every
// later batch would be discarded the same way. Waiting for `drain()` to
// report that means the agent keeps working β for minutes, on a long task
// β to produce output nobody will ever see. Stop it now; the drain below
// still raises the same error, so the finish leg reports a failed run.
abortForIngestLoss?.(error);
});
uploadImage = createFileStoreImageUploader(async () => {
const lambda = await getTrpcClient();
return {
abortS3Upload: (input) => lambda.upload.abortS3Upload.mutate(input),
checkFileHash: (input) => lambda.file.checkFileHash.mutate(input),
createFile: (input) => lambda.file.createFile.mutate(input),
createS3PreSignedUrl: (input) => lambda.upload.createS3PreSignedUrl.mutate(input),
};
});
}
const operationHeartbeat =
serverIngester && operationId
? createOperationHeartbeat({
operationId,
push: (event) => serverIngester.push(event),
})
: undefined;
// The heartbeat only renews the lease while the token under it is valid. The
// server signs that token for four hours; a longer run renews it in place, or
// every ingest after that point is rejected and the operation is reclaimed.
const operationTokenRenewal =
serverIngester && operationId
? createOperationTokenRenewal({
operationId,
renew: async (id) =>
(await getTrpcClient()).aiAgent.refreshHeteroOperationToken.mutate({ operationId: id }),
})
: undefined;
// DSH (an `acp`-profile runtime, no CLI descriptor) keeps the CLI agents' surface and
// identity echo, but drives its ACP session directly on the validated `dsh` + its PATH.
if (agentType === DSH_AGENT_TYPE) {
const hasImages =
typeof resolved.prompt !== 'string' &&
resolved.prompt.some((block) => block.type === 'image');
if (hasImages) {
log.error('DeepSeek Harness currently accepts text prompts only.');
process.exit(2);
}
const prompt =
typeof resolved.prompt === 'string'
? resolved.prompt
: resolved.prompt
.map((block) => (block.type === 'text' ? block.text : ''))
.filter(Boolean)
.join('\n');
let session: ReturnType<typeof spawnDshAcpSession> | undefined;
let exitCode = 0;
// Same contract as `runOneAgent`: once the server discards this run's
// output, stop the harness instead of letting it keep calling the model
// and running tools until natural idle.
let ingestLoss: Error | undefined;
abortForIngestLoss = (error) => {
if (ingestLoss) return;
ingestLoss = error;
log.error('Server is discarding this run output, stopping the agent:', error.message);
void session?.dispose().catch(() => {});
};
try {
const dshCommand = await resolveDshSpawnCommand(options.command);
session = spawnDshAcpSession({
args: options.agentArg,
clientVersion: 'lobehub-cli',
command: dshCommand.command,
cwd: options.cwd || process.cwd(),
env: buildAgentProcessEnv({
operationId: serverIngest ? operationId : undefined,
pathEnv: dshCommand.pathEnv,
topicId: options.topic,
}),
model: options.model,
operationId,
// `--resume` continues the persisted harness session.
resumeSessionId: options.resume,
});
// The loss may have landed (via the heartbeat) before the turn started.
if (ingestLoss) throw ingestLoss;
let terminalError: string | undefined;
for await (const event of session.prompt(prompt)) {
if (event.type === 'error') {
const data = event.data as Record<string, unknown> | undefined;
terminalError = String(data?.message ?? data?.error ?? '') || 'DSH execution failed';
}
if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
operationHeartbeat?.observe(event);
traceRecorder.observe(event);
serverIngester?.push(event);
if (ingestLoss) break;
}
if (ingestLoss) throw ingestLoss;
operationHeartbeat?.stop();
await serverIngester?.drain();
const finishError = terminalError
? { message: terminalError, type: 'AgentRuntimeError' }
: undefined;
// Before the sink, so a failing server call still leaves a snapshot.
await traceRecorder.finalize({
error: finishError,
result: terminalError ? 'error' : 'success',
});
if (sink) {
await sink.finish({
error: finishError,
result: terminalError ? 'error' : 'success',
sessionId: session.sessionId,
});
}
if (terminalError) exitCode = 1;
} catch (caught) {
exitCode = 1;
// A killed runtime reports its own exit; the ingest loss is the real cause.
const error = ingestLoss ?? caught;
const message = error instanceof Error ? error.message : String(error);
log.error('DeepSeek Harness execution failed:', message);
operationHeartbeat?.stop();
await traceRecorder.finalize({
error: { message, type: 'AgentRuntimeError' },
result: 'error',
});
if (sink) {
await serverIngester?.drain().catch(() => {});
await sink
.finish({
error: { message, type: 'AgentRuntimeError' },
result: 'error',
sessionId: session?.sessionId ?? options.resume,
})
.catch(() => {});
}
} finally {
abortForIngestLoss = undefined;
operationTokenRenewal?.stop();
await session?.dispose().catch(() => {});
}
process.exit(exitCode);
}
// The public set also contains runtime-backed providers such as DSH. Past
// this branch the existing spawn pipeline requires a descriptor-backed CLI.
if (!isLocalHeterogeneousType(agentType)) {
throw new TypeError(`Unsupported CLI-backed heterogeneous agent type: ${agentType}`);
}
// βββ AskUserQuestion MCP β remote Human-in-the-loop ββββββββββββββββββββββββ
//
// MCP and native Codex share the desktop's AskUserBridge. Requests flow
// through durable ingest to the question card; long-poll returns browser
// answers from the server's Redis stream to the blocked native callback.
// The bridge timeout bounds the wait, including native Codex requests.
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
let askServer: LobeBuiltinMcpServer | undefined;
let askBridge: AskUserBridge | undefined;
let askMcpConfigPath: string | undefined;
const askPollAbort = new AbortController();
const mcpAskUserProvider =
agentType === 'claude-code' || agentType === 'qoder' ? agentType : undefined;
const nativeAskUserProvider =
agentType === 'antigravity' ||
(agentType === 'codex' && options.codexAppServer) ||
agentType === 'copilot' ||
agentType === 'cursor' ||
agentType === 'devin' ||
agentType === 'droid'
? agentType
: undefined;
if (serverIngest && serverIngester && (mcpAskUserProvider || nativeAskUserProvider)) {
if (nativeAskUserProvider) {
askBridge = new AskUserBridge(operationId, {
identifier: nativeAskUserProvider === 'cursor' ? 'claude-code' : nativeAskUserProvider,
provider: nativeAskUserProvider,
});
} else if (mcpAskUserProvider) {
askServer = new LobeBuiltinMcpServer();
await askServer.start();
askBridge = askServer.registerOperation(
operationId,
new AskUserBridge(operationId, {
identifier: mcpAskUserProvider,
provider: mcpAskUserProvider,
}),
);
askMcpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);
await writeFile(
askMcpConfigPath,
JSON.stringify({
mcpServers: {
lobe_cc: {
alwaysLoad: true,
type: 'http',
url: askServer.urlForOperation(operationId),
},
},
}),
'utf8',
);
}
// (i) Forward every bridge event into the same ordered durable ingest path
// as CC's. Browser submit already XADDed a response for producer delivery,
// but that is only transport acceptance. The bridge echo after resolve is
// the producer ACK (producerAck=true + resolutionRequestId) that transitions
// Cloud from `resolving` to terminal. Persistence de-dupes transitions by
// (operationId, toolCallId, transition).
void (async () => {
for await (const event of askBridge!.events()) {
serverIngester!.push(event as AgentStreamEvent);
}
})();
// (ii) Long-poll the server for the user's answer β only while a question is
// actually pending, so an idle run holds no server invocation.
void (async () => {
const client = await getTrpcClient();
// Start at the beginning of this operation stream. A response can be
// published after `pendingCount` flips but before the first XREAD; `$`
// would skip that already-present response and strand the CLI until the
// bridge timeout. Unknown/stale tool ids are harmless (`resolve` no-ops).
let lastEventId = '0-0';
while (!askPollAbort.signal.aborted) {
if (askBridge!.pendingCount === 0) {
await sleep(200);
continue;
}
try {
const res = await client.aiAgent.waitInterventionResponse.query({
lastEventId,
operationId,
});
lastEventId = res.lastEventId;
for (const event of res.events) {
const data = event.data as {
cancelReason?: 'session_ended' | 'timeout' | 'user_cancelled';
cancelled?: boolean;
result?: unknown;
resolutionRequestId?: string;
toolCallId: string;
};
// Idempotent: resolve() no-ops on an unknown / already-settled id.
askBridge!.resolve(data.toolCallId, {
cancelReason: data.cancelReason,
cancelled: data.cancelled,
result: data.result,
resolutionRequestId: data.resolutionRequestId,
});
}
} catch {
// Transient (server hiccup / token refresh) β back off and retry.
// The bridge's 10-min timeout still bounds the overall wait.
await sleep(1000);
}
}
})();
}
/**
* 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,
command: options.command,
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.
*
* When `interceptResumeErrors` is true, any `error`-type event whose
* message matches `RESUME_RETRY_PATTERNS` is withheld from the
* ingester and signals a retry instead. This keeps the server's
* operation state clean: no terminal error event is pushed, so the
* retry's events land on the same operationId without confusing the
* renderer.
*
* Returns:
* code / signal β child exit info
* cancelled β true when this CLI received SIGINT/SIGTERM for the run
* sessionId β CC session id from `system.init` (undefined on resume failure)
* ingestError β true when a batch could not be flushed after retries
* resumeNotFound β true when a resume-not-found error was intercepted
* sawTerminalError β true when a terminal `error` event was pushed to the
* ingester (CC can relay an API/rate-limit error this way
* and still exit 0, so the exit code alone is not enough)
* terminalErrorMessage β the message from that terminal `error` event, used
* as the task-level error detail in the finish payload
* terminalErrorData β the full structured payload of that terminal `error`
* event when the adapter already classified it into a
* status-guide error (overloaded / rate_limit / β¦); the
* finish leg forwards it verbatim as the error `body` so
* the client renders the dedicated guide instead of the
* generic error card
* stderrContent β accumulated stderr (only when interceptResumeErrors=true)
*/
const runOneAgent = async (
spawnOpts: Parameters<typeof spawnAgent>[0],
interceptResumeErrors: boolean,
runLabel: string,
): Promise<{
cancelled: boolean;
code: number | null;
ingestError: boolean;
resumeNotFound: boolean;
sawTerminalError: boolean;
sessionId: string | undefined;
signal: NodeJS.Signals | null;
stderrContent: string;
terminalErrorData: Record<string, unknown> | undefined;
terminalErrorMessage: string | undefined;
}> => {
// Own terminal signals before the async factory starts. Pi exposes its
// startup control synchronously once constructed; cancellation received
// during prompt normalization is remembered and applied at that point.
const inheritsWrapperProcessGroup =
process.platform !== 'win32' && process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] === '1';
let interrupted = false;
let cancellationSignal: NodeJS.Signals | undefined;
let handle: Awaited<ReturnType<typeof spawnAgent>> | undefined;
let startupControl: PiRpcStartupControl | undefined;
const cancellations: Promise<void>[] = [];
let cancellationError: unknown;
const cancelStartup = (control: PiRpcStartupControl, signal: NodeJS.Signals) => {
cancellations.push(
control.cancel(signal).catch((error) => {
cancellationError ??= error;
log.error(
'Failed to cancel agent:',
error instanceof Error ? error.message : String(error),
);
}),
);
};
const drainCancellation = async () => {
await Promise.all(cancellations);
if (cancellationError) throw cancellationError;
};
// Deliberately NOT `interrupted`: the user did not stop this run, so the
// finish leg must report `error` (with the ingest failure as its detail)
// rather than `cancelled`, which would leave the operation running on the
// server with nothing left to drive it.
let ingestLoss: Error | undefined;
// Inside an inherited wrapper group an external SIGINT/SIGTERM already
// reaches the agent, so forwarding it would signal twice. An ingest-loss
// abort has no OS signal behind it β the CLI decided on its own β so it
// must always deliver the signal itself, or the agent keeps running (the
// desktop and connected-device dispatches are exactly the inherited case).
// Native app-server owns a detached process even inside the connect wrapper group.
const ownsSignalDelivery = () =>
options.codexAppServer || !inheritsWrapperProcessGroup || ingestLoss !== undefined;
const signalAgent = (signal: NodeJS.Signals) => {
if (startupControl) cancelStartup(startupControl, signal);
else handle?.kill(signal);
};
const applyCancellation = (signal: NodeJS.Signals) => {
cancellationSignal = signal;
if (!ownsSignalDelivery()) {
// The process group already delivered the OS signal, so a second one
// would be a duplicate β but session transports (ACP, RPC) carry a
// protocol-level cancel the signal cannot express. Notify it so the
// session classifies the agent's resulting exit as host-driven
// cancellation rather than reporting a transport crash.
if (startupControl) cancelStartup(startupControl, signal);
else handle?.interrupt?.(signal);
return;
}
signalAgent(signal);
};
const onSigint = () => {
const signal = interrupted ? 'SIGKILL' : 'SIGINT';
interrupted = true;
applyCancellation(signal);
};
const onSigterm = () => {
interrupted = true;
applyCancellation('SIGTERM');
};
const removeSignalListeners = () => {
process.off('SIGINT', onSigint);
process.off('SIGTERM', onSigterm);
abortForIngestLoss = undefined;
};
process.on('SIGINT', onSigint);
process.on('SIGTERM', onSigterm);
abortForIngestLoss = (error) => {
if (ingestLoss) return;
ingestLoss = error;
log.error('Server is discarding this run output, stopping the agent:', error.message);
applyCancellation('SIGTERM');
};
// One raw-dump file pair per spawn attempt (the resume retry is a second
// attempt). The stdout tee runs inside `spawnAgent` before the adapter.
const dumpAttempt = rawDump?.openAttempt(runLabel);
// `spawnAgent` is async and can reject DURING image normalization β fetch
// failures, missing local --image paths, decode errors. The runtime
// registry picks the transport: pi runs over RPC, everything else spawns
// one-shot (same handle shape, so the event loop below is unchanged).
try {
handle = await spawnAgentOrRuntime(
spawnOpts,
dumpAttempt?.writeStdout,
(control) => {
startupControl = control;
// `control.cancel` is protocol-level (session abort), not an OS signal
// β replay any cancellation received before the control bound, even
// when the process group already delivered the signal itself.
if (cancellationSignal) cancelStartup(control, cancellationSignal);
},
options.codexAppServer,
);
if (cancellationSignal && !startupControl) {
// Same split as `applyCancellation`: when the wrapper does not own
// signal delivery the process group already signaled the agent, but
// session transports still need the protocol-level cancel.
if (ownsSignalDelivery()) handle.kill(cancellationSignal);
else handle.interrupt?.(cancellationSignal);
}
} catch (err) {
try {
await drainCancellation();
await dumpAttempt?.close();
} finally {
removeSignalListeners();
}
if (cancellationSignal) {
return {
cancelled: !ingestLoss,
code: null,
ingestError: ingestLoss !== undefined,
resumeNotFound: false,
sawTerminalError: false,
sessionId: undefined,
signal: cancellationSignal,
stderrContent: '',
terminalErrorData: undefined,
terminalErrorMessage: undefined,
};
}
const message = err instanceof Error ? err.message : String(err);
const errnoCode =
typeof err === 'object' && err && 'code' in err && typeof err.code === 'string'
? err.code
: undefined;
log.error('Failed to start agent:', message);
await traceRecorder.finalize({
error: buildFinishError(message, 'AgentRuntimeError', errnoCode),
result: 'error',
});
if (serverIngester && sink) {
try {
await serverIngester.drain();
await sink.finish({
error: buildFinishError(message, 'AgentRuntimeError', errnoCode),
result: 'error',
});
} catch {
// best-effort; process is exiting anyway
}
}
process.exit(1);
}
// Always collect stderr β used for resume-error detection AND for
// surfacing a meaningful error message to the server when CC fails
// without emitting a structured error event. Cap at 8 KB so the
// collector doesn't grow unboundedly on a chatty run.
// Always pipe to process.stderr too so users see auth prompts / warnings.
const STDERR_CAP = 8 * 1024;
let stderrContent = '';
const stderrEnded = once(handle.stderr, 'end').then(() => undefined);
handle.stderr.on('data', (chunk: Buffer) => {
if (stderrContent.length < STDERR_CAP) {
stderrContent += chunk.toString();
}
dumpAttempt?.writeStderr(chunk);
});
handle.stderr.pipe(process.stderr);
const exit = handle.exit.catch((err) => {
const message = err instanceof Error ? err.message : String(err);
if (stderrContent.length < STDERR_CAP) {
stderrContent += `${stderrContent ? '\n' : ''}${message}`;
}
return { code: 1, signal: null as NodeJS.Signals | null };
});
// Stream events (steering Claude Code, native Codex or Antigravity, see withHeteroSteer); each is optionally written as JSONL
// and pushed into the ingester. A resume `error` is withheld and flags a retry instead.
let resumeNotFound = false;
let sawTerminalError = false;
let terminalErrorMessage: string | undefined;
let terminalErrorData: Record<string, unknown> | undefined;
try {
const steerContext = !!sink && {
getTrpcClient,
isWaitingForUser: () => (askBridge?.pendingCount ?? 0) > 0,
operationId,
};
for await (const event of withHeteroSteer(handle, steerContext)) {
if (interceptResumeErrors && event.type === 'error') {
const data = event.data as Record<string, unknown> | undefined;
const msg = String(data?.message ?? data?.error ?? '');
if (looksLikeNeedsRetryWithoutResume(msg) || isMissingGrokResumeSession(data)) {
resumeNotFound = true;
// Emit to JSONL for observability but do NOT push to ingester β
// we are about to retry; the server must not see a terminal error.
// The local trace still records it: "attempt 1 could not resume" is
// the whole reason someone reads the trace back.
if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
traceRecorder.observe(event);
continue;
}
}
// A terminal `error` (e.g. a rate limit CC relays on stdout) fails the run even on
// exit 0; its message becomes the finish payload's task-level error detail.
if (event.type === 'error') {
sawTerminalError = true;
const data = event.data as Record<string, unknown> | undefined;
terminalErrorMessage = String(data?.message ?? data?.error ?? '') || undefined;
// Keep the adapter's classified status-guide payload (overloaded / rate_limit carry
// `agentType` + `code`): the finish leg's classifier only knows cli/auth failures.
terminalErrorData = isHeteroStatusGuideErrorData(data) ? data : undefined;
}
if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
operationHeartbeat?.observe(event);
traceRecorder.observe(event);
serverIngester?.push(event);
}
} catch (err) {
log.error(
'Stream error from agent process:',
err instanceof Error ? err.message : String(err),
);
await traceRecorder.finalize({
error: buildFinishError(
String(err),
'stream_error',
(err as NodeJS.ErrnoException | null)?.code,
),
result: 'error',
});
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: buildFinishError(
String(err),
'stream_error',
(err as NodeJS.ErrnoException | null)?.code,
),
result: 'error',
});
} catch {
// best-effort
}
}
await dumpAttempt?.close();
try {
await drainCancellation();
} finally {
removeSignalListeners();
}
process.exit(1);
}
const { code, signal } = await exit;
await stderrEnded;
await dumpAttempt?.close();
try {
await drainCancellation();
} finally {
removeSignalListeners();
}
// Fallback stderr detection: CC may exit non-zero without emitting a
// result event (e.g. it writes to stderr and quits immediately).
if (
interceptResumeErrors &&
!resumeNotFound &&
code !== 0 &&
looksLikeNeedsRetryWithoutResume(stderrContent)
) {
resumeNotFound = true;
}
return {
cancelled: interrupted,
code,
// The shared ingester is permanently failed once the server refused a
// batch, so the caller must neither retry this run (every event of a
// retry would be dropped, with no second abort to stop it) nor report it
// as anything but failed.
ingestError: ingestLoss !== undefined,
resumeNotFound,
sawTerminalError,
sessionId: handle.sessionId,
signal,
stderrContent,
terminalErrorData,
terminalErrorMessage,
};
};
// βββ First run (with --resume if provided) βββββββββββββββββββββββββββββββ
const interceptResume = !!options.resume;
const extraArgs = [
...(buildExtraArgs(options) ?? []),
// Point the supported CLI at the lobe_cc AskUserQuestion MCP server we just mounted.
...(askMcpConfigPath ? ['--mcp-config', askMcpConfigPath] : []),
];
// Resolve the CLI binary once, up front, and reuse it for both the initial
// run and the resume-retry. For each provider's default bare command
// this finds the validated binary β including an app-bundled Codex CLI when
// a broken `codex` shim shadows PATH β so sandbox/terminal runs no longer
// ENOENT on a stale global install. Custom commands are used verbatim.
const resolvedCommand = await resolveHeteroSpawnCommand(agentType, options.command);
const commandEnv = buildAgentProcessEnv({
operationId: serverIngest ? operationId : undefined,
pathEnv: resolvedCommand.pathEnv,
topicId: options.topic,
});
const spawnOptions = {
agentType: options.type,
askUserBridge: askBridge,
command: resolvedCommand.command,
commandVersion: resolvedCommand.version,
cwd: options.cwd || process.cwd(),
detached: process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] !== '1',
env: commandEnv,
extraArgs,
// Device and sandbox executions are observed through the same gateway stream as native
// server agents. Ask Claude Code for content-block deltas so the current conversation
// receives text while the process is running, not only the terminal assistant snapshot.
includePartialMessages: options.type === 'claude-code',
initialModel: usesHeterogeneousSessionInitialModel(options.type) ? options.model : undefined,
// Keep Claude Code's stdin open while it can still use input: closing it
// early makes print mode kill background tasks after 10 minutes.
liveInput: options.type === 'claude-code',
operationId,
// Claude Code permission mode, Codex Plan switch.
...dispatchedModeSpawnOptions(options.type, resolved),
uploadImage,
};
const first = await runOneAgent(
{ ...spawnOptions, prompt: resolved.prompt, resumeSessionId: options.resume },
interceptResume,
'attempt-1',
);
// βββ Auto-retry without --resume when the session cannot be used βββββββββ
//
// Two classes of failure detected via `RESUME_RETRY_PATTERNS`:
// A. Sandbox recycled: container is ephemeral (~1 h idle TTL); new sandbox
// has no CC session files so `--resume <staleId>` is rejected with a
// "no conversation found" error.
// B. Context overflow: the resumed session carries accumulated history that
// pushes the combined token count past the model limit; the API rejects
// the call with a "prompt is too long" error.
//
// In both cases we transparently restart CC without `--resume` so it starts a
// fresh session. The server's `heteroSessionId` is updated with the new id,
// breaking the stale-session loop.
let result = first;
if (!first.cancelled && !first.ingestError && first.resumeNotFound) {
log.info('Resume failed (session not found or context overflow) β retrying without --resume');
result = await runOneAgent(
// No resumeSessionId β start fresh
{ ...spawnOptions, prompt: resolved.resumeFallbackPrompt ?? resolved.prompt },
false, // no need to intercept resume errors on a fresh run
'attempt-2-noresume',
);
}
// βββ Drain + finish βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const { code, signal, sessionId } = result;
// Why the run failed to upload, when it did. `sawTerminalError`/stderr stay
// ahead of it: those explain a failing agent, while this explains an agent
// that worked and lost its output β the least obvious of the three, and the
// only one with no other trace in the conversation.
let ingestErrorMessage: string | undefined;
if (serverIngester && sink) {
operationHeartbeat?.stop();
try {
await serverIngester.drain();
} catch (err) {
ingestErrorMessage = err instanceof Error ? err.message : String(err);
log.error('Failed to flush events to server:', ingestErrorMessage);
result = { ...result, ingestError: true };
}
}
// CC relays API/rate-limit errors as an in-stream terminal `error` event but
// still exits 0, so the exit code alone would report `success`. Treat any
// pushed terminal error as a failed run so the topic/task is marked failed.
const exitedClean =
!result.cancelled &&
!result.ingestError &&
!result.sawTerminalError &&
(code === 0 || signal === 'SIGTERM');
// When the run failed, pass an error detail so the server surfaces a useful
// message instead of the generic "Agent execution failed" fallback. Prefer
// the in-stream terminal error (CC relays API/rate-limit errors here while
// exiting 0, so stderr is empty), then the upload failure (a clean agent whose
// output never landed leaves nothing on stderr either), then the stderr tail.
// Trim to the last 1 KB β the tail is most informative and keeps the tRPC
// payload small.
const stderrTail = result.stderrContent.trim();
const errorDetail = result.terminalErrorMessage || ingestErrorMessage || stderrTail;
// The adapter's in-stream classification (overloaded / rate_limit) already
// carries the structured status-guide body β forward it verbatim instead of
// re-deriving from the flattened message via the process-only classifier,
// which would drop `agentType`/`code` and demote the client UI to the
// generic error card.
const finishError =
result.cancelled || exitedClean
? undefined
: result.terminalErrorData
? {
body: { ...result.terminalErrorData },
message: String(result.terminalErrorData.message ?? errorDetail ?? ''),
type: 'AgentRuntimeError',
}
: errorDetail
? buildFinishError(errorDetail.slice(-1024), 'AgentRuntimeError')
: undefined;
const runResult = result.cancelled ? 'cancelled' : exitedClean ? 'success' : 'error';
// Close the local trace for EVERY run β the outcome is derived above from the
// same signals the server finish uses, so a standalone run records the same
// completion reason a server-ingest one does. Runs before the sink so a
// failing server call still leaves a complete snapshot on disk.
await traceRecorder.finalize({ error: finishError, result: runResult });
let finishDeliveryFailed = false;
if (serverIngester && sink) {
try {
await sink.finish({
error: finishError,
resumeSessionInvalidated: first.resumeNotFound || undefined,
result: runResult,
sessionId,
});
} catch (err) {
finishDeliveryFailed = true;
log.error('Failed to send heteroFinish:', err instanceof Error ? err.message : String(err));
}
}
// Only now: the drain and the finish receipt above both authenticate with the
// operation token, and either can sit in retries long enough for it to expire.
operationTokenRenewal?.stop();
// Tear down the AskUserQuestion MCP: stop polling, cancel any in-flight
// pending (β CC's tool returns cleanly), close the server, drop the temp
// config. Best-effort β the process is about to exit anyway.
askPollAbort.abort();
if (askServer) {
askServer.unregisterOperation(operationId);
await askServer.stop().catch(() => {});
} else askBridge?.cancelAll('session_ended');
if (askMcpConfigPath) await unlink(askMcpConfigPath).catch(() => {});
if (code !== null) {
const hasRunError =
finishDeliveryFailed || result.ingestError || (!result.cancelled && result.sawTerminalError);
process.exit(hasRunError ? 1 : code);
}
if (signal === 'SIGINT') process.exit(130);
if (signal === 'SIGTERM') process.exit(143);
if (signal === 'SIGKILL') process.exit(137);
process.exit(1);
};
export function registerHeteroCommand(program: Command) {
const hetero = program
.command('hetero')
.description(
`Run heterogeneous agent CLIs (${SUPPORTED_AGENT_TITLES}) and stream their output`,
);
hetero
.command('exec')
.description(
'Spawn a heterogeneous agent CLI and stream its events as JSONL on stdout. Standalone mode (no server ingest).',
)
.requiredOption('-t, --type <type>', `Agent type: ${[...SUPPORTED_AGENT_TYPES].join(' | ')}`)
.option('-p, --prompt [text]', 'Prompt text. Pass `-` (or omit the value) to read from stdin.')
.option(
'-i, --image <path|url>',
'Attach an image (repeatable). Accepts a local path, http(s) URL, or data: URL.',
collectImage,
)
.option(
'--input-json <path>',
'Read full multimodal prompt as JSON content blocks from a file. Use `-` for stdin.',
)
.option('--codex-app-server', 'Run Codex through its native app-server protocol')
.option('-r, --resume <sessionId>', 'Resume an existing agent session by its native id')
.option('-d, --cwd <path>', 'Working directory for the spawned agent (default: process.cwd())')
.option('--mode <mode>', 'Forward a resolved Amp agent mode selection to the agent CLI')
.option('--model <model>', 'Forward a resolved model selection to the agent CLI')
.option('--effort <level>', 'Forward a resolved reasoning effort selection to the agent CLI')
.option(
'--speed <mode>',
'Forward a resolved speed selection to the agent CLI (codex only; `normal`, `fast`, or `ultrafast` selects the service tier)',
)
.option(
'--agent-arg <arg>',
'Forward one native agent CLI argument after wrapper parsing (repeatable)',
collectAgentArg,
)
.option(
'-c, --command <bin>',
`Override the agent runtime binary (CLI defaults: ${SUPPORTED_AGENT_COMMANDS}; DeepSeek Harness defaults to 'dsh --profile acp')`,
)
.option(
'--operation-id <id>',
'Operation id stamped onto every emitted event. Required in server-ingest mode (--topic). Generated as a UUID if omitted (standalone).',
)
.option(
'--topic <topicId>',
'Server topic id. Enables server-ingest mode: events are batch-POSTed to aiAgent.heteroIngest. Requires --operation-id.',
)
.option(
'--render <mode>',
'Output mode: jsonl (emit events as JSONL on stdout) | none (suppress stdout). Defaults to jsonl in standalone, none in server-ingest mode.',
)
.option(
'--raw-dump <dir>',
'Persist the agent process RAW stdout/stderr (pre-adapter stream-json) under <dir>/<timestamp>-<operationId>/ for debugging. Each spawn attempt writes its own .stdout.jsonl / .stderr.log. Best-effort; never affects the run.',
)
.action(exec);
}