π€― 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
β¨ feat(codex): run Codex app-server on connected devices behind Labs (#20820)
Neko5ea695b8b5e8
diff --git a/apps/cli/README.md b/apps/cli/README.mdindex 8f2e0d26127..89efcf33b00 100644--- a/apps/cli/README.md+++ b/apps/cli/README.md@@ -123,3 +123,24 @@ Signal and VFS tests additionally require their documented Agent ID variables.Search fixtures wait up to 60 seconds for asynchronous indexing; a timeout failsthe suite rather than accepting empty results. The command above supplies a livenetwork budget explicitly; this does not change unit-test timeouts or enable retries.++### Native Codex app-server on a connected device++A current CLI advertises `codex-app-server-v1` only after its resolved Codex binary+completes a native app-server handshake. The probe runs once per gateway connection+(and again after 10 minutes), not once per system-info request. `lh connect capabilities`+reports that same capability as JSON without logging in, connecting a device, or creating+a conversation. Desktop gateway connections invoke this command through their bundled+CLI, so an unrelated global CLI cannot determine support. Missing, incompatible, or+timed-out binaries do not advertise native support.++Codex topics run through `codex exec` unless the user enables the+**Codex App Server Runtime** Lab. With the Lab on and a capable connection, the server+runs them through app-server and persists each message's native session and turn IDs.+These topics keep the `codex exec` recovery: a missing native session is retried fresh+with the topic transcript.++The internal `lh hetero exec --codex-app-server` transport uses a per-operation process+that owns cancellation and shell identity. This transport rejects unsupported approval+or sandbox arguments instead of weakening permissions. The richer permission bridge is+maintained separately.diff --git a/apps/cli/src/auth/proactiveRefresh.ts b/apps/cli/src/auth/proactiveRefresh.tsnew file mode 100644index 00000000000..995694cc038--- /dev/null+++ b/apps/cli/src/auth/proactiveRefresh.ts@@ -0,0 +1,64 @@+// How far before expiry to proactively refresh (1 hour)+const PROACTIVE_REFRESH_BUFFER = 60 * 60;++/**+ * Parse the `exp` claim from a JWT without verifying the signature.+ */+function parseJwtExp(token: string): number | undefined {+ try {+ const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());+ return typeof payload.exp === 'number' ? payload.exp : undefined;+ } catch {+ return undefined;+ }+}++/**+ * Schedule a proactive token refresh before the (connect) token expires.+ * `refresh` performs the actual refresh β re-minting a workspace token or+ * refreshing the user token β and returns the new token. Returns a cleanup+ * function that cancels the scheduled timer.+ */+export function scheduleProactiveRefresh(+ token: string,+ tokenType: string,+ refresh: () => Promise<string | undefined>,+ info: (msg: string) => void,+ error: (msg: string) => void,+): (() => void) | null {+ if (tokenType !== 'jwt') return null;++ const exp = parseJwtExp(token);+ if (!exp) return null;++ const lifetimeMs = exp * 1000 - Date.now();+ if (lifetimeMs <= 0) {+ // Token already expired β refresh once on next tick.+ void doRefresh();+ return null;+ }++ // Refresh ahead of expiry, but never let the buffer meet or exceed the token's+ // remaining lifetime: a buffer >= lifetime collapses the refresh window to <=0+ // and busy-loops re-minting (e.g. a 1h token with a 1h buffer). Cap the buffer+ // at half the remaining lifetime so a short-lived token refreshes about once per+ // half-life instead of spinning.+ const bufferMs = Math.min(PROACTIVE_REFRESH_BUFFER * 1000, lifetimeMs / 2);+ const delay = lifetimeMs - bufferMs;++ const timer = setTimeout(() => void doRefresh(), delay);+ return () => clearTimeout(timer);++ async function doRefresh() {+ try {+ const newToken = await refresh();+ if (!newToken) {+ error('Proactive token refresh failed β no valid credentials.');+ return;+ }+ if (newToken !== token) info('Proactively refreshed token.');+ } catch {+ error('Proactive token refresh failed.');+ }+ }+}diff --git a/apps/cli/src/commands/connect.nativeRuntimes.test.ts b/apps/cli/src/commands/connect.nativeRuntimes.test.tsnew file mode 100644index 00000000000..2153fea3c87--- /dev/null+++ b/apps/cli/src/commands/connect.nativeRuntimes.test.ts@@ -0,0 +1,240 @@+import type * as DeviceControlModule from '@lobechat/device-control';+import { GatewayClient } from '@lobechat/device-gateway-client';+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type * as RefreshModule from '../auth/refresh';+import { resolveToken } from '../auth/resolveToken';+import type * as DeviceRegister from '../device/register';+import { registerConnectCommand } from './connect';++const codexProbe = vi.hoisted(() => ({+ close: vi.fn(),+ connect: vi.fn<() => Promise<{ userAgent: string }>>(),+ options: vi.fn(),+ resolve: vi.fn<() => Promise<{ command: string; pathEnv?: string }>>(),+}));+vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({+ resolveHeteroSpawnCommand: codexProbe.resolve,+}));+vi.mock('@lobechat/heterogeneous-agents/spawn', () => ({+ CodexAppServerClient: class {+ constructor(options: object) {+ codexProbe.options(options);+ }+ close = codexProbe.close;+ connect = codexProbe.connect;+ },+}));++const registerDeviceMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const mintWorkspaceConnectTokenMock = vi.hoisted(() => vi.fn());+const registerWorkspaceDeviceMock = vi.hoisted(() => vi.fn());++vi.mock('../device/register', async (importOriginal) => {+ const actual = await importOriginal<typeof DeviceRegister>();+ return {+ ...actual,+ mintWorkspaceConnectToken: mintWorkspaceConnectTokenMock,+ registerDevice: registerDeviceMock,+ registerWorkspaceDevice: registerWorkspaceDeviceMock,+ };+});++vi.mock('../auth/refresh', async (importOriginal) => ({+ ...(await importOriginal<typeof RefreshModule>()),+ getValidToken: vi.fn().mockResolvedValue({+ credentials: { accessToken: 'test-token', expiresAt: undefined, refreshToken: 'test-refresh' },+ status: 'ok',+ }),+}));+vi.mock('../auth/resolveToken', () => ({+ resolveToken: vi.fn().mockResolvedValue({+ serverUrl: 'https://app.lobehub.com',+ token: 'test-token',+ tokenType: 'jwt',+ userId: 'test-user',+ }),+}));+vi.mock('../settings', () => ({+ addWorkspaceEnrollment: vi.fn(),+ loadOrCreateConnectionId: vi.fn().mockReturnValue('test-connection-id'),+ loadSettings: vi.fn().mockReturnValue(null),+ // Default: no persisted workspace shares, so runConnect skips the restore path.+ loadWorkspaceEnrollments: vi.fn().mockReturnValue([]),+ normalizeUrl: vi.fn((url?: string) => (url ? url.replace(/\/$/, '') : undefined)),+ removeWorkspaceEnrollment: vi.fn(),+ resolveDeviceMetricsBacklogPath: vi.fn((id: string) => `/tmp/device-metrics/${id}.json`),+ saveSettings: vi.fn(),+}));++vi.mock('../tools/shell', () => ({+ cleanupAllProcesses: vi.fn(),+}));++let mockRunningPid: number | null = null;+let mockSpawnedPid = 0;+let mockStatus: any = null;+vi.mock('../daemon/manager', () => ({+ appendLog: vi.fn(),+ getLogPath: vi.fn().mockReturnValue('/tmp/test-daemon.log'),+ getRunningDaemonPid: vi.fn().mockImplementation(() => mockRunningPid),+ readStatus: vi.fn().mockImplementation(() => mockStatus),+ removePid: vi.fn(),+ removeStatus: vi.fn(),+ reportDaemonStartupReady: vi.fn().mockResolvedValue(undefined),+ spawnDaemon: vi.fn().mockImplementation(() => {+ mockSpawnedPid = 99999;+ return mockSpawnedPid;+ }),+ stopDaemon: vi.fn().mockImplementation(() => {+ if (mockRunningPid !== null) {+ mockRunningPid = null;+ return true;+ }+ return false;+ }),+ writeStatus: vi.fn(),+}));++vi.mock('../tools', () => ({+ executeToolCall: vi.fn().mockResolvedValue({+ content: 'tool result',+ success: true,+ }),+}));++let clientEventHandlers: Record<string, (...args: any[]) => any> = {};+let lastSentSystemInfoResponse: any = null;+const clientReportMetrics = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const metricsSampler = vi.hoisted(() => ({+ flush: vi.fn().mockResolvedValue(undefined),+ options: undefined as any,+ start: vi.fn().mockResolvedValue(undefined),+ stop: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@lobechat/device-control', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceControlModule>()),+ DeviceMetricsSampler: vi.fn().mockImplementation(function (opts: any) {+ metricsSampler.options = opts;+ return metricsSampler;+ }),+}));++vi.mock('@lobechat/device-gateway-client', () => ({+ GatewayClient: vi.fn().mockImplementation(function () {+ clientEventHandlers = {};+ lastSentSystemInfoResponse = null;+ return {+ connect: vi.fn().mockResolvedValue(undefined),+ currentDeviceId: 'mock-device-id',+ disconnect: vi.fn(),+ on: vi.fn().mockImplementation((event: string, handler: (...args: any[]) => any) => {+ clientEventHandlers[event] = handler;+ }),+ reconnect: vi.fn().mockResolvedValue(undefined),+ reportMetrics: clientReportMetrics,+ sendSystemInfoResponse: vi.fn().mockImplementation((data: any) => {+ lastSentSystemInfoResponse = data;+ }),+ sendToolCallResponse: vi.fn(),+ updateToken: vi.fn(),+ };+ }),+}));++describe('connect native agent runtimes', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;+ let signalListeners: Map<NodeJS.Signals, Set<(...args: unknown[]) => void>>;++ beforeEach(() => {+ codexProbe.connect.mockResolvedValue({ userAgent: 'codex/0.160.0' });+ codexProbe.resolve.mockResolvedValue({ command: '/resolved/codex', pathEnv: '/resolved/bin' });+ signalListeners = new Map(+ (['SIGINT', 'SIGTERM'] as const).map((signal) => [+ signal,+ new Set(process.listeners(signal)),+ ]),+ );+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);+ mockRunningPid = null;+ mockSpawnedPid = 0;+ mockStatus = null;+ });++ afterEach(() => {+ for (const [signal, existing] of signalListeners) {+ for (const listener of process.listeners(signal)) {+ if (!existing.has(listener)) process.removeListener(signal, listener);+ }+ }+ exitSpy.mockRestore();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ function createProgram() {+ const program = new Command();+ program.exitOverride();+ registerConnectCommand(program);+ return program;+ }++ /** @example Desktop can inspect its bundled runtime without registering a device. */+ it('reports native capabilities without authenticating or connecting', async () => {+ const output = vi.spyOn(console, 'log').mockImplementation(() => {});+ await createProgram().parseAsync(['node', 'test', 'connect', 'capabilities']);+ /** @example Only a successful native handshake is advertised in machine-readable output. */+ expect(output).toHaveBeenCalledWith(+ JSON.stringify({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ );+ /** @example Capability discovery does not consume a user login or gateway connection. */+ expect(resolveToken).not.toHaveBeenCalled();+ expect(GatewayClient).not.toHaveBeenCalled();+ expect(codexProbe.close).toHaveBeenCalledOnce();+ });++ // ROOT CAUSE:+ // Every system_info_request started a Codex app-server handshake (up to 6 s), and tool+ // runs query system info during ordinary turns, so every device run paid for it.+ /** @example Repeated system info requests reuse one native probe per connection. */+ it('probes native Codex once per connection', async () => {+ await createProgram().parseAsync(['node', 'test', 'connect']);+ for (const requestId of ['probe-1', 'probe-2', 'probe-3']) {+ await clientEventHandlers['system_info_request']?.({+ requestId,+ type: 'system_info_request',+ });+ }+ /** @example Resolution PATH is carried into the exact probed executable. */+ expect(codexProbe.options).toHaveBeenCalledWith(+ expect.objectContaining({+ commandPath: '/resolved/codex',+ env: expect.objectContaining({ PATH: '/resolved/bin' }),+ }),+ );+ expect(codexProbe.connect).toHaveBeenCalledOnce();+ expect(lastSentSystemInfoResponse.result.systemInfo.supportedAgentRuntimes).toEqual([+ 'codex-app-server-v1',+ ]);+ });++ /** @example Reconnecting detects a binary downgrade instead of keeping stale support. */+ it('reprobes native Codex when the gateway connection is re-established', async () => {+ await createProgram().parseAsync(['node', 'test', 'connect']);+ await clientEventHandlers['system_info_request']?.({+ requestId: 'probe-new',+ type: 'system_info_request',+ });+ codexProbe.connect.mockRejectedValueOnce(new Error('binary downgraded'));+ clientEventHandlers['connected']?.();+ await clientEventHandlers['system_info_request']?.({+ requestId: 'probe-downgrade',+ type: 'system_info_request',+ });+ /** @example A later unsupported binary revokes the previous capability. */+ expect(lastSentSystemInfoResponse.result.systemInfo.supportedAgentRuntimes).toEqual([]);+ expect(codexProbe.connect).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.tsindex 8211335e96f..88d838c1361 100644--- a/apps/cli/src/commands/connect.test.ts+++ b/apps/cli/src/commands/connect.test.ts@@ -11,12 +11,19 @@ import type * as RefreshModule from '../auth/refresh';import { resolveToken } from '../auth/resolveToken';import { removeStatus, spawnDaemon, stopDaemon, writeStatus } from '../daemon/manager';import type * as DeviceRegister from '../device/register';+import type * as SystemInfoModule from '../device/systemInfo';import { loadSettings, saveSettings } from '../settings';import { executeToolCall } from '../tools';import { cleanupAllProcesses } from '../tools/shell';import { log, setVerbose } from '../utils/logger';import { registerConnectCommand } from './connect';+// Native runtime probing spawns Codex; connect.nativeRuntimes.test.ts covers it.+vi.mock('../device/systemInfo', async (importOriginal) => ({+ ...(await importOriginal<typeof SystemInfoModule>()),+ probeNativeRuntimes: vi.fn().mockResolvedValue([]),+}));+const registerDeviceMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));const mintWorkspaceConnectTokenMock = vi.hoisted(() => vi.fn());const registerWorkspaceDeviceMock = vi.hoisted(() => vi.fn());diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 747707eca93..10a7300c217 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -20,9 +20,14 @@ import type {} from '@lobechat/device-gateway-client';import { GatewayClient } from '@lobechat/device-gateway-client';import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';+import {+ createRuntimeProbeCache,+ type RuntimeProbeCache,+} from '@lobechat/heterogeneous-agents/runtimeProbeCache';import type { Command } from 'commander';import { createLambdaClient } from '../api/client';+import { scheduleProactiveRefresh } from '../auth/proactiveRefresh';import { resolveToken } from '../auth/resolveToken';import { CLI_API_KEY_ENV } from '../constants/auth';import { CLI_CONNECT_SERVICE_NAME, CLI_DISPLAY_NAME, CLI_PRIMARY_BIN } from '../constants/identity';@@ -50,7 +55,7 @@ import {resolveDeviceIdentity,resolveWorkspaceDeviceIdentity,} from '../device/register';-import { collectSystemInfo } from '../device/systemInfo';+import { collectSystemInfo, probeNativeRuntimes } from '../device/systemInfo';import { TerminalSessionManager } from '../device/terminal';import {CONNECT_RETRYABLE_EXIT_CODE,@@ -130,6 +135,15 @@ export function registerConnectCommand(program: Command) {await runConnect(options, isDaemonChild);});+ // Capability discovery runs without login or opening a gateway connection. Desktop+ // invokes its bundled CLI here so the probe and subsequent dispatch share a runtime.+ connectCmd+ .command('capabilities')+ .description('Report native agent runtimes supported by this CLI and installed binaries')+ .action(async () => {+ console.log(JSON.stringify({ supportedAgentRuntimes: await probeNativeRuntimes() }));+ });+// SubcommandsconnectCmd.command('stop').description('Stop the background daemon process').action(handleStop);@@ -522,6 +536,10 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {writeTerminal: (params) => Promise.resolve(terminals.write(params)),};+ // One native runtime probe per connection: system info is queried by tool runs and+ // agent dispatch alike, and each probe starts a Codex app-server process.+ const nativeRuntimes = createRuntimeProbeCache(probeNativeRuntimes);+const handlerContext: GatewayHandlerContext = {computerUse,deps: deviceControlDeps,@@ -531,6 +549,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {info,isDaemonChild,maintenance,+ nativeRuntimes,recordRequest,};@@ -561,6 +580,10 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {client.on('connected', () => {updateStatus('connected');void metricsSampler?.flush();+ // A (re)connection reprobes so an upgraded or downgraded Codex is reported, and+ // warms the cache before the gateway's first system_info_request.+ nativeRuntimes.invalidate();+ void nativeRuntimes.get();});client.on('disconnected', () => {@@ -953,6 +976,8 @@ interface GatewayHandlerContext {info: (msg: string) => void;isDaemonChild: boolean;maintenance: CliMaintenance;+ /** Process-wide native runtime probe, shared by every gateway connection. */+ nativeRuntimes: RuntimeProbeCache;recordRequest: () => void;}@@ -973,7 +998,7 @@ function bindGatewayClientHandlers(// Handle system info requestsclient.on('system_info_request', async (request: SystemInfoRequestMessage) => {info(`Received system_info_request: requestId=${request.requestId}`);- const systemInfo = await collectSystemInfo(computerUse);+ const systemInfo = await collectSystemInfo(ctx.nativeRuntimes, computerUse);client.sendSystemInfoResponse({requestId: request.requestId,result: { success: true, systemInfo },@@ -1116,68 +1141,3 @@ function formatUptime(startedAt: Date): string {if (minutes > 0) return `${minutes}m ${seconds % 60}s`;return `${seconds}s`;}--// How far before expiry to proactively refresh (1 hour)-const PROACTIVE_REFRESH_BUFFER = 60 * 60;--/**- * Parse the `exp` claim from a JWT without verifying the signature.- */-function parseJwtExp(token: string): number | undefined {- try {- const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());- return typeof payload.exp === 'number' ? payload.exp : undefined;- } catch {- return undefined;- }-}--/**- * Schedule a proactive token refresh before the (connect) token expires.- * `refresh` performs the actual refresh β re-minting a workspace token or- * refreshing the user token β and returns the new token. Returns a cleanup- * function that cancels the scheduled timer.- */-function scheduleProactiveRefresh(- token: string,- tokenType: string,- refresh: () => Promise<string | undefined>,- info: (msg: string) => void,- error: (msg: string) => void,-): (() => void) | null {- if (tokenType !== 'jwt') return null;-- const exp = parseJwtExp(token);- if (!exp) return null;-- const lifetimeMs = exp * 1000 - Date.now();- if (lifetimeMs <= 0) {- // Token already expired β refresh once on next tick.- void doRefresh();- return null;- }-- // Refresh ahead of expiry, but never let the buffer meet or exceed the token's- // remaining lifetime: a buffer >= lifetime collapses the refresh window to <=0- // and busy-loops re-minting (e.g. a 1h token with a 1h buffer). Cap the buffer- // at half the remaining lifetime so a short-lived token refreshes about once per- // half-life instead of spinning.- const bufferMs = Math.min(PROACTIVE_REFRESH_BUFFER * 1000, lifetimeMs / 2);- const delay = lifetimeMs - bufferMs;-- const timer = setTimeout(() => void doRefresh(), delay);- return () => clearTimeout(timer);-- async function doRefresh() {- try {- const newToken = await refresh();- if (!newToken) {- error('Proactive token refresh failed β no valid credentials.');- return;- }- if (newToken !== token) info('Proactively refreshed token.');- } catch {- error('Proactive token refresh failed.');- }- }-}diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 97fe162e285..28072ee9a22 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -14,11 +14,13 @@ import { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';import { registerHeteroCommand, SUPPORTED_AGENT_TYPES } from './hetero';const {+ mockCreateCodexAgentHandle,mockCreatePiRpcAgentHandle,mockResolveHeteroSpawnCommand,mockSpawnAgent,mockSpawnDshAcpSession,} = vi.hoisted(() => ({+ mockCreateCodexAgentHandle: vi.fn(),mockCreatePiRpcAgentHandle: vi.fn(),mockResolveHeteroSpawnCommand: vi.fn(),mockSpawnAgent: vi.fn(),@@ -36,6 +38,7 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => ({...(await importOriginal<typeof HeteroSpawn>()),spawnAgent: mockSpawnAgent,spawnDshAcpSession: mockSpawnDshAcpSession,+ createCodexAgentHandle: mockCreateCodexAgentHandle,}));vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({@@ -133,6 +136,7 @@ describe('hetero exec command', () => {return { command: command ?? defaultCommand };},);+ mockCreateCodexAgentHandle.mockReset();mockCreatePiRpcAgentHandle.mockReset();mockSpawnAgent.mockReset();mockSpawnDshAcpSession.mockReset();@@ -473,6 +477,57 @@ describe('hetero exec command', () => {expect(signalHandlers.size).toBe(0);});+ /** @example Connected-device Stop reaches native startup and escalates the second interrupt. */+ it('cancels detached native Codex startup inside the connected wrapper group', async () => {+ // ROOT CAUSE:+ // Native app-server detaches even when connect groups the wrapper, so signals must be forwarded.+ vi.stubEnv(HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV, '1');+ const signalHandlers = new Map<string, () => void>();+ vi.spyOn(process, 'on').mockImplementation(((event: string, listener: () => void) => {+ if (event === 'SIGINT' || event === 'SIGTERM') signalHandlers.set(event, listener);+ return process;+ }) as typeof process.on);+ vi.spyOn(process, 'off').mockImplementation(((event: string) => {+ signalHandlers.delete(event);+ return process;+ }) as typeof process.off);++ const cancel = vi.fn().mockResolvedValue(undefined);+ let rejectFactory: ((error: Error) => void) | undefined;+ mockCreateCodexAgentHandle.mockImplementation(+ (options: { onStartupControl?: (control: { cancel: typeof cancel }) => void }) => {+ options.onStartupControl?.({ cancel });+ return new Promise((_resolve, reject) => {+ rejectFactory = reject;+ });+ },+ );++ const command = runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'codex',+ '--codex-app-server',+ '--prompt',+ 'hi',+ ]);+ for (let index = 0; index < 20 && !signalHandlers.get('SIGINT'); index += 1) {+ await Promise.resolve();+ }+ signalHandlers.get('SIGINT')?.();+ signalHandlers.get('SIGINT')?.();+ for (let index = 0; index < 20 && cancel.mock.calls.length === 0; index += 1) {+ await Promise.resolve();+ }++ expect(cancel.mock.calls.at(-1)).toEqual(['SIGKILL']);+ rejectFactory!(new Error('Native Codex session is closed'));+ await command;+ expect(exitSpy).toHaveBeenCalledWith(137);+ expect(signalHandlers.size).toBe(0);+ });+it('runs Qoder with its default command and forwards model and effort', async () => {mockSpawnAgent.mockReturnValue(createFakeHandle());@@ -1165,6 +1220,62 @@ describe('hetero exec command', () => {);});+ // ROOT CAUSE:+ // An app-server device run whose native session was lost must keep the `codex exec`+ // recovery: Codex reports the missing thread as "no rollout found", and the run+ // continues from its transcript instead of failing every later turn.+ /** @example An ordinary app-server topic recovers from a missing native session. */+ it('retries an ordinary app-server Codex topic with its transcript fallback', async () => {+ const dir = await mkdtemp(`${tmpdir()}/hetero-native-fallback-`);+ const file = path.join(dir, 'input.json');+ const fallbackPrompt = [+ { text: 'previous conversation', type: 'text' },+ { text: 'continue', type: 'text' },+ ];+ await writeFile(+ file,+ JSON.stringify({+ content: [{ text: 'continue', type: 'text' }],+ resumeFallback: fallbackPrompt,+ }),+ );+ mockCreateCodexAgentHandle+ .mockResolvedValueOnce(+ createFakeHandle({+ exitCode: 1,+ // The exact message Codex 0.160 returns for a deleted rollout.+ stderrChunks: [+ 'thread/resume failed: no rollout found for thread id stale-native (code -32600)\n',+ ],+ }),+ )+ .mockResolvedValueOnce(createFakeHandle({ exitCode: 0 }));+ try {+ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'codex',+ '--input-json',+ file,+ '--codex-app-server',+ '--resume',+ 'stale-native',+ ]);+ } finally {+ await rm(dir, { force: true, recursive: true });+ }+ /** @example The first attempt resumes; the retry starts fresh with the transcript. */+ expect(mockCreateCodexAgentHandle).toHaveBeenCalledTimes(2);+ expect(mockCreateCodexAgentHandle.mock.calls[0][0]).toMatchObject({+ resumeSessionId: 'stale-native',+ });+ expect(mockCreateCodexAgentHandle.mock.calls[1][0].resumeSessionId).toBeUndefined();+ expect(mockCreateCodexAgentHandle.mock.calls[1][0].prompt).toEqual(fallbackPrompt);+ expect(mockSpawnAgent).not.toHaveBeenCalled();+ expect(exitSpy).toHaveBeenCalledWith(0);+ });+it('runs Pi over the RPC transport with model, resume, and native args while ignoring effort and speed', async () => {vi.stubEnv('HOME', '/pi-test-home');vi.stubEnv('PI_CODING_AGENT_DIR', '/pi-test-config');@@ -1956,6 +2067,38 @@ describe('hetero exec command', () => {expect(exitSpy).toHaveBeenCalledWith(0);});+ // ROOT CAUSE:+ // Codex reports a deleted rollout as "no rollout found", which matched none of the+ // retry patterns, so the stale binding failed every later turn instead of retrying.+ /** @example A missing Codex rollout is retried without --resume. */+ it('retries a Codex exec run whose saved rollout is missing', async () => {+ mockSpawnAgent+ .mockReturnValueOnce(+ createFakeHandle({+ exitCode: 1,+ stderrChunks: [+ 'Error: thread/resume: thread/resume failed: no rollout found for thread id stale (code -32600)\n',+ ],+ }),+ )+ .mockReturnValueOnce(createFakeHandle({ exitCode: 0 }));++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'codex',+ '--prompt',+ 'continue',+ '--resume',+ 'stale',+ ]);++ expect(mockSpawnAgent).toHaveBeenCalledTimes(2);+ expect(mockSpawnAgent.mock.calls[1][0].resumeSessionId).toBeUndefined();+ expect(exitSpy).toHaveBeenCalledWith(0);+ });+it('retries a missing Grok ACP session from its structured filesystem error', async () => {const missingSessionEvent = {data: {diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex fc45ac092d0..fcf57a7367e 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -29,6 +29,7 @@ import type {} from '@lobechat/heterogeneous-agents/spawn';import {classifyHeteroProcessFailure,+ createCodexAgentHandle,createFileStoreImageUploader,isHeteroStatusGuideErrorData,spawnAgent,@@ -38,6 +39,7 @@ 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 { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';import { log } from '../utils/logger';@@ -132,7 +134,21 @@ 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({+ clientVersion: cliVersion,+ args: spawnOpts.extraArgs ?? [],+ 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 });@@ -162,6 +178,9 @@ const RESUME_RETRY_PATTERNS = [/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,@@ -181,6 +200,8 @@ const isMissingGrokResumeSession = (data: Record<string, unknown> | undefined):interface ExecOptions {agentArg?: string[];+ /** Explicit device protocol capability; unsupported native options fail closed. */+ codexAppServer?: boolean;command?: string;cwd?: string;effort?: string;@@ -480,6 +501,9 @@ const exec = async (options: ExecOptions): Promise<void> => {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);@@ -946,7 +970,9 @@ const exec = async (options: ExecOptions): Promise<void> => {// 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).- const ownsSignalDelivery = () => !inheritsWrapperProcessGroup || ingestLoss !== undefined;+ // 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);@@ -998,13 +1024,18 @@ const exec = async (options: ExecOptions): Promise<void> => {// 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);- });+ 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@@ -1422,6 +1453,7 @@ export function registerHeteroCommand(program: Command) {'--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')diff --git a/apps/cli/src/device/systemInfo.test.ts b/apps/cli/src/device/systemInfo.test.tsnew file mode 100644index 00000000000..e62dafae86c--- /dev/null+++ b/apps/cli/src/device/systemInfo.test.ts@@ -0,0 +1,75 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { collectSystemInfo, probeNativeRuntimes } from './systemInfo';++const codexProbe = vi.hoisted(() => ({+ close: vi.fn(),+ connect: vi.fn<() => Promise<{ userAgent: string }>>(),+ options: vi.fn(),+ resolve: vi.fn<() => Promise<{ command: string; pathEnv?: string }>>(),+}));+vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({+ resolveHeteroSpawnCommand: codexProbe.resolve,+}));+vi.mock('@lobechat/heterogeneous-agents/spawn', () => ({+ CodexAppServerClient: class {+ constructor(options: object) {+ codexProbe.options(options);+ }+ close = codexProbe.close;+ connect = codexProbe.connect;+ },+}));++const uncachedProbe = { get: probeNativeRuntimes, invalidate: () => {} };++describe('probeNativeRuntimes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ codexProbe.connect.mockResolvedValue({ userAgent: 'codex/0.160.0' });+ codexProbe.resolve.mockResolvedValue({ command: '/resolved/codex', pathEnv: '/resolved/bin' });+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('advertises native Codex after a successful handshake on the resolved binary', async () => {+ await expect(probeNativeRuntimes()).resolves.toEqual(['codex-app-server-v1']);+ /** @example Resolution PATH is carried into the exact probed executable. */+ expect(codexProbe.options).toHaveBeenCalledWith(+ expect.objectContaining({+ commandPath: '/resolved/codex',+ env: expect.objectContaining({ PATH: '/resolved/bin' }),+ }),+ );+ expect(codexProbe.close).toHaveBeenCalledOnce();+ });++ /** @example Unsupported Codex keeps ordinary device sends on the existing exec runtime. */+ it('does not advertise native Codex when the binary rejects initialization', async () => {+ // ROOT CAUSE:+ // collectSystemInfo unconditionally advertised codex-app-server-v1, so even an+ // exec-only binary was selected for native ordinary sends and failed before answering.+ // Native support must come from the resolved binary's actual handshake.+ codexProbe.connect.mockRejectedValueOnce(new Error('unsupported app-server'));+ /** @example Unavailable native capability preserves the successful system-info response. */+ await expect(collectSystemInfo(uncachedProbe)).resolves.toMatchObject({+ supportedAgentRuntimes: [],+ });+ /** @example A failed probe does not leave its subprocess alive. */+ expect(codexProbe.close).toHaveBeenCalledOnce();+ });++ /** @example A handshake timeout must not stall device discovery or advertise support. */+ it('bounds native Codex probing and closes the stalled client', async () => {+ vi.useFakeTimers();+ codexProbe.connect.mockImplementationOnce(() => new Promise(() => {}));+ const systemInfo = collectSystemInfo(uncachedProbe);+ await vi.advanceTimersByTimeAsync(6000);+ /** @example A stalled app-server falls back to the existing capability set. */+ expect((await systemInfo).supportedAgentRuntimes).toEqual([]);+ /** @example Timeout releases the owned native process. */+ expect(codexProbe.close).toHaveBeenCalledOnce();+ });+});diff --git a/apps/cli/src/device/systemInfo.ts b/apps/cli/src/device/systemInfo.tsindex 5aae6a2844d..4984daeb962 100644--- a/apps/cli/src/device/systemInfo.ts+++ b/apps/cli/src/device/systemInfo.ts@@ -3,17 +3,92 @@ import path from 'node:path';import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';import type { DeviceSystemInfo } from '@lobechat/device-gateway-client';+import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';+import type { RuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';+import { CodexAppServerClient } from '@lobechat/heterogeneous-agents/spawn';import { getShellInfo } from '@lobechat/local-file-shell';import { CLI_CONFIG_DIR_NAME } from '../constants/identity';+import { cliVersion } from '../pkg';import type { ComputerUseDevice } from '../tools/computerUse';/**- * The answer to a gateway `system_info_request`. `supportedTools` lists the- * opt-in tools this device can run; the server refuses those tools on a- * device that does not list them.+ * Checks the currently resolved Codex binary without creating a conversation.+ *+ * Use when:+ * - Reporting native runtime support to a connected gateway.+ * Expects:+ * - The same binary resolution and PATH as ordinary CLI dispatch.+ * Returns:+ * - False for missing, incompatible, malformed, or stalled native handshakes.+ *+ * Call stack:+ * registerConnectCommand -> connect capabilities+ * bindGatewayClientHandlers+ * -> {@link collectSystemInfo}+ * -> {@link supportsNativeCodex}+ * -> {@link resolveHeteroSpawnCommand}+ * -> {@link CodexAppServerClient.connect}+ */+async function supportsNativeCodex(): Promise<boolean> {+ let client: CodexAppServerClient | undefined;+ let expired = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ // Device discovery has a 10-second budget. Bound binary resolution and handshake+ // together so a broken installation cannot block unrelated device tools.+ // Cold Codex startup can exceed 3 seconds; reserve 6 seconds below the gateway budget.+ const deadline = new Promise<boolean>((resolve) => {+ timer = setTimeout(() => {+ expired = true;+ resolve(false);+ }, 6000);+ });+ const probe = async () => {+ try {+ const resolved = await resolveHeteroSpawnCommand('codex');+ // A late resolver must not create a subprocess after the caller has timed out.+ if (expired) return false;+ client = new CodexAppServerClient({+ clientVersion: cliVersion,+ commandPath: resolved.command,+ cwd: process.cwd(),+ env: { ...process.env, ...(resolved.pathEnv ? { PATH: resolved.pathEnv } : {}) },+ });+ const response = await client.connect();+ return typeof response?.userAgent === 'string' && response.userAgent.length > 0;+ } catch {+ return false;+ }+ };+ try {+ return await Promise.race([probe(), deadline]);+ } finally {+ clearTimeout(timer);+ // The probe owns only its handshake process, never a user's native session.+ client?.close();+ }+}++/** Native agent runtimes the resolved binaries support; one handshake per call. */+export async function probeNativeRuntimes(): Promise<string[]> {+ return (await supportsNativeCodex()) ? ['codex-app-server-v1'] : [];+}++/**+ * The answer to a gateway `system_info_request`: host paths and live native capabilities.+ * `supportedTools` lists the opt-in tools this device can run; the server refuses those+ * tools on a device that does not list them.+ *+ * Use when: a gateway requests this connection's current system information.+ * Expects: local paths and binary resolution belong to this connect process.+ * Returns: system information even when Codex is unavailable.+ *+ * Call stack:+ * bindGatewayClientHandlers -> {@link collectSystemInfo}+ * -> RuntimeProbeCache.get -> {@link probeNativeRuntimes} -> {@link supportsNativeCodex}*/export async function collectSystemInfo(+ nativeRuntimes: RuntimeProbeCache,computerUse?: ComputerUseDevice,): Promise<DeviceSystemInfo> {const home = os.homedir();@@ -30,6 +105,7 @@ export async function collectSystemInfo(homePath: home,musicPath: path.join(home, 'Music'),picturesPath: path.join(home, 'Pictures'),+ supportedAgentRuntimes: await nativeRuntimes.get(),...(computerUse && { supportedTools: [COMPUTER_USE_IDENTIFIER] }),userDataPath: path.join(home, CLI_CONFIG_DIR_NAME),videosPath: path.join(home, videosDir),diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.tsindex a181bd87180..5d3bc052f9e 100644--- a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts@@ -7,7 +7,15 @@ import type { App } from '@/core/App';import GatewayConnectionService from '../gatewayConnectionSrv';-const { getShellInfoMock } = vi.hoisted(() => ({ getShellInfoMock: vi.fn() }));+const { getShellInfoMock, execFileMock } = vi.hoisted(() => ({+ getShellInfoMock: vi.fn(),+ execFileMock: vi.fn(),+}));++vi.mock('node:child_process', () => ({+ execFile: Object.assign(vi.fn(), { [Symbol.for('nodejs.util.promisify.custom')]: execFileMock }),+}));+vi.mock('@/modules/cliEmbedding', () => ({ resolveCliScript: () => 'bundled-cli.js' }));vi.mock('electron', () => ({app: {@@ -33,6 +41,9 @@ describe('GatewayConnectionService system_info_request', () => {beforeEach(() => {getShellInfoMock.mockReset();+ execFileMock+ .mockReset()+ .mockResolvedValue({ stdout: JSON.stringify({ supportedAgentRuntimes: [] }) });service = new GatewayConnectionService({} as App);});@@ -55,6 +66,124 @@ describe('GatewayConnectionService system_info_request', () => {});});+ /** @example A capable bundled CLI enables native app-server runs on a Desktop gateway connection. */+ it('advertises the native runtimes reported by the bundled execution CLI', async () => {+ // ROOT CAUSE:+ // Desktop forwards agent runs to its bundled CLI but omitted native capabilities+ // from system-info, so the server could never select the native runtime for it.+ // Probe that bundled runtime instead of a potentially older global lh binary.+ getShellInfoMock.mockResolvedValue({ displayName: 'zsh' });+ execFileMock.mockResolvedValue({+ stdout: JSON.stringify({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ });+ const client = createClient();+ await service['handleSystemInfoRequest'](client, {+ requestId: 'native-desktop',+ type: 'system_info_request',+ });+ /** @example The live system-info response supplies the server's dispatch capability. */+ expect(client.sendSystemInfoResponse).toHaveBeenCalledWith(+ expect.objectContaining({+ result: {+ success: true,+ systemInfo: expect.objectContaining({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ },+ }),+ );+ /** @example The probe executes the bundled CLI under Electron's Node runtime. */+ expect(execFileMock).toHaveBeenCalledWith(+ process.execPath,+ ['bundled-cli.js', 'connect', 'capabilities'],+ expect.objectContaining({+ env: expect.objectContaining({ ELECTRON_RUN_AS_NODE: '1' }),+ timeout: 9000,+ windowsHide: true,+ }),+ );+ });++ // ROOT CAUSE:+ // Every system_info_request spawned the bundled CLI (up to 9 s) plus a Codex handshake,+ // and system info is queried during ordinary runs, so every device user paid for it.+ /** @example Repeated system-info requests reuse one bundled CLI probe per connection. */+ it('probes the bundled CLI once per connection', async () => {+ getShellInfoMock.mockResolvedValue({ displayName: 'zsh' });+ execFileMock.mockResolvedValue({+ stdout: JSON.stringify({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ });+ const client = createClient();+ for (const requestId of ['first', 'second', 'third']) {+ await service['handleSystemInfoRequest'](client, {+ requestId,+ type: 'system_info_request',+ });+ }+ expect(execFileMock).toHaveBeenCalledOnce();+ expect(client.sendSystemInfoResponse).toHaveBeenLastCalledWith(+ expect.objectContaining({+ requestId: 'third',+ result: {+ success: true,+ systemInfo: expect.objectContaining({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ },+ }),+ );+ });++ /** @example Updating or removing Codex changes the capability after reconnecting. */+ it('revokes native support when a reconnect probe fails', async () => {+ getShellInfoMock.mockResolvedValue({ displayName: 'zsh' });+ execFileMock.mockResolvedValueOnce({+ stdout: JSON.stringify({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ });+ const client = createClient();+ await service['handleSystemInfoRequest'](client, {+ requestId: 'first',+ type: 'system_info_request',+ });+ execFileMock.mockRejectedValueOnce(new Error('bundled CLI unavailable or timed out'));+ // Only the status transition matters here; keep-awake and broadcasting are out of scope.+ vi.spyOn(service as any, 'syncPowerSaveBlocker').mockImplementation(() => {});+ vi.spyOn(service as any, 'scheduleStatusBroadcast').mockImplementation(() => {});+ service['setStatus']('reconnecting');+ service['setStatus']('connected');+ await service['handleSystemInfoRequest'](client, {+ requestId: 'second',+ type: 'system_info_request',+ });+ /** @example A failed probe preserves other device tools but cannot authorize native runs. */+ expect(client.sendSystemInfoResponse).toHaveBeenLastCalledWith(+ expect.objectContaining({+ requestId: 'second',+ result: {+ success: true,+ systemInfo: expect.objectContaining({ supportedAgentRuntimes: [] }),+ },+ }),+ );+ expect(execFileMock).toHaveBeenCalledTimes(2);+ });++ /** @example An older CLI's help output must not be interpreted as native support. */+ it('omits native support when the bundled probe returns malformed output', async () => {+ getShellInfoMock.mockResolvedValue({ displayName: 'zsh' });+ execFileMock.mockResolvedValue({ stdout: 'Usage: lh connect' });+ const client = createClient();+ await service['handleSystemInfoRequest'](client, {+ requestId: 'malformed',+ type: 'system_info_request',+ });+ /** @example Ordinary system information remains available after a probe failure. */+ expect(client.sendSystemInfoResponse).toHaveBeenCalledWith(+ expect.objectContaining({+ result: {+ success: true,+ systemInfo: expect.objectContaining({ supportedAgentRuntimes: [] }),+ },+ }),+ );+ });+it('omits an optional folder Electron cannot resolve and still answers successfully', async () => {getShellInfoMock.mockResolvedValue({ displayName: 'pwsh' });const { app } = await import('electron');diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex e9a5ec65809..8d59dec1a5a 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -8,11 +8,9 @@ import type {EnrollWorkspaceResult,UnenrollWorkspaceParams,} from '@lobechat/device-control';-import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';import type { DeviceMetricsSampler } from '@lobechat/device-control/metrics';import type {AgentRunRequestMessage,- DeviceSystemInfo,GatewayClient,GatewayMcpParams,MessageApiRequestMessage,@@ -23,6 +21,7 @@ import type {} from '@lobechat/device-gateway-client';import type { IdentitySource } from '@lobechat/device-identity';import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';+import { createRuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';import { app, powerSaveBlocker } from 'electron';import { isDev } from '@/const/env';@@ -31,6 +30,7 @@ import { createLogger } from '@/utils/logger';import { getDesktopUserAgent } from '@/utils/user-agent';import { safeGetPath } from '@/utils/user-path';+import { collectBundledCliAgentRuntimes, collectGatewaySystemInfo } from './gatewaySystemInfo';import { ServiceModule } from './index';const logger = createLogger('services:GatewayConnectionSrv');@@ -161,6 +161,13 @@ export default class GatewayConnectionService extends ServiceModule {private identitySource: IdentitySource | null = null;+ /**+ * Bundled CLI capability probe. Each probe starts an Electron-as-node CLI plus a Codex+ * app-server handshake, while system info is requested during ordinary runs, so it is+ * probed once per connection (and refreshed after the cache lifetime).+ */+ private readonly agentRuntimes = createRuntimeProbeCache(collectBundledCliAgentRuntimes);+private tokenProvider: (() => Promise<string | null>) | null = null;private tokenRefresher: (() => Promise<{ error?: string; success: boolean }>) | null = null;private toolCallHandler: ToolCallHandler | null = null;@@ -855,7 +862,7 @@ export default class GatewayConnectionService extends ServiceModule {try {client.sendSystemInfoResponse({requestId: request.requestId,- result: { success: true, systemInfo: await this.collectSystemInfo() },+ result: { success: true, systemInfo: await collectGatewaySystemInfo(this.agentRuntimes) },});} catch (error) {// The gateway keeps the agent run parked until a correlated reply arrives,@@ -865,25 +872,6 @@ export default class GatewayConnectionService extends ServiceModule {}}- private async collectSystemInfo(): Promise<DeviceSystemInfo> {- const { getShellInfo } = await import('@lobechat/local-file-shell/shell');- return {- supportedTools: [COMPUTER_USE_IDENTIFIER],- arch: os.arch(),- // Tell the server-side prompt builder which shell runCommand spawns here.- defaultShell: (await getShellInfo()).displayName,- desktopPath: app.getPath('desktop'),- documentsPath: app.getPath('documents'),- downloadsPath: safeGetPath('downloads'),- homePath: app.getPath('home'),- musicPath: safeGetPath('music'),- picturesPath: safeGetPath('pictures'),- userDataPath: app.getPath('userData'),- videosPath: safeGetPath('videos'),- workingDirectory: process.cwd(),- };- }-// βββ Generic Device RPC βββprivate async handleRpcRequest(client: GatewayClient, request: RpcRequestMessage) {@@ -1157,7 +1145,12 @@ export default class GatewayConnectionService extends ServiceModule {this.status = status;// Upload what accrued while offline right away, not at the next tick.- if (status === 'connected') void this.metricsSampler?.sampler.flush();+ if (status === 'connected') {+ void this.metricsSampler?.sampler.flush();+ // A (re)connection reprobes the bundled CLI and warms the cache for the first request.+ this.agentRuntimes.invalidate();+ void this.agentRuntimes.get();+ }this.syncPowerSaveBlocker();this.scheduleStatusBroadcast(status);}diff --git a/apps/desktop/src/main/services/gatewaySystemInfo.ts b/apps/desktop/src/main/services/gatewaySystemInfo.tsnew file mode 100644index 00000000000..c8380ebad23--- /dev/null+++ b/apps/desktop/src/main/services/gatewaySystemInfo.ts@@ -0,0 +1,76 @@+import { execFile } from 'node:child_process';+import os from 'node:os';+import { promisify } from 'node:util';++import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';+import type { DeviceSystemInfo } from '@lobechat/device-gateway-client';+import type { RuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';+import { isRecord } from '@lobechat/utils/object';+import { app } from 'electron';++import { resolveCliScript } from '@/modules/cliEmbedding';+import { createLogger } from '@/utils/logger';+import { safeGetPath } from '@/utils/user-path';++const logger = createLogger('services:GatewayConnectionSrv');++/**+ * Reports only native capabilities confirmed by the CLI bundled with this Desktop.+ *+ * Use when: the gateway requests live execution capabilities for a bound device.+ * Expects: the same embedded script and Electron Node runtime used for agent runs.+ * Returns: an empty capability list if the CLI is absent, incompatible, or unresponsive.+ *+ * Call stack:+ * GatewayConnectionService.handleSystemInfoRequest -> {@link collectGatewaySystemInfo}+ * -> agentRuntimes.get -> {@link collectBundledCliAgentRuntimes} -> resolveCliScript+ * -> lh connect capabilities -> supportsNativeCodex -> Codex initialize+ */+export const collectBundledCliAgentRuntimes = async (): Promise<string[]> => {+ try {+ // Use the bundled entrypoint rather than a global lh that may lag this build.+ // The CLI bounds its native handshake to 6 seconds; this outer deadline also+ // bounds process startup while staying within the gateway's 10-second budget.+ const { stdout } = await promisify(execFile)(+ process.execPath,+ [resolveCliScript(), 'connect', 'capabilities'],+ {+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },+ maxBuffer: 64 * 1024,+ timeout: 9000,+ windowsHide: true,+ },+ );+ const result: unknown = JSON.parse(stdout);+ if (!isRecord(result) || !Array.isArray(result.supportedAgentRuntimes)) return [];+ return result.supportedAgentRuntimes.includes('codex-app-server-v1')+ ? ['codex-app-server-v1']+ : [];+ } catch (error) {+ logger.debug('Bundled CLI native capability probe unavailable', error);+ return [];+ }+};++/** Host paths, desktop tools, and the cached native runtimes this Desktop reports. */+export const collectGatewaySystemInfo = async (+ agentRuntimes: RuntimeProbeCache,+): Promise<DeviceSystemInfo> => {+ const { getShellInfo } = await import('@lobechat/local-file-shell/shell');+ return {+ supportedTools: [COMPUTER_USE_IDENTIFIER],+ supportedAgentRuntimes: await agentRuntimes.get(),+ arch: os.arch(),+ // Tell the server-side prompt builder which shell runCommand spawns here.+ defaultShell: (await getShellInfo()).displayName,+ desktopPath: app.getPath('desktop'),+ documentsPath: app.getPath('documents'),+ downloadsPath: safeGetPath('downloads'),+ homePath: app.getPath('home'),+ musicPath: safeGetPath('music'),+ picturesPath: safeGetPath('pictures'),+ userDataPath: app.getPath('userData'),+ videosPath: safeGetPath('videos'),+ workingDirectory: process.cwd(),+ };+};diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.codexDeviceRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.codexDeviceRuntime.test.tsnew file mode 100644index 00000000000..0cb60cf1077--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.codexDeviceRuntime.test.ts@@ -0,0 +1,500 @@+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';++import { AgentOperationModel } from '@/database/models/agentOperation';+import type * as UserModelModule from '@/database/models/user';+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';++import { AiAgentService } from '../index';++const {+ mockGetUserPreference,+ mockQueryDeviceSystemInfo,+ mockReadDeviceSystemInfo,+ mockDeviceFindByDeviceId,+ mockDeviceFindWorkspaceDeviceById,+ mockBuildRemoteDeviceHeteroContext,+ mockCreateOperationMetadata,+ mockDispatchAgentRun,+ mockExecuteToolCall,+ mockInterruptOperation,+ mockGetHeterogeneousResumeSessionId,+ mockMessageCreate,+ mockMessageQuery,+ mockMessageUpdate,+ mockResolveAttachmentsByFileIds,+ mockSpawnHeteroSandbox,+ mockIngestAttachment,+ mockPublishAgentRuntimeInit,+ mockPublishAgentRuntimeEnd,+} = vi.hoisted(() => ({+ mockGetUserPreference: vi.fn(),+ mockQueryDeviceSystemInfo: vi.fn(),+ mockReadDeviceSystemInfo: vi.fn(),+ mockBuildRemoteDeviceHeteroContext: vi.fn().mockReturnValue('device context'),+ mockCreateOperationMetadata: vi.fn().mockResolvedValue(undefined),+ mockDeviceFindByDeviceId: vi.fn(),+ mockDeviceFindWorkspaceDeviceById: vi.fn(),+ mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),+ mockExecuteToolCall: vi.fn().mockResolvedValue({ success: true }),+ mockInterruptOperation: vi.fn().mockResolvedValue(true),+ mockGetHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),+ mockIngestAttachment: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockMessageQuery: vi.fn(),+ mockMessageUpdate: vi.fn().mockResolvedValue({}),+ mockPublishAgentRuntimeEnd: vi.fn().mockResolvedValue('end-event-id'),+ mockPublishAgentRuntimeInit: vi.fn().mockResolvedValue('init-event-id'),+ mockResolveAttachmentsByFileIds: vi.fn(),+ mockSpawnHeteroSandbox: vi.fn().mockResolvedValue(undefined),+}));++// Local hetero (claude-code / codebuddy / codex / cursor / opencode / pi / qoder) seeds+// publishAgentRuntimeInit so the agent-gateway DO reports `running` on a later reconnect. Stub the factory so+// the assertion below can verify the init, and so the real one (which probes+// Redis synchronously) doesn't throw a server-env error in the test env.+vi.mock('@/server/modules/AgentRuntime/factory', () => ({+ createAgentStateManager: vi.fn(function () {+ return {+ createOperationMetadata: mockCreateOperationMetadata,+ };+ }),+ createStreamEventManager: () => ({+ publishAgentRuntimeEnd: mockPublishAgentRuntimeEnd,+ publishAgentRuntimeInit: mockPublishAgentRuntimeInit,+ }),+ isRedisAvailable: vi.fn(function () {+ return false;+ }),+}));++const emptyResolvedAttachments = {+ audioList: [],+ fileList: [],+ imageList: [],+ orderedFileIds: [],+ videoList: [],+ warnings: [],+};++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(function () {+ return {};+ }),+}));++vi.mock('../ingestAttachment', () => ({+ ingestAttachment: mockIngestAttachment,+}));++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signHeteroOperationJWT: vi.fn().mockResolvedValue('op-jwt'),+ signUserJWT: vi.fn().mockResolvedValue('user-jwt'),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return {+ create: mockMessageCreate,+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),+ query: mockMessageQuery,+ update: mockMessageUpdate,+ };+ }),+}));++const heteroAgentConfig = {+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'claude-code',+ plugins: [],+ provider: 'anthropic',+ systemRole: 'You are a helpful assistant',+};++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),+ queryAgents: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn().mockImplementation(function () {+ return {+ findByDeviceId: mockDeviceFindByDeviceId,+ findWorkspaceDeviceById: mockDeviceFindWorkspaceDeviceById,+ };+ }),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),+ };+ }),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(function () {+ return {+ query: vi.fn().mockResolvedValue([]),+ };+ }),+}));++const topicMock = {+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),+ create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),+ findById: vi.fn().mockResolvedValue(undefined),+ patchRunningOperation: vi.fn().mockResolvedValue(true),+ settleRunningOperation: vi.fn().mockResolvedValue({ status: 'settled' }),+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ updateMetadata: vi.fn().mockResolvedValue(undefined),+};+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return topicMock;+ }),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(function () {+ return {+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ };+ }),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ market: {+ creds: {+ get: vi.fn(),+ list: vi.fn().mockResolvedValue({ data: [] }),+ },+ },+ };+ }),+}));++vi.mock('@/server/services/heterogeneousAgent', () => ({+ HeterogeneousAgentService: vi.fn().mockImplementation(function () {+ return {+ getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,+ };+ }),+}));++// Only the Lab preference read is replaced; the rest of UserModel stays real.+vi.mock('@/database/models/user', async (importOriginal) => {+ const actual = await importOriginal<typeof UserModelModule>();+ class UserModel extends actual.UserModel {+ getUserPreference = mockGetUserPreference;+ }+ return { ...actual, UserModel };+});++vi.mock('@/server/services/heterogeneousAgent/sandboxRunner', () => ({+ spawnHeteroSandbox: mockSpawnHeteroSandbox,+}));++vi.mock('@/server/services/file/resolveAttachments', () => ({+ resolveAttachmentsByFileIds: mockResolveAttachmentsByFileIds,+}));++vi.mock('@/server/services/document', () => ({+ DocumentService: vi.fn().mockImplementation(function () {+ return {+ parseFile: vi.fn().mockResolvedValue({ content: '' }),+ };+ }),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return {+ createOperation: vi.fn().mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ }),+ interruptOperation: mockInterruptOperation,+ };+ }),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ queryDeviceSystemInfo: mockQueryDeviceSystemInfo,+ readDeviceSystemInfo: mockReadDeviceSystemInfo,+ dispatchAgentRun: mockDispatchAgentRun,+ executeToolCall: mockExecuteToolCall,+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),+ },+}));++vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({+ resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@/server/services/heterogeneousAgent/remoteDeviceHeteroContext', () => ({+ buildRemoteDeviceHeteroContext: mockBuildRemoteDeviceHeteroContext,+}));++describe('AiAgentService.execAgent - Codex device runtime', () => {+ let service: AiAgentService;+ let recordStartSpy: MockInstance<CompletionLifecycle['recordStart']>;+ const mockDb = {} as any;+ const userId = 'test-user-id';++ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(AgentOperationModel.prototype, 'settleRunning').mockResolvedValue(true);+ recordStartSpy = vi.spyOn(CompletionLifecycle.prototype, 'recordStart').mockResolvedValue(true);+ topicMock.appendRunningOperationChild.mockResolvedValue(true);+ topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });+ topicMock.findById.mockResolvedValue(undefined);+ topicMock.patchRunningOperation.mockResolvedValue(true);+ topicMock.releaseTaskCallbackReservation.mockResolvedValue(undefined);+ topicMock.tryReserveTaskCallback.mockResolvedValue(true);+ topicMock.updateMetadata.mockResolvedValue(undefined);+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockMessageQuery.mockResolvedValue([]);+ mockResolveAttachmentsByFileIds.mockResolvedValue({ ...emptyResolvedAttachments });+ mockSpawnHeteroSandbox.mockResolvedValue(undefined);+ mockDispatchAgentRun.mockResolvedValue({ success: true });+ mockExecuteToolCall.mockResolvedValue({ success: true });+ mockGetHeterogeneousResumeSessionId.mockResolvedValue(undefined);+ mockQueryDeviceSystemInfo.mockResolvedValue(undefined);+ mockReadDeviceSystemInfo.mockResolvedValue({ ok: false, reason: 'DEVICE_OFFLINE' });+ mockGetUserPreference.mockResolvedValue(undefined);+ mockMessageQuery.mockResolvedValue([]);+ mockBuildRemoteDeviceHeteroContext.mockImplementation(function ({ conversationHistory }) {+ return conversationHistory ? 'device recovery context' : 'device context';+ });+ mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });+ mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);+ mockCreateOperationMetadata.mockResolvedValue(undefined);+ mockIngestAttachment.mockReset();+ heteroAgentConfig.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } } as any;+ heteroAgentConfig.model = 'claude-code';+ heteroAgentConfig.provider = 'anthropic';+ delete (heteroAgentConfig as any).userId;+ delete (heteroAgentConfig as any).visibility;+ delete (heteroAgentConfig as any).workspaceId;++ service = new AiAgentService(mockDb, userId);+ });++ afterEach(() => {+ recordStartSpy.mockRestore();+ vi.clearAllMocks();+ });++ // ROOT CAUSE:+ // Sending a new wrapper flag to every Codex device broke installed CLIs.+ // Native mode must come from the live connection.+ /** @example An older connection still accepts an ordinary Codex prompt. */+ it('preserves ordinary Codex sends on an older connected CLI', async () => {+ Object.assign(heteroAgentConfig.agencyConfig, {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'codex' },+ });+ mockGetUserPreference.mockResolvedValue({ lab: { enableCodexAppServer: true } });+ await service.execAgent({ agentId: 'agent-1', prompt: 'ordinary device turn' });+ /** @example No unsupported native wrapper option reaches the old process. */+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(expect.objectContaining({ args: undefined }));+ /** @example The capability is obtained from the current connection rather than stale registration. */+ expect(mockReadDeviceSystemInfo).toHaveBeenCalledWith(userId, 'device-1', undefined, {+ clientKinds: ['cli'],+ });+ });++ // ROOT CAUSE:+ // Every Codex device run switched to app-server once the CLI advertised it, so the+ // whole device population changed runtime and each dispatch paid a live capability query.+ // The app-server runtime is opt-in through the existing Labs preference.+ /** @example Without the Labs opt-in, an ordinary Codex send stays on codex exec. */+ it('keeps ordinary Codex sends on exec unless the app-server Lab is enabled', async () => {+ Object.assign(heteroAgentConfig.agencyConfig, {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'codex' },+ });+ mockReadDeviceSystemInfo.mockResolvedValue({+ ok: true,+ systemInfo: { supportedAgentRuntimes: ['codex-app-server-v1'] },+ });+ await service.execAgent({ agentId: 'agent-1', prompt: 'ordinary device turn' });+ /** @example A capable device still receives the existing exec arguments. */+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(expect.objectContaining({ args: undefined }));+ /** @example The ordinary path does not query live device capabilities. */+ expect(mockReadDeviceSystemInfo).not.toHaveBeenCalled();+ });++ // ROOT CAUSE:+ // App-server device runs dropped `conversationHistory` and the resume fallback for every+ // topic, so an ordinary topic whose native session was lost restarted with no context.+ /** @example An ordinary app-server topic keeps its transcript recovery. */+ it('keeps transcript recovery for ordinary app-server Codex topics', async () => {+ mockGetHeterogeneousResumeSessionId.mockResolvedValue('native-session-existing');+ mockGetUserPreference.mockResolvedValue({ lab: { enableCodexAppServer: true } });+ mockReadDeviceSystemInfo.mockResolvedValue({+ ok: true,+ systemInfo: { supportedAgentRuntimes: ['codex-app-server-v1'] },+ });+ mockMessageQuery.mockResolvedValue([+ { content: 'Earlier question', id: 'old-user', role: 'user' },+ { content: 'Earlier answer', id: 'old-assistant', role: 'assistant' },+ { content: 'Continue on my device', id: 'msg-1', role: 'user' },+ ]);+ Object.assign(heteroAgentConfig.agencyConfig, {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'codex' },+ });++ await service.execAgent({ agentId: 'agent-1', prompt: 'Continue on my device' });++ /** @example The native runtime keeps the transcript fallback. */+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--codex-app-server'],+ resumeFallbackSystemContext: 'device recovery context',+ resumeSessionId: 'native-session-existing',+ systemContext: 'device context',+ }),+ );+ });++ /** @example A fresh ordinary app-server topic still receives its prior turns. */+ it('injects topic history into a fresh ordinary app-server Codex run', async () => {+ mockGetUserPreference.mockResolvedValue({ lab: { enableCodexAppServer: true } });+ mockReadDeviceSystemInfo.mockResolvedValue({+ ok: true,+ systemInfo: { supportedAgentRuntimes: ['codex-app-server-v1'] },+ });+ mockMessageQuery.mockResolvedValue([+ { content: 'Create the GPU pod', id: 'old-user', role: 'user' },+ { content: 'The pod is electron-gpu-shell', id: 'old-assistant', role: 'assistant' },+ { content: 'Delete it', id: 'msg-1', role: 'user' },+ ]);+ Object.assign(heteroAgentConfig.agencyConfig, {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'codex' },+ });++ await service.execAgent({ agentId: 'agent-1', prompt: 'Delete it' });++ expect(mockDispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--codex-app-server'],+ resumeSessionId: undefined,+ systemContext: 'device recovery context',+ }),+ );+ });++ // ROOT CAUSE:+ // A capable Labs device always received `--codex-app-server`, even when the provider+ // carried options (e.g. `--profile`) the native handle rejects, so valid exec configs failed.+ /** @example Provider options app-server cannot honor keep the device on codex exec. */+ it('keeps Codex exec when provider arguments are unsupported by app-server', async () => {+ mockGetUserPreference.mockResolvedValue({ lab: { enableCodexAppServer: true } });+ mockReadDeviceSystemInfo.mockResolvedValue({+ ok: true,+ systemInfo: { supportedAgentRuntimes: ['codex-app-server-v1'] },+ });+ Object.assign(heteroAgentConfig.agencyConfig, {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { args: ['--profile', 'work'], type: 'codex' },+ });++ await service.execAgent({ agentId: 'agent-1', prompt: 'ordinary device turn' });++ /** @example The exec arguments are forwarded unchanged, without the native wrapper flag. */+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({ args: ['--agent-arg=--profile', '--agent-arg=work'] }),+ );+ });++ // ROOT CAUSE:+ // The capability probe preferred the Desktop connection, while the gateway routes agent+ // runs to `lh connect` first, so an older CLI beside a current Desktop got native flags.+ /** @example A current Desktop does not enable native flags for an older CLI run. */+ it('probes native Codex on the connection that receives the agent run', async () => {+ mockGetUserPreference.mockResolvedValue({ lab: { enableCodexAppServer: true } });+ // The desktop-preferring read sees the current Desktop's runtime.+ mockQueryDeviceSystemInfo.mockResolvedValue({+ supportedAgentRuntimes: ['codex-app-server-v1'],+ });+ mockReadDeviceSystemInfo.mockImplementation(async (_u, _d, _w, options) =>+ options?.clientKinds?.[0] === 'desktop'+ ? { ok: true, systemInfo: { supportedAgentRuntimes: ['codex-app-server-v1'] } }+ : { ok: true, systemInfo: {} },+ );+ Object.assign(heteroAgentConfig.agencyConfig, {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'codex' },+ });++ await service.execAgent({ agentId: 'agent-1', prompt: 'ordinary device turn' });++ /** @example The older CLI that receives the run keeps codex exec. */+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(expect.objectContaining({ args: undefined }));+ });++ /** @example A Desktop-only device runs natively, pinned to the Desktop connection. */+ it('pins a native Codex run to the client that advertised the runtime', async () => {+ mockGetUserPreference.mockResolvedValue({ lab: { enableCodexAppServer: true } });+ mockReadDeviceSystemInfo.mockImplementation(async (_u, _d, _w, options) =>+ options?.clientKinds?.[0] === 'desktop'+ ? { ok: true, systemInfo: { supportedAgentRuntimes: ['codex-app-server-v1'] } }+ : { ok: false, reason: 'NO_CAPABLE_CONNECTION' },+ );+ Object.assign(heteroAgentConfig.agencyConfig, {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'codex' },+ });++ await service.execAgent({ agentId: 'agent-1', prompt: 'ordinary device turn' });++ expect(mockDispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({ args: ['--codex-app-server'], clientKinds: ['desktop'] }),+ );+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/codexDeviceRuntime.ts b/apps/server/src/services/aiAgent/pipeline/codexDeviceRuntime.tsnew file mode 100644index 00000000000..58f7c54e77e--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/codexDeviceRuntime.ts@@ -0,0 +1,197 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { getCodexAppServerUnsupportedArgs } from '@lobechat/heterogeneous-agents/codexAppServerParams';+import type { DeviceClient, LobeAgentAgencyConfig } from '@lobechat/types';+import debug from 'debug';++import { UserModel } from '@/database/models/user';++const log = debug('lobe-server:ai-agent-service');++/** Device capability advertised by a CLI that can run `lh hetero exec --codex-app-server`. */+export const CODEX_APP_SERVER_RUNTIME = 'codex-app-server-v1';++/**+ * Clients in the order the device gateway routes an agent run among one device's+ * connections: `lh connect` ranks ahead of the Desktop app.+ */+const AGENT_RUN_CLIENT_ORDER: readonly DeviceClient[][] = [['cli'], ['desktop']];++/** A system-info read of one client's connection; a failure keeps the gateway's reason. */+export type AgentRunSystemInfoRead =+ | { ok: true; systemInfo: { supportedAgentRuntimes?: readonly string[] } }+ | { ok: false; reason: string };++export interface AgentRunRuntimeProbe {+ /** The client whose connection answered; pin the native dispatch to it. */+ clientKinds?: DeviceClient[];+ runtimes?: readonly string[];+}++/**+ * Reads native runtimes from the connection an agent run will actually reach.+ *+ * Use when:+ * - Deciding whether a device run may carry native wrapper flags.+ * Expects:+ * - `read` restricts the system-info request to the given clients.+ * Returns:+ * - The runtimes of the first client in agent-run routing order that is connected,+ * with that client so the dispatch can be pinned to the same connection; no+ * runtimes when that client did not answer.+ *+ * Call stack:+ *+ * dispatchHeteroAgent+ * -> {@link probeAgentRunRuntimes}+ * -> deviceGateway.readDeviceSystemInfo+ */+export const probeAgentRunRuntimes = async (+ read: (clientKinds: DeviceClient[]) => Promise<AgentRunSystemInfoRead>,+): Promise<AgentRunRuntimeProbe> => {+ for (const clientKinds of AGENT_RUN_CLIENT_ORDER) {+ const result = await read(clientKinds);+ if (result.ok) return { clientKinds, runtimes: result.systemInfo.supportedAgentRuntimes };+ // Only "no connection of this client" moves on; an unanswered read is not a capability.+ if (result.reason !== 'NO_CAPABLE_CONNECTION') return {};+ }+ return {};+};++/** How a connected device runs one Codex turn. */+export type CodexDeviceRuntime =+ /** Keep the existing `codex exec` path and its transcript recovery. */+ | { kind: 'exec' }+ /** The turn must not run; the caller settles it as a dispatch error. */+ | { kind: 'error'; message: string }+ | {+ /** Extra `lh hetero exec` wrapper flags. */+ args: string[];+ kind: 'native';+ };++export interface ResolveCodexDeviceRuntimeParams {+ /** Raw Codex provider arguments forwarded to the agent; native mode must honor all of them. */+ agentArgs?: readonly string[];+ /** `api` auth uses the hosted provider binding, which has no native app-server session. */+ authMode?: string;+ heteroType: string;+ /** Reads the user's Labs `enableCodexAppServer` preference. */+ isAppServerLabEnabled: () => Promise<boolean>;+ /** Reads the live connection's advertised runtimes, never merged DB metadata. */+ querySupportedRuntimes: () => Promise<readonly string[] | undefined>;+ /** Whether this turn resumes a saved native session. */+ resume?: boolean;+}++/**+ * Chooses between `codex exec` and the native app-server runtime for a device run.+ *+ * Use when:+ * - Dispatching a Codex turn to a connected device.+ * Expects:+ * - The live connection reports `codex-app-server-v1` only after a native handshake.+ * Returns:+ * - `exec` for every run unless the user enabled the Labs app-server runtime, the+ * device supports it, and app-server can honor every provider argument; native runs+ * keep transcript recovery.+ *+ * Call stack:+ *+ * dispatchHeteroAgent+ * -> {@link resolveCodexDeviceRuntime}+ */+export const resolveCodexDeviceRuntime = async (+ params: ResolveCodexDeviceRuntimeParams,+): Promise<CodexDeviceRuntime> => {+ if (params.heteroType !== 'codex') return { kind: 'exec' };+ const nativeAuth = params.authMode !== 'api';++ // Codex topics keep `codex exec` by default. The app-server runtime is opt-in through+ // the same Labs preference Desktop local runs use; it records native turn IDs.+ if (!nativeAuth || !(await params.isAppServerLabEnabled())) return { kind: 'exec' };+ // `codex exec` accepts options (e.g. `--profile`) the native thread contract cannot+ // represent; the device handle rejects them, so keep those configurations on exec.+ const unsupported = getCodexAppServerUnsupportedArgs([...(params.agentArgs ?? [])], {+ resume: params.resume,+ });+ if (unsupported.length > 0) return { kind: 'exec' };+ const runtimes = await params.querySupportedRuntimes();+ if (!runtimes?.includes(CODEX_APP_SERVER_RUNTIME)) return { kind: 'exec' };+ return { args: ['--codex-app-server'], kind: 'native' };+};++/** A {@link CodexDeviceRuntime} whose native variant names the connection to pin. */+export type CodexDeviceDispatch =+ | Exclude<CodexDeviceRuntime, { kind: 'native' }>+ | (Extract<CodexDeviceRuntime, { kind: 'native' }> & {+ /** The client that advertised the native runtime; the native dispatch is pinned to it. */+ clientKinds?: DeviceClient[];+ });++export interface SelectCodexDeviceDispatchParams {+ db: LobeChatDatabase;+ heterogeneousProvider?: LobeAgentAgencyConfig['heterogeneousProvider'];+ heteroType: string;+ /** Reads system info from the dispatch device, restricted to the given clients. */+ readSystemInfo: (clientKinds: DeviceClient[]) => Promise<AgentRunSystemInfoRead>;+ /** Whether this turn resumes a saved native session. */+ resume: boolean;+ userId: string;+}++/**+ * Chooses how a device dispatch runs Codex and which connection a native run is pinned to.+ *+ * Use when:+ * - `dispatchHeteroAgent` has resolved the device a hetero run is dispatched to.+ * Expects:+ * - `readSystemInfo` reads the live connection of that device, not merged DB metadata.+ * Returns:+ * - The {@link resolveCodexDeviceRuntime} result, with the probed client on `native`;+ * a thrown failure becomes `error` so the caller settles the turn as a dispatch error.+ *+ * Call stack:+ *+ * dispatchHeteroAgent+ * -> {@link selectCodexDeviceDispatch}+ * -> {@link resolveCodexDeviceRuntime}+ * -> {@link probeAgentRunRuntimes}+ */+export const selectCodexDeviceDispatch = async (+ params: SelectCodexDeviceDispatchParams,+): Promise<CodexDeviceDispatch> => {+ const { heterogeneousProvider, heteroType } = params;+ let clientKinds: DeviceClient[] | undefined;+ let runtime: CodexDeviceRuntime;+ try {+ runtime = await resolveCodexDeviceRuntime({+ agentArgs:+ heterogeneousProvider?.type === heteroType ? heterogeneousProvider.args : undefined,+ authMode: heterogeneousProvider?.authMode,+ heteroType,+ isAppServerLabEnabled: async () => {+ try {+ const preference = await new UserModel(params.db, params.userId).getUserPreference();+ return preference?.lab?.enableCodexAppServer === true;+ } catch (err) {+ log('execAgent: failed to read Codex app-server Lab preference: %O', err);+ return false;+ }+ },+ // Query the live connection that receives the run, not merged DB metadata:+ // downgrade/reconnect must revoke it, and another client may differ.+ querySupportedRuntimes: async () => {+ const probe = await probeAgentRunRuntimes(params.readSystemInfo);+ clientKinds = probe.clientKinds;+ return probe.runtimes;+ },+ resume: params.resume,+ });+ } catch (err) {+ runtime = { kind: 'error', message: err instanceof Error ? err.message : String(err) };+ }+ if (runtime.kind === 'error') {+ log('execAgent: native Codex dispatch rejected: %s', runtime.message);+ }+ return runtime.kind === 'native' ? { ...runtime, clientKinds } : runtime;+};diff --git a/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.ts b/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.tsnew file mode 100644index 00000000000..852caa2f285--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.ts@@ -0,0 +1,140 @@+import type { LobeChatDatabase } from '@lobechat/database';+import type { DeviceUnavailableErrorData, ErrorType } from '@lobechat/types';+import { ChatErrorType } from '@lobechat/types';+import debug from 'debug';++import type { MessageModel } from '@/database/models/message';+import type { TopicModel } from '@/database/models/topic';+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';+import { hookDispatcher } from '@/server/services/agentRuntime/hooks';++import type { DeviceDispatchRoute } from '../helpers/heteroErrors';++const log = debug('lobe-server:ai-agent-service');++/** The part of `HeteroDispatchDeps` that settling a dispatch failure needs. */+export interface HeteroDispatchErrorDeps {+ db: LobeChatDatabase;+ messageModel: MessageModel;+ topicModel: TopicModel;+ userId: string;+ workspaceId?: string;+}++/**+ * Finalize a hetero run that fails *synchronously at dispatch* β before the+ * CLI/agent process ever starts (device offline β DEVICE_NOT_FOUND, no bound+ * device, access denied, sandbox spawn rejected). These paths never produce a+ * `heteroFinish` (CLI exit) or `agentNotify` done callback, so without this+ * each one would strand the run: the assistant bubble would show an error but+ * the UI stream would never close and a long-run task would hang in `running`.+ *+ * Routes through the SAME terminal funnel a normal exit uses β+ * `CompletionLifecycle.completeOperation` finalizes the op row and fires the+ * run's onComplete/onError hooks, so the task lifecycle (onTopicComplete β task+ * failed) and any IM bot completion callback fire exactly as they would for a+ * real failure β then closes the UI stream and clears the (never-started)+ * running operation. The hooks were registered and serialized onto+ * `runningOperation` at dispatch time.+ *+ * Stream-close / hook dispatch / metadata clear are best-effort: a failure+ * there must not mask the original dispatch error the caller surfaces.+ *+ * Returns whether an `onComplete` consumer was there to be told. Callers hand+ * that back to the invoker as `terminalReported` so a surface that renders+ * failures itself (the IM bot bridge) can tell "the lifecycle already announced+ * this" from "nobody did" β see {@link HookDispatcher.canDeliver}.+ */+export const finalizeHeteroDispatchError = async (+ deps: HeteroDispatchErrorDeps,+ params: {+ agentId?: string;+ assistantMessageId: string;+ detail: string;+ /** The device this dispatch was routed to, when it was a device dispatch. */+ deviceRoute?: DeviceDispatchRoute;+ errorData?: DeviceUnavailableErrorData;+ /**+ * Client error type. Defaults to the generic `ServerAgentRuntimeError`; pass a+ * dedicated `ChatErrorType` (e.g. `DeviceGatewayNotConfigured`) so the web+ * client renders a specific localized headline instead of the generic copy.+ */+ errorType?: ErrorType;+ message: string;+ operationId: string;+ topicId: string;+ },+): Promise<boolean> => {+ const {+ agentId,+ assistantMessageId,+ detail,+ deviceRoute,+ errorData,+ errorType = ChatErrorType.ServerAgentRuntimeError,+ message,+ operationId,+ topicId,+ } = params;++ // 1. Error bubble β written first so a stream subscriber reacting to the+ // end event below re-reads a message that already carries the error.+ await deps.messageModel.update(assistantMessageId, {+ content: '',+ error: { body: { detail, ...errorData }, message, type: errorType },+ });++ // 1b. Finalize the run through CompletionLifecycle's single entry β the SAME+ // owner the CLI exit (heteroFinish) / in-process paths use. It marks the+ // agent_operations row terminal (the row was inserted at recordStart, but a+ // dispatch failure goes through THIS path, not heteroFinish, so without+ // finalizing it the row stays status='running' forever) AND fires the run's+ // onComplete/onError hooks (task lifecycle β task failed + IM bot callback).+ // `skipErrorMessageWrite` keeps the bespoke device-specific bubble written+ // in step 1; verify is done-only, so it no-ops on this error path.+ // Read BEFORE dispatching: a settled lifecycle unregisters the operation's+ // hooks, so asking afterwards can no longer tell "delivered" from "never+ // had one".+ const terminalReported = hookDispatcher.canDeliver(operationId, 'onComplete');+ await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId).completeOperation(+ {+ agentId,+ assistantMessageId,+ error: { message, type: errorType, ...(deviceRoute && { deviceRoute }) },+ operationId,+ serializedHooks: hookDispatcher.getSerializedHooks(operationId),+ topicId,+ userId: deps.userId,+ },+ 'error',+ { skipErrorMessageWrite: true },+ );++ // 2. Close the UI stream.+ try {+ await createStreamEventManager().publishAgentRuntimeEnd({+ finalState: { error: detail },+ operationId,+ reason: 'error',+ reasonDetail: detail,+ stepIndex: 0,+ });+ } catch (err) {+ log('finalizeHeteroDispatchError: publishAgentRuntimeEnd failed (non-fatal): %O', err);+ }++ // 3. The operation never started β settle the topic so reconnect /+ // heteroIngest validation and the next turn don't see a stale operation.+ // Settle, not take: dropping the marker alone would strand `status` on+ // 'running' with nothing left for any later settle to match β see+ // `ServerOperationStore.clearRunningMark`. 'active' rather than 'unread'+ // because a dispatch that never started produced nothing to read.+ try {+ await deps.topicModel.settleRunningOperation(topicId, operationId, 'active');+ } catch (err) {+ log('finalizeHeteroDispatchError: clear runningOperation failed (non-fatal): %O', err);+ }++ return terminalReported;+};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.tsindex 65f3fbd4185..0e635410069 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts@@ -10,8 +10,6 @@ import {isRemoteHeterogeneousType,} from '@lobechat/heterogeneous-agents';import type {- DeviceUnavailableErrorData,- ErrorType,ExecAgentResult,HeterogeneousRuntimePinSources,HeterogeneousTopicPin,@@ -21,7 +19,6 @@ import type {import {applyTopicModelToHeterogeneousProvider,buildHeteroExecArgs,- ChatErrorType,getWorkingDirEffectivePath,resolveHeterogeneousRuntimeConfig,} from '@lobechat/types';@@ -54,7 +51,6 @@ import {} from '@/server/services/sandbox/session';import {- type DeviceDispatchRoute,getHeterogeneousAgentTitle,humanizeHeteroDispatchError,resolveHeteroDispatchErrorType,@@ -66,6 +62,8 @@ import type {ExecRunContext,InternalExecAgentParams,} from '../types';+import { selectCodexDeviceDispatch } from './codexDeviceRuntime';+import { finalizeHeteroDispatchError } from './finalizeHeteroDispatchError';import { heteroOperationCapabilities } from './heteroOperationCapabilities';import type { RunAttachments } from './turnSetup';@@ -90,123 +88,6 @@ export interface HeteroDispatchDeps {workspaceId?: string;}-/**- * Finalize a hetero run that fails *synchronously at dispatch* β before the- * CLI/agent process ever starts (device offline β DEVICE_NOT_FOUND, no bound- * device, access denied, sandbox spawn rejected). These paths never produce a- * `heteroFinish` (CLI exit) or `agentNotify` done callback, so without this- * each one would strand the run: the assistant bubble would show an error but- * the UI stream would never close and a long-run task would hang in `running`.- *- * Routes through the SAME terminal funnel a normal exit uses β- * `CompletionLifecycle.completeOperation` finalizes the op row and fires the- * run's onComplete/onError hooks, so the task lifecycle (onTopicComplete β task- * failed) and any IM bot completion callback fire exactly as they would for a- * real failure β then closes the UI stream and clears the (never-started)- * running operation. The hooks were registered and serialized onto- * `runningOperation` at dispatch time.- *- * Stream-close / hook dispatch / metadata clear are best-effort: a failure- * there must not mask the original dispatch error the caller surfaces.- *- * Returns whether an `onComplete` consumer was there to be told. Callers hand- * that back to the invoker as `terminalReported` so a surface that renders- * failures itself (the IM bot bridge) can tell "the lifecycle already announced- * this" from "nobody did" β see {@link HookDispatcher.canDeliver}.- */-const finalizeHeteroDispatchError = async (- deps: HeteroDispatchDeps,- params: {- agentId?: string;- assistantMessageId: string;- detail: string;- /** The device this dispatch was routed to, when it was a device dispatch. */- deviceRoute?: DeviceDispatchRoute;- errorData?: DeviceUnavailableErrorData;- /**- * Client error type. Defaults to the generic `ServerAgentRuntimeError`; pass a- * dedicated `ChatErrorType` (e.g. `DeviceGatewayNotConfigured`) so the web- * client renders a specific localized headline instead of the generic copy.- */- errorType?: ErrorType;- message: string;- operationId: string;- topicId: string;- },-): Promise<boolean> => {- const {- agentId,- assistantMessageId,- detail,- deviceRoute,- errorData,- errorType = ChatErrorType.ServerAgentRuntimeError,- message,- operationId,- topicId,- } = params;-- // 1. Error bubble β written first so a stream subscriber reacting to the- // end event below re-reads a message that already carries the error.- await deps.messageModel.update(assistantMessageId, {- content: '',- error: { body: { detail, ...errorData }, message, type: errorType },- });-- // 1b. Finalize the run through CompletionLifecycle's single entry β the SAME- // owner the CLI exit (heteroFinish) / in-process paths use. It marks the- // agent_operations row terminal (the row was inserted at recordStart, but a- // dispatch failure goes through THIS path, not heteroFinish, so without- // finalizing it the row stays status='running' forever) AND fires the run's- // onComplete/onError hooks (task lifecycle β task failed + IM bot callback).- // `skipErrorMessageWrite` keeps the bespoke device-specific bubble written- // in step 1; verify is done-only, so it no-ops on this error path.- // Read BEFORE dispatching: a settled lifecycle unregisters the operation's- // hooks, so asking afterwards can no longer tell "delivered" from "never- // had one".- const terminalReported = hookDispatcher.canDeliver(operationId, 'onComplete');- await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId).completeOperation(- {- agentId,- assistantMessageId,- error: { message, type: errorType, ...(deviceRoute && { deviceRoute }) },- operationId,- serializedHooks: hookDispatcher.getSerializedHooks(operationId),- topicId,- userId: deps.userId,- },- 'error',- { skipErrorMessageWrite: true },- );-- // 2. Close the UI stream.- try {- await createStreamEventManager().publishAgentRuntimeEnd({- finalState: { error: detail },- operationId,- reason: 'error',- reasonDetail: detail,- stepIndex: 0,- });- } catch (err) {- log('finalizeHeteroDispatchError: publishAgentRuntimeEnd failed (non-fatal): %O', err);- }-- // 3. The operation never started β settle the topic so reconnect /- // heteroIngest validation and the next turn don't see a stale operation.- // Settle, not take: dropping the marker alone would strand `status` on- // 'running' with nothing left for any later settle to match β see- // `ServerOperationStore.clearRunningMark`. 'active' rather than 'unread'- // because a dispatch that never started produced nothing to read.- try {- await deps.topicModel.settleRunningOperation(topicId, operationId, 'active');- } catch (err) {- log('finalizeHeteroDispatchError: clear runningOperation failed (non-fatal): %O', err);- }-- return terminalReported;-};-/*** Liveness probe for the ONE dispatch failure that races a live run: the cloud* sandbox `runCommand` call (see the `spawnHeteroSandbox` catch below). Every@@ -1032,6 +913,44 @@ export const dispatchHeteroAgent = async (userMessageId: userMessageId ?? parentMessageId ?? '',};}+ const codexRuntime = await selectCodexDeviceDispatch({+ db: deps.db,+ heterogeneousProvider,+ heteroType,+ readSystemInfo: (clientKinds) =>+ deviceGateway.readDeviceSystemInfo(deps.userId, dispatchDeviceId, cliDeviceWorkspaceId, {+ clientKinds,+ }),+ resume: Boolean(resumeSessionId),+ userId: deps.userId,+ });+ if (codexRuntime.kind === 'error') {+ const terminalReported = await finalizeHeteroDispatchError(deps, {+ agentId: resolvedAgentId,+ assistantMessageId,+ detail: codexRuntime.message,+ message: 'Native Codex dispatch rejected',+ operationId,+ topicId,+ });+ return {+ agentId: resolvedAgentId,+ assistantMessageId,+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: codexRuntime.message,+ message: codexRuntime.message,+ operationId,+ status: 'error',+ success: false,+ terminalReported,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: userMessageId ?? parentMessageId ?? '',+ };+ }+ const nativeCodex = codexRuntime.kind === 'native' ? codexRuntime : undefined;+// Resolve the working directory for the run: a topic-level override// wins, else the device's user-configured defaultCwd. The device row// lives in the DB (the gateway only knows live connections), so read@@ -1099,7 +1018,9 @@ export const dispatchHeteroAgent = async (: await deviceGateway.dispatchAgentRun({...heteroParams,agentId: resolvedAgentId,- args: heteroExecArgs,+ // Only a live client advertising the native protocol receives these wrapper flags.+ args: nativeCodex ? [...(heteroExecArgs ?? []), ...nativeCodex.args] : heteroExecArgs,+ clientKinds: nativeCodex?.clientKinds,cwd: deviceCwd,deviceId: dispatchDeviceId,resumeFallbackSystemContext: deviceResumeFallbackSystemContext,diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex d3ffd1ab5a0..9d34702e58c 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -1990,6 +1990,8 @@ export class DeviceGateway {assistantMessageId: string;/** Resolved `lh hetero exec` wrapper args. */args?: string[];+ /** Restricts the run to connections of these clients; omitted means any client. */+ clientKinds?: DeviceClient[];cwd?: string;deviceId?: string;/** Image attachments forwarded to the device as fetchable (signed) URLs. */diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.tsindex 02c85d8b405..70fcb2c2d84 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts@@ -43,6 +43,12 @@ import type { ThreadModel } from '@/database/models/thread';import type { TopicModel } from '@/database/models/topic';import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';+import {+ heteroProvenance,+ persistCodexTurnProvenance,+ restoreHeteroProvenance,+} from './heteroProvenance';+const log = debug('lobe-server:hetero-agent:persistence');const generateThreadId = () => `thd_${createNanoId(16)()}`;@@ -127,6 +133,8 @@ interface AssistantMessageDbLike {*/interface OperationState {agentId: string | null;+ /** Native turn boundary shared by the user prompt and every assistant/tool step. */+ codexTurnId?: string;/*** CC-native session id this run is producing, captured off the stream_start* event stream and stamped on every persisted message's@@ -153,6 +161,8 @@ interface OperationState {* after the event's XADD succeeds.*/publishedKeys: Set<string>;+ /** User message answered by this operation, checked against its topic/thread before stamping. */+ sourceUserMessageId?: string;/** Isolation thread that owns this heterogeneous run, when applicable. */threadId: string | undefined;/**@@ -653,6 +663,7 @@ export class HeterogeneousPersistenceHandler {// topic.metadata.heteroSessionId: that holds the id we ASKED CC to resume,// which differs from the actual id when a fork/new session occurred.heteroSessionId: undefined,+ sourceUserMessageId: baseAssistantMessage?.parentId ?? undefined,lastStepIndex: 0,lastAppliedToolStateSeqByCallId: new Map(),main: createMainAgentRunState(currentAssistantMessageId),@@ -840,9 +851,7 @@ export class HeterogeneousPersistenceHandler {// Recover the run's CC session id from a previously-stamped message so a// cold replica that never saw this run's stream_start still stamps the// right session id on the messages it persists.- if (!state.heteroSessionId && typeof snapshot.metadata.heteroSessionId === 'string') {- state.heteroSessionId = snapshot.metadata.heteroSessionId;- }+ restoreHeteroProvenance(state, snapshot.metadata);if (snapshot.textSnapshotSeq > state.main.lastTextSnapshotSeq) {state.main.accContent = snapshot.content;@@ -1129,6 +1138,11 @@ export class HeterogeneousPersistenceHandler {}}+ if (event.type === 'stream_start' && typeof event.data?.codexTurnId === 'string') {+ state.codexTurnId = event.data.codexTurnId;+ await persistCodexTurnProvenance(this.deps.messageModel, state);+ }+const { intents, state: next } = reduceMainAgent(state.main, event, this.mainReduceCtx(state));for (const intent of intents) {@@ -1142,30 +1156,11 @@ export class HeterogeneousPersistenceHandler {state.main = next;}- /**- * Per-message provenance stamped on every hetero-persisted row: the CC- * session id the turn ran under (`heteroSessionId`) and, when known, the CC- * `message.id` of the turn (`heteroMessageId`). A per-message copy lets a- * diff pinpoint the exact row where CC forked to a new session / lost- * `--resume` history β something the topic-level single `heteroSessionId`- * can never show. Returns `{}` when neither is known, so callers can spread- * it without minting empty metadata.- */- private heteroProvenance(- state: OperationState,- heteroMessageId?: string,- ): { heteroMessageId?: string; heteroSessionId?: string } {- const out: { heteroMessageId?: string; heteroSessionId?: string } = {};- if (state.heteroSessionId) out.heteroSessionId = state.heteroSessionId;- if (heteroMessageId) out.heteroMessageId = heteroMessageId;- return out;- }-private async applyMainIntent(state: OperationState, intent: MainAgentIntent, stepIndex: number) {switch (intent.kind) {case 'createAssistant': {const createMetadata: Record<string, any> = {- ...this.heteroProvenance(state, intent.mainMessageId),+ ...heteroProvenance(state, intent.mainMessageId),};if (intent.signal) createMetadata.signal = intent.signal;// Persist the turn's CC message.id so a cold replica can recover@@ -1234,7 +1229,7 @@ export class HeterogeneousPersistenceHandler {// Phase 2: create new tool rows with reducer-preallocated ids.for (const tool of intent.tools) {if (!tool.isNew) continue;- const toolMetadata = this.heteroProvenance(state, state.main.currentMainMessageId);+ const toolMetadata = heteroProvenance(state, state.main.currentMainMessageId);await this.deps.messageModel.create({agentId: state.agentId ?? undefined,@@ -1284,7 +1279,7 @@ export class HeterogeneousPersistenceHandler {// provenance the createAssistant write put there, or usage would wipe it.update.metadata = {...state.main.turnMetadata,- ...this.heteroProvenance(state, state.main.currentMainMessageId),+ ...heteroProvenance(state, state.main.currentMainMessageId),usage: intent.usage,};}@@ -1623,7 +1618,7 @@ export class HeterogeneousPersistenceHandler {case 'createMessage': {const subMetadata: Record<string, any> = {- ...this.heteroProvenance(state, intent.subagentMessageId),+ ...heteroProvenance(state, intent.subagentMessageId),};// Persist the turn's CC message.id so a cold replica can recover// `currentSubagentMessageId` (via buildSubagentSnapshot) and avoid@@ -1686,7 +1681,7 @@ export class HeterogeneousPersistenceHandler {// register them in the global tool-message map for tool_result lookup.for (const t of intent.tools) {if (!t.isNew) continue;- const subToolMetadata = this.heteroProvenance(state, intent.subagentMessageId);+ const subToolMetadata = heteroProvenance(state, intent.subagentMessageId);await this.deps.messageModel.create({agentId: state.agentId ?? undefined,@@ -1719,7 +1714,7 @@ export class HeterogeneousPersistenceHandler {// Wholesale metadata overwrite β re-stamp the session + message// provenance the createMessage write put there, or usage would wipe it.metadata: {- ...this.heteroProvenance(state, intent.subagentMessageId),+ ...heteroProvenance(state, intent.subagentMessageId),usage: intent.usage as any,},...(intent.model && { model: intent.model }),diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.codexTurnProvenance.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.codexTurnProvenance.test.tsnew file mode 100644index 00000000000..80e57869876--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.codexTurnProvenance.test.ts@@ -0,0 +1,193 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ __resetOperationStatesForTesting,+ HeterogeneousPersistenceHandler,+} from '../HeterogeneousPersistenceHandler';++interface FakeMessage {+ agentId: string | null;+ content: string;+ id: string;+ metadata?: any;+ parentId?: string | null;+ role: 'user' | 'assistant' | 'tool' | 'task' | 'system';+ threadId?: string | null;+ tool_call_id?: string;+ topicId: string | null;+}++const createHarness = (params: {+ assistantMessageId: string;+ operationId: string;+ topicId: string;+}) => {+ let nextMsgIdSeq = 0;+ const messages = new Map<string, FakeMessage>([+ [+ params.assistantMessageId,+ {+ agentId: null,+ content: '',+ id: params.assistantMessageId,+ role: 'assistant',+ threadId: null,+ topicId: params.topicId,+ },+ ],+ ]);++ const messageModel = {+ create: vi.fn(async (input: Partial<FakeMessage>, id?: string) => {+ nextMsgIdSeq += 1;+ const msg = {+ agentId: input.agentId ?? null,+ content: input.content ?? '',+ id: id ?? `msg_${nextMsgIdSeq}`,+ metadata: input.metadata,+ parentId: input.parentId ?? null,+ role: input.role!,+ threadId: input.threadId ?? null,+ tool_call_id: input.tool_call_id,+ topicId: input.topicId ?? null,+ } as FakeMessage;+ messages.set(msg.id, msg);+ return msg;+ }),+ findById: vi.fn(async (id: string) => messages.get(id) ?? null),+ getLatestSpineMessageId: vi.fn(async () => undefined),+ listMessagePluginsByTopic: vi.fn(async () => []),+ query: vi.fn(async () => [...messages.values()]),+ update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {+ const existing = messages.get(id);+ if (!existing) return { success: false };+ messages.set(id, { ...existing, ...patch });+ return { success: true };+ }),+ updateToolMessage: vi.fn(async () => ({ success: true })),+ };++ const topicModel = {+ findById: vi.fn(async (id: string) =>+ id === params.topicId+ ? {+ agentId: null,+ id,+ metadata: {+ runningOperation: {+ assistantMessageId: params.assistantMessageId,+ operationId: params.operationId,+ },+ },+ }+ : null,+ ),+ updateMetadata: vi.fn(async () => {}),+ };++ const threadModel = {+ create: vi.fn(async () => {}),+ findById: vi.fn(async () => null),+ queryByTopicId: vi.fn(async () => []),+ update: vi.fn(async () => {}),+ };++ const handler = new HeterogeneousPersistenceHandler({+ messageModel: messageModel as any,+ threadModel: threadModel as any,+ topicModel: topicModel as any,+ });++ return { handler, messages, topicModel };+};++/** @example A native Codex turn is recorded on both rows of the exchange. */+describe('native Codex turn provenance', () => {+ beforeEach(() => __resetOperationStatesForTesting());+ afterEach(() => __resetOperationStatesForTesting());++ // ROOT CAUSE:+ // Device stream_start carried only the native session, so a device-run Codex message+ // had no turn boundary and no later operation could locate it in the native thread.+ /** @example The user prompt and its answer share the native turn before any text arrives. */+ it('stamps the native turn on the source user prompt and the assistant', async () => {+ const h = createHarness({+ assistantMessageId: 'answer',+ operationId: 'native-op',+ topicId: 'topic-1',+ });+ h.messages.set('prompt', {+ agentId: null,+ content: 'question',+ id: 'prompt',+ role: 'user',+ threadId: null,+ topicId: 'topic-1',+ });+ h.messages.get('answer')!.parentId = 'prompt';++ await h.handler.ingest({+ events: [+ {+ data: { codexTurnId: 'native-turn', sessionId: 'native-thread' },+ operationId: 'native-op',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_start',+ },+ ],+ operationId: 'native-op',+ topicId: 'topic-1',+ });++ /** @example The prompt can be located in the native thread after reload. */+ expect(h.messages.get('prompt')?.metadata).toEqual({+ codexTurnId: 'native-turn',+ heteroSessionId: 'native-thread',+ });+ /** @example The assistant carries the same boundary before it has content. */+ expect(h.messages.get('answer')?.metadata).toEqual({+ codexTurnId: 'native-turn',+ heteroSessionId: 'native-thread',+ });+ /** @example The topic resume binding is unchanged by the provenance write. */+ expect(h.topicModel.updateMetadata).toHaveBeenCalledWith('topic-1', {+ heteroSessionId: 'native-thread',+ });+ });++ /** @example A user row in another topic is never stamped with this run's turn. */+ it('does not stamp a parent row outside the run topic', async () => {+ const h = createHarness({+ assistantMessageId: 'answer',+ operationId: 'native-op',+ topicId: 'topic-1',+ });+ h.messages.set('foreign', {+ agentId: null,+ content: 'question',+ id: 'foreign',+ role: 'user',+ threadId: null,+ topicId: 'topic-2',+ });+ h.messages.get('answer')!.parentId = 'foreign';++ await h.handler.ingest({+ events: [+ {+ data: { codexTurnId: 'native-turn', sessionId: 'native-thread' },+ operationId: 'native-op',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_start',+ },+ ],+ operationId: 'native-op',+ topicId: 'topic-1',+ });++ expect(h.messages.get('foreign')?.metadata).toBeUndefined();+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/heteroProvenance.ts b/apps/server/src/services/heterogeneousAgent/heteroProvenance.tsnew file mode 100644index 00000000000..313b6780825--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/heteroProvenance.ts@@ -0,0 +1,94 @@+import type { MessageModel } from '@/database/models/message';++/** Native provenance an operation has learned so far. */+export interface HeteroProvenanceState {+ /** Native turn boundary shared by the user prompt and every assistant/tool step. */+ codexTurnId?: string;+ heteroSessionId?: string;+}++export interface HeteroProvenance {+ codexTurnId?: string;+ heteroMessageId?: string;+ heteroSessionId?: string;+}++/**+ * Per-message provenance stamped on every hetero-persisted row: the CC+ * session id the turn ran under (`heteroSessionId`) and, when known, the CC+ * `message.id` of the turn (`heteroMessageId`). A per-message copy lets a+ * diff pinpoint the exact row where CC forked to a new session / lost+ * `--resume` history β something the topic-level single `heteroSessionId`+ * can never show. Returns `{}` when neither is known, so callers can spread+ * it without minting empty metadata.+ */+export const heteroProvenance = (+ state: HeteroProvenanceState,+ heteroMessageId?: string,+): HeteroProvenance => {+ const out: HeteroProvenance = {};+ if (state.codexTurnId) out.codexTurnId = state.codexTurnId;+ if (state.heteroSessionId) out.heteroSessionId = state.heteroSessionId;+ if (heteroMessageId) out.heteroMessageId = heteroMessageId;+ return out;+};++/**+ * Recovers provenance from a previously-stamped message so a cold replica that+ * never saw this run's stream_start still stamps the right ids on the messages+ * it persists. Ids already known to this replica win.+ */+export const restoreHeteroProvenance = (+ state: HeteroProvenanceState,+ metadata: Record<string, any>,+): void => {+ if (!state.codexTurnId && typeof metadata.codexTurnId === 'string') {+ state.codexTurnId = metadata.codexTurnId;+ }+ if (!state.heteroSessionId && typeof metadata.heteroSessionId === 'string') {+ state.heteroSessionId = metadata.heteroSessionId;+ }+};++export interface CodexTurnProvenanceState extends HeteroProvenanceState {+ main: { currentAssistantId: string };+ /** User message answered by this operation, checked against its topic/thread before stamping. */+ sourceUserMessageId?: string;+ threadId: string | undefined;+ topicId: string;+}++/**+ * Stamps a native Codex turn on the assistant and the user prompt it answers.+ *+ * Use when:+ * - A `stream_start` carrying `codexTurnId` reaches the server persistence path.+ * Expects:+ * - `state.codexTurnId` is already set to the event's turn.+ * Returns:+ * - After both writes; throws on a failed write so the ingest retry reapplies it.+ *+ * Call stack:+ *+ * HeterogeneousPersistenceHandler.reduceAndApply+ * -> {@link persistCodexTurnProvenance}+ */+export const persistCodexTurnProvenance = async (+ messageModel: Pick<MessageModel, 'findById' | 'update'>,+ state: CodexTurnProvenanceState,+): Promise<void> => {+ const metadata = heteroProvenance(state);+ // Save provenance before any visible answer. An ingest retry must reapply a failed handoff.+ const assistantWrite = await messageModel.update(state.main.currentAssistantId, { metadata });+ if (!assistantWrite.success) throw new Error('Native assistant provenance could not be saved');+ if (!state.sourceUserMessageId) return;+ const user = await messageModel.findById(state.sourceUserMessageId);+ if (+ user?.role === 'user' &&+ user.topicId === state.topicId &&+ (user.threadId ?? undefined) === state.threadId+ ) {+ const userWrite = await messageModel.update(user.id, { metadata });+ if (!userWrite.success) throw new Error('Native user provenance could not be saved');+ }+};diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex dfae4f1a396..60bfdb4e6e1 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -317,6 +317,8 @@ export class GatewayHttpClient {assistantMessageId: string;/** Resolved `lh hetero exec` wrapper args. */args?: string[];+ /** Restricts the run to connections of these clients; omitted means any client. */+ clientKinds?: DeviceClient[];cwd?: string;deviceId?: string;/** Image attachments forwarded into the `agent_run_request` message. */diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex cfafb2a2ed2..8dd86e3e661 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -40,6 +40,10 @@ export interface DeviceSystemInfo {homePath: string;musicPath?: string;picturesPath?: string;+ /** Native agent protocol versions supported by this live connection; absent on older clients.+ * `codex-app-server-v1` runs `lh hetero exec --codex-app-server` with native turn provenance.+ */+ supportedAgentRuntimes?: string[];/** Opt-in tool identifiers supported by this client; absent on older clients. */supportedTools?: string[];userDataPath: string;diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex 6e0ab7beee0..db7c4a8689e 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -9,6 +9,7 @@"./builtinMcp": "./src/builtinMcp/index.ts","./errors": "./src/errors/index.ts","./client": "./src/client/index.ts",+ "./codexAppServerParams": "./src/codex/appServerParams.ts","./models": "./src/models/index.ts","./processFailure": "./src/spawn/classifyProcessFailure.ts","./protocol": "./src/protocol/index.ts",@@ -16,6 +17,7 @@"./quota-sampler": "./src/quota-sampler/index.ts","./resolveCliCommand": "./src/spawn/resolveCliCommand.ts","./rpc": "./src/rpc/index.ts",+ "./runtimeProbeCache": "./src/runtimeProbeCache.ts","./scanHost": "./src/scan/scanHost.ts","./spawn": "./src/spawn/index.ts","./transcript": "./src/transcript/index.ts",diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.test.tsindex 9a0debf9f91..2cbe4fd5740 100644--- a/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts@@ -29,6 +29,20 @@ const loadParityFixture = async () => {};describe('CodexAppServerAdapter', () => {+ it('carries the native turn boundary across tool-separated steps', async () => {+ const adapter = new CodexAppServerAdapter({ sessionId: 'native-thread' });+ const events = (await loadFixture()).flatMap(({ method, params }) =>+ adapter.adapt(method, params),+ );+ const starts = events.filter(({ type }) => type === 'stream_start');+ expect(starts.length).toBeGreaterThan(1);+ for (const start of starts) {+ expect(start.data).toMatchObject({+ codexTurnId: 'turn-1',+ sessionId: 'native-thread',+ });+ }+ });it('maps a native v2 turn directly into the existing stream contract', async () => {const adapter = new CodexAppServerAdapter({ initialModel: 'gpt-5.5-codex' });const raw = await loadFixture();diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.tsindex 710aa8a03ce..8b8eede94a5 100644--- a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.ts@@ -375,6 +375,8 @@ const classifyCodexError = (export class CodexAppServerAdapter {private currentAgentMessageItemId?: string;private currentModel?: string;+ private currentTurnId?: string;+ private readonly sessionId?: string;private hasTextInCurrentStep = false;private hasToolActivity = false;private lastCumulativeUsage?: UsageData;@@ -390,9 +392,12 @@ export class CodexAppServerAdapter {private stepIndex = 0;private terminal = false;- constructor(options: { initialCumulativeUsage?: UsageData; initialModel?: string } = {}) {+ constructor(+ options: { initialCumulativeUsage?: UsageData; initialModel?: string; sessionId?: string } = {},+ ) {this.currentModel = options.initialModel;this.lastCumulativeUsage = options.initialCumulativeUsage;+ this.sessionId = options.sessionId;}get cumulativeUsage(): UsageData | undefined {@@ -440,9 +445,18 @@ export class CodexAppServerAdapter {return this.handlePlanUpdated(rawParams as TurnPlanUpdatedNotification);}case 'thread/tokenUsage/updated': {- this.latestCumulativeUsage = toUsage(- (rawParams as ThreadTokenUsageUpdatedNotification).tokenUsage.total,- );+ const { tokenUsage } = rawParams as ThreadTokenUsageUpdatedNotification;+ const cumulativeUsage = toUsage(tokenUsage.total);+ if (!this.lastCumulativeUsage && !this.latestCumulativeUsage && tokenUsage.last) {+ // A resumed thread without saved cumulative usage (connected devices+ // have no local rollout to read) would otherwise report its whole+ // history as this turn. Reconstruct the baseline from the first request.+ this.lastCumulativeUsage = toTurnUsageFromCumulative(+ cumulativeUsage,+ toUsage(tokenUsage.last),+ );+ }+ this.latestCumulativeUsage = cumulativeUsage;return [];}case 'error': {@@ -466,10 +480,11 @@ export class CodexAppServerAdapter {return this.completeTurn('interrupted');}- private handleTurnStarted(_params: TurnStartedNotification): HeterogeneousAgentEvent[] {+ private handleTurnStarted(params: TurnStartedNotification): HeterogeneousAgentEvent[] {if (this.started) return [];this.started = true;- return [this.makeEvent('stream_start', this.streamStartData())];+ this.currentTurnId = params.turn.id;+ return [this.makeEvent('stream_start', this.streamStartData({ messageId: params.turn.id }))];}private handleItemStarted({ item }: ItemStartedNotification): HeterogeneousAgentEvent[] {@@ -801,8 +816,10 @@ export class CodexAppServerAdapter {private streamStartData(extra: Record<string, unknown> = {}): StreamStartData {return {+ ...(this.currentTurnId ? { codexTurnId: this.currentTurnId } : {}),...(this.currentModel ? { model: this.currentModel } : {}),provider: CODEX_IDENTIFIER,+ ...(this.sessionId ? { sessionId: this.sessionId } : {}),...extra,};}diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.tsindex 6a0b27e9297..3ad5ae859bb 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts@@ -171,7 +171,12 @@ const createClientHarness = (const createSession = (harness: ClientHarness,- options: { initialThreadId?: string; onEventsError?: Error; threadName?: string } = {},+ options: {+ ephemeral?: boolean;+ initialThreadId?: string;+ onEventsError?: Error;+ threadName?: string;+ } = {},) => {const events: any[] = [];const statuses: string[] = [];@@ -190,6 +195,7 @@ const createSession = (threadParams: {approvalPolicy: 'never',cwd: '/workspace',+ ...(options.ephemeral ? { ephemeral: true } : {}),sandbox: 'danger-full-access',},});@@ -372,6 +378,77 @@ describe('CodexThreadSession', () => {}});+ // ROOT CAUSE:+ // A connected device resumes a native thread without the rollout usage that Desktop+ // reads locally. Without a baseline, the first turn reported the thread's entire+ // cumulative usage as its own. Rebase from the first native total/last pair instead.+ /** @example A resumed device turn reports only its own native steps. */+ it('rebases usage on a resumed thread that has no saved cumulative usage', async () => {+ const harness = createClientHarness({ autoComplete: false, initialThreadId: 'thread-1' });+ const { events, session } = createSession(harness, { initialThreadId: 'thread-1' });+ const run = session.run({+ input: [{ text: 'continue', text_elements: [], type: 'text' }],+ operationId: 'resumed-usage',+ onRawMessage: vi.fn(),+ });+ await vi.waitFor(() => {+ /** @example Usage is observed only after the resumed turn starts. */+ expect(harness.requests.some((request) => request.method === 'turn/start')).toBe(true);+ });+ await harness.notify('turn/started', {+ threadId: 'thread-1',+ turn: turn('turn-1', 'inProgress'),+ });+ for (const [total, last] of [+ [350, 250],+ [370, 20],+ ]) {+ const usage = (tokens: number) => ({+ cachedInputTokens: 0,+ inputTokens: tokens,+ outputTokens: 0,+ reasoningOutputTokens: 0,+ totalTokens: tokens,+ });+ await harness.notify('thread/tokenUsage/updated', {+ threadId: 'thread-1',+ tokenUsage: { last: usage(last), total: usage(total) },+ turnId: 'turn-1',+ });+ }+ await harness.notify('turn/completed', {+ threadId: 'thread-1',+ turn: turn('turn-1', 'completed'),+ });+ await run;+ session.close();+ /** @example Both new steps count once; the 100 earlier thread tokens are excluded. */+ expect(events).toContainEqual(+ expect.objectContaining({+ data: expect.objectContaining({+ usage: expect.objectContaining({ totalInputTokens: 270 }),+ }),+ type: 'step_complete',+ }),+ );+ });++ // ROOT CAUSE:+ // stream_start carried the thread id as `sessionId` even for `--ephemeral` threads, so the+ // server saved it as the topic resume binding and the next turn resumed an ephemeral thread.+ /** @example An ephemeral native thread is never reported as a resumable session. */+ it('does not report an ephemeral thread as the stream session', async () => {+ const { events, onSessionId, run, session } = createSession(createClientHarness(), {+ ephemeral: true,+ });+ await run('ephemeral-op', 'hello');+ session.close();+ const streamStart = events.find((event) => event.type === 'stream_start');+ /** @example The turn still starts, without a session id the server would persist. */+ expect(streamStart?.data).not.toHaveProperty('sessionId');+ expect(onSessionId).not.toHaveBeenCalled();+ });+it('sets the original prompt as the name of a new persisted thread', async () => {const harness = createClientHarness();const { run, session } = createSession(harness, { threadName: 'Original prompt title' });diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.tsindex 318e411bb49..417ddc92142 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts@@ -142,6 +142,8 @@ export class CodexThreadSession {const adapter = new CodexAppServerAdapter({initialCumulativeUsage: this.cumulativeUsage,initialModel: this.model,+ // An ephemeral thread cannot be resumed, so it is never reported as the session.+ sessionId: this.options.threadParams.ephemeral ? undefined : threadId,});let resolveTurn!: () => void;const completion = new Promise<void>((resolve) => {diff --git a/packages/heterogeneous-agents/src/codex/codexAgentHandle.test.ts b/packages/heterogeneous-agents/src/codex/codexAgentHandle.test.tsnew file mode 100644index 00000000000..eaa62a32873--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/codexAgentHandle.test.ts@@ -0,0 +1,172 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createCodexAgentHandle } from './codexAgentHandle';+import type { CodexThreadSessionOptions, CodexThreadTurnOptions } from './CodexThreadSession';++const mocks = vi.hoisted(() => ({+ clientClose: vi.fn(),+ clientOptions: vi.fn(),+ interrupt: vi.fn(),+ options: [] as CodexThreadSessionOptions[],+ run: vi.fn<+ (options: CodexThreadTurnOptions, session: CodexThreadSessionOptions) => Promise<void>+ >(),+ sessionClose: vi.fn(),+}));+vi.mock('./CodexAppServerClient', () => ({+ CodexAppServerClient: class {+ constructor(options: object) {+ mocks.clientOptions(options);+ }+ close = mocks.clientClose;+ onStderr() {+ return () => {};+ }+ },+}));+vi.mock('./CodexThreadSession', () => ({+ CodexThreadSession: class {+ constructor(private readonly options: CodexThreadSessionOptions) {+ mocks.options.push(options);+ }+ close = mocks.sessionClose;+ interrupt = mocks.interrupt;+ run(options: CodexThreadTurnOptions) {+ return mocks.run(options, this.options);+ }+ },+}));++/** @example Native device turns use the same thread state machine as Desktop, with the normal CLI event handle. */+describe('createCodexAgentHandle', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.options.length = 0;+ mocks.run.mockResolvedValue();+ });+ const options = {+ args: [],+ clientVersion: '0.0.61',+ commandPath: 'codex',+ cwd: process.cwd(),+ env: { LOBEHUB_AGENT_ID: 'agent-device', LOBEHUB_TOPIC_ID: 'topic-device' },+ operationId: 'op-device',+ prompt: 'one prompt',+ };++ /** @example Native session and turn provenance reach the ingest loop unchanged. */+ it('resumes the native session and exposes its turn provenance', async () => {+ const event: AgentStreamEvent = {+ data: { sessionId: 'native-session', codexTurnId: 'native-turn' },+ operationId: 'op-device',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_start',+ };+ mocks.run.mockImplementation(async (_turn, session) => {+ session.onSessionId('native-session');+ await session.onEvents([event]);+ });+ const handle = await createCodexAgentHandle({ ...options, resumeSessionId: 'native-session' });+ // ROOT CAUSE:+ // The client appends app-server itself; passing that subcommand here launched it twice.+ /** @example The transport exclusively owns its app-server subcommand. */+ expect(mocks.clientOptions).toHaveBeenCalledWith(expect.objectContaining({ args: undefined }));+ /** @example Shell identity is pinned per operation and remains compatible with shared app-server provenance. */+ expect(mocks.options[0].threadParams.config).toMatchObject({+ 'shell_environment_policy.set.LOBEHUB_AGENT_ID': 'agent-device',+ 'shell_environment_policy.set.LOBEHUB_OPERATION_ID': 'op-device',+ 'shell_environment_policy.set.LOBEHUB_TOPIC_ID': 'topic-device',+ });+ const events: AgentStreamEvent[] = [];+ for await (const event of handle.events) events.push(event);+ /** @example The saved native session is resumed rather than replayed as text. */+ expect(mocks.options[0]).toMatchObject({ initialThreadId: 'native-session' });+ /** @example The session reported by the native thread is exposed on finish. */+ expect(handle.sessionId).toBe('native-session');+ /** @example The normal stream retains codexTurnId for message provenance. */+ expect(events).toEqual([event]);+ /** @example Successful native completion closes the per-operation process. */+ expect(await handle.exit).toEqual({ code: 0, signal: null });+ /** @example A completed device operation leaves no app-server process alive. */+ expect(mocks.clientClose).toHaveBeenCalledOnce();+ });++ /** @example An ordinary topic surfaces the raw Codex error so the CLI can retry fresh. */+ it('surfaces a missing ordinary session so the CLI can retry fresh', async () => {+ mocks.run.mockRejectedValue(+ new Error('thread/resume failed: no rollout found for thread id stale'),+ );+ const handle = await createCodexAgentHandle({ ...options, resumeSessionId: 'stale' });+ let stderr = '';+ handle.stderr.on('data', (chunk: Buffer) => {+ stderr += chunk.toString();+ });+ for await (const _event of handle.events) {+ /* Drain the actual async event contract. */+ }+ expect(await handle.exit).toEqual({ code: 1, signal: null });+ expect(stderr).toContain('no rollout found');+ });++ const interruptedEnd: AgentStreamEvent = {+ data: { reason: 'interrupted' },+ operationId: 'op-device',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ };++ // ROOT CAUSE:+ // A transport crash ends the native turn with an interrupted runtime end while run()+ // resolves, so the handle exited 0 and `lh hetero exec` finished a truncated run as success.+ /** @example A turn lost to transport failure exits as a failure, not a success. */+ it('fails a native turn interrupted by transport loss', async () => {+ mocks.run.mockImplementation(async (_turn, session) => {+ await session.onEvents([interruptedEnd]);+ });+ const handle = await createCodexAgentHandle(options);+ let stderr = '';+ handle.stderr.on('data', (chunk: Buffer) => {+ stderr += chunk.toString();+ });+ for await (const _event of handle.events) {+ /* Drain the actual async event contract. */+ }+ /** @example A nonzero exit makes the CLI report the operation as failed. */+ expect(await handle.exit).toEqual({ code: 1, signal: null });+ /** @example The failure detail explains the truncated turn. */+ expect(stderr).toContain('interrupted the turn');+ });++ /** @example A user Stop keeps its cancellation outcome even though the turn ends interrupted. */+ it('keeps a user Stop as cancellation', async () => {+ let releaseTurn!: () => void;+ const stopped = new Promise<void>((resolve) => {+ releaseTurn = resolve;+ });+ mocks.interrupt.mockImplementation(async () => releaseTurn());+ mocks.run.mockImplementation(async (_turn, session) => {+ await stopped;+ await session.onEvents([interruptedEnd]);+ });+ const handle = await createCodexAgentHandle(options);+ handle.kill('SIGINT');+ for await (const _event of handle.events) {+ /* Drain the actual async event contract. */+ }+ /** @example Stop is reported as a signal-driven cancellation, never as a failure. */+ expect(await handle.exit).toEqual({ code: null, signal: 'SIGINT' });+ });++ /** @example Unsupported approval policy is refused before executing any native request. */+ it('does not downgrade an unsupported native permission policy', async () => {+ /** @example The Full access-only base must reject Ask until its permission bridge is available. */+ await expect(+ createCodexAgentHandle({ ...options, args: ['--ask-for-approval', 'on-request'] }),+ ).rejects.toThrow('does not support');+ /** @example No session is created under weakened permissions. */+ expect(mocks.run).not.toHaveBeenCalled();+ });+});diff --git a/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts b/packages/heterogeneous-agents/src/codex/codexAgentHandle.tsnew file mode 100644index 00000000000..2fd21a7c1b6--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts@@ -0,0 +1,180 @@+import { PassThrough } from 'node:stream';++import type { AgentPromptInput } from '../protocol';+import { createEventQueue } from '../spawn/agentEventQueue';+import { buildAgentInput } from '../spawn/input';+import type { SpawnAgentHandle } from '../spawn/spawnAgent';+import {+ buildCodexAppServerInput,+ buildCodexAppServerThreadParams,+ getCodexAppServerUnsupportedArgs,+} from './appServerParams';+import { CodexAppServerClient } from './CodexAppServerClient';+import { CodexThreadSession } from './CodexThreadSession';++/** Native Codex execution inputs for a single connected-device operation. */+export interface CodexAgentHandleOptions {+ /** Existing provider arguments; unsupported policies are rejected, never weakened. */+ args: string[];+ /** Caller version sent in the native initialize handshake. */+ clientVersion: string;+ /** Resolved, validated Codex executable path. */+ commandPath: string;+ /** Working directory already authorized by device dispatch. */+ cwd: string;+ /** Environment inherited by the native process. */+ env: NodeJS.ProcessEnv;+ /** Raw native protocol trace callback. */+ onRawStdout?: (chunk: Buffer) => void;+ /** Registers cancellation before native startup begins. */+ onStartupControl?: (control: { cancel: (signal: NodeJS.Signals) => Promise<void> }) => void;+ /** Server operation receiving the normal event stream. */+ operationId: string;+ /** Current user input and attachments; native history is never reconstructed from text. */+ prompt: AgentPromptInput;+ /**+ * Native session to resume. A missing session fails this attempt; the caller decides+ * whether to retry fresh with its transcript fallback.+ */+ resumeSessionId?: string;+}++/**+ * Runs a native Codex turn through the CLI's normal ingest and cancellation loop.+ *+ * Use when:+ * - A connected device receives an explicitly native Codex operation.+ * Expects:+ * - Supported native arguments and, when resuming, a saved native session.+ * Returns:+ * - A spawn-compatible handle preserving native session and turn provenance.+ *+ * Call stack:+ *+ * lh hetero exec+ * -> {@link createCodexAgentHandle}+ * -> {@link CodexThreadSession.run}+ * -> {@link CodexAppServerClient.request}+ */+export const createCodexAgentHandle = async (+ options: CodexAgentHandleOptions,+): Promise<SpawnAgentHandle> => {+ const unsupported = getCodexAppServerUnsupportedArgs(options.args, {+ resume: Boolean(options.resumeSessionId),+ });+ if (unsupported.length > 0) {+ throw new Error(`Native Codex does not support these arguments: ${unsupported.join(', ')}`);+ }+ // Use the existing input materializer so local/remote attachments have the same semantics.+ const input = await buildAgentInput('codex', options.prompt);+ const events = createEventQueue();+ // stderr stays a stream because the CLI classifies startup failures from this channel.+ const stderr = new PassThrough();+ const client = new CodexAppServerClient({+ // CodexAppServerClient owns the app-server subcommand. Thread options belong in RPC params.+ args: undefined,+ clientVersion: options.clientVersion,+ commandPath: options.commandPath,+ cwd: options.cwd,+ env: options.env,+ });+ const stopStderr = client.onStderr((chunk) => {+ stderr.write(chunk);+ });+ let nativeSessionId: string | undefined;+ let cancelledSignal: NodeJS.Signals | undefined;+ // The session ends a turn lost to a transport crash with an interrupted runtime end and+ // resolves; without a Stop from this operation that is a truncated run, not a success.+ let nativeTurnInterrupted = false;+ const provenance = {+ LOBEHUB_AGENT_ID: options.env.LOBEHUB_AGENT_ID ?? '',+ LOBEHUB_OPERATION_ID: options.operationId,+ LOBEHUB_TOPIC_ID: options.env.LOBEHUB_TOPIC_ID ?? '',+ };+ const threadParams = buildCodexAppServerThreadParams(options.args, options.cwd);+ // Pin shell identity on native start/resume as well as the operation-owned process.+ // The same per-turn context is consumed by the shared app-server isolation contract.+ threadParams.config = {+ ...threadParams.config,+ 'shell_environment_policy.set.LOBEHUB_AGENT_ID': provenance.LOBEHUB_AGENT_ID,+ 'shell_environment_policy.set.LOBEHUB_OPERATION_ID': provenance.LOBEHUB_OPERATION_ID,+ 'shell_environment_policy.set.LOBEHUB_TOPIC_ID': provenance.LOBEHUB_TOPIC_ID,+ };+ const session = new CodexThreadSession({+ client,+ initialThreadId: options.resumeSessionId,+ onEvents: (batch) => {+ if (+ batch.some(+ (event) =>+ event.type === 'agent_runtime_end' &&+ (event.data as { reason?: unknown } | undefined)?.reason === 'interrupted',+ )+ ) {+ nativeTurnInterrupted = true;+ }+ events.push(batch);+ },+ onRuntimeStatus: () => {},+ onSessionId: (id) => {+ nativeSessionId = id;+ },+ sessionId: options.operationId,+ threadParams,+ });+ const cancel = async (signal: NodeJS.Signals) => {+ cancelledSignal = signal;+ if (signal === 'SIGINT') await session.interrupt();+ else {+ session.close();+ client.close();+ }+ };+ options.onStartupControl?.({ cancel });+ const turnOptions = {+ // Keep the already materialized user input and attachment paths unchanged.+ input: buildCodexAppServerInput(input),+ onRawMessage: (line: string) => options.onRawStdout?.(Buffer.from(line)),+ operationId: options.operationId,+ provenance,+ };+ // A Stop queued during input materialization must not start a new native turn.+ const execution = cancelledSignal ? Promise.resolve() : session.run(turnOptions);+ const exit = execution+ .then(+ () => {+ if (cancelledSignal) return { code: null, signal: cancelledSignal };+ if (!nativeTurnInterrupted) return { code: 0, signal: null };+ stderr.write('Codex app-server interrupted the turn before it completed\n');+ return { code: 1, signal: null };+ },+ (error: unknown) => {+ const detail = error instanceof Error ? error.message : String(error);+ stderr.write(`${detail}\n`);+ return { code: cancelledSignal ? null : 1, signal: cancelledSignal ?? null };+ },+ )+ .finally(() => {+ // Each CLI operation owns its app-server process; closing it leaves the native history on disk.+ session.close();+ client.close();+ stopStderr();+ events.close();+ stderr.end();+ });+ return {+ events,+ exit,+ kill: (signal = 'SIGINT') => {+ void cancel(signal).catch(() => {+ session.close();+ client.close();+ });+ },+ pid: undefined,+ get sessionId() {+ return nativeSessionId;+ },+ stderr,+ };+};diff --git a/packages/heterogeneous-agents/src/codex/codexAgentHandleCancellation.test.ts b/packages/heterogeneous-agents/src/codex/codexAgentHandleCancellation.test.tsnew file mode 100644index 00000000000..08c64eb6269--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/codexAgentHandleCancellation.test.ts@@ -0,0 +1,38 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createCodexAgentHandle } from './codexAgentHandle';+import { CodexAppServerClient } from './CodexAppServerClient';++/** @example A Stop received while materializing input must prevent native startup. */+describe('native device startup cancellation', () => {+ afterEach(() => vi.restoreAllMocks());++ /** @example A single queued SIGINT closes the real session without starting Codex. */+ it('does not start a native session when startup control delivers a queued Stop', async () => {+ // ROOT CAUSE:+ // Input materialization can finish after Stop. Registering startup control then+ // calls interrupt before run; the real idle session ignores that interrupt.+ // Starting run afterwards previously launched a turn despite the queued Stop.+ // Keep the real session state machine and intercept only the process boundary.+ const connect = vi+ .spyOn(CodexAppServerClient.prototype, 'connect')+ .mockRejectedValue(new Error('A cancelled operation must never connect'));+ const handle = await createCodexAgentHandle({+ args: [],+ clientVersion: '0.0.61',+ commandPath: 'codex',+ cwd: process.cwd(),+ env: {},+ onStartupControl: ({ cancel }) => {+ void cancel('SIGINT');+ },+ operationId: 'cancelled-device-operation',+ prompt: 'already materialized input',+ });+ const exit = await handle.exit;+ /** @example Cancellation is terminal without creating a native process. */+ expect(connect).not.toHaveBeenCalled();+ /** @example The ingest lifecycle receives the original cancellation signal. */+ expect(exit).toEqual({ code: null, signal: 'SIGINT' });+ });+});diff --git a/packages/heterogeneous-agents/src/codex/index.ts b/packages/heterogeneous-agents/src/codex/index.tsindex 12b48335842..3287e2d7e94 100644--- a/packages/heterogeneous-agents/src/codex/index.ts+++ b/packages/heterogeneous-agents/src/codex/index.ts@@ -4,6 +4,7 @@ export {buildCodexAppServerThreadParams,getCodexAppServerUnsupportedArgs,} from './appServerParams';+export { type CodexAgentHandleOptions, createCodexAgentHandle } from './codexAgentHandle';export {CodexAppServerClient,type CodexAppServerClientOptions,diff --git a/packages/heterogeneous-agents/src/runtimeProbeCache.test.ts b/packages/heterogeneous-agents/src/runtimeProbeCache.test.tsnew file mode 100644index 00000000000..6441e0ee52b--- /dev/null+++ b/packages/heterogeneous-agents/src/runtimeProbeCache.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it, vi } from 'vitest';++import { createRuntimeProbeCache } from './runtimeProbeCache';++describe('createRuntimeProbeCache', () => {+ /** @example Repeated system-info requests share one native probe. */+ it('probes once for concurrent and repeated reads', async () => {+ const probe = vi.fn().mockResolvedValue(['codex-app-server-v1']);+ const cache = createRuntimeProbeCache(probe);++ const [first, second] = await Promise.all([cache.get(), cache.get()]);+ const third = await cache.get();++ expect(first).toEqual(['codex-app-server-v1']);+ expect(second).toBe(first);+ expect(third).toBe(first);+ expect(probe).toHaveBeenCalledOnce();+ });++ /** @example A reconnect reprobes, so a downgraded binary revokes its capability. */+ it('reprobes after invalidation', async () => {+ const probe = vi.fn().mockResolvedValueOnce(['codex-app-server-v1']).mockResolvedValueOnce([]);+ const cache = createRuntimeProbeCache(probe);++ expect(await cache.get()).toEqual(['codex-app-server-v1']);+ cache.invalidate();+ expect(await cache.get()).toEqual([]);+ expect(probe).toHaveBeenCalledTimes(2);+ });++ /** @example An installed or upgraded binary is picked up after the entry expires. */+ it('reprobes after the entry expires', async () => {+ let time = 0;+ const probe = vi.fn().mockResolvedValueOnce([]).mockResolvedValueOnce(['codex-app-server-v1']);+ const cache = createRuntimeProbeCache(probe, { now: () => time, ttlMs: 1000 });++ expect(await cache.get()).toEqual([]);+ time = 999;+ expect(await cache.get()).toEqual([]);+ time = 1000;+ expect(await cache.get()).toEqual(['codex-app-server-v1']);+ });++ /** @example A failing probe reports no runtimes instead of rejecting system info. */+ it('treats a rejected probe as no supported runtimes', async () => {+ const cache = createRuntimeProbeCache(() => Promise.reject(new Error('spawn failed')));+ expect(await cache.get()).toEqual([]);+ });+});diff --git a/packages/heterogeneous-agents/src/runtimeProbeCache.ts b/packages/heterogeneous-agents/src/runtimeProbeCache.tsnew file mode 100644index 00000000000..1b0f0fc1c26--- /dev/null+++ b/packages/heterogeneous-agents/src/runtimeProbeCache.ts@@ -0,0 +1,46 @@+/** Default lifetime of a cached native runtime probe. */+export const RUNTIME_PROBE_TTL_MS = 10 * 60 * 1000;++export interface RuntimeProbeCache {+ /** Returns the cached probe, starting one when none is cached or the entry expired. */+ get: () => Promise<string[]>;+ /** Drops the cached probe; the next `get` probes again. */+ invalidate: () => void;+}++/**+ * Caches a device's native agent runtime probe for one connection.+ *+ * Use when:+ * - Answering gateway `system_info_request`s, which run tools and agent dispatch both+ * issue during ordinary runs. Each probe starts a native process, so it must not run+ * once per request.+ * Expects:+ * - `probe` resolves (never rejects) to the supported runtime identifiers.+ * - The owner calls `invalidate` when its gateway connection is (re-)established, so a+ * reconnect after an upgrade or downgrade reprobes.+ * Returns:+ * - A cache whose concurrent callers share one in-flight probe. Entries expire after+ * `ttlMs`, so a Codex install or upgrade is also picked up without reconnecting.+ */+export const createRuntimeProbeCache = (+ probe: () => Promise<string[]>,+ { now = Date.now, ttlMs = RUNTIME_PROBE_TTL_MS }: { now?: () => number; ttlMs?: number } = {},+): RuntimeProbeCache => {+ let entry: { startedAt: number; value: Promise<string[]> } | undefined;+ return {+ get: () => {+ if (!entry || now() - entry.startedAt >= ttlMs) {+ const current = {+ startedAt: now(),+ value: probe().catch(() => [] as string[]),+ };+ entry = current;+ }+ return entry.value;+ },+ invalidate: () => {+ entry = undefined;+ },+ };+};diff --git a/packages/heterogeneous-agents/src/spawn/agentEventQueue.ts b/packages/heterogeneous-agents/src/spawn/agentEventQueue.tsnew file mode 100644index 00000000000..e8d023abd2d--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/agentEventQueue.ts@@ -0,0 +1,51 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';++interface EventQueue {+ [Symbol.asyncIterator]: () => AsyncIterator<AgentStreamEvent>;+ close: () => void;+ push: (batch: AgentStreamEvent[]) => void;+}++/**+ * Bridges agent event batches to an ordered, buffered async iterator.+ *+ * Use when:+ * - A native RPC session pushes events into the CLI's pull-based ingest loop.+ *+ * NOTICE:+ * `rpc/piRpcAgentHandle.ts` keeps an identical private queue. Sharing this one is a+ * separate refactor so this change cannot alter the pi runtime.+ * Expects:+ * - Producers close the queue after their final event.+ * Returns:+ * - Every queued event in arrival order, followed by iterator completion.+ */+export const createEventQueue = (): EventQueue => {+ const items: AgentStreamEvent[] = [];+ const waiters: Array<() => void> = [];+ let closed = false;++ const notify = () => {+ for (const waiter of waiters.splice(0)) waiter();+ };++ return {+ push(batch) {+ items.push(...batch);+ notify();+ },+ close() {+ closed = true;+ notify();+ },+ async *[Symbol.asyncIterator]() {+ while (true) {+ while (items.length > 0) {+ yield items.shift()!;+ }+ if (closed) return;+ await new Promise<void>((resolve) => waiters.push(resolve));+ }+ },+ };+};diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 5eab6c108a8..a3710595e7e 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -16,12 +16,14 @@ export {buildCodexAppServerArgs,buildCodexAppServerInput,buildCodexAppServerThreadParams,+ type CodexAgentHandleOptions,CodexAppServerClient,type CodexAppServerClientOptions,CodexAppServerConnectionError,CodexAppServerRpcError,CodexThreadSession,type CodexThreadSessionOptions,+ createCodexAgentHandle,getCodexAppServerUnsupportedArgs,isCodexAppServerCompatibilityError,pickCodexRunProvenance,diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.tsindex 4c5ce820f88..36713b9ac95 100644--- a/packages/heterogeneous-agents/src/types.ts+++ b/packages/heterogeneous-agents/src/types.ts@@ -56,6 +56,8 @@ export interface HeterogeneousAgentEvent {/** Data shape for stream_start events */export interface StreamStartData {assistantMessage?: { id: string };+ /** Native Codex turn boundary, stable across tool-separated assistant steps. */+ codexTurnId?: string;/*** External-trigger context for the step opened by this stream_start.* Set when the new step was opened in response to a repeated tooldiff --git a/packages/types/src/message/common/metadata.test.ts b/packages/types/src/message/common/metadata.test.tsindex 9b77a894d3a..ccec3217140 100644--- a/packages/types/src/message/common/metadata.test.ts+++ b/packages/types/src/message/common/metadata.test.ts@@ -4,6 +4,14 @@ import { RequestTrigger } from '../../agentRuntime';import { MessageMetadataSchema } from './metadata';describe('MessageMetadataSchema', () => {+ it('preserves the native Codex turn separately from message item provenance', () => {+ const metadata = {+ codexTurnId: 'turn-7',+ heteroMessageId: 'item-3',+ heteroSessionId: 'native-thread',+ };+ expect(MessageMetadataSchema.parse(metadata)).toEqual(metadata);+ });it('preserves explicit internal agent-dispatch semantics', () => {const parsed = MessageMetadataSchema.parse({agentDispatch: { kind: 'callAgent', visibility: 'internal' },diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex 80d2a7b4eac..9fd1788e1c9 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -266,6 +266,7 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche// NOT strip them from writes going through UpdateMessageParamsSchema /// CreateMessageParamsSchema (the renderer executor's `messageService` path).heteroMessageId: z.string().optional(),+ codexTurnId: z.string().optional(),heteroSessionId: z.string().optional(),// Durable watermark for replace-only heterogeneous tool-state snapshots.// The pair is scoped by operation so a later run may restart seq at 1.@@ -364,6 +365,8 @@ export interface MessageMetadata {* Real platform author of a bot-channel user message; see `BotSenderMetadata`.*/botSender?: BotSenderMetadata;+ /** Native Codex turn, distinct from an assistant item inside that turn. */+ codexTurnId?: string;/*** Message collapse state* true: collapsed, false/undefined: expanded