π€― 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
π fix(hetero): give external agents the workspace, run context and bundled lh under any Codex shell policy (#21179)
Arvin Xua1c4b911eef6
diff --git a/apps/cli/src/auth/envJwt.test.ts b/apps/cli/src/auth/envJwt.test.tsnew file mode 100644index 00000000000..a745731ffa6--- /dev/null+++ b/apps/cli/src/auth/envJwt.test.ts@@ -0,0 +1,84 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { hydrateJwtFromFile, JWT_FILE_ENV } from './envJwt';++describe('hydrateJwtFromFile', () => {+ let dir: string;+ let jwtPath: string;++ beforeEach(async () => {+ dir = await mkdtemp(path.join(os.tmpdir(), 'lh-envjwt-'));+ jwtPath = path.join(dir, 'jwt');+ await writeFile(jwtPath, ' header.payload.sig\n', { mode: 0o600 });+ });++ afterEach(async () => {+ await rm(dir, { force: true, recursive: true });+ });++ it('reads and trims the token from LOBEHUB_JWT_FILE when LOBEHUB_JWT is unset', () => {+ const env: NodeJS.ProcessEnv = { [JWT_FILE_ENV]: jwtPath };+ hydrateJwtFromFile(env);+ expect(env.LOBEHUB_JWT).toBe('header.payload.sig');+ });++ it('prefers the file over an inherited token, which goes stale after renewal', () => {+ // Codex's default policy passes the original LOBEHUB_JWT alongside the file;+ // only the file is rewritten when the operation token renews.+ const env: NodeJS.ProcessEnv = { LOBEHUB_JWT: 'expired', [JWT_FILE_ENV]: jwtPath };+ hydrateJwtFromFile(env);+ expect(env.LOBEHUB_JWT).toBe('header.payload.sig');+ });++ it('keeps an inherited token when the file is missing or empty', async () => {+ const missing: NodeJS.ProcessEnv = { LOBEHUB_JWT: 'from-env', [JWT_FILE_ENV]: `${jwtPath}x` };+ hydrateJwtFromFile(missing);+ expect(missing.LOBEHUB_JWT).toBe('from-env');++ await writeFile(jwtPath, '\n');+ const empty: NodeJS.ProcessEnv = { LOBEHUB_JWT: 'from-env', [JWT_FILE_ENV]: jwtPath };+ hydrateJwtFromFile(empty);+ expect(empty.LOBEHUB_JWT).toBe('from-env');+ });++ it('treats an explicitly empty LOBEHUB_JWT as an opt-out of the file', () => {+ const env: NodeJS.ProcessEnv = { LOBEHUB_JWT: '', [JWT_FILE_ENV]: jwtPath };+ hydrateJwtFromFile(env);+ expect(env.LOBEHUB_JWT).toBe('');+ });++ it('behaves as unset when the file is missing, empty, or the path is blank', async () => {+ const missing: NodeJS.ProcessEnv = { [JWT_FILE_ENV]: path.join(dir, 'nope') };+ hydrateJwtFromFile(missing);+ expect(missing.LOBEHUB_JWT).toBeUndefined();++ await writeFile(jwtPath, '\n');+ const empty: NodeJS.ProcessEnv = { [JWT_FILE_ENV]: jwtPath };+ hydrateJwtFromFile(empty);+ expect(empty.LOBEHUB_JWT).toBeUndefined();++ const blank: NodeJS.ProcessEnv = { [JWT_FILE_ENV]: ' ' };+ hydrateJwtFromFile(blank);+ expect(blank.LOBEHUB_JWT).toBeUndefined();+ });++ it('makes the file token the winning auth source', async () => {+ const saved = { file: process.env[JWT_FILE_ENV], jwt: process.env.LOBEHUB_JWT };+ delete process.env.LOBEHUB_JWT;+ process.env[JWT_FILE_ENV] = jwtPath;+ try {+ hydrateJwtFromFile();+ const { pickAuthSource } = await import('./source');+ expect(pickAuthSource()).toMatchObject({ kind: 'env-jwt', token: 'header.payload.sig' });+ } finally {+ if (saved.jwt === undefined) delete process.env.LOBEHUB_JWT;+ else process.env.LOBEHUB_JWT = saved.jwt;+ if (saved.file === undefined) delete process.env[JWT_FILE_ENV];+ else process.env[JWT_FILE_ENV] = saved.file;+ }+ });+});diff --git a/apps/cli/src/auth/envJwt.ts b/apps/cli/src/auth/envJwt.tsnew file mode 100644index 00000000000..2072f2f12fa--- /dev/null+++ b/apps/cli/src/auth/envJwt.ts@@ -0,0 +1,38 @@+import { readFileSync } from 'node:fs';++/**+ * Path of a file holding the run's JWT. Codex runs its shell commands with an+ * env built from the user's `[shell_environment_policy]`, which can drop+ * `LOBEHUB_JWT` (`inherit = "core"`). `spawnAgent` therefore hands Codex's+ * shell this path (a per-run 0600 file) instead of the token itself, which+ * would be visible in Codex's argv.+ */+export const JWT_FILE_ENV = 'LOBEHUB_JWT_FILE';++/**+ * Fill `LOBEHUB_JWT` from `LOBEHUB_JWT_FILE` once at startup, so every reader of+ * `LOBEHUB_JWT` (auth source, tRPC/HTTP clients, workspace scope, doctor) sees+ * the same credential.+ *+ * - A readable, non-empty file wins over an inherited non-empty `LOBEHUB_JWT`.+ * Under Codex's default `inherit = "all"` the shell gets both, and only the+ * file is rewritten when the operation token renews, so the env copy goes+ * stale.+ * - A `LOBEHUB_JWT` that is defined but empty (`LOBEHUB_JWT= lh β¦`) is an+ * explicit opt-out: the file is ignored, so the agent's "clear LOBEHUB_JWT+ * and retry with the machine's login" fallback keeps working.+ * - A missing, unreadable or empty file behaves as if no file were configured.+ */+export const hydrateJwtFromFile = (env: NodeJS.ProcessEnv = process.env): void => {+ if (env.LOBEHUB_JWT === '') return;++ const filePath = env[JWT_FILE_ENV]?.trim();+ if (!filePath) return;++ try {+ const token = readFileSync(filePath, 'utf8').trim();+ if (token) env.LOBEHUB_JWT = token;+ } catch {+ // Missing or unreadable: fall through to the other credential sources.+ }+};diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex 0b865cbef58..b972073fc88 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -67,6 +67,21 @@ describe('spawnHeteroAgentRun', () => {vi.unstubAllEnvs();});+ it('does not hand the dispatched run an ancestor agent run identity or JWT file', () => {+ // `lh connect` running inside a Codex shell: the CLI prefers LOBEHUB_JWT_FILE over+ // LOBEHUB_JWT, so an inherited file would replace this dispatch's fresh token.+ vi.stubEnv('LOBEHUB_JWT_FILE', '/tmp/ancestor/jwt');+ vi.stubEnv('LOBEHUB_TASK_ID', 'ancestor-task');+ spawnMock.mockReturnValue(makeFakeChild());++ void spawnHeteroAgentRun({ ...baseParams, jwt: 'fresh-token' });++ const { env } = spawnMock.mock.calls[0][2];+ expect(env.LOBEHUB_JWT).toBe('fresh-token');+ expect(env).not.toHaveProperty('LOBEHUB_JWT_FILE');+ expect(env).not.toHaveProperty('LOBEHUB_TASK_ID');+ });+it('spawns `lh hetero exec` in server-ingest mode via the current CLI entry', async () => {const child = makeFakeChild();spawnMock.mockReturnValue(child);diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex acaa97ec439..1e796d405b8 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -4,6 +4,7 @@ import {buildHeteroExecStdinPayload,HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,type HeteroExecImageRef,+ stripInheritedRunIdentity,} from '@lobechat/heterogeneous-agents/protocol';import { resolveHeteroSpawnCwd } from '@lobechat/heterogeneous-agents/workingDirectory';@@ -118,17 +119,8 @@ export function spawnHeteroAgentRun(});// A connector can itself be started inside another agent run. Its ambient- // identity belongs to the launcher, not this dispatched conversation; CLI- // evidence commands must never attach this run's outputs to that ancestor.- const childEnv = { ...process.env };- for (const key of [- 'LOBEHUB_AGENT_ID',- 'LOBEHUB_ASSISTANT_MESSAGE_ID',- 'LOBEHUB_TASK_ID',- 'LOBEHUB_WORKSPACE_ID',- ]) {- delete childEnv[key];- }+ // identity (and JWT file) belongs to that ancestor, not this dispatched run.+ const childEnv = stripInheritedRunIdentity(process.env);return new Promise<AgentRunAckResult>((resolve) => {let settled = false;diff --git a/apps/cli/src/doctor/checks/credentials.ts b/apps/cli/src/doctor/checks/credentials.tsindex 3057a0b4af2..ae6ccafae5a 100644--- a/apps/cli/src/doctor/checks/credentials.ts+++ b/apps/cli/src/doctor/checks/credentials.ts@@ -36,7 +36,7 @@ const credentialSource: DoctorCheck = {return {detail: `Authenticating with the LOBEHUB_JWT in this environment (${maskSecret(source.token)}), not with the stored login.`,evidence,- fix: 'Expected? This is how server-dispatched runs authenticate. If not, unset LOBEHUB_JWT.',+ fix: 'Expected? This is how server-dispatched runs authenticate. If not, unset LOBEHUB_JWT and LOBEHUB_JWT_FILE.',status: 'warn',};diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.tsindex a1453d4ea31..de8a1b3e6e6 100644--- a/apps/cli/src/index.ts+++ b/apps/cli/src/index.ts@@ -1,8 +1,11 @@+import { hydrateJwtFromFile } from './auth/envJwt';import { reportDaemonStartupError } from './daemon/manager';import { createProgram } from './program';import { formatError } from './utils/error';import { log } from './utils/logger';+hydrateJwtFromFile();+void createProgram().parseAsync(process.argv, { from: 'node' }).catch(async (error: unknown) => {diff --git a/apps/cli/src/utils/OperationTokenRenewal.test.ts b/apps/cli/src/utils/OperationTokenRenewal.test.tsindex 671dec55858..117b2f4b0f8 100644--- a/apps/cli/src/utils/OperationTokenRenewal.test.ts+++ b/apps/cli/src/utils/OperationTokenRenewal.test.ts@@ -1,3 +1,6 @@+import { readFile } from 'node:fs/promises';++import { createCodexJwtFile } from '@lobechat/heterogeneous-agents/spawn';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createOperationTokenRenewal } from './OperationTokenRenewal';@@ -57,6 +60,24 @@ describe('createOperationTokenRenewal', () => {renewal.stop();});+ it('hands the renewed token to a running Codex agent through its JWT file', async () => {+ process.env.LOBEHUB_JWT = operationToken(NOW + 4 * HOUR);+ const next = operationToken(NOW + 7 * HOUR);+ const jwtFile = await createCodexJwtFile(process.env.LOBEHUB_JWT);+ const renew = vi.fn().mockResolvedValueOnce({ jwt: next });++ const renewal = createOperationTokenRenewal({ operationId: 'op-1', renew });+ try {+ await vi.advanceTimersByTimeAsync(3 * HOUR);+ expect(renew).toHaveBeenCalledWith('op-1');+ // The rewrite is real file I/O that fake timers do not settle.+ await vi.waitFor(async () => expect(await readFile(jwtFile.path, 'utf8')).toBe(next));+ } finally {+ renewal.stop();+ await jwtFile.cleanup();+ }+ });+it('retries a transient failure instead of letting the token lapse', async () => {process.env.LOBEHUB_JWT = operationToken(NOW + 4 * HOUR);const next = operationToken(NOW + 8 * HOUR);@@ -90,7 +111,9 @@ describe('createOperationTokenRenewal', () => {it('does not poll a server that has no renewal endpoint', async () => {process.env.LOBEHUB_JWT = operationToken(NOW + 4 * HOUR);- const renew = vi.fn().mockRejectedValue({ data: { code: 'NOT_FOUND' }, message: 'No procedure' });+ const renew = vi+ .fn()+ .mockRejectedValue({ data: { code: 'NOT_FOUND' }, message: 'No procedure' });const renewal = createOperationTokenRenewal({ operationId: 'op-1', renew });await vi.advanceTimersByTimeAsync(3 * HOUR);diff --git a/apps/cli/src/utils/OperationTokenRenewal.ts b/apps/cli/src/utils/OperationTokenRenewal.tsindex 35c3938c1e5..66542f13d33 100644--- a/apps/cli/src/utils/OperationTokenRenewal.ts+++ b/apps/cli/src/utils/OperationTokenRenewal.ts@@ -1,3 +1,5 @@+import { refreshCodexJwtFiles } from '@lobechat/heterogeneous-agents/spawn';+import { log } from './logger';/** Renew this long before expiry, so a slow or failed attempt still has room to retry. */@@ -35,7 +37,8 @@ const readOperationTokenExpiry = (jwt: string): number | undefined => {* it expires every ingest is rejected β heartbeats included β so the lease stops* renewing and the server reclaims the operation as abandoned while the agent is* still working. Renewing writes the new token back to `LOBEHUB_JWT`, which the- * tRPC clients read on every request.+ * tRPC clients read on every request, and into any Codex JWT file the agent's+ * nested `lh` commands read.** Only a `hetero-operation` token is renewed. A desktop run authenticates with* its own session token, which has its own refresh flow.@@ -66,6 +69,8 @@ export const createOperationTokenRenewal = ({const { jwt } = await renew(operationId);if (stopped) return;process.env.LOBEHUB_JWT = jwt;+ // A Codex agent's shell reads the token from a file, not this env.+ await refreshCodexJwtFiles(jwt);scheduleFromCurrentToken();} catch (error) {const code = (error as { data?: { code?: string } } | null)?.data?.code;diff --git a/apps/desktop/src/main/controllers/CliCtr.ts b/apps/desktop/src/main/controllers/CliCtr.tsindex 7d0727c5cdd..985725099d9 100644--- a/apps/desktop/src/main/controllers/CliCtr.ts+++ b/apps/desktop/src/main/controllers/CliCtr.ts@@ -49,6 +49,9 @@ export default class CliCtr extends ControllerModule {if (token && serverUrl) {env.LOBEHUB_JWT = token;+ // Callers layer this over process.env, so blank (not delete) an inherited+ // agent-run JWT file pointer: the CLI would prefer it over this token.+ env.LOBEHUB_JWT_FILE = '';env.LOBEHUB_SERVER = normalizeServerUrl(serverUrl);logger.debug('Injected LOBEHUB_JWT / LOBEHUB_SERVER for CLI command');}diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 1a90e1880b3..0155a15cb51 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -11,6 +11,7 @@ import {import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';import type { HeterogeneousAgentCancellationSignal } from '@lobechat/heterogeneous-agents/protocol';+import { stripInheritedRunIdentity } from '@lobechat/heterogeneous-agents/protocol';import type { RemotePlatformCommandRuntime } from '@lobechat/heterogeneous-agents/scanHost';import {resolveRemotePlatformCommand,@@ -20,6 +21,7 @@ import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechatimport { managedProcessEnvironment, spawnManaged } from '@lobechat/utils/managedProcess';import { app as electronApp } from 'electron';+import { withEmbeddedCliEnv } from '@/modules/cliEmbedding';import { updaterConfig } from '@/modules/updater/configs';import { createRemoteAppUpdateDeps } from '@/modules/updater/remoteUpdate';import AuvService, { type AuvRunCommandParams } from '@/services/auvSrv';@@ -862,23 +864,14 @@ export default class GatewayConnectionCtr extends ControllerModule {this.remoteServerConfigCtr.getAccessToken(),]);- // Never inherit the launcher's conversation identity for a dispatched run.- const inheritedEnv = { ...process.env };- for (const key of [- 'LOBEHUB_AGENT_ID',- 'LOBEHUB_ASSISTANT_MESSAGE_ID',- 'LOBEHUB_TASK_ID',- 'LOBEHUB_WORKSPACE_ID',- ]) {- delete inheritedEnv[key];- }+ // Never inherit the launcher's run identity (or JWT file) for a dispatched run.+ const inheritedEnv = stripInheritedRunIdentity(process.env);- // Inject auth + workspace scope into child env so `lh notify` can- // authenticate AND target the same workspace as the dispatched topic- // (without LOBEHUB_WORKSPACE_ID, the CLI's notify falls back to personal- // mode and the workspace topic 404s).+ // Inject auth + workspace scope so `lh notify` authenticates AND targets the+ // dispatched topic's workspace (without it, the CLI falls back to personal+ // mode and the workspace topic 404s), plus the bundled `lh` ahead of PATH.const childEnv: NodeJS.ProcessEnv = {- ...inheritedEnv,+ ...withEmbeddedCliEnv(inheritedEnv),...(agentId && { LOBEHUB_AGENT_ID: agentId }),...(accessToken && { LOBEHUB_JWT: accessToken }),LOBEHUB_OPERATION_ID: operationId,diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 4bf9cff01e7..48fd92c03d5 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -48,6 +48,7 @@ import {buildHeteroExecStdinPayload,buildHeterogeneousPrompt,HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,+ stripInheritedRunIdentity,} from '@lobechat/heterogeneous-agents/protocol';import {CLAUDE_CODE_QUOTA_FRESH_MS,@@ -130,8 +131,8 @@ import semver from 'semver';import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';import type { App } from '@/core/App';import { detectHeterogeneousCliCommand } from '@/modules/binaries';-import { resolveCliScript } from '@/modules/cliEmbedding';-import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';+import { resolveCliScript, withEmbeddedCliEnv } from '@/modules/cliEmbedding';+import { getHeterogeneousAgentDriver, withCodexContextArgs } from '@/modules/heterogeneousAgent';import {consumeCodexRateLimitResetCredit as consumeCodexRateLimitResetCreditRequest,fetchCodexQuota,@@ -199,14 +200,14 @@ const STRIPPED_INHERITED_ENV_KEYS = [] as const;/**- * Inherited `process.env` with the Anthropic auth vars removed. Keep this pure- * and exported so the "never leak host Anthropic creds into the CLI" invariant- * can be unit-tested directly.+ * Inherited `process.env` without the Anthropic auth vars or an ancestor agent run's+ * identity (a Desktop launched from an agent shell carries its JWT file, which the CLI+ * prefers over any token). Pure and exported so the invariant is unit-tested directly.*/export const buildInheritedSpawnEnv = (sourceEnv: NodeJS.ProcessEnv = process.env,): NodeJS.ProcessEnv => {- const env = { ...sourceEnv };+ const env = stripInheritedRunIdentity(sourceEnv);for (const key of STRIPPED_INHERITED_ENV_KEYS) delete env[key];return env;};@@ -1074,7 +1075,7 @@ export default class HeterogeneousAgentCtr {// shim finds its interpreter. `session.env` still wins if it sets PATH.if (session.resolvedCommandSearchPath) inheritedEnv.PATH = session.resolvedCommandSearchPath;const env: NodeJS.ProcessEnv = {- ...inheritedEnv,+ ...withEmbeddedCliEnv(inheritedEnv),...proxyEnv,...(session.agentType === 'codebuddy'? { CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS: '1' }@@ -1619,7 +1620,7 @@ export default class HeterogeneousAgentCtr {this.sessions.set(sessionId, {agentSessionId: resumeSessionId,agentType,- args: hostedProviderBinding?.args ?? params.args ?? [],+ args: withCodexContextArgs(agentType, params.env, hostedProviderBinding?.args ?? params.args),command: params.command,cwd: params.cwd,env: hostedProviderBinding?.env ?? params.env,@@ -4172,19 +4173,11 @@ export default class HeterogeneousAgentCtr {});}- // Never inherit the launcher's conversation identity for a dispatched run.- const childEnv = { ...process.env };- for (const key of [- 'LOBEHUB_AGENT_ID',- 'LOBEHUB_ASSISTANT_MESSAGE_ID',- 'LOBEHUB_TASK_ID',- 'LOBEHUB_WORKSPACE_ID',- ]) {- delete childEnv[key];- }+ // Never inherit the launcher's run identity (or JWT file) for a dispatched run.+ const childEnv = stripInheritedRunIdentity(process.env);const env = {- ...childEnv,+ ...withEmbeddedCliEnv(childEnv),...buildProxyEnv(this.app.storeManager.get('networkProxy')),ELECTRON_RUN_AS_NODE: '1',[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',diff --git a/apps/desktop/src/main/controllers/__tests__/CliCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/CliCtr.test.tsindex 4e714154e0e..d26925e4c64 100644--- a/apps/desktop/src/main/controllers/__tests__/CliCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/CliCtr.test.ts@@ -11,6 +11,13 @@ vi.mock('electron', () => ({ipcMain: { handle: vi.fn() },}));+const { execMock } = vi.hoisted(() => ({+ execMock: vi.fn((_cmd: string, _opts: unknown, callback: (...args: unknown[]) => void) =>+ callback(null, { stderr: '', stdout: 'ok' }),+ ),+}));+vi.mock('node:child_process', () => ({ exec: execMock }));+vi.mock('@/modules/cliEmbedding', () => ({getCliWrapperDir: () => '/app/userData/bin',}));@@ -57,7 +64,9 @@ describe('CliCtr.buildCliEnv', () => {const env = await ctr.buildCliEnv();- expect(env.PATH).toBe(`/app/userData/bin${path.delimiter}/usr/local/bin${path.delimiter}/usr/bin`);+ expect(env.PATH).toBe(+ `/app/userData/bin${path.delimiter}/usr/local/bin${path.delimiter}/usr/bin`,+ );});it('prepends to a PATH the caller overrode instead of discarding it', async () => {@@ -76,3 +85,23 @@ describe('CliCtr.buildCliEnv', () => {expect(env).not.toHaveProperty('LOBEHUB_SERVER');});});++describe('CliCtr.runCliCommand', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('does not let an inherited agent-run JWT file outrank the app token', async () => {+ // Desktop launched from a Codex shell inherits LOBEHUB_JWT_FILE; the CLI prefers the+ // file, so it must not survive the merge with process.env.+ vi.stubEnv('LOBEHUB_JWT_FILE', '/tmp/ancestor/jwt');+ mockRemoteCtr.getAccessToken.mockResolvedValue('jwt-token');+ mockRemoteCtr.getRemoteServerUrl.mockResolvedValue('https://app.example.com/');++ await new CliCtr(mockApp).runCliCommand('whoami');++ const { env } = execMock.mock.calls[0][1] as { env: NodeJS.ProcessEnv };+ expect(env.LOBEHUB_JWT).toBe('jwt-token');+ expect(env.LOBEHUB_JWT_FILE).toBe('');+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex e24cae3c624..73027938543 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -1860,8 +1860,8 @@ describe('HeterogeneousAgentCtr', () => {expect(options.env).not.toHaveProperty('ANTHROPIC_API_KEY');expect(options.env).not.toHaveProperty('ANTHROPIC_AUTH_TOKEN');expect(options.env).not.toHaveProperty('ANTHROPIC_BASE_URL');- // Unrelated inherited vars must still pass through.- expect(options.env.PATH).toBe(process.env.PATH);+ // Unrelated inherited vars pass through, behind the bundled CLI's dir.+ expect(options.env.PATH).toBe(`/fake/userData/bin${path.delimiter}${process.env.PATH}`);} finally {for (const [key, value] of Object.entries(original)) {if (value === undefined) delete process.env[key];@@ -3434,9 +3434,7 @@ describe('HeterogeneousAgentCtr', () => {});it('carries the detector login-shell PATH into the spawn env for `env node` shims', async () => {- // `codex` resolved via the login-shell PATH (mise/nvm). Spawning the- // absolute shim under the leaner inherited PATH would fail at its- // `#!/usr/bin/env node` shebang β the resolved PATH must reach the child.+ // A login-shell-resolved shim needs that PATH for its `#!/usr/bin/env node` shebang.const resolvedPath = '/Users/h/.local/share/mise/shims/codex';const searchPath = '/Users/h/.local/share/mise/shims:/usr/bin:/bin';const detect = vi@@ -3454,7 +3452,9 @@ describe('HeterogeneousAgentCtr', () => {await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId });expect(spawnCalls[0].command).toBe(resolvedPath);- expect(spawnCalls[0].options.env.PATH).toBe(searchPath);+ expect(spawnCalls[0].options.env.PATH).toBe(+ `/fake/userData/bin${path.delimiter}${searchPath}`,+ );});it('keeps an explicit path-like command for spawn instead of the detector result', async () => {diff --git a/apps/desktop/src/main/controllers/__tests__/buildInheritedSpawnEnv.test.ts b/apps/desktop/src/main/controllers/__tests__/buildInheritedSpawnEnv.test.tsnew file mode 100644index 00000000000..9a92389da3e--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/buildInheritedSpawnEnv.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import { buildInheritedSpawnEnv } from '../HeterogeneousAgentImpl';++describe('buildInheritedSpawnEnv', () => {+ it('drops host Anthropic creds and an ancestor agent run identity', () => {+ // A Desktop launched from a Codex shell inherits that run's JWT file; every agent it+ // spawns (and the shared Codex app-server) would hand nested `lh` the ancestor token.+ const env = buildInheritedSpawnEnv({+ ANTHROPIC_API_KEY: 'host-key',+ HOME: '/home/u',+ LOBEHUB_JWT_FILE: '/tmp/ancestor/jwt',+ LOBEHUB_TASK_ID: 'ancestor-task',+ PATH: '/usr/bin',+ });++ expect(env).toEqual({ HOME: '/home/u', PATH: '/usr/bin' });+ });+});diff --git a/apps/desktop/src/main/modules/cliEmbedding/embeddedCliEnv.test.ts b/apps/desktop/src/main/modules/cliEmbedding/embeddedCliEnv.test.tsnew file mode 100644index 00000000000..78d7e71374a--- /dev/null+++ b/apps/desktop/src/main/modules/cliEmbedding/embeddedCliEnv.test.ts@@ -0,0 +1,63 @@+import path from 'node:path';++import { describe, expect, it, vi } from 'vitest';++import { withEmbeddedCliEnv } from './embeddedCliEnv';++vi.mock('electron', () => ({ app: { getPath: () => '/userData' } }));++const wrapperDir = path.join('/userData', 'bin');+const pathOf = (...dirs: string[]) => dirs.join(path.delimiter);++describe('withEmbeddedCliEnv', () => {+ it('puts the bundled CLI ahead of an older global lh', () => {+ // The app appends its wrapper dir, so a pnpm-global `lh` without `goal` won.+ const env = withEmbeddedCliEnv({ PATH: pathOf('/pnpm', '/usr/bin', wrapperDir) });++ expect(env.PATH).toBe(pathOf(wrapperDir, '/pnpm', '/usr/bin'));+ });++ it('names the bundled wrapper for shells whose profile reorders PATH', () => {+ const env = withEmbeddedCliEnv({ HOME: '/home/u', PATH: '/usr/bin' });++ expect(env.LOBEHUB_CLI).toBe(+ path.join(wrapperDir, process.platform === 'win32' ? 'lh.cmd' : 'lh'),+ );+ expect(env.HOME).toBe('/home/u');+ });++ it('works when the env carries no PATH', () => {+ expect(withEmbeddedCliEnv({}).PATH).toBe(wrapperDir);+ });++ it('prefixes the Windows `Path` key instead of adding a wrapper-only PATH', () => {+ // process.env spells it `Path` on Windows; a second `PATH` holding only the+ // wrapper dir made the child drop System32 and every inherited directory.+ const env = withEmbeddedCliEnv(+ { Path: 'C:\\Windows\\System32;C:\\Git\\cmd' },+ 'C:\\lh\\bin',+ 'win32',+ );++ expect(env.Path).toBe('C:\\lh\\bin;C:\\Windows\\System32;C:\\Git\\cmd');+ expect(env).not.toHaveProperty('PATH');+ });++ it('on Windows, prefers an explicit PATH and drops other spellings', () => {+ const env = withEmbeddedCliEnv(+ { PATH: 'C:\\login\\bin', Path: 'C:\\Windows' },+ 'C:\\lh\\bin',+ 'win32',+ );++ expect(env.PATH).toBe('C:\\lh\\bin;C:\\login\\bin');+ expect(env).not.toHaveProperty('Path');+ });++ it('keeps differently-cased names apart on case-sensitive platforms', () => {+ const env = withEmbeddedCliEnv({ PATH: '/usr/bin', Path: 'other' }, '/lh/bin', 'darwin');++ expect(env.PATH).toBe('/lh/bin:/usr/bin');+ expect(env.Path).toBe('other');+ });+});diff --git a/apps/desktop/src/main/modules/cliEmbedding/embeddedCliEnv.ts b/apps/desktop/src/main/modules/cliEmbedding/embeddedCliEnv.tsnew file mode 100644index 00000000000..ed477175020--- /dev/null+++ b/apps/desktop/src/main/modules/cliEmbedding/embeddedCliEnv.ts@@ -0,0 +1,51 @@+import path from 'node:path';++import { getCliWrapperDir } from './generateCliWrapper';++/**+ * Absolute path of the `lh` this desktop build ships, for an agent whose shell+ * resolves an older global install first. Login shells (`zsh -lc`, which Codex+ * uses) re-run the user's profile and can move a pnpm/npm bin dir back in front+ * of the PATH entry below, so the path alone is the reliable handle.+ */+export const LOBEHUB_CLI_ENV = 'LOBEHUB_CLI';++const CLI_WRAPPER_NAME = process.platform === 'win32' ? 'lh.cmd' : 'lh';++export const getEmbeddedCliPath = (wrapperDir: string = getCliWrapperDir()): string =>+ path.join(wrapperDir, CLI_WRAPPER_NAME);++/**+ * The env key holding the search path. Windows env names are case-insensitive and+ * `process.env` usually spells it `Path`, which a plain-object copy keeps; writing+ * `PATH` beside it would make the child keep only one of the two. An explicit+ * `PATH` (e.g. a resolved login-shell PATH set by the caller) wins.+ */+const findPathKey = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform): string => {+ if (platform !== 'win32' || 'PATH' in env) return 'PATH';+ return Object.keys(env).find((key) => key.toUpperCase() === 'PATH') ?? 'PATH';+};++/**+ * Spawn env for an external agent: the bundled CLI's wrapper dir goes to the+ * front of PATH (the app only appends it, so a stale global `lh` wins) and+ * `LOBEHUB_CLI` names the wrapper itself.+ */+export const withEmbeddedCliEnv = (+ env: NodeJS.ProcessEnv,+ wrapperDir: string = getCliWrapperDir(),+ platform: NodeJS.Platform = process.platform,+): NodeJS.ProcessEnv => {+ const delimiter = platform === 'win32' ? ';' : ':';+ const pathKey = findPathKey(env, platform);+ const rest = (env[pathKey] ?? '').split(delimiter).filter((dir) => dir && dir !== wrapperDir);+ const next: NodeJS.ProcessEnv = { ...env, [LOBEHUB_CLI_ENV]: getEmbeddedCliPath(wrapperDir) };+ // Drop other spellings so the child cannot pick a stale duplicate over the prefixed one.+ if (platform === 'win32') {+ for (const key of Object.keys(next)) {+ if (key !== pathKey && key.toUpperCase() === 'PATH') delete next[key];+ }+ }+ next[pathKey] = [wrapperDir, ...rest].join(delimiter);+ return next;+};diff --git a/apps/desktop/src/main/modules/cliEmbedding/index.ts b/apps/desktop/src/main/modules/cliEmbedding/index.tsindex d2507f8edf4..a943259fb4f 100644--- a/apps/desktop/src/main/modules/cliEmbedding/index.ts+++ b/apps/desktop/src/main/modules/cliEmbedding/index.ts@@ -1 +1,2 @@+export { getEmbeddedCliPath, LOBEHUB_CLI_ENV, withEmbeddedCliEnv } from './embeddedCliEnv';export { generateCliWrapper, getCliWrapperDir, resolveCliScript } from './generateCliWrapper';diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.tsindex 4bd08b633db..c7acf7a82d7 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts@@ -1,9 +1,10 @@import path from 'node:path';+import { buildCodexAppServerThreadParams } from '@lobechat/heterogeneous-agents/spawn';import { describe, expect, it } from 'vitest';import type { PrepareProviderBindingContext } from '../types';-import { codexDriver, sanitizeCodexProviderBindingArgs } from './codex';+import { codexDriver, sanitizeCodexProviderBindingArgs, withCodexContextArgs } from './codex';const bindingContext = (): PrepareProviderBindingContext => ({args: ['--model', 'stale-model', '-c', 'model_provider="other"', '--json'],@@ -233,3 +234,57 @@ describe('codexDriver provider binding', () => {).toEqual(['-c', 'sandbox_workspace_write.network_access=true']);});});++describe('withCodexContextArgs', () => {+ const env = {+ LOBEHUB_AGENT_ID: 'agt_1',+ LOBEHUB_OPERATION_ID: 'op "1"',+ LOBEHUB_TOPIC_ID: 'tpc_1',+ LOBEHUB_WORKSPACE_ID: 'ws_1',+ };+ const cliPath = path.join(+ '/mock/userData',+ 'bin',+ process.platform === 'win32' ? 'lh.cmd' : 'lh',+ );++ it('prefixes Codex args with shell_environment_policy.set overrides for the run ids', () => {+ expect(withCodexContextArgs('codex', env, ['--model', 'gpt-test'])).toEqual([+ '-c',+ 'shell_environment_policy.set.LOBEHUB_AGENT_ID="agt_1"',+ '-c',+ `shell_environment_policy.set.LOBEHUB_CLI=${JSON.stringify(cliPath)}`,+ '-c',+ 'shell_environment_policy.set.LOBEHUB_OPERATION_ID="op \\"1\\""',+ '-c',+ 'shell_environment_policy.set.LOBEHUB_TOPIC_ID="tpc_1"',+ '-c',+ 'shell_environment_policy.set.LOBEHUB_WORKSPACE_ID="ws_1"',+ '--model',+ 'gpt-test',+ ]);+ });++ it('reaches the app-server thread config as plain strings', () => {+ const params = buildCodexAppServerThreadParams(withCodexContextArgs('codex', env), '/work');+ expect(params.config).toEqual({+ 'shell_environment_policy.set.LOBEHUB_AGENT_ID': 'agt_1',+ 'shell_environment_policy.set.LOBEHUB_CLI': cliPath,+ 'shell_environment_policy.set.LOBEHUB_OPERATION_ID': 'op "1"',+ 'shell_environment_policy.set.LOBEHUB_TOPIC_ID': 'tpc_1',+ 'shell_environment_policy.set.LOBEHUB_WORKSPACE_ID': 'ws_1',+ });+ });++ it('lets the session env name its own CLI', () => {+ expect(withCodexContextArgs('codex', { LOBEHUB_CLI: '/custom/lh' })).toEqual([+ '-c',+ 'shell_environment_policy.set.LOBEHUB_CLI="/custom/lh"',+ ]);+ });++ it('leaves other agents and env-less sessions unchanged', () => {+ expect(withCodexContextArgs('claude-code', env, ['-p'])).toEqual(['-p']);+ expect(withCodexContextArgs('codex', undefined, ['--json'])).toEqual(['--json']);+ });+});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.tsindex ec670b355f8..e218dacc485 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts@@ -1,6 +1,7 @@import path from 'node:path';import {+ buildCodexLobeHubContextArgs,CODEX_DEFAULT_EXECUTION_ARGS,CODEX_EXECUTION_MODE_FLAGS,CODEX_REQUIRED_ARGS,@@ -16,6 +17,8 @@ import {isCodexServerDefaultCustomModel,} from '@lobechat/types';+import { getEmbeddedCliPath, LOBEHUB_CLI_ENV } from '@/modules/cliEmbedding';+import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';const hasAnyFlag = (args: string[], flags: readonly string[]) =>@@ -231,6 +234,27 @@ const buildServerDefaultModelCatalog = ()}\n`;};+/**+ * Prefix a Codex session's args with `shell_environment_policy.set.*`+ * overrides for the LobeHub run context in its env (agent/operation/topic/+ * workspace ids) plus the bundled `lh` path, so `lh` inside Codex's shell sees+ * them even when the user's config sets `inherit = "core"`. Both the+ * `codex exec` plan and the app-server thread config+ * (`buildCodexAppServerThreadParams`) read these args. Other agent types are+ * returned unchanged.+ */+export const withCodexContextArgs = (+ agentType: string,+ env: Record<string, string> | undefined,+ args: string[] = [],+): string[] =>+ agentType === 'codex' && env+ ? [+ ...buildCodexLobeHubContextArgs({ [LOBEHUB_CLI_ENV]: getEmbeddedCliPath(), ...env }),+ ...args,+ ]+ : args;+const buildCodexOptionArgs = async ({args,helpers,diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.tsindex 0c3e111de8d..d94fbbdfb1c 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts@@ -40,3 +40,5 @@ export const getHeterogeneousAgentDriver = (agentType: string): HeterogeneousAgereturn driver;};++export { withCodexContextArgs } from './drivers/codex';diff --git a/apps/desktop/src/main/services/remoteFileUploadSrv.ts b/apps/desktop/src/main/services/remoteFileUploadSrv.tsindex 5b2b67703af..306d5e1095c 100644--- a/apps/desktop/src/main/services/remoteFileUploadSrv.ts+++ b/apps/desktop/src/main/services/remoteFileUploadSrv.ts@@ -174,6 +174,8 @@ export default class RemoteFileUploadService extends ServiceModule {]);if (token && serverUrl) {env.LOBEHUB_JWT = token;+ // An inherited agent-run JWT file would win over this fresh token.+ delete env.LOBEHUB_JWT_FILE;env.LOBEHUB_SERVER = serverUrl.replace(/\/$/, '');}}diff --git a/packages/heterogeneous-agents/src/codex/codexAgentHandle.test.ts b/packages/heterogeneous-agents/src/codex/codexAgentHandle.test.tsindex eaa62a32873..90e2f98af64 100644--- a/packages/heterogeneous-agents/src/codex/codexAgentHandle.test.ts+++ b/packages/heterogeneous-agents/src/codex/codexAgentHandle.test.ts@@ -1,3 +1,5 @@+import { existsSync, readFileSync } from 'node:fs';+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -94,6 +96,31 @@ describe('createCodexAgentHandle', () => {});/** @example An ordinary topic surfaces the raw Codex error so the CLI can retry fresh. */+ /** @example `inherit = "core"` cannot strip the scope and credentials `lh` needs. */+ it('forwards workspace, server and a JWT file through the shell policy', async () => {+ const handle = await createCodexAgentHandle({+ ...options,+ env: {+ ...options.env,+ LOBEHUB_JWT: 'secret-jwt',+ LOBEHUB_SERVER: 'https://app.lobehub.com',+ LOBEHUB_WORKSPACE_ID: 'ws-airi',+ },+ });+ const config = mocks.options[0].threadParams.config ?? {};+ expect(config).toMatchObject({+ 'shell_environment_policy.set.LOBEHUB_SERVER': 'https://app.lobehub.com',+ 'shell_environment_policy.set.LOBEHUB_WORKSPACE_ID': 'ws-airi',+ });+ // The token itself never enters the persisted thread config, only its 0600 file.+ expect(JSON.stringify(config)).not.toContain('secret-jwt');+ const jwtPath = config['shell_environment_policy.set.LOBEHUB_JWT_FILE'] as string;+ expect(readFileSync(jwtPath, 'utf8')).toBe('secret-jwt');++ await handle.exit;+ await vi.waitFor(() => expect(existsSync(jwtPath)).toBe(false));+ });+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'),diff --git a/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts b/packages/heterogeneous-agents/src/codex/codexAgentHandle.tsindex 2fd21a7c1b6..2c3af4f1714 100644--- a/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts+++ b/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts@@ -2,6 +2,7 @@ import { PassThrough } from 'node:stream';import type { AgentPromptInput } from '../protocol';import { createEventQueue } from '../spawn/agentEventQueue';+import { buildCodexLobeHubContextArgs, createCodexJwtFile } from '../spawn/codexShellEnv';import { buildAgentInput } from '../spawn/input';import type { SpawnAgentHandle } from '../spawn/spawnAgent';import {@@ -11,6 +12,7 @@ import {} from './appServerParams';import { CodexAppServerClient } from './CodexAppServerClient';import { CodexThreadSession } from './CodexThreadSession';+import { pickCodexRunProvenance } from './environment';/** Native Codex execution inputs for a single connected-device operation. */export interface CodexAgentHandleOptions {@@ -86,19 +88,30 @@ export const createCodexAgentHandle = async (// 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 ?? '',+ const provenance = pickCodexRunProvenance({+ ...options.env,LOBEHUB_OPERATION_ID: options.operationId,- LOBEHUB_TOPIC_ID: options.env.LOBEHUB_TOPIC_ID ?? '',- };- const threadParams = buildCodexAppServerThreadParams(options.args, options.cwd);+ });+ // Codex shells get their env from `[shell_environment_policy]`, so a user's+ // `inherit = "core"` would drop the run context `lh` needs. Forward it as+ // `set` overrides; the JWT travels as a 0600 file path, never in the config.+ const jwtFile = options.env.LOBEHUB_JWT+ ? await createCodexJwtFile(options.env.LOBEHUB_JWT)+ : undefined;+ const threadParams = buildCodexAppServerThreadParams(+ [...buildCodexLobeHubContextArgs(options.env), ...(jwtFile?.args ?? []), ...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,+ ...Object.fromEntries(+ Object.entries(provenance).map(([key, value]) => [+ `shell_environment_policy.set.${key}`,+ value ?? '',+ ]),+ ),};const session = new CodexThreadSession({client,@@ -161,6 +174,7 @@ export const createCodexAgentHandle = async (stopStderr();events.close();stderr.end();+ void jwtFile?.cleanup();});return {events,diff --git a/packages/heterogeneous-agents/src/codex/environment.test.ts b/packages/heterogeneous-agents/src/codex/environment.test.tsindex c4ce728233c..744e5611597 100644--- a/packages/heterogeneous-agents/src/codex/environment.test.ts+++ b/packages/heterogeneous-agents/src/codex/environment.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { pickCodexRunProvenance, withCodexThreadEnv } from './environment';+import { getCodexProcessEnv, pickCodexRunProvenance, withCodexThreadEnv } from './environment';describe('Codex thread environment', () => {it('picks only run provenance from a launch environment', () => {@@ -15,9 +15,19 @@ describe('Codex thread environment', () => {LOBEHUB_AGENT_ID: undefined,LOBEHUB_OPERATION_ID: 'op',LOBEHUB_TOPIC_ID: 'topic',+ LOBEHUB_WORKSPACE_ID: undefined,});});+ it('keeps the workspace out of the shared app-server process env', () => {+ // Runs from two workspaces must reuse one app-server; a workspace in the process env made+ // the reuse check reject the second run as a different environment.+ const launch = (workspace: string) =>+ getCodexProcessEnv({ CODEX_HOME: '/codex', LOBEHUB_WORKSPACE_ID: workspace });+ expect(launch('ws-a')).toEqual(launch('ws-b'));+ expect(launch('ws-a')).toEqual({ CODEX_HOME: '/codex' });+ });+it('folds every shell policy override into one table carrying the run provenance', () => {const params = {config: {@@ -47,6 +57,7 @@ describe('Codex thread environment', () => {LOBEHUB_AGENT_ID: '',LOBEHUB_OPERATION_ID: 'current',LOBEHUB_TOPIC_ID: '',+ LOBEHUB_WORKSPACE_ID: '',},},});diff --git a/packages/heterogeneous-agents/src/codex/environment.ts b/packages/heterogeneous-agents/src/codex/environment.tsindex 959dc1822ee..c3d946f0337 100644--- a/packages/heterogeneous-agents/src/codex/environment.ts+++ b/packages/heterogeneous-agents/src/codex/environment.ts@@ -2,11 +2,15 @@ import { isRecord } from '@lobechat/utils/object';import type { ThreadStartParams } from './protocol';-/** These values identify one run; credentials and every other setting stay process-scoped. */+/**+ * These values identify one run; credentials and every other setting stay process-scoped.+ * The workspace is run-scoped too: runs from different workspaces share one app-server.+ */const CODEX_PROVENANCE_KEYS = ['LOBEHUB_AGENT_ID','LOBEHUB_OPERATION_ID','LOBEHUB_TOPIC_ID',+ 'LOBEHUB_WORKSPACE_ID',] as const;const isProvenanceKey = (key: string) => (CODEX_PROVENANCE_KEYS as readonly string[]).includes(key);diff --git a/packages/heterogeneous-agents/src/protocol/index.ts b/packages/heterogeneous-agents/src/protocol/index.tsindex 341873c5f05..5872108bbd0 100644--- a/packages/heterogeneous-agents/src/protocol/index.ts+++ b/packages/heterogeneous-agents/src/protocol/index.ts@@ -13,6 +13,7 @@ export type {} from './cancellation';export { buildHeteroExecStdinPayload, type HeteroExecImageRef } from './execStdinPayload';export { lobeHubCliGuide } from './lobeHubCliGuide';+export { INHERITED_RUN_IDENTITY_ENV_KEYS, stripInheritedRunIdentity } from './runIdentityEnv';export const HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV = 'LOBEHUB_HETERO_EXEC_INHERIT_PROCESS_GROUP';export {buildHeterogeneousPrompt,diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.tsindex b3a28ee0c55..08afd0f5d76 100644--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts@@ -28,7 +28,10 @@* apply itself rather than claiming it is signed in. That fallback is phrased* as "clear the variable", not `env -u`: devices run Windows too, and* `pickAuthSource` only tests `LOBEHUB_JWT` for truthiness, so an empty value- * falls through to the stored login in every shell.+ * falls through to the stored login in every shell. Codex runs may carry the+ * token as `LOBEHUB_JWT_FILE` instead (see `codexShellEnv`); the CLI prefers+ * it over an inherited token unless `LOBEHUB_JWT` is set empty, and+ * PowerShell/cmd unset a variable assigned an empty value, so the guide clears both.* - **`LOBEHUB_AGENT_ID`.** Desktop client mode sets it through* `buildLobeHubSessionEnv`. CLI/Desktop dispatch launchers, including* OpenClaw/Hermes, clear inherited identity and inject the current dispatch's@@ -44,11 +47,12 @@ export const lobeHubCliGuide = ['',"You are running inside a LobeHub conversation, on a machine where the `lh` CLI is already installed and the run normally carries the user's credentials in its environment β never install it, and never run `lh login`.",'',- '- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) is too whenever the run carries one. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id.',+ '- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) and `LOBEHUB_WORKSPACE_ID` (the workspace this conversation belongs to, which scopes every `lh` call) are too whenever the run carries them. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id.',+ '- **If `lh` is older than this app**, the shell may have found a stale global install first: `lh man` lacks a command you expect, or `lh` reports an unknown command. When `LOBEHUB_CLI` is set it is the path of the CLI this app ships β run that path instead of `lh` for the rest of the session.','- **Look commands up, do not guess them.** `lh man <command>` (e.g. `lh man doc create`) prints the manual for the CLI actually installed here, including exactly which flags that command takes. Many commands offer `--json` for structured output, but not all of them β the manual is what says so, and an invented flag just fails the call.','- **What it reaches:** `lh kb` knowledge bases Β· `lh doc` documents Β· `lh file` files Β· `lh artifact` artifacts Β· `lh topic` / `lh message` past conversations Β· `lh agent` agents Β· `lh task` / `lh project` work Β· `lh widget` / `lh dashboard` monitoring widgets and dashboards Β· `lh search` local resources and the web Β· `lh gen` text/image/video/TTS/ASR generation Β· `lh memory` user memory Β· `lh notify` notifications to the user Β· `lh model` / `lh provider` / `lh plugin` / `lh skill` platform configuration Β· `lh bot` chat-platform bots.',"- **Widgets run code with the user's credentials.** Before `lh widget dry-run` of a draft that declares connector credentials (`manifest.env`) or network hosts (`manifest.network.allow`), show the user that version id, what the script does and which credentials and hosts it uses, and wait for their explicit approval of that exact version before passing `--version <id> --yes`. Never publish (`lh widget publish`) without the user's confirmation.",'- **When to use it:** whenever the user asks for something that lives in LobeHub rather than in this working directory β saving a document, recalling an earlier conversation, generating an image, or changing your own agent configuration. Say what you did and where it landed.',- "- **If a command comes back with an authentication or permission error**, clear `LOBEHUB_JWT` and retry it once β some runs carry a narrow token scoped to this conversation, which shadows the machine's own login. An empty value is enough, so use whichever form your shell takes: `LOBEHUB_JWT= lh β¦` (sh/bash/zsh), `$env:LOBEHUB_JWT=''; lh β¦` (PowerShell), `set LOBEHUB_JWT=` then `lh β¦` (cmd). If it still fails, tell the user what you were trying to do β do not work around it.",+ "- **If a command comes back with an authentication or permission error**, clear `LOBEHUB_JWT` and `LOBEHUB_JWT_FILE` and retry it once β some runs carry a narrow token scoped to this conversation, which shadows the machine's own login. An empty value is enough, so use whichever form your shell takes: `LOBEHUB_JWT= LOBEHUB_JWT_FILE= lh β¦` (sh/bash/zsh), `$env:LOBEHUB_JWT=''; $env:LOBEHUB_JWT_FILE=''; lh β¦` (PowerShell), `set LOBEHUB_JWT=` and `set LOBEHUB_JWT_FILE=` then `lh β¦` (cmd). If it still fails, tell the user what you were trying to do β do not work around it.",'- **Leave these alone:** `lh hetero` and `lh connect` run the infrastructure that is executing you. And never change the persistent workspace scope with `lh workspace use` β it silently rewrites the target of every later command in this session.',].join('\n');diff --git a/packages/heterogeneous-agents/src/protocol/runIdentityEnv.test.ts b/packages/heterogeneous-agents/src/protocol/runIdentityEnv.test.tsnew file mode 100644index 00000000000..bd0f642f664--- /dev/null+++ b/packages/heterogeneous-agents/src/protocol/runIdentityEnv.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import { stripInheritedRunIdentity } from './runIdentityEnv';++describe('stripInheritedRunIdentity', () => {+ it('drops the ancestor run identity and JWT file, keeping everything else', () => {+ const env = {+ HOME: '/home/u',+ LOBEHUB_AGENT_ID: 'agt',+ LOBEHUB_ASSISTANT_MESSAGE_ID: 'msg',+ LOBEHUB_JWT: 'launcher-token',+ LOBEHUB_JWT_FILE: '/tmp/ancestor/jwt',+ LOBEHUB_TASK_ID: 'task',+ LOBEHUB_WORKSPACE_ID: 'ws',+ };++ // The launcher overwrites LOBEHUB_JWT itself; only the file pointer could outrank it.+ expect(stripInheritedRunIdentity(env)).toEqual({+ HOME: '/home/u',+ LOBEHUB_JWT: 'launcher-token',+ });+ expect(env.LOBEHUB_JWT_FILE).toBe('/tmp/ancestor/jwt');+ });+});diff --git a/packages/heterogeneous-agents/src/protocol/runIdentityEnv.ts b/packages/heterogeneous-agents/src/protocol/runIdentityEnv.tsnew file mode 100644index 00000000000..e971cea4611--- /dev/null+++ b/packages/heterogeneous-agents/src/protocol/runIdentityEnv.ts@@ -0,0 +1,25 @@+/**+ * Env a launcher must not pass from its own run to one it dispatches.+ *+ * A launcher (`lh connect`, the desktop gateway, a desktop `lh` command) can+ * itself run inside an agent's shell. Its ambient run identity belongs to that+ * ancestor: inherited ids would attach the dispatched run's output to the wrong+ * conversation, and an inherited `LOBEHUB_JWT_FILE` points at the ancestor's+ * token, which the CLI prefers over the fresh `LOBEHUB_JWT` the launcher injects.+ */+export const INHERITED_RUN_IDENTITY_ENV_KEYS = [+ 'LOBEHUB_AGENT_ID',+ 'LOBEHUB_ASSISTANT_MESSAGE_ID',+ 'LOBEHUB_JWT_FILE',+ 'LOBEHUB_TASK_ID',+ 'LOBEHUB_WORKSPACE_ID',+] as const;++/** A copy of `env` without the ancestor run's identity; the launcher sets its own. */+export const stripInheritedRunIdentity = <T extends Record<string, string | undefined>>(+ env: T,+): T => {+ const next = { ...env };+ for (const key of INHERITED_RUN_IDENTITY_ENV_KEYS) delete next[key];+ return next;+};diff --git a/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts b/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.tsnew file mode 100644index 00000000000..cdf3a289dad--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts@@ -0,0 +1,327 @@+import path from 'node:path';+import { PassThrough } from 'node:stream';++import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';++import { resolveHeterogeneousAgentCommand } from '../config';+import { isPathLikeCommand } from './cliSpawn';+import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';+import { buildDevinAcpPrompt, DevinAcpSession } from './devinAcpSession';+import { buildDroidAcpPrompt, DroidAcpSession } from './droidAcpSession';+import { buildGrokAcpPrompt, GrokAcpSession } from './grokAcpSession';+import type { SpawnAgentHandle, SpawnAgentOptions } from './spawnAgent';+import { buildTraeAcpPrompt, TraeAcpSession } from './traeAcpSession';+import { assertSpawnableWorkingDirectory } from './workingDirectory';++/**+ * ACP runtimes (Cursor, Devin, Droid, Grok, TRAE) behind the ordinary+ * `SpawnAgentHandle` contract returned by `spawnAgent`.+ */++/** Guarded raw-stdout tee: diagnostic sink failures must not affect the ACP run. */+const teeAcpRawStdout =+ (onRawStdout?: (chunk: Buffer) => void) =>+ (line: string): void => {+ if (!onRawStdout) return;+ try {+ onRawStdout(Buffer.from(line));+ } catch {+ // raw dump is diagnostic-only; never let it disrupt the run+ }+ };++/**+ * Bridge a bidirectional ACP session onto the ordinary `SpawnAgentHandle`+ * contract shared by the one-shot CLI spawns.+ *+ * Exit/error policy (uniform for every ACP agent):+ * - Host kills resolve `exit` as `{ code: null, signal }`.+ * - ACP request failures are first adapted into a terminal error event and+ * then reject the session's run() promise. Once that structured event is+ * queued, the iterable ends normally so callers can apply their error+ * policy; transport failures with no terminal event still throw from the+ * iterator.+ */+const createAcpSpawnBridge = () => {+ const stderr = new PassThrough();+ const queue: AgentStreamEvent[] = [];+ let emittedTerminalError = false;+ let hostSignal: NodeJS.Signals | null = null;+ let streamEnded = false;+ let streamError: Error | undefined;+ let wakeup: (() => void) | undefined;++ const wake = () => {+ const resolve = wakeup;+ wakeup = undefined;+ resolve?.();+ };+ const getHostExit = (): { code: null; signal: NodeJS.Signals } | undefined =>+ hostSignal ? { code: null, signal: hostSignal } : undefined;++ const onEvents = (events: AgentStreamEvent[]): void => {+ if (events.some(({ type }) => type === 'error')) emittedTerminalError = true;+ queue.push(...events);+ wake();+ };+ const onStderr = (data: string): void => {+ stderr.write(data);+ };++ const events: AsyncIterable<AgentStreamEvent> = {+ [Symbol.asyncIterator]() {+ return {+ async next(): Promise<IteratorResult<AgentStreamEvent>> {+ while (true) {+ const event = queue.shift();+ if (event) return { done: false, value: event };+ if (streamError) throw streamError;+ if (streamEnded) return { done: true, value: undefined };+ await new Promise<void>((resolve) => {+ wakeup = resolve;+ });+ }+ },+ };+ },+ };++ const attach = (session: {+ close: (signal?: NodeJS.Signals | null) => void;+ interrupt: () => void;+ run: () => Promise<void>;+ }): Pick<SpawnAgentHandle, 'exit' | 'interrupt' | 'kill'> => {+ const exit: SpawnAgentHandle['exit'] = session+ .run()+ .then(() => getHostExit() ?? { code: 0, signal: null })+ .catch((error) => {+ const hostExit = getHostExit();+ if (hostExit) return hostExit;++ if (!emittedTerminalError) {+ streamError = error instanceof Error ? error : new Error(String(error));+ }+ return { code: 1, signal: null };+ })+ .finally(() => {+ streamEnded = true;+ stderr.end();+ wake();+ });++ const kill = (signal: NodeJS.Signals = 'SIGINT'): void => {+ hostSignal = signal;+ if (signal === 'SIGINT') session.interrupt();+ else session.close(signal);+ };+ const interrupt = (signal: NodeJS.Signals = 'SIGINT'): void => {+ hostSignal = signal;+ // SIGTERM already reached the child through the inherited process group.+ // Close pending RPCs without interrupting the child's shutdown again.+ if (signal === 'SIGTERM') session.close(null);+ else kill(signal);+ };+ return { exit, interrupt, kill };+ };++ return { attach, events, onEvents, onStderr, stderr };+};++interface AcpSpawnSession {+ close: (signal?: NodeJS.Signals | null) => void;+ interrupt: () => void;+ pid?: number;+ run: () => Promise<void>;+ sessionId?: string;+}++const createAcpSpawnHandle = (+ bridge: ReturnType<typeof createAcpSpawnBridge>,+ session: AcpSpawnSession,+ getSessionId: () => string | undefined = () => session.sessionId,+): SpawnAgentHandle => {+ const { exit, interrupt, kill } = bridge.attach(session);++ return {+ events: bridge.events,+ exit,+ interrupt,+ kill,+ get pid() {+ return session.pid;+ },+ get sessionId() {+ return getSessionId();+ },+ stderr: bridge.stderr,+ };+};++export const spawnGrokAcpAgent = async (+ options: SpawnAgentOptions,+ command: string,+ cwd: string,+): Promise<SpawnAgentHandle> => {+ const prompt = await buildGrokAcpPrompt(options.prompt, options.inputOptions);+ const bridge = createAcpSpawnBridge();+ const session = new GrokAcpSession({+ args: options.extraArgs ?? [],+ clientVersion: 'lobehub-cli',+ commandPath: command,+ cwd,+ detached: options.detached,+ env: { ...process.env, ...options.env },+ onEvents: bridge.onEvents,+ onRawMessage: teeAcpRawStdout(options.onRawStdout),+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: bridge.onStderr,+ operationId: options.operationId,+ prompt,+ resumeSessionId: options.resumeSessionId,+ sessionId: options.operationId,+ });+ return createAcpSpawnHandle(bridge, session);+};++export const spawnCursorAcpAgent = async (+ options: SpawnAgentOptions,+ command: string,+ cwd: string,+): Promise<SpawnAgentHandle> => {+ const prompt = buildCursorAcpPrompt(options.prompt);+ const bridge = createAcpSpawnBridge();+ const session = new CursorAcpSession({+ args: options.extraArgs ?? [],+ askUserBridge: options.askUserBridge,+ clientVersion: 'lobehub-cli',+ commandPath: command,+ cwd,+ detached: options.detached,+ env: { ...process.env, ...options.env },+ onEvents: bridge.onEvents,+ onRawMessage: teeAcpRawStdout(options.onRawStdout),+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: bridge.onStderr,+ operationId: options.operationId,+ prompt,+ resumeSessionId: options.resumeSessionId,+ sessionId: options.operationId,+ });+ return createAcpSpawnHandle(bridge, session);+};++export const spawnDroidAcpAgent = async (+ options: SpawnAgentOptions,+ command: string,+ cwd: string,+): Promise<SpawnAgentHandle> => {+ const prompt = await buildDroidAcpPrompt(options.prompt, options.inputOptions);+ const bridge = createAcpSpawnBridge();+ const session = new DroidAcpSession({+ args: options.extraArgs ?? [],+ askUserBridge: options.askUserBridge,+ clientVersion: 'lobehub-cli',+ commandPath: command,+ cwd,+ env: { ...process.env, ...options.env },+ initialModel: options.initialModel,+ onEvents: bridge.onEvents,+ onRawMessage: teeAcpRawStdout(options.onRawStdout),+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: bridge.onStderr,+ operationId: options.operationId,+ prompt,+ resumeSessionId: options.resumeSessionId,+ sessionId: options.operationId,+ });+ const { exit, interrupt, kill } = bridge.attach(session);++ return {+ events: bridge.events,+ exit,+ interrupt,+ kill,+ get pid() {+ return session.pid;+ },+ get sessionId() {+ return session.nativeSessionId;+ },+ stderr: bridge.stderr,+ };+};++export const spawnDevinAcpAgent = async (+ options: SpawnAgentOptions,+ command: string,+ cwd: string,+): Promise<SpawnAgentHandle> => {+ const prompt = await buildDevinAcpPrompt(options.prompt, options.inputOptions);+ const bridge = createAcpSpawnBridge();+ const session = new DevinAcpSession({+ args: options.extraArgs ?? [],+ askUserBridge: options.askUserBridge,+ clientVersion: 'lobehub-cli',+ commandPath: command,+ cwd,+ detached: options.detached,+ env: { ...process.env, ...options.env },+ initialModel: options.initialModel,+ onEvents: bridge.onEvents,+ permissionMode: options.permissionMode,+ onRawMessage: teeAcpRawStdout(options.onRawStdout),+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: bridge.onStderr,+ operationId: options.operationId,+ prompt,+ resumeSessionId: options.resumeSessionId,+ sessionId: options.operationId,+ });+ return createAcpSpawnHandle(bridge, session);+};++/** Spawn TRAE's bidirectional ACP runtime behind the ordinary SpawnAgentHandle contract. */+export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentHandle> => {+ const requestedCommand = resolveHeterogeneousAgentCommand('trae', options.command);+ const cwd = options.cwd || process.cwd();+ assertSpawnableWorkingDirectory(cwd);+ const command =+ isPathLikeCommand(requestedCommand) && !path.isAbsolute(requestedCommand)+ ? path.resolve(cwd, requestedCommand)+ : requestedCommand;+ const childEnv = { ...process.env, ...options.env };+ const { detectHeterogeneousCliCommand } = await import('./resolveCliCommand');+ const commandStatus = await detectHeterogeneousCliCommand('trae', command, childEnv);+ if (!commandStatus.available || !commandStatus.path) {+ throw new Error(`TRAE command does not expose the required ACP runtime: ${requestedCommand}`);+ }++ const prompt = await buildTraeAcpPrompt(options.prompt, options.inputOptions);+ const bridge = createAcpSpawnBridge();+ const session = new TraeAcpSession({+ args: options.extraArgs ?? [],+ clientVersion: '1.0.0',+ commandPath: commandStatus.path,+ cwd,+ detached: options.detached,+ env: {+ ...childEnv,+ ...(commandStatus.resolvedPathEnv ? { PATH: commandStatus.resolvedPathEnv } : {}),+ },+ initialModel: options.initialModel,+ onEvents: bridge.onEvents,+ onRawMessage: teeAcpRawStdout(options.onRawStdout),+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: bridge.onStderr,+ operationId: options.operationId,+ prompt,+ resumeSessionId: options.resumeSessionId,+ sessionId: options.operationId,+ });+ return createAcpSpawnHandle(bridge, session, () => session.nativeSessionId);+};diff --git a/packages/heterogeneous-agents/src/spawn/codexShellEnv.test.ts b/packages/heterogeneous-agents/src/spawn/codexShellEnv.test.tsnew file mode 100644index 00000000000..062d99d10c1--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/codexShellEnv.test.ts@@ -0,0 +1,116 @@+import { readFile, stat } from 'node:fs/promises';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import {+ buildCodexLobeHubContextArgs,+ createCodexJwtFile,+ LOBEHUB_JWT_FILE_ENV,+ refreshCodexJwtFiles,+ toTomlBasicString,+} from './codexShellEnv';++/** Decode the way Codex does: the `-c` value is a TOML basic string, which is JSON-compatible here. */+const decode = (arg: string) => {+ const [key, ...rest] = arg.split('=');+ return { key, value: JSON.parse(rest.join('=')) as string };+};++describe('toTomlBasicString', () => {+ it('quotes plain ids and URLs so Codex never falls back to raw-string parsing', () => {+ expect(toTomlBasicString('op_123')).toBe('"op_123"');+ expect(toTomlBasicString('https://app.lobehub.com/a?b=c&d=e')).toBe(+ '"https://app.lobehub.com/a?b=c&d=e"',+ );+ // Valid TOML scalars on their own must still arrive as strings.+ expect(toTomlBasicString('123')).toBe('"123"');+ expect(toTomlBasicString('true')).toBe('"true"');+ });++ it('escapes quotes, backslashes and control characters', () => {+ const raw = 'a"b\\c\nd\te\u0000f\u007Fg';+ const encoded = toTomlBasicString(raw);++ expect(encoded).toBe('"a\\"b\\\\c\\u000ad\\u0009e\\u0000f\\u007fg"');+ expect(JSON.parse(encoded)).toBe(raw);+ });+});++describe('buildCodexLobeHubContextArgs', () => {+ it('forwards every present run-context var as a shell_environment_policy.set override', () => {+ const args = buildCodexLobeHubContextArgs({+ LOBEHUB_AGENT_ID: 'agt_1',+ LOBEHUB_ASSISTANT_MESSAGE_ID: 'msg_1',+ LOBEHUB_JWT: 'secret.jwt.token',+ LOBEHUB_OPERATION_ID: 'op_1',+ LOBEHUB_SERVER: 'https://app.lobehub.com',+ LOBEHUB_TASK_ID: 'task_1',+ LOBEHUB_TOPIC_ID: 'tpc_1',+ LOBEHUB_WORKSPACE_ID: '',+ UNRELATED: 'x',+ });++ const flags = args.filter((_, index) => index % 2 === 0);+ expect(new Set(flags)).toEqual(new Set(['-c']));+ expect(args.filter((_, index) => index % 2 === 1).map(decode)).toEqual([+ { key: 'shell_environment_policy.set.LOBEHUB_AGENT_ID', value: 'agt_1' },+ { key: 'shell_environment_policy.set.LOBEHUB_ASSISTANT_MESSAGE_ID', value: 'msg_1' },+ { key: 'shell_environment_policy.set.LOBEHUB_OPERATION_ID', value: 'op_1' },+ { key: 'shell_environment_policy.set.LOBEHUB_SERVER', value: 'https://app.lobehub.com' },+ { key: 'shell_environment_policy.set.LOBEHUB_TASK_ID', value: 'task_1' },+ { key: 'shell_environment_policy.set.LOBEHUB_TOPIC_ID', value: 'tpc_1' },+ ]);+ expect(args.join(' ')).not.toContain('secret.jwt.token');+ expect(args.join(' ')).not.toContain('LOBEHUB_JWT');+ });++ it('returns nothing outside a LobeHub run', () => {+ expect(buildCodexLobeHubContextArgs({ PATH: '/usr/bin' })).toEqual([]);+ });+});++describe('createCodexJwtFile', () => {+ it('writes the token to a private 0600 file and removes it on cleanup', async () => {+ const jwtFile = await createCodexJwtFile('header.payload.sig');+ const dir = path.dirname(jwtFile.path);++ try {+ expect(await readFile(jwtFile.path, 'utf8')).toBe('header.payload.sig');+ if (process.platform !== 'win32') {+ expect((await stat(jwtFile.path)).mode & 0o777).toBe(0o600);+ expect((await stat(dir)).mode & 0o777).toBe(0o700);+ }+ expect(jwtFile.args).toEqual([+ '-c',+ `shell_environment_policy.set.${LOBEHUB_JWT_FILE_ENV}=${JSON.stringify(jwtFile.path)}`,+ ]);+ expect(jwtFile.args.join(' ')).not.toContain('header.payload.sig');+ } finally {+ await jwtFile.cleanup();+ }++ await expect(stat(dir)).rejects.toMatchObject({ code: 'ENOENT' });+ // Idempotent.+ await expect(jwtFile.cleanup()).resolves.toBeUndefined();+ });++ it('rewrites live files with a renewed token and leaves removed ones gone', async () => {+ // A run outliving its operation token: nested `lh` reads the file, not the host env.+ const live = await createCodexJwtFile('old-token');+ const ended = await createCodexJwtFile('old-token');+ await ended.cleanup();++ try {+ await refreshCodexJwtFiles('renewed-token');++ expect(await readFile(live.path, 'utf8')).toBe('renewed-token');+ if (process.platform !== 'win32') {+ expect((await stat(live.path)).mode & 0o777).toBe(0o600);+ }+ await expect(stat(ended.path)).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ await live.cleanup();+ }+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/codexShellEnv.ts b/packages/heterogeneous-agents/src/spawn/codexShellEnv.tsnew file mode 100644index 00000000000..59ded80577b--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/codexShellEnv.ts@@ -0,0 +1,149 @@+import { rmSync } from 'node:fs';+import { mkdtemp, rename, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++/**+ * Codex does not hand its own process env to the commands it runs: every shell+ * command gets an env built from `[shell_environment_policy]` (codex-rs+ * `protocol/src/shell_environment.rs` `populate_env`). With `inherit = "core"`+ * only PATH/HOME/USER/β¦ survive, so the LobeHub run context injected into the+ * Codex process never reaches `lh` inside the agent's shell. `set` entries are+ * applied after `inherit` and the default/custom excludes, so passing the+ * context as `-c shell_environment_policy.set.<KEY>=<value>` reaches the shell+ * under every `inherit` mode while leaving the user's own policy untouched.+ * (`include_only` still filters `set` entries; a user who narrows the shell+ * env that far has opted out of passing anything through.)+ */+export const CODEX_LOBEHUB_CONTEXT_ENV_KEYS = [+ 'LOBEHUB_AGENT_ID',+ 'LOBEHUB_ASSISTANT_MESSAGE_ID',+ // The desktop's bundled `lh`, for shells that resolve an older global one first.+ 'LOBEHUB_CLI',+ 'LOBEHUB_OPERATION_ID',+ 'LOBEHUB_SERVER',+ 'LOBEHUB_TASK_ID',+ 'LOBEHUB_TOPIC_ID',+ 'LOBEHUB_WORKSPACE_ID',+] as const;++/**+ * Points the CLI at a 0600 file holding the run's JWT. The token itself never+ * goes into Codex argv (readable by any local user through `ps`); only this+ * path does. The `lh` CLI prefers it over an inherited `LOBEHUB_JWT` (only the+ * file follows token renewals) unless `LOBEHUB_JWT` is set empty.+ */+export const LOBEHUB_JWT_FILE_ENV = 'LOBEHUB_JWT_FILE';++const CODEX_SHELL_ENV_SET_PREFIX = 'shell_environment_policy.set.';++/**+ * Encode a value as a TOML basic string. Codex parses a `-c` value as TOML+ * first and only falls back to the raw text (with surrounding quotes stripped)+ * when that fails, so an unquoted URL or an id that happens to be valid TOML+ * (`123`, `true`) would be misread. Escaping `"`, `\` and every control+ * character as `\uXXXX` yields a string TOML and JSON parse identically, which+ * also keeps the desktop app-server path (`parseConfigValue` β JSON.parse)+ * consistent.+ */+export const toTomlBasicString = (value: string): string => {+ let encoded = '"';+ for (const char of value) {+ const code = char.codePointAt(0)!;+ if (char === '"' || char === '\\') encoded += `\\${char}`;+ else if (code < 0x20 || code === 0x7f) encoded += `\\u${code.toString(16).padStart(4, '0')}`;+ else encoded += char;+ }+ return `${encoded}"`;+};++export const buildCodexShellEnvSetArgs = (key: string, value: string): string[] => [+ '-c',+ `${CODEX_SHELL_ENV_SET_PREFIX}${key}=${toTomlBasicString(value)}`,+];++/**+ * `-c` overrides that forward the non-secret LobeHub run context present in+ * `env` into Codex's shell commands. Never includes `LOBEHUB_JWT`.+ */+export const buildCodexLobeHubContextArgs = (env: Record<string, string | undefined>): string[] =>+ CODEX_LOBEHUB_CONTEXT_ENV_KEYS.flatMap((key) => {+ const value = env[key];+ return value ? buildCodexShellEnvSetArgs(key, value) : [];+ });++export interface CodexJwtFile {+ /** `-c` override exposing the file path as `LOBEHUB_JWT_FILE` in Codex's shell. */+ args: string[];+ /** Remove the file and its private directory. Idempotent and never throws. */+ cleanup: () => Promise<void>;+ path: string;+}++/** JWT files of runs still in progress, keyed by path, so a renewed token can reach them. */+const liveJwtFiles = new Set<string>();++/**+ * Rewrite every live Codex JWT file with a renewed token. The Codex process and+ * the `lh` commands it runs cannot see the host's `process.env`, so without this+ * a run outliving its operation token keeps handing nested commands the expired+ * one. Each file is replaced atomically, so a concurrent read never sees half a+ * token. Never throws: a file removed mid-write just drops out.+ */+export const refreshCodexJwtFiles = async (jwt: string): Promise<void> => {+ await Promise.all(+ [...liveJwtFiles].map(async (filePath) => {+ const tmpPath = `${filePath}.${process.pid}.tmp`;+ try {+ await writeFile(tmpPath, jwt, { encoding: 'utf8', mode: 0o600 });+ await rename(tmpPath, filePath);+ } catch {+ await rm(tmpPath, { force: true }).catch(() => {});+ }+ }),+ );+};++/**+ * Write the run's JWT to a per-run file only the current user can read: a+ * fresh `mkdtemp` directory (created 0700) holding a 0600 file. The caller+ * must call `cleanup` when the run ends; a synchronous `exit` hook covers the+ * host process dying first (SIGKILL aside).+ */+export const createCodexJwtFile = async (jwt: string): Promise<CodexJwtFile> => {+ const dir = await mkdtemp(path.join(tmpdir(), 'lobehub-codex-'));+ const filePath = path.join(dir, 'jwt');+ let removed = false;+ const removeSync = () => {+ if (removed) return;+ removed = true;+ liveJwtFiles.delete(filePath);+ try {+ rmSync(dir, { force: true, recursive: true });+ } catch {+ // best-effort+ }+ };+ process.once('exit', removeSync);++ try {+ await writeFile(filePath, jwt, { encoding: 'utf8', flag: 'wx', mode: 0o600 });+ } catch (error) {+ process.off('exit', removeSync);+ removeSync();+ throw error;+ }++ liveJwtFiles.add(filePath);+ return {+ args: buildCodexShellEnvSetArgs(LOBEHUB_JWT_FILE_ENV, filePath),+ cleanup: async () => {+ process.off('exit', removeSync);+ if (removed) return;+ removed = true;+ liveJwtFiles.delete(filePath);+ await rm(dir, { force: true, recursive: true }).catch(() => {});+ },+ path: filePath,+ };+};diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex a3710595e7e..ecf6731216f 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -77,6 +77,16 @@ export {readCodexSessionModel,resolveCodexInitialModel,} from './codexModel';+export {+ buildCodexLobeHubContextArgs,+ buildCodexShellEnvSetArgs,+ CODEX_LOBEHUB_CONTEXT_ENV_KEYS,+ type CodexJwtFile,+ createCodexJwtFile,+ LOBEHUB_JWT_FILE_ENV,+ refreshCodexJwtFiles,+ toTomlBasicString,+} from './codexShellEnv';export {buildCursorAcpArgs,buildCursorAcpPrompt,diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.codexShellEnv.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.codexShellEnv.test.tsnew file mode 100644index 00000000000..d7da3483319--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.codexShellEnv.test.ts@@ -0,0 +1,192 @@+import type * as childProcess from 'node:child_process';+import { EventEmitter } from 'node:events';+import { mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises';+import * as os from 'node:os';+import path from 'node:path';+import { PassThrough } from 'node:stream';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const spawnCalls: Array<{ args: string[]; command: string; options: any }> = [];+let nextFakeProc: any = null;++vi.mock('node:child_process', async () => {+ const actual = await vi.importActual<typeof childProcess>('node:child_process');+ return {+ ...actual,+ execFile: vi.fn(),+ spawn: vi.fn((command: string, args: string[], options: any) => {+ spawnCalls.push({ args, command, options });+ return nextFakeProc;+ }),+ };+});++vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => 'linux') };+});++/** A child that stays alive until `finish()` so the JWT file can be inspected mid-run. */+const createHeldProc = () => {+ const proc = new EventEmitter() as any;+ const stdout = new PassThrough();+ proc.stdout = stdout;+ proc.stderr = new PassThrough();+ proc.stdin = {+ end: vi.fn(),+ once: vi.fn(),+ write: vi.fn((_: string, cb?: () => void) => cb?.()),+ };+ proc.kill = vi.fn();+ proc.killed = false;+ proc.pid = 4242;+ const finish = () => {+ stdout.end();+ proc.stderr.end();+ proc.emit('exit', 0, null);+ };+ return { finish, proc };+};++const RUN_ENV = {+ LOBEHUB_AGENT_ID: 'agt_1',+ LOBEHUB_ASSISTANT_MESSAGE_ID: 'msg_1',+ LOBEHUB_JWT: 'header.payload.signature',+ LOBEHUB_OPERATION_ID: 'op_1',+ LOBEHUB_SERVER: 'https://app.lobehub.com',+ LOBEHUB_TOPIC_ID: 'tpc_1',+ LOBEHUB_WORKSPACE_ID: 'ws_1',+};++const configOverrides = (args: string[]) =>+ args.flatMap((arg, index) => (args[index - 1] === '-c' ? [arg] : []));++const setOverride = (args: string[], key: string) => {+ const prefix = `shell_environment_policy.set.${key}=`;+ const raw = configOverrides(args).find((arg) => arg.startsWith(prefix));+ return raw === undefined ? undefined : (JSON.parse(raw.slice(prefix.length)) as string);+};++describe('spawnAgent codex shell environment', () => {+ let codexHome: string;++ beforeEach(async () => {+ spawnCalls.length = 0;+ codexHome = await mkdtemp(path.join(os.tmpdir(), 'lobe-codex-shell-env-'));+ });++ afterEach(async () => {+ nextFakeProc = null;+ await rm(codexHome, { force: true, recursive: true });+ });++ it('forwards the run context through shell_environment_policy.set and keeps the JWT out of argv', async () => {+ const held = createHeldProc();+ nextFakeProc = held.proc;+ const { spawnAgent } = await import('./spawnAgent');++ const handle = await spawnAgent({+ agentType: 'codex',+ env: { ...RUN_ENV, CODEX_HOME: codexHome },+ extraArgs: ['-c', 'model_reasoning_effort="high"'],+ operationId: 'op_1',+ prompt: 'hello',+ });+ const { args, options } = spawnCalls[0];++ for (const key of [+ 'LOBEHUB_AGENT_ID',+ 'LOBEHUB_ASSISTANT_MESSAGE_ID',+ 'LOBEHUB_OPERATION_ID',+ 'LOBEHUB_SERVER',+ 'LOBEHUB_TOPIC_ID',+ 'LOBEHUB_WORKSPACE_ID',+ ] as const) {+ expect(setOverride(args, key)).toBe(RUN_ENV[key]);+ }+ expect(setOverride(args, 'LOBEHUB_JWT')).toBeUndefined();+ expect(args.join('\n')).not.toContain(RUN_ENV.LOBEHUB_JWT);+ // The user's own overrides stay last so they can still win.+ expect(args.at(-1)).toBe('model_reasoning_effort="high"');+ // The process env itself is unchanged; only the shell policy is extended.+ expect(options.env.LOBEHUB_JWT).toBe(RUN_ENV.LOBEHUB_JWT);++ const jwtPath = setOverride(args, 'LOBEHUB_JWT_FILE')!;+ expect(await readFile(jwtPath, 'utf8')).toBe(RUN_ENV.LOBEHUB_JWT);+ expect((await stat(jwtPath)).mode & 0o777).toBe(0o600);++ held.finish();+ for await (const _ of handle.events) {+ // drain+ }+ await handle.exit;+ await vi.waitFor(async () => {+ await expect(stat(path.dirname(jwtPath))).rejects.toMatchObject({ code: 'ENOENT' });+ });+ });++ it('keeps the overrides before the resume thread id positional', async () => {+ const held = createHeldProc();+ nextFakeProc = held.proc;+ const { spawnAgent } = await import('./spawnAgent');++ const handle = await spawnAgent({+ agentType: 'codex',+ env: { ...RUN_ENV, CODEX_HOME: codexHome },+ operationId: 'op_1',+ prompt: 'hello',+ resumeSessionId: 'thread-1',+ });+ const { args } = spawnCalls[0];++ expect(args.slice(0, 2)).toEqual(['exec', 'resume']);+ expect(args.slice(-2)).toEqual(['thread-1', '-']);+ expect(setOverride(args, 'LOBEHUB_OPERATION_ID')).toBe('op_1');++ held.finish();+ for await (const _ of handle.events) {+ // drain+ }+ await handle.exit;+ });++ it('removes the JWT file when the spawn fails', async () => {+ nextFakeProc = null;+ const { spawnAgent } = await import('./spawnAgent');+ const listJwtDirs = async () =>+ (await readdir(os.tmpdir())).filter((name) => name.startsWith('lobehub-codex-'));+ const before = new Set(await listJwtDirs());++ await expect(+ spawnAgent({+ agentType: 'codex',+ env: { ...RUN_ENV, CODEX_HOME: codexHome },+ operationId: 'op_1',+ prompt: 'hello',+ }),+ ).rejects.toThrow();++ expect((await listJwtDirs()).filter((name) => !before.has(name))).toEqual([]);+ });++ it('leaves other agent types untouched', async () => {+ const held = createHeldProc();+ nextFakeProc = held.proc;+ const { spawnAgent } = await import('./spawnAgent');++ const handle = await spawnAgent({+ agentType: 'claude-code',+ env: RUN_ENV,+ operationId: 'op_1',+ prompt: 'hello',+ });+ expect(spawnCalls[0].args.join('\n')).not.toContain('shell_environment_policy');++ held.finish();+ for await (const _ of handle.events) {+ // drain+ }+ await handle.exit;+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.tsindex bff4ec42693..e4bc748ecf5 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts@@ -346,15 +346,15 @@ describe('spawnAgent', () => {nextFakeProc = null;platformMock.mockReturnValue('linux');execFileMock.mockReset();- // ACP/stdio sessions read `process.platform` directly (unlike the CLI- // spawn plan which uses `os.platform()`), so pin it too β otherwise the- // signal-path tests exercise the win32 taskkill branch on Windows hosts.+ // ACP sessions read `process.platform` directly; pin it so signal tests skip win32 taskkill.Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' });+ vi.stubEnv('LOBEHUB_JWT', ''); // a host token would land in a never-cleaned Codex JWT filedetectHeterogeneousCliCommandMock.mockResolvedValue({ available: true, path: 'traecli' });});afterEach(async () => {nextFakeProc = null;+ vi.unstubAllEnvs();Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform });await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 23e4de93540..57b532c99e1 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -1,7 +1,5 @@import type { ChildProcess } from 'node:child_process';import { platform } from 'node:os';-import path from 'node:path';-import { PassThrough } from 'node:stream';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { spawnManaged } from '@lobechat/utils/managedProcess';@@ -9,18 +7,25 @@ import { spawnManaged } from '@lobechat/utils/managedProcess';import { ClaudeCodeAdapter } from '../adapters/claudeCode';import type { AskUserBridge } from '../askUser/AskUserBridge';import { resolveHeterogeneousAgentCommand } from '../config';+import {+ spawnCursorAcpAgent,+ spawnDevinAcpAgent,+ spawnDroidAcpAgent,+ spawnGrokAcpAgent,+ spawnTraeAcpAgent,+} from './acpSpawnAgent';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';import { ClaudeCodeLiveInput } from './claudeCodeLiveInput';import { readClaudeCodeSessionCost } from './claudeCodeSessionCost';-import { isPathLikeCommand, resolveCliSpawnPlan } from './cliSpawn';+import { resolveCliSpawnPlan } from './cliSpawn';import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';-import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';-import { buildDevinAcpPrompt, DevinAcpSession } from './devinAcpSession';-import { buildDroidAcpPrompt, DroidAcpSession } from './droidAcpSession';-import { buildGrokAcpPrompt, GrokAcpSession } from './grokAcpSession';+import {+ buildCodexLobeHubContextArgs,+ type CodexJwtFile,+ createCodexJwtFile,+} from './codexShellEnv';import type { AgentPromptInput, BuildAgentInputOptions } from './input';import { buildAgentInput } from './input';-import { buildTraeAcpPrompt, TraeAcpSession } from './traeAcpSession';import { assertSpawnableWorkingDirectory } from './workingDirectory';export interface SpawnAgentOptions {@@ -261,6 +266,8 @@ const hasAnyFlag = (args: string[], flags: readonly string[]) =>interface BuildSpawnArgsParams {agentType: string;+ /** (Codex only) `-c` overrides placed before `extraArgs` so callers can still override them. */+ configArgs?: string[];/** Extra CLI arguments appended after the agent's preset flags. */extraArgs: string[];/** (Claude Code only) Stream `--include-partial-messages` deltas. */@@ -304,11 +311,22 @@ const buildCodeBuddyArgs = ({...extraArgs,];-const buildCodexArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArgsParams) => {+const buildCodexArgs = ({+ configArgs = [],+ extraArgs,+ inputArgs,+ resumeSessionId,+}: BuildSpawnArgsParams) => {const executionModeArgs = hasAnyFlag(extraArgs, CODEX_EXECUTION_MODE_FLAGS)? []: [...CODEX_DEFAULT_EXECUTION_ARGS];- const optionArgs = [...CODEX_REQUIRED_ARGS, ...executionModeArgs, ...inputArgs, ...extraArgs];+ const optionArgs = [+ ...CODEX_REQUIRED_ARGS,+ ...executionModeArgs,+ ...inputArgs,+ ...configArgs,+ ...extraArgs,+ ];return resumeSessionId? ['exec', 'resume', ...optionArgs, resumeSessionId, '-']@@ -426,272 +444,6 @@ const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals, detached: b}};-/** Guarded raw-stdout tee: diagnostic sink failures must not affect the ACP run. */-const teeAcpRawStdout =- (onRawStdout?: (chunk: Buffer) => void) =>- (line: string): void => {- if (!onRawStdout) return;- try {- onRawStdout(Buffer.from(line));- } catch {- // raw dump is diagnostic-only; never let it disrupt the run- }- };--/**- * Bridge a bidirectional ACP session onto the ordinary `SpawnAgentHandle`- * contract shared by the one-shot CLI spawns.- *- * Exit/error policy (uniform for every ACP agent):- * - Host kills resolve `exit` as `{ code: null, signal }`.- * - ACP request failures are first adapted into a terminal error event and- * then reject the session's run() promise. Once that structured event is- * queued, the iterable ends normally so callers can apply their error- * policy; transport failures with no terminal event still throw from the- * iterator.- */-const createAcpSpawnBridge = () => {- const stderr = new PassThrough();- const queue: AgentStreamEvent[] = [];- let emittedTerminalError = false;- let hostSignal: NodeJS.Signals | null = null;- let streamEnded = false;- let streamError: Error | undefined;- let wakeup: (() => void) | undefined;-- const wake = () => {- const resolve = wakeup;- wakeup = undefined;- resolve?.();- };- const getHostExit = (): { code: null; signal: NodeJS.Signals } | undefined =>- hostSignal ? { code: null, signal: hostSignal } : undefined;-- const onEvents = (events: AgentStreamEvent[]): void => {- if (events.some(({ type }) => type === 'error')) emittedTerminalError = true;- queue.push(...events);- wake();- };- const onStderr = (data: string): void => {- stderr.write(data);- };-- const events: AsyncIterable<AgentStreamEvent> = {- [Symbol.asyncIterator]() {- return {- async next(): Promise<IteratorResult<AgentStreamEvent>> {- while (true) {- const event = queue.shift();- if (event) return { done: false, value: event };- if (streamError) throw streamError;- if (streamEnded) return { done: true, value: undefined };- await new Promise<void>((resolve) => {- wakeup = resolve;- });- }- },- };- },- };-- const attach = (session: {- close: (signal?: NodeJS.Signals | null) => void;- interrupt: () => void;- run: () => Promise<void>;- }): Pick<SpawnAgentHandle, 'exit' | 'interrupt' | 'kill'> => {- const exit: SpawnAgentHandle['exit'] = session- .run()- .then(() => getHostExit() ?? { code: 0, signal: null })- .catch((error) => {- const hostExit = getHostExit();- if (hostExit) return hostExit;-- if (!emittedTerminalError) {- streamError = error instanceof Error ? error : new Error(String(error));- }- return { code: 1, signal: null };- })- .finally(() => {- streamEnded = true;- stderr.end();- wake();- });-- const kill = (signal: NodeJS.Signals = 'SIGINT'): void => {- hostSignal = signal;- if (signal === 'SIGINT') session.interrupt();- else session.close(signal);- };- const interrupt = (signal: NodeJS.Signals = 'SIGINT'): void => {- hostSignal = signal;- // SIGTERM already reached the child through the inherited process group.- // Close pending RPCs without interrupting the child's shutdown again.- if (signal === 'SIGTERM') session.close(null);- else kill(signal);- };- return { exit, interrupt, kill };- };-- return { attach, events, onEvents, onStderr, stderr };-};--interface AcpSpawnSession {- close: (signal?: NodeJS.Signals | null) => void;- interrupt: () => void;- pid?: number;- run: () => Promise<void>;- sessionId?: string;-}--const createAcpSpawnHandle = (- bridge: ReturnType<typeof createAcpSpawnBridge>,- session: AcpSpawnSession,- getSessionId: () => string | undefined = () => session.sessionId,-): SpawnAgentHandle => {- const { exit, interrupt, kill } = bridge.attach(session);-- return {- events: bridge.events,- exit,- interrupt,- kill,- get pid() {- return session.pid;- },- get sessionId() {- return getSessionId();- },- stderr: bridge.stderr,- };-};--const spawnGrokAcpAgent = async (- options: SpawnAgentOptions,- command: string,- cwd: string,-): Promise<SpawnAgentHandle> => {- const prompt = await buildGrokAcpPrompt(options.prompt, options.inputOptions);- const bridge = createAcpSpawnBridge();- const session = new GrokAcpSession({- args: options.extraArgs ?? [],- clientVersion: 'lobehub-cli',- commandPath: command,- cwd,- detached: options.detached,- env: { ...process.env, ...options.env },- onEvents: bridge.onEvents,- onRawMessage: teeAcpRawStdout(options.onRawStdout),- onRuntimeStatus: () => {},- onSessionId: () => {},- onStderr: bridge.onStderr,- operationId: options.operationId,- prompt,- resumeSessionId: options.resumeSessionId,- sessionId: options.operationId,- });- return createAcpSpawnHandle(bridge, session);-};--const spawnCursorAcpAgent = async (- options: SpawnAgentOptions,- command: string,- cwd: string,-): Promise<SpawnAgentHandle> => {- const prompt = buildCursorAcpPrompt(options.prompt);- const bridge = createAcpSpawnBridge();- const session = new CursorAcpSession({- args: options.extraArgs ?? [],- askUserBridge: options.askUserBridge,- clientVersion: 'lobehub-cli',- commandPath: command,- cwd,- detached: options.detached,- env: { ...process.env, ...options.env },- onEvents: bridge.onEvents,- onRawMessage: teeAcpRawStdout(options.onRawStdout),- onRuntimeStatus: () => {},- onSessionId: () => {},- onStderr: bridge.onStderr,- operationId: options.operationId,- prompt,- resumeSessionId: options.resumeSessionId,- sessionId: options.operationId,- });- return createAcpSpawnHandle(bridge, session);-};--const spawnDroidAcpAgent = async (- options: SpawnAgentOptions,- command: string,- cwd: string,-): Promise<SpawnAgentHandle> => {- const prompt = await buildDroidAcpPrompt(options.prompt, options.inputOptions);- const bridge = createAcpSpawnBridge();- const session = new DroidAcpSession({- args: options.extraArgs ?? [],- askUserBridge: options.askUserBridge,- clientVersion: 'lobehub-cli',- commandPath: command,- cwd,- env: { ...process.env, ...options.env },- initialModel: options.initialModel,- onEvents: bridge.onEvents,- onRawMessage: teeAcpRawStdout(options.onRawStdout),- onRuntimeStatus: () => {},- onSessionId: () => {},- onStderr: bridge.onStderr,- operationId: options.operationId,- prompt,- resumeSessionId: options.resumeSessionId,- sessionId: options.operationId,- });- const { exit, interrupt, kill } = bridge.attach(session);-- return {- events: bridge.events,- exit,- interrupt,- kill,- get pid() {- return session.pid;- },- get sessionId() {- return session.nativeSessionId;- },- stderr: bridge.stderr,- };-};--const spawnDevinAcpAgent = async (- options: SpawnAgentOptions,- command: string,- cwd: string,-): Promise<SpawnAgentHandle> => {- const prompt = await buildDevinAcpPrompt(options.prompt, options.inputOptions);- const bridge = createAcpSpawnBridge();- const session = new DevinAcpSession({- args: options.extraArgs ?? [],- askUserBridge: options.askUserBridge,- clientVersion: 'lobehub-cli',- commandPath: command,- cwd,- detached: options.detached,- env: { ...process.env, ...options.env },- initialModel: options.initialModel,- onEvents: bridge.onEvents,- permissionMode: options.permissionMode,- onRawMessage: teeAcpRawStdout(options.onRawStdout),- onRuntimeStatus: () => {},- onSessionId: () => {},- onStderr: bridge.onStderr,- operationId: options.operationId,- prompt,- resumeSessionId: options.resumeSessionId,- sessionId: options.operationId,- });- return createAcpSpawnHandle(bridge, session);-};-/*** Spawn an external agent CLI (Amp, Claude Code, CodeBuddy, Codex, Cursor,* Factory Droid, Kimi Code, OpenCode, Pi, Qoder, or TRAE) and yield its stream as unified@@ -727,20 +479,49 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent}const inputPlan = await buildAgentInput(options.agentType, options.prompt, options.inputOptions);+ const childEnv: NodeJS.ProcessEnv = {+ ...process.env,+ ...(options.agentType === 'codebuddy' ? { CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS: '1' } : {}),+ ...options.env,+ };+ // Codex builds each shell command's env from `[shell_environment_policy]`,+ // not from its own process env, so a user's `inherit = "core"` strips the+ // run context `lh` needs. Forward it as `shell_environment_policy.set.*`+ // overrides; the JWT travels as a 0600 file path, never in argv.+ const codexJwtFile: CodexJwtFile | undefined =+ options.agentType === 'codex' && childEnv.LOBEHUB_JWT+ ? await createCodexJwtFile(childEnv.LOBEHUB_JWT)+ : undefined;+ try {+ return await spawnCliAgent(options, command, cwd, inputPlan, childEnv, codexJwtFile);+ } catch (error) {+ await codexJwtFile?.cleanup();+ throw error;+ }+};++/** One-shot JSONL CLI spawn; `spawnAgent` owns the Codex JWT file around it. */+const spawnCliAgent = async (+ options: SpawnAgentOptions,+ command: string,+ cwd: string,+ inputPlan: Awaited<ReturnType<typeof buildAgentInput>>,+ childEnv: NodeJS.ProcessEnv,+ codexJwtFile: CodexJwtFile | undefined,+): Promise<SpawnAgentHandle> => {const liveInput = options.agentType === 'claude-code' && options.liveInput === true;const args = buildSpawnArgs({agentType: options.agentType,+ configArgs:+ options.agentType === 'codex'+ ? [...buildCodexLobeHubContextArgs(childEnv), ...(codexJwtFile?.args ?? [])]+ : undefined,extraArgs: options.extraArgs ?? [],includePartialMessages: options.includePartialMessages ?? false,inputArgs: inputPlan.args,liveInput,resumeSessionId: options.resumeSessionId,});- const childEnv: NodeJS.ProcessEnv = {- ...process.env,- ...(options.agentType === 'codebuddy' ? { CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS: '1' } : {}),- ...options.env,- };const initialModel =options.agentType === 'codex'? (await resolveCodexInitialModel({ args, env: childEnv }))?.model@@ -829,6 +610,10 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent});},);+ if (codexJwtFile) {+ const removeJwtFile = () => codexJwtFile.cleanup();+ void exit.then(removeJwtFile, removeJwtFile);+ }const live = liveInput && proc.stdin ? new ClaudeCodeLiveInput(proc.stdin) : undefined;if (live) {@@ -971,44 +756,4 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent};};-/** Spawn TRAE's bidirectional ACP runtime behind the ordinary SpawnAgentHandle contract. */-export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentHandle> => {- const requestedCommand = resolveHeterogeneousAgentCommand('trae', options.command);- const cwd = options.cwd || process.cwd();- assertSpawnableWorkingDirectory(cwd);- const command =- isPathLikeCommand(requestedCommand) && !path.isAbsolute(requestedCommand)- ? path.resolve(cwd, requestedCommand)- : requestedCommand;- const childEnv = { ...process.env, ...options.env };- const { detectHeterogeneousCliCommand } = await import('./resolveCliCommand');- const commandStatus = await detectHeterogeneousCliCommand('trae', command, childEnv);- if (!commandStatus.available || !commandStatus.path) {- throw new Error(`TRAE command does not expose the required ACP runtime: ${requestedCommand}`);- }-- const prompt = await buildTraeAcpPrompt(options.prompt, options.inputOptions);- const bridge = createAcpSpawnBridge();- const session = new TraeAcpSession({- args: options.extraArgs ?? [],- clientVersion: '1.0.0',- commandPath: commandStatus.path,- cwd,- detached: options.detached,- env: {- ...childEnv,- ...(commandStatus.resolvedPathEnv ? { PATH: commandStatus.resolvedPathEnv } : {}),- },- initialModel: options.initialModel,- onEvents: bridge.onEvents,- onRawMessage: teeAcpRawStdout(options.onRawStdout),- onRuntimeStatus: () => {},- onSessionId: () => {},- onStderr: bridge.onStderr,- operationId: options.operationId,- prompt,- resumeSessionId: options.resumeSessionId,- sessionId: options.operationId,- });- return createAcpSpawnHandle(bridge, session, () => session.nativeSessionId);-};+export { spawnTraeAcpAgent } from './acpSpawnAgent';diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 6875b77caa7..26fd17a1b88 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -16,6 +16,7 @@ import { toast } from '@lobehub/ui';import { t } from 'i18next';import { type StateCreator } from 'zustand';+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { MESSAGE_CANCEL_FLAT } from '@/const/index';import { saveDraft } from '@/features/ChatInput/draftStorage';import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';@@ -263,9 +264,8 @@ export const runHeterogeneousFromExistingMessage = async (parentOperationId: string;prompt: string;/**- * Replay the topic's on-disk CLI transcript into this row instead of- * spawning the CLI (desktop restart recovery). The saved session id must- * resolve, or there is nothing to read.+ * Replay the topic's on-disk CLI transcript into this row instead of spawning the CLI+ * (desktop restart recovery). The saved session id must resolve, or there is nothing to read.*/replayTranscript?: boolean;/** Claude profile root the interrupted run's transcript was written under. */@@ -274,6 +274,7 @@ export const runHeterogeneousFromExistingMessage = async (replayTranscriptStartedAt?: string;/** Topic row when the caller already holds it (not necessarily in the paginated store). */topic?: ChatTopic;+ workspaceId?: string | null; // where the caller's flow started; omitted = read now},): Promise<{assistantMessageId: string;@@ -296,7 +297,7 @@ export const runHeterogeneousFromExistingMessage = async (} = params;const agentId = context.agentId;if (!agentId) throw new Error('agentId is required for heterogeneous agent');-+ const workspaceId = 'workspaceId' in params ? params.workspaceId : getActiveWorkspaceId();await ensureEffectiveAgencyAccess(agentId);const { cwdChanged, reason, resumeBindingKey, resumeSessionId, workingDirectory } =resolveHeteroRunContext(chatStore, context, agentId, topicOverride);@@ -329,12 +330,10 @@ export const runHeterogeneousFromExistingMessage = async (topicId: context.topicId ?? undefined,});- // Pull the new row into the store so the loading bubble is visible while- // the executor runs (the executor only dispatches updates, not creates).- // Scoped to THIS context: restart recovery runs this for a topic the user- // may not be looking at, and an unscoped refresh would hit the active topic- // instead β leaving the new row out of the store, so every step the executor- // chains under it renders as an orphan group.+ // Pull the new row into the store so the loading bubble shows while the executor+ // runs (it only dispatches updates, not creates). Scoped to THIS context: restart+ // recovery runs this for a topic the user may not be looking at, and an unscoped+ // refresh would leave the new row out, orphaning every step chained under it.await chatStore.refreshMessages(context);const { operationId: heteroOpId } = chatStore.startOperation({@@ -365,6 +364,7 @@ export const runHeterogeneousFromExistingMessage = async (resumeBindingKey,resumeSessionId,workingDirectory,+ workspaceId,});return {diff --git a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.tsindex 095a3cc8f9a..ebec967aefd 100644--- a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts+++ b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts@@ -69,8 +69,11 @@ vi.mock('@/store/chat', () => ({useChatStore: { getState: () => chatStore },}));+const { mockActiveWorkspaceId } = vi.hoisted(() => ({+ mockActiveWorkspaceId: vi.fn((): string | null => 'ws-1'),+}));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({- getActiveWorkspaceId: () => 'ws-1',+ getActiveWorkspaceId: () => mockActiveWorkspaceId(),}));vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));@@ -105,6 +108,7 @@ const messages = [describe('recoverInterruptedHeteroRuns', () => {beforeEach(() => {vi.clearAllMocks();+ mockActiveWorkspaceId.mockReturnValue('ws-1');agentState.agentMap = {};mockListInterruptedRuns.mockResolvedValue([run]);mockGetTopicDetail.mockResolvedValue(topic);@@ -142,6 +146,25 @@ describe('recoverInterruptedHeteroRuns', () => {});});+ it('replays and resumes in the workspace the ledger was read for, not the one navigated to', async () => {+ // The user switches workspace while recovery awaits; the run still belongs to ws-1.+ mockListInterruptedRuns.mockImplementation(async () => {+ mockActiveWorkspaceId.mockReturnValue('ws-2');+ return [run];+ });+ mockRunHetero+ .mockResolvedValueOnce({ assistantMessageId: 'a-new', replayComplete: false })+ .mockResolvedValueOnce({ assistantMessageId: 'a-cont' });++ await recoverInterruptedHeteroRuns();++ expect(mockRunHetero).toHaveBeenCalledTimes(2);+ expect(mockRunHetero.mock.calls.map(([, params]) => params.workspaceId)).toEqual([+ 'ws-1',+ 'ws-1',+ ]);+ });+it('does nothing when the ledger is empty', async () => {mockListInterruptedRuns.mockResolvedValue([]);diff --git a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.tsindex 21bd8fa54e6..e07cf1637c8 100644--- a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts+++ b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts@@ -141,7 +141,11 @@ const ensureAgentLoaded = async (agentId: string): Promise<void> => {);};-const recoverRun = async (run: InterruptedRun): Promise<RestartRecoveryResult> => {+const recoverRun = async (+ run: InterruptedRun,+ /** The workspace the ledger was read for; navigation may move on during recovery. */+ workspaceId: string | null,+): Promise<RestartRecoveryResult> => {const { agentId, topicId } = run;if (!agentId || !topicId) return { outcome: 'skipped', reason: 'missing-context', topicId };@@ -367,6 +371,7 @@ const recoverRun = async (run: InterruptedRun): Promise<RestartRecoveryResult> =replayTranscriptConfigDir: run.configDir,replayTranscriptStartedAt: run.startedAt,topic: topic as ChatTopic,+ workspaceId,});if (replayComplete === true) {@@ -393,6 +398,7 @@ const recoverRun = async (run: InterruptedRun): Promise<RestartRecoveryResult> =parentOperationId: operationId,prompt: HETERO_RESTART_CONTINUE_PROMPT,topic: topic as ChatTopic,+ workspaceId,});// The executor persists a terminal error rather than throwing, so the call// resolving is not success. Reporting `resumed` here would tell the user a@@ -432,9 +438,12 @@ export const recoverInterruptedHeteroRuns = async (): Promise<RestartRecoveryRes// through both, so a run recorded elsewhere stays on the ledger until the// launch that owns it. Personal space has no workspace, which is why the// account has to be part of the key.+ // Snapshot once: every recovered run belongs to this workspace, even if the user+ // navigates elsewhere during the awaits that follow.+ const workspaceId = getActiveWorkspaceId();const runs = (await heterogeneousAgentService.listInterruptedRuns({userId: userProfileSelectors.userId(getUserStoreState()),- workspaceId: getActiveWorkspaceId() ?? undefined,+ workspaceId: workspaceId ?? undefined,})) as InterruptedRun[];if (!runs?.length) return [];@@ -460,7 +469,7 @@ export const recoverInterruptedHeteroRuns = async (): Promise<RestartRecoveryResconst results: RestartRecoveryResult[] = [];for (const run of [...byTopic.values(), ...unkeyed]) {try {- results.push(await recoverRun(run));+ results.push(await recoverRun(run, workspaceId));// Recovery reached an outcome, so the ledger entry has done its job.// It is only released here: main hands entries over as CLAIMS, which is// what lets a crash in the middle of all this be retried at next launch.diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex fbfc49941ad..12b92747a9a 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -701,7 +701,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {}),],{- params: { heterogeneousProvider: provider, operationId },+ params: { heterogeneousProvider: provider, operationId, workspaceId: 'ws-1' },store: createMockStore({ topicDataMap: {} }),},);@@ -713,12 +713,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {LOBEHUB_AGENT_ID: 'agent-1',...(operationId ? { LOBEHUB_OPERATION_ID: operationId } : {}),LOBEHUB_TOPIC_ID: 'topic-1',+ LOBEHUB_WORKSPACE_ID: 'ws-1', // the caller's captured workspace, not live navigation})),);- expect(mockSendPrompt.mock.calls.map(([params]) => params.operationId)).toEqual([- 'op-1',- 'op-2',- ]);+ const sent = mockSendPrompt.mock.calls.map(([p]) => [p.operationId, p.workspaceId]);+ expect(sent.flat()).toEqual(['op-1', 'ws-1', 'op-2', 'ws-1']);},);diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 0c48f11c01d..ad870c327ad 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -30,6 +30,7 @@ import { generateEntityId, nanoid } from '@lobechat/utils';import { toast } from '@lobehub/ui';import { t } from 'i18next';+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { type ChatInputEditor } from '@/features/ChatInput';import { saveDraft } from '@/features/ChatInput/draftStorage';import {@@ -348,15 +349,13 @@ export class ConversationLifecycleActionImpl {let detachCallerAbort = () => {};let hasNotifiedMessageAccepted = false;let sendOperationId: string | undefined = undefined;- // Where the user was when they hit send. This send's continuations adopt the- // topic it creates only while the conversation is still here β the awaited- // preflight (access check, snapshots, topic resolution) is long enough for- // the user to open another topic, and following them with a switchTopic- // would yank both the message list and the URL back (see the- // `onlyIfActiveTopicIn` guards below). The agent and group are pinned too:- // two blank views share `activeTopicId === null`, so the topic guard alone- // cannot tell "still on the origin blank view" from "moved to another- // agent's/group's blank view".+ // Where the user was when they hit send. Continuations adopt the topic this send+ // creates only while the conversation is still here β the awaited preflight (access+ // check, snapshots, topic resolution) is long enough to open another topic, and a+ // switchTopic would yank the message list and URL back (`onlyIfActiveTopicIn`+ // below). Agent and group are pinned too: two blank views share+ // `activeTopicId === null`. The workspace scopes the agent CLI run it may start.+ const sendOriginWorkspaceId = getActiveWorkspaceId();const sendOriginActiveTopicId = this.#get().activeTopicId || null;const sendOriginActiveAgentId = this.#get().activeAgentId ?? null;const sendOriginActiveGroupId = this.#get().activeGroupId ?? null;@@ -1829,6 +1828,7 @@ export class ConversationLifecycleActionImpl {resumeSessionId,workingDirectory,workingDirectoryConfig,+ workspaceId: sendOriginWorkspaceId,});if (directMentionThreadId) {diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex b681919cf1d..2569632d3c1 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -260,6 +260,7 @@ export interface HeterogeneousAgentExecutorParams {resumeSessionId?: string;workingDirectory?: string;workingDirectoryConfig?: WorkingDirConfig;+ workspaceId?: string | null; // workspace the run started in (null = personal)}export interface HeterogeneousAgentExecutionOutcome {@@ -524,6 +525,8 @@ export const executeHeterogeneousAgent = async (workingDirectory,workingDirectoryConfig,} = params;+ // Navigation can move to another workspace during the awaits below.+ const workspaceId = 'workspaceId' in params ? params.workspaceId : getActiveWorkspaceId();let outcome: HeterogeneousAgentExecutionOutcome | undefined;/** Set by `persistTerminalError`; surfaced on the outcome, see its doc. */let terminalErrorPersisted = false;@@ -538,21 +541,18 @@ export const executeHeterogeneousAgent = async (? heterogeneousProvider.apiConfig.model.trim() || undefined: undefined;- // Which real provider account this run consumes, resolved once after spawn- // from the FINAL env (so an agent-env override is attributed correctly, not- // the routed choice). Read by the per-turn usageβledger hook below.+ // The real provider account this run consumes, resolved once after spawn from the+ // FINAL env (an agent-env override, not the routed choice). Read by the ledger hook.let runExternalAccountId: string | undefined;- // Settles when that identity read finishes, one way or another. Ledger rows- // are permanent, so a turn must never be submitted before this settles β an- // early unattributed row is one the later assignment cannot repair.+ // Settles when that identity read finishes. Ledger rows are permanent, so no turn is+ // submitted before this settles β a later assignment cannot repair an unattributed row.let runIdentitySettled: Promise<unknown> = Promise.resolve();- // Usage ledger: one turn's spend, attributed to the account the run is on β- // the "our own cost" half calibration crosses with the provider's utilization- // meter. Main-agent AND subagent turns both route here: a CC Task/subagent- // burns the same subscription as its parent, so skipping it would understate- // the account and skew calibration high. Fire-and-forget: accounting must- // never stall or fail the run, and the server dedupes by message id.+ // Usage ledger: one turn's spend, attributed to the run's account β the "our own cost"+ // half calibration crosses with the provider's utilization meter. Main-agent AND subagent+ // turns route here: a CC Task/subagent burns its parent's subscription, so skipping it+ // would understate the account and skew calibration high. Fire-and-forget: accounting+ // must never stall or fail the run, and the server dedupes by message id.const recordQuotaLedgerUsage = (intent: {messageId: string;model?: string;@@ -1163,7 +1163,7 @@ export const executeHeterogeneousAgent = async ({ ns: 'chat' },),);- await executeHeterogeneousAgent(get, { ...params, resumeSessionId: undefined });+ await executeHeterogeneousAgent(get, { ...params, resumeSessionId: undefined, workspaceId });})();return true;@@ -2009,15 +2009,15 @@ export const executeHeterogeneousAgent = async (: await resolveQuotaAccountSpawnPlan(context.agentId, adapterType);const sessionEnv = {- // Tell the CLI which LobeHub conversation it is running inside. The child- // (and every subprocess it spawns, e.g. `lh`) inherits these, so a tool- // running under the agent can attribute its output back to this topic- // without the agent having to pass ids it can't see. User-configured env- // wins β this is provenance, never an override the user can't escape.+ // Tell the CLI which LobeHub conversation and workspace it runs inside.+ // Every subprocess it spawns (e.g. `lh`) inherits these, so its output+ // lands in this topic and workspace without ids the agent can't see.+ // User-configured env wins β provenance, never an inescapable override....buildLobeHubSessionEnv({agentId: context.agentId,operationId,topicId: context.topicId,+ workspaceId,}),...quotaAccountPlan.env,// The agent's own env is the most specific choice and keeps winning β@@ -2670,7 +2670,7 @@ export const executeHeterogeneousAgent = async (assistantMessageId,imageList,userId: userProfileSelectors.userId(getUserStoreState()),- workspaceId: getActiveWorkspaceId() ?? undefined,+ workspaceId: workspaceId ?? undefined,operationId,// `/goal` travels as system-context instructions; the CLI gets only the// request so its own `/goal` command does not take the message over.diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.test.tsindex 035d72eea7d..a50f391ca78 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.test.ts@@ -21,6 +21,18 @@ describe('buildLobeHubSessionEnv', () => {).toEqual({ LOBEHUB_AGENT_ID: 'agt_1' });});+ it('scopes the child to the workspace the topic lives in', () => {+ // Without it `lh` falls back to personal scope and a workspace goal reads+ // as "Goal not found".+ expect(+ buildLobeHubSessionEnv({ operationId: 'op_1', topicId: 'tpc_1', workspaceId: 'ws_1' }),+ ).toEqual({+ LOBEHUB_OPERATION_ID: 'op_1',+ LOBEHUB_TOPIC_ID: 'tpc_1',+ LOBEHUB_WORKSPACE_ID: 'ws_1',+ });+ });+it('is empty when the run carries no conversation at all', () => {expect(buildLobeHubSessionEnv({})).toEqual({});});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.tsindex 55249709583..d25c767700c 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.ts@@ -10,12 +10,15 @@* back to this topic without the agent having to pass ids it cannot see.** Read by `lh acceptance run ingest`, which stamps them onto the report's- * `metadata.origin`.+ * `metadata.origin`. The workspace id scopes every `lh` call to the workspace+ * the topic lives in; without it the CLI falls back to personal scope and a+ * workspace goal, task or topic reads as "not found".*/export interface LobeHubSessionEnvIds {agentId?: string | null;operationId?: string | null;topicId?: string | null;+ workspaceId?: string | null;}/** Only the ids that actually resolved β never an env var set to "undefined". */@@ -23,12 +26,14 @@ export const buildLobeHubSessionEnv = ({agentId,operationId,topicId,+ workspaceId,}: LobeHubSessionEnvIds): Record<string, string> => {const env: Record<string, string> = {};if (agentId) env.LOBEHUB_AGENT_ID = agentId;if (operationId) env.LOBEHUB_OPERATION_ID = operationId;if (topicId) env.LOBEHUB_TOPIC_ID = topicId;+ if (workspaceId) env.LOBEHUB_WORKSPACE_ID = workspaceId;return env;};