Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Add the team configuration option

Jakub Novak4fdecb5ed1d6
diff --git a/packages/cli/src/api.ts b/packages/cli/src/api.ts
index b080dae6c..0bed5aa02 100644
--- a/packages/cli/src/api.ts
+++ b/packages/cli/src/api.ts
@@ -37,6 +37,15 @@ export function ensureAPIKey() {
}
}
+export function ensureUserConfig() {
+ const userConfig = getUserConfig()
+ if (!userConfig) {
+ console.error('No user config found, run `e2b auth login` to log in first.')
+ process.exit(1)
+ }
+ return userConfig
+}
+
export function ensureAccessToken() {
// If accessToken is not already set (either from env var or from user config), try to get it from config file
if (!accessToken) {
diff --git a/packages/cli/src/commands/auth/configure.ts b/packages/cli/src/commands/auth/configure.ts
new file mode 100644
index 000000000..6c7fa4327
--- /dev/null
+++ b/packages/cli/src/commands/auth/configure.ts
@@ -0,0 +1,57 @@
+import * as commander from 'commander'
+import * as fs from 'fs'
+import * as chalk from 'chalk'
+import * as e2b from 'e2b'
+import * as path from 'path'
+
+import { USER_CONFIG_PATH } from 'src/user'
+import { client, ensureAccessToken, ensureUserConfig } from 'src/api'
+import { asFormattedTeam } from '../../utils/format'
+
+const getTeams = e2b.withAccessToken(client.api.path('/teams').method('get').create())
+
+export const configureCommand = new commander.Command('configure')
+ .description('configure user')
+ .action(async () => {
+ const inquirer = await import('inquirer')
+
+ console.log('Configuring user...\n')
+
+ if (!fs.existsSync(USER_CONFIG_PATH)) {
+ console.log('No user config found, run `e2b auth login` to log in first.')
+ return
+ }
+
+ const userConfig = ensureUserConfig()
+ const accessToken = ensureAccessToken()
+ const res = await getTeams(accessToken, {})
+ if (!res.ok) {
+ const error: e2b.paths['/teams']['get']['responses']['500']['content']['application/json'] = res.data as any
+
+ throw new Error(
+ `Error getting user teams: ${res.statusText}, ${error.message ?? 'no message'
+ }`,
+ )
+ }
+
+ const team = (await inquirer.default.prompt([
+ {
+ name: 'team',
+ message: chalk.default.underline('Select team'),
+ type: 'list',
+ pageSize: 50,
+ choices: res.data.map(team => ({
+ name: asFormattedTeam(team),
+ value: team,
+ })),
+ },
+ ]))['team']
+
+ userConfig.teamName = team.name
+ userConfig.teamId = team.teamID
+ userConfig.teamApiKey = team.apiKey
+ fs.mkdirSync(path.dirname(USER_CONFIG_PATH), {recursive: true})
+ fs.writeFileSync(USER_CONFIG_PATH, JSON.stringify(userConfig, null, 2))
+
+ console.log(`Team ${asFormattedTeam(team)} selected.\n`)
+ })
diff --git a/packages/cli/src/commands/auth/index.ts b/packages/cli/src/commands/auth/index.ts
index 4931dd450..755fcdaef 100644
--- a/packages/cli/src/commands/auth/index.ts
+++ b/packages/cli/src/commands/auth/index.ts
@@ -2,9 +2,11 @@ import * as commander from 'commander'
import { loginCommand } from './login'
import { logoutCommand } from './logout'
import { infoCommand } from './info'
+import { configureCommand } from './configure'
export const authCommand = new commander.Command('auth').description('authentication commands')
.addCommand(loginCommand)
.addCommand(logoutCommand)
.addCommand(infoCommand)
+ .addCommand(configureCommand)
diff --git a/packages/cli/src/commands/auth/info.ts b/packages/cli/src/commands/auth/info.ts
index 7aae0d76d..a99a3a5d5 100644
--- a/packages/cli/src/commands/auth/info.ts
+++ b/packages/cli/src/commands/auth/info.ts
@@ -1,7 +1,7 @@
import * as commander from 'commander'
import { getUserConfig } from 'src/user'
-import { asBold, asFormattedError } from 'src/utils/format'
+import { asFormattedConfig, asFormattedError} from 'src/utils/format'
export const infoCommand = new commander.Command('info')
.description('get information about the current user')
@@ -18,6 +18,6 @@ export const infoCommand = new commander.Command('info')
return
}
- console.log(`Logged in as ${asBold(userConfig.email)}`)
+ console.log(asFormattedConfig(userConfig))
process.exit(0)
})
diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.ts
index 06e86fe1b..7b7191e4a 100644
--- a/packages/cli/src/commands/auth/login.ts
+++ b/packages/cli/src/commands/auth/login.ts
@@ -4,10 +4,14 @@ import * as fs from 'fs'
import * as http from 'http'
import * as open from 'open'
import * as path from 'path'
+import * as e2b from 'e2b'
import { pkg } from 'src'
import { DOCS_BASE, getUserConfig, USER_CONFIG_PATH, UserConfig } from 'src/user'
-import { asBold, asFormattedError } from 'src/utils/format'
+import { asBold, asFormattedConfig, asFormattedError } from 'src/utils/format'
+import { client, ensureAccessToken } from 'src/api'
+
+const getTeams = e2b.withAccessToken(client.api.path('/teams').method('get').create())
export const loginCommand = new commander.Command('login')
.description('log in to CLI')
@@ -20,22 +24,44 @@ export const loginCommand = new commander.Command('login')
}
if (userConfig) {
console.log(
- `Already logged in as ${asBold(
- userConfig.email,
- )}, if you want to login as a different user, logout first by running 'e2b auth logout'.`,
+ `\nAlready logged in. ${asFormattedConfig(userConfig)}.\n\nIf you want to log in as a different user, log out first by running 'e2b auth logout'.\nTo change the team, run 'e2b auth configure'.\n`,
)
return
} else if (!userConfig) {
- console.log('Attempting to login...')
+ console.log('Attempting to log in...')
userConfig = await signInWithBrowser()
if (!userConfig) {
console.info('Login aborted')
return
}
- fs.mkdirSync(path.dirname(USER_CONFIG_PATH), { recursive: true })
+
+ const accessToken = ensureAccessToken()
+ const res = await getTeams(accessToken, {})
+ if (!res.ok) {
+ const error: e2b.paths['/teams']['get']['responses']['500']['content']['application/json'] = res.data as any
+
+ throw new Error(
+ `Error getting user teams: ${res.statusText}, ${error.message ?? 'no message'
+ }`,
+ )
+ }
+
+ const defaultTeam = res.data.find((team) => team.isDefault)
+ if (!defaultTeam) {
+ console.error(asFormattedError('No default team found, please contact support'))
+ process.exit(1)
+ }
+
+ userConfig.teamName = defaultTeam.name
+ userConfig.teamId = defaultTeam.teamID
+ userConfig.teamApiKey = defaultTeam.apiKey
+ fs.mkdirSync(path.dirname(USER_CONFIG_PATH), {recursive: true})
fs.writeFileSync(USER_CONFIG_PATH, JSON.stringify(userConfig, null, 2))
}
- console.log(`Logged in as ${asBold(userConfig.email)}`)
+
+
+
+ console.log(`Logged in as ${asBold(userConfig.email)} with default team ${asBold(userConfig.teamName)}`)
process.exit(0)
})
diff --git a/packages/cli/src/commands/sandbox/list.ts b/packages/cli/src/commands/sandbox/list.ts
index 22ba18ad8..32a304c90 100644
--- a/packages/cli/src/commands/sandbox/list.ts
+++ b/packages/cli/src/commands/sandbox/list.ts
@@ -50,7 +50,7 @@ export const listCommand = new commander.Command('list')
export async function listSandboxes({
apiKey,
-}: { apiKey: string }): Promise<e2b.components['schemas']['RunningSandboxes'][]> {
+}: { apiKey: string }): Promise<e2b.components['schemas']['RunningSandbox'][]> {
const response = await listRunningSandboxes(apiKey, {})
return response.data
}
diff --git a/packages/cli/src/commands/template/build.ts b/packages/cli/src/commands/template/build.ts
index 7b6837b24..a20fcb945 100644
--- a/packages/cli/src/commands/template/build.ts
+++ b/packages/cli/src/commands/template/build.ts
@@ -19,7 +19,7 @@ import {
asTypescript,
withDelimiter,
} from 'src/utils/format'
-import { configOption, pathOption } from 'src/options'
+import { configOption, pathOption, teamOption } from 'src/options'
import {
defaultDockerfileName,
fallbackDockerfileName,
@@ -88,10 +88,7 @@ export const buildCommand = new commander.Command('build')
'-c, --cmd <start-command>',
'specify command that will be executed when the sandbox is started.',
)
- .option(
- '-t, --team <team-id>',
- 'specify the team ID that the sandbox template will be associated with. You can find it in the team settings in the E2B dashboard.',
- )
+ .addOption(teamOption)
.addOption(configOption)
.option(
'--cpu-count <cpu-count>',
@@ -116,7 +113,7 @@ export const buildCommand = new commander.Command('build')
dockerfile?: string
name?: string
cmd?: string
- team?: string
+ teamID?: string
config?: string
cpuCount?: number
memoryMb?: number
@@ -157,7 +154,7 @@ export const buildCommand = new commander.Command('build')
let startCmd = opts.cmd
let cpuCount = opts.cpuCount
let memoryMB = opts.memoryMb
- let teamID = opts.team
+ let teamID = opts.teamID
const root = getRoot(opts.path)
const configPath = getConfigPath(root, opts.config)
@@ -185,7 +182,7 @@ export const buildCommand = new commander.Command('build')
startCmd = opts.cmd || config.start_cmd
cpuCount = opts.cpuCount || config.cpu_count
memoryMB = opts.memoryMb || config.memory_mb
- teamID = opts.team || config.team_id
+ teamID = opts.teamID || config.team_id
}
if (config && templateID && config.template_id !== templateID) {
@@ -279,7 +276,7 @@ export const buildCommand = new commander.Command('build')
)
} catch (err: any) {
console.error(
- 'Docker login failed. Please try to login with `e2b auth login` and try again.',
+ 'Docker login failed. Please try to log in with `e2b auth login` and try again.',
)
process.exit(1)
}
diff --git a/packages/cli/src/commands/template/delete.ts b/packages/cli/src/commands/template/delete.ts
index 81333396d..835627c5b 100644
--- a/packages/cli/src/commands/template/delete.ts
+++ b/packages/cli/src/commands/template/delete.ts
@@ -3,7 +3,7 @@ import * as chalk from 'chalk'
import * as e2b from 'e2b'
import * as fs from 'fs'
-import { ensureAccessToken } from 'src/api'
+import { ensureAccessToken, ensureUserConfig } from 'src/api'
import {
asBold,
@@ -12,7 +12,7 @@ import {
asLocal,
asLocalRelative,
} from 'src/utils/format'
-import { configOption, pathOption, selectMultipleOption } from 'src/options'
+import { configOption, pathOption, selectMultipleOption, teamOption } from 'src/options'
import {
E2BConfig,
configName,
@@ -43,6 +43,7 @@ export const deleteCommand = new commander.Command('delete')
.addOption(pathOption)
.addOption(configOption)
.addOption(selectMultipleOption)
+ .addOption(teamOption)
.alias('dl')
.option('-y, --yes', 'skip manual delete confirmation')
.action(
@@ -53,11 +54,12 @@ export const deleteCommand = new commander.Command('delete')
config?: string
yes?: boolean
select?: boolean
+ teamID?: string
},
) => {
try {
+ const userConfig = ensureUserConfig()
const accessToken = ensureAccessToken()
-
const root = getRoot(opts.path)
const templates: (Pick<E2BConfig, 'template_id'> & {
@@ -69,7 +71,10 @@ export const deleteCommand = new commander.Command('delete')
template_id: template,
})
} else if (opts.select) {
- const allTemplates = await listSandboxTemplates({ accessToken })
+ const allTemplates = await listSandboxTemplates({
+ accessToken: accessToken,
+ teamID: opts.teamID || userConfig.teamId || userConfig.defaultTeamId! // default team ID is here for backwards compatibility
+ })
const selectedTemplates = await getPromptTemplates(
allTemplates,
'Select sandbox templates to delete',
diff --git a/packages/cli/src/commands/template/list.ts b/packages/cli/src/commands/template/list.ts
index bd41896e2..6bfef30a5 100644
--- a/packages/cli/src/commands/template/list.ts
+++ b/packages/cli/src/commands/template/list.ts
@@ -2,10 +2,10 @@ import * as tablePrinter from 'console-table-printer'
import * as commander from 'commander'
import * as e2b from 'e2b'
-import { ensureAccessToken } from 'src/api'
import { listAliases } from '../../utils/format'
import { sortTemplatesAliases } from 'src/utils/templateSort'
-import { client } from 'src/api'
+import { client, ensureAccessToken, ensureUserConfig } from 'src/api'
+import { teamOption } from '../../options'
const listTemplates = e2b.withAccessToken(
client.api.path('/templates').method('get').create(),
@@ -14,12 +14,21 @@ const listTemplates = e2b.withAccessToken(
export const listCommand = new commander.Command('list')
.description('list sandbox templates')
.alias('ls')
- .action(async () => {
+ .addOption(teamOption)
+ .action(async (
+ opts: {
+ teamID: string
+ },
+ ) => {
try {
+ const userConfig = ensureUserConfig()
const accessToken = ensureAccessToken()
process.stdout.write('\n')
- const templates = await listSandboxTemplates({ accessToken })
+ const templates = await listSandboxTemplates({
+ accessToken: accessToken,
+ teamID: opts.teamID || userConfig.teamId || userConfig.defaultTeamId! // default team ID is here for backwards compatibility
+ })
for (const template of templates) {
sortTemplatesAliases(template.aliases)
@@ -53,8 +62,8 @@ export const listCommand = new commander.Command('list')
})
export async function listSandboxTemplates({
- accessToken,
-}: { accessToken: string }): Promise<e2b.components['schemas']['Template'][]> {
- const templates = await listTemplates(accessToken, {})
+ accessToken, teamID
+}: { accessToken: string, teamID: string }): Promise<e2b.components['schemas']['Template'][]> {
+ const templates = await listTemplates(accessToken, {teamID})
return templates.data
}
diff --git a/packages/cli/src/options.ts b/packages/cli/src/options.ts
index ef1de2905..bce8f5775 100644
--- a/packages/cli/src/options.ts
+++ b/packages/cli/src/options.ts
@@ -23,3 +23,8 @@ export const selectMultipleOption = new commander.Option(
'-s, --select',
'select sandbox template from interactive list',
)
+
+export const teamOption = new commander.Option(
+ '-t, --team <team-id>',
+ 'specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team).',
+ )
diff --git a/packages/cli/src/user.ts b/packages/cli/src/user.ts
index 26d715d1f..d90580972 100644
--- a/packages/cli/src/user.ts
+++ b/packages/cli/src/user.ts
@@ -5,8 +5,11 @@ import * as fs from 'fs'
export interface UserConfig {
email: string
accessToken: string
- defaultTeamApiKey: string
- defaultTeamId: string
+ defaultTeamApiKey?: string
+ defaultTeamId?: string
+ teamName: string
+ teamId: string
+ teamApiKey: string
}
export const USER_CONFIG_PATH = path.join(os.homedir(), '.e2b', 'config.json') // TODO: Keep in Keychain
diff --git a/packages/cli/src/utils/format.ts b/packages/cli/src/utils/format.ts
index 81b858302..509343840 100644
--- a/packages/cli/src/utils/format.ts
+++ b/packages/cli/src/utils/format.ts
@@ -4,9 +4,28 @@ import * as highlight from 'cli-highlight'
import * as boxen from 'boxen'
import { cwdRelative } from './filesystem'
+import { UserConfig } from '../user'
export const primaryColor = '#FFB766'
+export function asFormattedConfig(
+ config: UserConfig,
+) {
+ const email = asBold(config.email)
+ const team = config.teamName ? asBold(config.teamName) : asRed('Log out and log in to get team name')
+ const teamId = asBold(config.teamId || config.defaultTeamId!)
+ return `You are logged in as ${email},\nSelected team: ${team} (${teamId})`
+}
+
+export function asFormattedTeam(
+ team: e2b.components['schemas']['Team'],
+) {
+ const name = asBold(team.name)
+ const id = asBold(team.teamID)
+ const isDefault = team.isDefault ? asPrimary(' (default team)') : ''
+ return `${name} (${id})${isDefault}`
+}
+
export function asFormattedSandboxTemplate(
template: Pick<e2b.components['schemas']['Template'], 'templateID' | 'aliases'>,
configLocalPath?: string,
@@ -23,6 +42,11 @@ export function asFormattedSandboxTemplate(
return `${id}${name}${configPath}`.trim()
}
+
+export function asRed(text: string) {
+ return chalk.default.redBright(text)
+}
+
export function asFormattedError(text: string | undefined, err?: any) {
return chalk.default.redBright(
`${text ? `${text} \n` : ''}${err ? err.stack : ''}\n`,
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index b69500ff5..e2b165163 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -163,6 +163,11 @@ export interface paths {
"/templates": {
/** List all templates */
get: {
+ parameters: {
+ query: {
+ teamID?: string;
+ };
+ };
responses: {
/** Successfully returned all templates */
200: {
@@ -173,11 +178,6 @@ export interface paths {
401: components["responses"]["401"];
500: components["responses"]["500"];
};
- requestBody: {
- content: {
- "application/json": components["schemas"]["TemplatesListRequest"];
- };
- };
};
/** Create a new template */
post: {
@@ -384,10 +384,6 @@ export interface components {
cpuCount?: components["schemas"]["CPUCount"];
memoryMB?: components["schemas"]["MemoryMB"];
};
- TemplatesListRequest: {
- /** @description Identifier of the team */
- teamID: string;
- };
TemplateBuild: {
/**
* @description Build logs
diff --git a/spec/openapi.yml b/spec/openapi.yml
index e2963f994..4194a443f 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -82,8 +82,8 @@ components:
type: string
description: API key for the team
isDefault:
- type: boolean
- description: Whether the team is the default team
+ type: boolean
+ description: Whether the team is the default team
CPUCount:
type: integer
@@ -247,14 +247,6 @@ components:
memoryMB:
$ref: "#/components/schemas/MemoryMB"
- TemplatesListRequest:
- required:
- - teamID
- properties:
- teamID:
- type: string
- description: Identifier of the team
-
TemplateBuild:
required:
- templateID
@@ -497,13 +489,13 @@ paths:
tags: [templates]
security:
- AccessTokenAuth: []
- requestBody:
- required: false
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/TemplatesListRequest"
-
+ parameters:
+ - in: query
+ required: false
+ name: teamID
+ schema:
+ type: string
+ description: Identifier of the team
responses:
"200":
description: Successfully returned all templates