🤯 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(sandbox): export an environment's variables into every conversation command (#21544)
Lobehub Coderb8485fcef2d0
diff --git a/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts b/apps/server/src/services/sandbox/__tests__/environmentInit.test.tsindex 3623c7ff5ae..bfb8a671c0e 100644--- a/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts+++ b/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts@@ -17,8 +17,10 @@ import {buildSandboxEnvironmentInitCommand,environmentInitRan,environmentInitReport,+ hasEnvironmentInitWork,type SandboxInitialization,toSandboxInitialization,+ withEnvironmentVariables,} from '../environmentInit';const sandbox = { home: '', tmp: '' };@@ -69,6 +71,67 @@ describe('toSandboxInitialization', () => {}),).toBeUndefined();});++ it('keeps an environment that only declares variables, with nothing to apply to the folder', () => {+ const init = toSandboxInitialization({+ configuration: { env: { LOBEHUB_ADMIN_URL: 'https://admin.example.com' } },+ id: 'env_1',+ name: 'lobe-admin',+ });++ expect(init).toEqual({+ env: { LOBEHUB_ADMIN_URL: 'https://admin.example.com' },+ environmentId: 'env_1',+ name: 'lobe-admin',+ sources: [],+ });+ expect(hasEnvironmentInitWork(init!)).toBe(false);+ });+});++describe('withEnvironmentVariables', () => {+ let work: string;++ beforeEach(() => {+ work = mkdtempSync(join(tmpdir(), 'lobe-env-vars-'));+ sandbox.home = work;+ sandbox.tmp = work;+ });++ afterEach(() => {+ rmSync(work, { force: true, recursive: true });+ });++ it('exports the variables into the command and whatever it starts', () => {+ const command = withEnvironmentVariables(+ 'bash -c "printenv LOBEHUB_ADMIN_URL"; echo "$REGION"',+ {+ LOBEHUB_ADMIN_URL: 'https://admin.example.com',+ REGION: 'us',+ },+ );++ expect(run(command, work).stdout).toBe('https://admin.example.com\nus\n');+ });++ it('keeps values literal, quotes and substitutions included', () => {+ const value = `it's $(echo pwned) \`id\` $HOME`;++ expect(+ run(withEnvironmentVariables('printf %s "$TRICKY"', { TRICKY: value }), work).stdout,+ ).toBe(value);+ });++ it('lets the command override a variable for itself', () => {+ expect(+ run(withEnvironmentVariables('REGION=eu; echo "$REGION"', { REGION: 'us' }), work).stdout,+ ).toBe('eu\n');+ });++ it('skips names a shell cannot export and leaves the command alone without variables', () => {+ expect(withEnvironmentVariables('ls', { 'BAD-NAME': 'x' })).toBe('ls');+ expect(withEnvironmentVariables('ls', undefined)).toBe('ls');+ });});describe('buildSandboxEnvironmentInitCommand', () => {diff --git a/apps/server/src/services/sandbox/__tests__/service.test.ts b/apps/server/src/services/sandbox/__tests__/service.test.tsindex 2570ef0ed85..0d3e8004e79 100644--- a/apps/server/src/services/sandbox/__tests__/service.test.ts+++ b/apps/server/src/services/sandbox/__tests__/service.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { FileService } from '@/server/services/file';import type { MarketService } from '@/server/services/market';+import type { SandboxInitialization } from '../environmentInit';import type { SandboxProvider, SandboxProviderKind } from '../types';describe('normalizeSandboxCommandResult', () => {@@ -72,7 +73,7 @@ describe('SandboxMiddlewareService', () => {sources: [{ url: 'https://github.com/octocat/Hello-World' }],};- const serviceWith = async (stdout: string) => {+ const serviceWith = async (stdout: string, initialization: SandboxInitialization = init) => {const { SandboxMiddlewareService: TestSandboxMiddlewareService } = await import('../service');const callTool = vi.fn(async (name: string, params: Record<string, unknown>) =>String(params.command).includes('__lobe_environment_ran')@@ -87,7 +88,7 @@ describe('SandboxMiddlewareService', () => {} satisfies SandboxProvider;const service = new TestSandboxMiddlewareService(provider, {marketService: {} as MarketService,- sandboxInitialization: init,+ sandboxInitialization: initialization,topicId: 'topic-1',userId: 'user-1',});@@ -156,6 +157,57 @@ describe('SandboxMiddlewareService', () => {expect((result.result as { stdout: string }).stdout).toBe('ran runCommand');});++ it("exports the environment's variables into every shell command the conversation runs", async () => {+ const { callTool, service } = await serviceWith('', {+ ...init,+ env: { LOBEHUB_ADMIN_URL: 'https://admin.example.com' },+ });++ await service.callTool('runCommand', { command: 'printenv LOBEHUB_ADMIN_URL' });+ await service.callTool('execScript', { command: 'node admin.js' });+ await service.callTool('runCommand', { background: true, command: 'claude -p hi' });+ await service.callTool('listFiles', { path: '.' });++ const [initCall, ...calls] = callTool.mock.calls;+ expect(String(initCall[1].command)).toContain('__lobe_environment_ran');+ expect(calls.map(([name, params]) => [name, params])).toEqual([+ [+ 'runCommand',+ {+ command:+ "export LOBEHUB_ADMIN_URL='https://admin.example.com'\nprintenv LOBEHUB_ADMIN_URL",+ },+ ],+ [+ 'execScript',+ { command: "export LOBEHUB_ADMIN_URL='https://admin.example.com'\nnode admin.js" },+ ],+ [+ 'runCommand',+ {+ background: true,+ command: "export LOBEHUB_ADMIN_URL='https://admin.example.com'\nclaude -p hi",+ },+ ],+ ['listFiles', { path: '.' }],+ ]);+ });++ it('exports the variables of an environment with nothing to clone or set up, without an initializer', async () => {+ const { callTool, service } = await serviceWith('', {+ env: { REGION: 'us' },+ environmentId: 'env-1',+ name: 'Vars only',+ sources: [],+ });++ await service.callTool('runCommand', { command: 'echo $REGION' });++ expect(callTool.mock.calls).toEqual([+ ['runCommand', { command: "export REGION='us'\necho $REGION" }],+ ]);+ });});it('uploads provider exports through the shared file record flow', async () => {diff --git a/apps/server/src/services/sandbox/environmentInit.ts b/apps/server/src/services/sandbox/environmentInit.tsindex 9797f187398..2e2441a53f8 100644--- a/apps/server/src/services/sandbox/environmentInit.ts+++ b/apps/server/src/services/sandbox/environmentInit.ts@@ -14,7 +14,8 @@ export const SANDBOX_ENVIRONMENT_RAN_LINE = '__lobe_environment_ran';/*** What a working directory is initialized from: an environment's repository- * and setup, and nothing else of it. Nothing is tracked once it has run, in+ * and setup, plus the variables both of them — and every command the+ * conversation runs afterwards — see. Nothing is tracked once it has run, in* the database or in the folder.*/export interface SandboxInitialization {@@ -37,8 +38,9 @@ const ENV_NAME = /^[A-Z_]\w*$/i;/*** The initialization an environment asks for, or `undefined` when it asks for- * nothing — no repository and no setup — so picking an empty definition runs- * nothing.+ * nothing — no repository, no setup and no variables — so picking an empty+ * definition runs nothing. One that only declares variables is kept: they are+ * exported into every command, even with nothing to clone or set up.** Only git sources: a `files` source belongs to the release before folders on* the drive replaced it, and has no meaning in a folder that already is one.@@ -61,18 +63,48 @@ export const toSandboxInitialization = (environment: {: [],);const bootstrapCommand = configuration.bootstrapCommand?.trim() || undefined;- if (sources.length === 0 && !bootstrapCommand) return undefined;+ const env =+ configuration.env && Object.keys(configuration.env).length > 0 ? configuration.env : undefined;+ if (sources.length === 0 && !bootstrapCommand && !env) return undefined;return {environmentId: environment.id,name: environment.name,sources,...(bootstrapCommand && { bootstrapCommand }),- ...(configuration.env &&- Object.keys(configuration.env).length > 0 && { env: configuration.env }),+ ...(env && { env }),};};+/** Whether applying the environment does anything to the folder: a clone or a setup to run. */+export const hasEnvironmentInitWork = (init: SandboxInitialization): boolean =>+ init.sources.length > 0 || !!init.bootstrapCommand;++const toExports = (env: Record<string, string> | undefined): string[] =>+ Object.entries(env ?? {})+ .filter(([key]) => ENV_NAME.test(key))+ .map(([key, value]) => `export ${key}=${shellQuote(value)}`);++/**+ * A conversation's shell command with the environment's variables exported in+ * front of it.+ *+ * Every tool call starts a fresh shell, so the variables are put in front of+ * each command rather than set once: a value exported by the initializer, or+ * by an earlier call, is gone by the next one. In front, so the command can+ * still override one for itself. The command is unchanged when the+ * environment declares none.+ */+export const withEnvironmentVariables = (+ command: string,+ env: Record<string, string> | undefined,+): string => {+ const exports = toExports(env);+ if (exports.length === 0) return command;++ return `${exports.join('\n')}\n${command}`;+};+/** A destination inside the working directory, or `undefined` for a path that would leave it. */const safeDestination = (path: string | undefined): string | undefined => {const value = (path ?? '.').trim() || '.';@@ -97,15 +129,14 @@ const safeDestination = (path: string | undefined): string | undefined => {* so it is not retried on every call either. The record goes with the* sandbox — and so do global installs — so a new sandbox initializes again.*- * The variables are exported in a subshell, so they reach clone and setup and- * not the commands the conversation runs afterwards.+ * The variables are exported in a subshell, so they reach clone and setup+ * here; the commands the conversation runs afterwards get them from+ * {@link withEnvironmentVariables}, not from this shell.*/export const buildSandboxEnvironmentInitCommand = (init: SandboxInitialization): string => {const label = shellQuote(init.name);- const exports = Object.entries(init.env ?? {})- .filter(([key]) => ENV_NAME.test(key))- .map(([key, value]) => `export ${key}=${shellQuote(value)}`);+ const exports = toExports(init.env);const clones = init.sources.map((source, index) => {const destination = safeDestination(source.path);diff --git a/apps/server/src/services/sandbox/service.ts b/apps/server/src/services/sandbox/service.tsindex 2765c6fff7a..659c4533e90 100644--- a/apps/server/src/services/sandbox/service.ts+++ b/apps/server/src/services/sandbox/service.ts@@ -21,7 +21,9 @@ import {buildSandboxEnvironmentInitCommand,environmentInitRan,environmentInitReport,+ hasEnvironmentInitWork,SANDBOX_ENVIRONMENT_INIT_TIMEOUT_MS,+ withEnvironmentVariables,} from './environmentInit';import { isSandboxAccessDeniedError, isSandboxAuthError } from './errors';import type {@@ -68,7 +70,10 @@ export class SandboxMiddlewareService implements SandboxService {if (mimeType) return this.readSandboxImageFile(params.path, mimeType);}- const result = await this.provider.callTool(toolName, params);+ const result = await this.provider.callTool(+ toolName,+ this.applyEnvironmentVariables(toolName, params),+ );// Held until a shell result can carry it: a first call that lists or// reads files has no output to put it in, and dropping it would hide a@@ -80,6 +85,29 @@ export class SandboxMiddlewareService implements SandboxService {return withEnvironmentReport(toolName, result, pending);}+ /**+ * A shell call with the topic's environment variables exported in front of+ * its command, so the conversation's commands — and anything they start,+ * like a coding agent — see what the environment declares, not only its+ * clone and setup. Other tools, and calls without a string command, pass+ * through unchanged.+ */+ private applyEnvironmentVariables(+ toolName: string,+ params: Record<string, unknown>,+ ): Record<string, unknown> {+ const env = this.options.sandboxInitialization?.env;+ if (+ !env ||+ !SHELL_TOOLS.has(toolName) ||+ typeof params.command !== 'string' ||+ !params.command.trim()+ )+ return params;++ return { ...params, command: withEnvironmentVariables(params.command, env) };+ }+/*** Apply the topic's environment to the working directory the first time this* service instance is used: clone its repository and run its setup there.@@ -97,7 +125,9 @@ export class SandboxMiddlewareService implements SandboxService {this.environmentInitialized = true;const init = this.options.sandboxInitialization;- if (!init || !this.provider.capabilities.shell) return;+ // An environment that only declares variables has nothing to apply to the+ // folder: its variables go on each command instead.+ if (!init || !hasEnvironmentInitWork(init) || !this.provider.capabilities.shell) return;try {const result = await this.provider.callTool('runCommand', {diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 8750fcc5762..9fc857b2663 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -671,7 +671,7 @@"environments.form.envCount_other": "{{count}} variables","environments.form.envEmpty": "No variables yet","environments.form.envEmptyHint": "Add one, or paste a whole .env file in the",- "environments.form.envHint": "Non-secret values only — stored as plain text and exported while the repository is cloned and the setup command runs.",+ "environments.form.envHint": "Non-secret values only — stored as plain text and exported while the repository is cloned, while the setup command runs, and into every command the conversation runs.","environments.form.exclude": "Regenerable paths","environments.form.excludeHint": "One per line, relative to the copy. Listing a path says it can be rebuilt, so it is kept apart from your work and may be discarded to reclaim space. Anything named here that cannot be rebuilt is work you can lose.","environments.form.filesDesc": "What this folder is called and what it holds for the agent.",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 00e80cc96ab..667c7319d08 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -671,7 +671,7 @@"environments.form.envCount_other": "{{count}} 个变量","environments.form.envEmpty": "还没有环境变量","environments.form.envEmptyHint": "逐条添加,或整份 .env 粘贴到",- "environments.form.envHint": "仅限非敏感值——以明文保存,在克隆仓库和执行初始化命令时导出。",+ "environments.form.envHint": "仅限非敏感值——以明文保存,在克隆仓库、执行初始化命令以及对话运行的每条命令中导出。","environments.form.exclude": "可再生路径","environments.form.excludeHint": "一行一个,相对于副本。列在这里等于声明它可以重建,于是它会跟你的产出分开存放、并且可能被清理掉。写进来但其实重建不了的东西,就是你可能丢掉的东西。","environments.form.filesDesc": "这个文件夹叫什么、放了哪些给 agent 处理的文件。",diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex db398bb4c84..0525e85cb9d 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -4308,7 +4308,7 @@ When I am ___, I need ___'Runs once in the checkout, with network access, before the conversation starts.','environments.form.env': 'Environment variables','environments.form.envHint':- 'Non-secret values only — stored as plain text and exported while the repository is cloned and the setup command runs.',+ 'Non-secret values only — stored as plain text and exported while the repository is cloned, while the setup command runs, and into every command the conversation runs.','environments.form.addEnv': 'New variable','environments.form.envCount_one': '{{count}} variable','environments.form.envCount_other': '{{count}} variables',