Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Support `Template.aliasExists` for JavaScript and Python SDKs (#1068)

Jiri Svecenyd8ef36d84f69
diff --git a/.changeset/funny-apples-visit.md b/.changeset/funny-apples-visit.md
new file mode 100644
index 000000000..1c4652477
--- /dev/null
+++ b/.changeset/funny-apples-visit.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': minor
+'e2b': minor
+---
+
+Support for Template.aliasExists to check if template alias is available
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index e4a64f899..d11fb8874 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -15,7 +15,7 @@ export interface paths {
get: {
parameters: {
query?: {
- /** @description Metadata query used to filter the sandboxes (e.g. "user=abc&app=prod"). Each key and values must be URL encoded. */
+ /** @description Metadata query used to filter the sandboxes (e.g. 'user=abc&app=prod'). Each key and values must be URL encoded. */
metadata?: string;
};
header?: never;
@@ -878,6 +878,57 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/templates/{templateID}/builds/{buildID}/logs": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /** @description Get template build logs */
+ get: {
+ parameters: {
+ query?: {
+ /** @description Starting timestamp of the logs that should be returned in milliseconds */
+ cursor?: number;
+ direction?: components["schemas"]["LogsDirection"];
+ level?: components["schemas"]["LogLevel"];
+ /** @description Maximum number of logs that should be returned */
+ limit?: number;
+ /** @description Source of the logs that should be returned from */
+ source?: components["schemas"]["LogsSource"];
+ };
+ header?: never;
+ path: {
+ buildID: components["parameters"]["buildID"];
+ templateID: components["parameters"]["templateID"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successfully returned the template build logs */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["TemplateBuildLogsResponse"];
+ };
+ };
+ 401: components["responses"]["401"];
+ 404: components["responses"]["404"];
+ 500: components["responses"]["500"];
+ };
+ };
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/templates/{templateID}/builds/{buildID}/status": {
parameters: {
query?: never;
@@ -890,6 +941,8 @@ export interface paths {
parameters: {
query?: {
level?: components["schemas"]["LogLevel"];
+ /** @description Maximum number of logs that should be returned */
+ limit?: number;
/** @description Index of the starting build log that should be returned with the template */
logsOffset?: number;
};
@@ -967,6 +1020,48 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/templates/aliases/{alias}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /** @description Check if template with given alias exists */
+ get: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ alias: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successfully queried template by alias */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["TemplateAliasResponse"];
+ };
+ };
+ 400: components["responses"]["400"];
+ 403: components["responses"]["403"];
+ 404: components["responses"]["404"];
+ 500: components["responses"]["500"];
+ };
+ };
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/v2/sandboxes": {
parameters: {
query?: never;
@@ -980,7 +1075,7 @@ export interface paths {
query?: {
/** @description Maximum number of items to return per page */
limit?: components["parameters"]["paginationLimit"];
- /** @description Metadata query used to filter the sandboxes (e.g. "user=abc&app=prod"). Each key and values must be URL encoded. */
+ /** @description Metadata query used to filter the sandboxes (e.g. 'user=abc&app=prod'). Each key and values must be URL encoded. */
metadata?: string;
/** @description Cursor to start the list from */
nextToken?: components["parameters"]["paginationNextToken"];
@@ -1151,6 +1246,18 @@ export interface paths {
export type webhooks = Record<string, never>;
export interface components {
schemas: {
+ AdminSandboxKillResult: {
+ /** @description Number of sandboxes that failed to kill */
+ failedCount: number;
+ /** @description Number of sandboxes successfully killed */
+ killedCount: number;
+ };
+ AssignTemplateTagRequest: {
+ /** @description Names of the template */
+ names: string[];
+ /** @description Target template name in 'alias:tag' format */
+ target: string;
+ };
AWSRegistry: {
/** @description AWS Access Key ID for ECR authentication */
awsAccessKeyId: string;
@@ -1341,6 +1448,26 @@ export interface components {
* @enum {string}
*/
LogLevel: "debug" | "info" | "warn" | "error";
+ /**
+ * @description Direction of the logs that should be returned
+ * @enum {string}
+ */
+ LogsDirection: "forward" | "backward";
+ /**
+ * @description Source of the logs that should be returned
+ * @enum {string}
+ */
+ LogsSource: "temporary" | "persistent";
+ MachineInfo: {
+ /** @description CPU architecture of the node */
+ cpuArchitecture: string;
+ /** @description CPU family of the node */
+ cpuFamily: string;
+ /** @description CPU model of the node */
+ cpuModel: string;
+ /** @description CPU model name of the node */
+ cpuModelName: string;
+ };
/** @description Team metric with timestamp */
MaxTeamMetric: {
/**
@@ -1414,6 +1541,7 @@ export interface components {
createSuccesses: number;
/** @description Identifier of the node */
id: string;
+ machineInfo: components["schemas"]["MachineInfo"];
metrics: components["schemas"]["NodeMetrics"];
/**
* @deprecated
@@ -1455,6 +1583,7 @@ export interface components {
createSuccesses: number;
/** @description Identifier of the node */
id: string;
+ machineInfo: components["schemas"]["MachineInfo"];
metrics: components["schemas"]["NodeMetrics"];
/**
* @deprecated
@@ -1787,6 +1916,12 @@ export interface components {
*/
updatedAt: string;
};
+ TemplateAliasResponse: {
+ /** @description Whether the template is public or only accessible by the team */
+ public: boolean;
+ /** @description Identifier of the template */
+ templateID: string;
+ };
TemplateBuild: {
/**
* Format: uuid
@@ -1838,6 +1973,13 @@ export interface components {
/** @description Identifier of the template */
templateID: string;
};
+ TemplateBuildLogsResponse: {
+ /**
+ * @description Build logs structured
+ * @default []
+ */
+ logs: components["schemas"]["BuildLogEntry"][];
+ };
TemplateBuildRequest: {
/** @description Alias of the template */
alias?: string;
@@ -1861,10 +2003,15 @@ export interface components {
teamID?: string;
};
TemplateBuildRequestV3: {
- /** @description Alias of the template */
- alias: string;
+ /**
+ * @deprecated
+ * @description Alias of the template. Deprecated, use names instead.
+ */
+ alias?: string;
cpuCount?: components["schemas"]["CPUCount"];
memoryMB?: components["schemas"]["MemoryMB"];
+ /** @description Names of the template */
+ names?: string[];
/** @description Identifier of the team */
teamID?: string;
};
@@ -1961,6 +2108,15 @@ export interface components {
/** @description Type of the step */
type: string;
};
+ TemplateTag: {
+ /**
+ * Format: uuid
+ * @description Identifier of the build associated with this tag
+ */
+ buildID: string;
+ /** @description Tags of the template */
+ tags: string[];
+ };
TemplateUpdateRequest: {
/** @description Whether the template is public or only accessible by the team */
public?: boolean;
@@ -2066,6 +2222,7 @@ export interface components {
/** @description Cursor to start the list from */
paginationNextToken: string;
sandboxID: string;
+ tag: string;
teamID: string;
templateID: string;
};
diff --git a/packages/js-sdk/src/template/buildApi.ts b/packages/js-sdk/src/template/buildApi.ts
index 505817db1..75d15df0e 100644
--- a/packages/js-sdk/src/template/buildApi.ts
+++ b/packages/js-sdk/src/template/buildApi.ts
@@ -27,6 +27,10 @@ type GetBuildStatusInput = {
logsOffset?: number
}
+type CheckAliasExistsInput = {
+ alias: string
+}
+
export type GetBuildStatusResponse =
paths['/templates/{templateID}/builds/{buildID}/status']['get']['responses']['200']['content']['application/json']
@@ -185,6 +189,38 @@ export async function getBuildStatus(
return buildStatusRes.data
}
+export async function checkAliasExists(
+ client: ApiClient,
+ { alias }: CheckAliasExistsInput
+): Promise<boolean> {
+ const aliasRes = await client.api.GET('/templates/aliases/{alias}', {
+ params: {
+ path: {
+ alias,
+ },
+ },
+ })
+
+ // If we get a NotFound, the alias doesn't exist
+ if (aliasRes.response.status === 404) {
+ return false
+ }
+
+ // If we get a Forbidden, alias exists, but you are not owner
+ if (aliasRes.response.status === 403) {
+ return true
+ }
+
+ // Handle other errors
+ const error = handleApiError(aliasRes, BuildError)
+ if (error) {
+ throw error
+ }
+
+ // If we get Ok with data, you are owner and the alias exists
+ return aliasRes.data !== undefined
+}
+
export async function waitForBuildFinish(
client: ApiClient,
{
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 177ffc131..6f202c100 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -4,6 +4,7 @@ import { ConnectionConfig } from '../connectionConfig'
import { BuildError } from '../errors'
import { runtime } from '../utils'
import {
+ checkAliasExists,
getBuildStatus,
GetBuildStatusResponse,
getFileUploadLink,
@@ -18,6 +19,7 @@ import { parseDockerfile } from './dockerfileParser'
import { LogEntry, LogEntryEnd, LogEntryStart } from './logger'
import { ReadyCmd, waitForFile } from './readycmd'
import {
+ AliasExistsOptions,
BuildInfo,
BuildOptions,
CopyItem,
@@ -122,10 +124,7 @@ export class TemplateBase
options.onBuildLogs?.(new LogEntryStart(new Date(), 'Build started'))
const baseTemplate = template as TemplateBase
- const config = new ConnectionConfig({
- domain: options.domain,
- apiKey: options.apiKey,
- })
+ const config = new ConnectionConfig(options)
const client = new ApiClient(config)
const data = await baseTemplate.build(client, options)
@@ -168,10 +167,7 @@ export class TemplateBase
template: TemplateClass,
options: BuildOptions
): Promise<BuildInfo> {
- const config = new ConnectionConfig({
- domain: options.domain,
- apiKey: options.apiKey,
- })
+ const config = new ConnectionConfig(options)
const client = new ApiClient(config)
return await (template as TemplateBase).build(client, options)
@@ -192,10 +188,7 @@ export class TemplateBase
data: Pick<BuildInfo, 'templateId' | 'buildId'>,
options?: GetBuildStatusOptions
): Promise<GetBuildStatusResponse> {
- const config = new ConnectionConfig({
- domain: options?.domain,
- apiKey: options?.apiKey,
- })
+ const config = new ConnectionConfig(options)
const client = new ApiClient(config)
return await getBuildStatus(client, {
@@ -205,6 +198,31 @@ export class TemplateBase
})
}
+ /**
+ * Check if a template with the given alias exists.
+ *
+ * @param alias Template alias to check
+ * @param options Authentication options
+ * @returns True if the alias exists, false otherwise
+ *
+ * @example
+ * ```ts
+ * const exists = await Template.aliasExists('my-python-env')
+ * if (exists) {
+ * console.log('Template exists!')
+ * }
+ * ```
+ */
+ static async aliasExists(
+ alias: string,
+ options?: AliasExistsOptions
+ ): Promise<boolean> {
+ const config = new ConnectionConfig(options)
+ const client = new ApiClient(config)
+
+ return checkAliasExists(client, { alias })
+ }
+
fromDebianImage(variant: string = 'stable'): TemplateBuilder {
return this.fromImage(`debian:${variant}`)
}
@@ -1070,10 +1088,12 @@ export function Template(options?: TemplateOptions): TemplateFromImage {
Template.build = TemplateBase.build
Template.buildInBackground = TemplateBase.buildInBackground
Template.getBuildStatus = TemplateBase.getBuildStatus
+Template.aliasExists = TemplateBase.aliasExists
Template.toJSON = TemplateBase.toJSON
Template.toDockerfile = TemplateBase.toDockerfile
export type {
+ AliasExistsOptions,
BuildInfo,
BuildOptions,
CopyItem,
diff --git a/packages/js-sdk/src/template/types.ts b/packages/js-sdk/src/template/types.ts
index eb10ca435..bfba96e49 100644
--- a/packages/js-sdk/src/template/types.ts
+++ b/packages/js-sdk/src/template/types.ts
@@ -2,6 +2,7 @@ import { ReadyCmd } from './readycmd'
import type { PathLike } from 'node:fs'
import type { LogEntry } from './logger'
import type { McpServer } from '../sandbox/mcp'
+import { ConnectionOpts } from '../connectionConfig'
/**
* Options for creating a new template.
@@ -47,24 +48,10 @@ export type BasicBuildOptions = {
onBuildLogs?: (logEntry: LogEntry) => void
}
-/**
- * Authentication options for E2B API.
- */
-export type AuthOptions = {
- /**
- * E2B API key for authentication.
- */
- apiKey?: string
- /**
- * Domain of the E2B API.
- */
- domain?: string
-}
-
/**
* Options for building a template with authentication.
*/
-export type BuildOptions = AuthOptions & BasicBuildOptions
+export type BuildOptions = ConnectionOpts & BasicBuildOptions
/**
* Information about a built template.
@@ -78,7 +65,12 @@ export type BuildInfo = {
/**
* Response from getting build status.
*/
-export type GetBuildStatusOptions = AuthOptions & { logsOffset?: number }
+export type GetBuildStatusOptions = ConnectionOpts & { logsOffset?: number }
+
+/**
+ * Options for checking if a template alias exists.
+ */
+export type AliasExistsOptions = ConnectionOpts
/**
* Types of instructions that can be used in a template.
diff --git a/packages/js-sdk/tests/template/aliasExists.test.ts b/packages/js-sdk/tests/template/aliasExists.test.ts
new file mode 100644
index 000000000..a91449dfb
--- /dev/null
+++ b/packages/js-sdk/tests/template/aliasExists.test.ts
@@ -0,0 +1,14 @@
+import { randomUUID } from 'node:crypto'
+import { expect, test } from 'vitest'
+import { Template } from '../../src'
+
+test('check if base template alias exists', async () => {
+ const exists = await Template.aliasExists('base')
+ expect(exists).toBe(true)
+})
+
+test('check non existing alias', async () => {
+ const nonExistingAlias = `nonexistent-${randomUUID()}`
+ const exists = await Template.aliasExists(nonExistingAlias)
+ expect(exists).toBe(false)
+})
diff --git a/packages/python-sdk/e2b/api/client/api/templates/get_templates_aliases_alias.py b/packages/python-sdk/e2b/api/client/api/templates/get_templates_aliases_alias.py
new file mode 100644
index 000000000..c862846d6
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/templates/get_templates_aliases_alias.py
@@ -0,0 +1,167 @@
+from http import HTTPStatus
+from typing import Any, Optional, Union
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error import Error
+from ...models.template_alias_response import TemplateAliasResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ alias: str,
+) -> dict[str, Any]:
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": f"/templates/aliases/{alias}",
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Optional[Union[Error, TemplateAliasResponse]]:
+ if response.status_code == 200:
+ response_200 = TemplateAliasResponse.from_dict(response.json())
+
+ return response_200
+ if response.status_code == 400:
+ response_400 = Error.from_dict(response.json())
+
+ return response_400
+ if response.status_code == 403:
+ response_403 = Error.from_dict(response.json())
+
+ return response_403
+ if response.status_code == 404:
+ response_404 = Error.from_dict(response.json())
+
+ return response_404
+ if response.status_code == 500:
+ response_500 = Error.from_dict(response.json())
+
+ return response_500
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Response[Union[Error, TemplateAliasResponse]]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ alias: str,
+ *,
+ client: AuthenticatedClient,
+) -> Response[Union[Error, TemplateAliasResponse]]:
+ """Check if template with given alias exists
+
+ Args:
+ alias (str): Template alias
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, TemplateAliasResponse]]
+ """
+
+ kwargs = _get_kwargs(
+ alias=alias,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ alias: str,
+ *,
+ client: AuthenticatedClient,
+) -> Optional[Union[Error, TemplateAliasResponse]]:
+ """Check if template with given alias exists
+
+ Args:
+ alias (str): Template alias
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, TemplateAliasResponse]
+ """
+
+ return sync_detailed(
+ alias=alias,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ alias: str,
+ *,
+ client: AuthenticatedClient,
+) -> Response[Union[Error, TemplateAliasResponse]]:
+ """Check if template with given alias exists
+
+ Args:
+ alias (str): Template alias
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, TemplateAliasResponse]]
+ """
+
+ kwargs = _get_kwargs(
+ alias=alias,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ alias: str,
+ *,
+ client: AuthenticatedClient,
+) -> Optional[Union[Error, TemplateAliasResponse]]:
+ """Check if template with given alias exists
+
+ Args:
+ alias (str): Template alias
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, TemplateAliasResponse]
+ """
+
+ return (
+ await asyncio_detailed(
+ alias=alias,
+ client=client,
+ )
+ ).parsed
diff --git a/packages/python-sdk/e2b/api/client/api/templates/get_templates_template_id_builds_build_id_logs.py b/packages/python-sdk/e2b/api/client/api/templates/get_templates_template_id_builds_build_id_logs.py
new file mode 100644
index 000000000..1f4fee6f3
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/templates/get_templates_template_id_builds_build_id_logs.py
@@ -0,0 +1,272 @@
+from http import HTTPStatus
+from typing import Any, Optional, Union
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error import Error
+from ...models.log_level import LogLevel
+from ...models.logs_direction import LogsDirection
+from ...models.logs_source import LogsSource
+from ...models.template_build_logs_response import TemplateBuildLogsResponse
+from ...types import UNSET, Response, Unset
+
+
+def _get_kwargs(
+ template_id: str,
+ build_id: str,
+ *,
+ cursor: Union[Unset, int] = UNSET,
+ limit: Union[Unset, int] = 100,
+ direction: Union[Unset, LogsDirection] = UNSET,
+ level: Union[Unset, LogLevel] = UNSET,
+ source: Union[Unset, LogsSource] = UNSET,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+
+ params["cursor"] = cursor
+
+ params["limit"] = limit
+
+ json_direction: Union[Unset, str] = UNSET
+ if not isinstance(direction, Unset):
+ json_direction = direction.value
+
+ params["direction"] = json_direction
+
+ json_level: Union[Unset, str] = UNSET
+ if not isinstance(level, Unset):
+ json_level = level.value
+
+ params["level"] = json_level
+
+ json_source: Union[Unset, str] = UNSET
+ if not isinstance(source, Unset):
+ json_source = source.value
+
+ params["source"] = json_source
+
+ params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
+
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": f"/templates/{template_id}/builds/{build_id}/logs",
+ "params": params,
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Optional[Union[Error, TemplateBuildLogsResponse]]:
+ if response.status_code == 200:
+ response_200 = TemplateBuildLogsResponse.from_dict(response.json())
+
+ return response_200
+ if response.status_code == 401:
+ response_401 = Error.from_dict(response.json())
+
+ return response_401
+ if response.status_code == 404:
+ response_404 = Error.from_dict(response.json())
+
+ return response_404
+ if response.status_code == 500:
+ response_500 = Error.from_dict(response.json())
+
+ return response_500
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Response[Union[Error, TemplateBuildLogsResponse]]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ template_id: str,
+ build_id: str,
+ *,
+ client: AuthenticatedClient,
+ cursor: Union[Unset, int] = UNSET,
+ limit: Union[Unset, int] = 100,
+ direction: Union[Unset, LogsDirection] = UNSET,
+ level: Union[Unset, LogLevel] = UNSET,
+ source: Union[Unset, LogsSource] = UNSET,
+) -> Response[Union[Error, TemplateBuildLogsResponse]]:
+ """Get template build logs
+
+ Args:
+ template_id (str):
+ build_id (str):
+ cursor (Union[Unset, int]):
+ limit (Union[Unset, int]): Default: 100.
+ direction (Union[Unset, LogsDirection]): Direction of the logs that should be returned
+ level (Union[Unset, LogLevel]): State of the sandbox
+ source (Union[Unset, LogsSource]): Source of the logs that should be returned
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, TemplateBuildLogsResponse]]
+ """
+
+ kwargs = _get_kwargs(
+ template_id=template_id,
+ build_id=build_id,
+ cursor=cursor,
+ limit=limit,
+ direction=direction,
+ level=level,
+ source=source,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ template_id: str,
+ build_id: str,
+ *,
+ client: AuthenticatedClient,
+ cursor: Union[Unset, int] = UNSET,
+ limit: Union[Unset, int] = 100,
+ direction: Union[Unset, LogsDirection] = UNSET,
+ level: Union[Unset, LogLevel] = UNSET,
+ source: Union[Unset, LogsSource] = UNSET,
+) -> Optional[Union[Error, TemplateBuildLogsResponse]]:
+ """Get template build logs
+
+ Args:
+ template_id (str):
+ build_id (str):
+ cursor (Union[Unset, int]):
+ limit (Union[Unset, int]): Default: 100.
+ direction (Union[Unset, LogsDirection]): Direction of the logs that should be returned
+ level (Union[Unset, LogLevel]): State of the sandbox
+ source (Union[Unset, LogsSource]): Source of the logs that should be returned
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, TemplateBuildLogsResponse]
+ """
+
+ return sync_detailed(
+ template_id=template_id,
+ build_id=build_id,
+ client=client,
+ cursor=cursor,
+ limit=limit,
+ direction=direction,
+ level=level,
+ source=source,
+ ).parsed
+
+
+async def asyncio_detailed(
+ template_id: str,
+ build_id: str,
+ *,
+ client: AuthenticatedClient,
+ cursor: Union[Unset, int] = UNSET,
+ limit: Union[Unset, int] = 100,
+ direction: Union[Unset, LogsDirection] = UNSET,
+ level: Union[Unset, LogLevel] = UNSET,
+ source: Union[Unset, LogsSource] = UNSET,
+) -> Response[Union[Error, TemplateBuildLogsResponse]]:
+ """Get template build logs
+
+ Args:
+ template_id (str):
+ build_id (str):
+ cursor (Union[Unset, int]):
+ limit (Union[Unset, int]): Default: 100.
+ direction (Union[Unset, LogsDirection]): Direction of the logs that should be returned
+ level (Union[Unset, LogLevel]): State of the sandbox
+ source (Union[Unset, LogsSource]): Source of the logs that should be returned
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, TemplateBuildLogsResponse]]
+ """
+
+ kwargs = _get_kwargs(
+ template_id=template_id,
+ build_id=build_id,
+ cursor=cursor,
+ limit=limit,
+ direction=direction,
+ level=level,
+ source=source,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ template_id: str,
+ build_id: str,
+ *,
+ client: AuthenticatedClient,
+ cursor: Union[Unset, int] = UNSET,
+ limit: Union[Unset, int] = 100,
+ direction: Union[Unset, LogsDirection] = UNSET,
+ level: Union[Unset, LogLevel] = UNSET,
+ source: Union[Unset, LogsSource] = UNSET,
+) -> Optional[Union[Error, TemplateBuildLogsResponse]]:
+ """Get template build logs
+
+ Args:
+ template_id (str):
+ build_id (str):
+ cursor (Union[Unset, int]):
+ limit (Union[Unset, int]): Default: 100.
+ direction (Union[Unset, LogsDirection]): Direction of the logs that should be returned
+ level (Union[Unset, LogLevel]): State of the sandbox
+ source (Union[Unset, LogsSource]): Source of the logs that should be returned
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, TemplateBuildLogsResponse]
+ """
+
+ return (
+ await asyncio_detailed(
+ template_id=template_id,
+ build_id=build_id,
+ client=client,
+ cursor=cursor,
+ limit=limit,
+ direction=direction,
+ level=level,
+ source=source,
+ )
+ ).parsed
diff --git a/packages/python-sdk/e2b/api/client/api/templates/get_templates_template_id_builds_build_id_status.py b/packages/python-sdk/e2b/api/client/api/templates/get_templates_template_id_builds_build_id_status.py
index 2fa0feed1..8185e2e08 100644
--- a/packages/python-sdk/e2b/api/client/api/templates/get_templates_template_id_builds_build_id_status.py
+++ b/packages/python-sdk/e2b/api/client/api/templates/get_templates_template_id_builds_build_id_status.py
@@ -16,12 +16,15 @@ def _get_kwargs(
build_id: str,
*,
logs_offset: Union[Unset, int] = 0,
+ limit: Union[Unset, int] = 100,
level: Union[Unset, LogLevel] = UNSET,
) -> dict[str, Any]:
params: dict[str, Any] = {}
params["logsOffset"] = logs_offset
+ params["limit"] = limit
+
json_level: Union[Unset, str] = UNSET
if not isinstance(level, Unset):
json_level = level.value
@@ -81,6 +84,7 @@ def sync_detailed(
*,
client: AuthenticatedClient,
logs_offset: Union[Unset, int] = 0,
+ limit: Union[Unset, int] = 100,
level: Union[Unset, LogLevel] = UNSET,
) -> Response[Union[Error, TemplateBuildInfo]]:
"""Get template build info
@@ -89,6 +93,7 @@ def sync_detailed(
template_id (str):
build_id (str):
logs_offset (Union[Unset, int]): Default: 0.
+ limit (Union[Unset, int]): Default: 100.
level (Union[Unset, LogLevel]): State of the sandbox
Raises:
@@ -103,6 +108,7 @@ def sync_detailed(
template_id=template_id,
build_id=build_id,
logs_offset=logs_offset,
+ limit=limit,
level=level,
)
@@ -119,6 +125,7 @@ def sync(
*,
client: AuthenticatedClient,
logs_offset: Union[Unset, int] = 0,
+ limit: Union[Unset, int] = 100,
level: Union[Unset, LogLevel] = UNSET,
) -> Optional[Union[Error, TemplateBuildInfo]]:
"""Get template build info
@@ -127,6 +134,7 @@ def sync(
template_id (str):
build_id (str):
logs_offset (Union[Unset, int]): Default: 0.
+ limit (Union[Unset, int]): Default: 100.
level (Union[Unset, LogLevel]): State of the sandbox
Raises:
@@ -142,6 +150,7 @@ def sync(
build_id=build_id,
client=client,
logs_offset=logs_offset,
+ limit=limit,
level=level,
).parsed
@@ -152,6 +161,7 @@ async def asyncio_detailed(
*,
client: AuthenticatedClient,
logs_offset: Union[Unset, int] = 0,
+ limit: Union[Unset, int] = 100,
level: Union[Unset, LogLevel] = UNSET,
) -> Response[Union[Error, TemplateBuildInfo]]:
"""Get template build info
@@ -160,6 +170,7 @@ async def asyncio_detailed(
template_id (str):
build_id (str):
logs_offset (Union[Unset, int]): Default: 0.
+ limit (Union[Unset, int]): Default: 100.
level (Union[Unset, LogLevel]): State of the sandbox
Raises:
@@ -174,6 +185,7 @@ async def asyncio_detailed(
template_id=template_id,
build_id=build_id,
logs_offset=logs_offset,
+ limit=limit,
level=level,
)
@@ -188,6 +200,7 @@ async def asyncio(
*,
client: AuthenticatedClient,
logs_offset: Union[Unset, int] = 0,
+ limit: Union[Unset, int] = 100,
level: Union[Unset, LogLevel] = UNSET,
) -> Optional[Union[Error, TemplateBuildInfo]]:
"""Get template build info
@@ -196,6 +209,7 @@ async def asyncio(
template_id (str):
build_id (str):
logs_offset (Union[Unset, int]): Default: 0.
+ limit (Union[Unset, int]): Default: 100.
level (Union[Unset, LogLevel]): State of the sandbox
Raises:
@@ -212,6 +226,7 @@ async def asyncio(
build_id=build_id,
client=client,
logs_offset=logs_offset,
+ limit=limit,
level=level,
)
).parsed
diff --git a/packages/python-sdk/e2b/api/client/models/__init__.py b/packages/python-sdk/e2b/api/client/models/__init__.py
index 6c81cf276..68ca7c004 100644
--- a/packages/python-sdk/e2b/api/client/models/__init__.py
+++ b/packages/python-sdk/e2b/api/client/models/__init__.py
@@ -1,5 +1,7 @@
"""Contains all the data models used in inputs/outputs"""
+from .admin_sandbox_kill_result import AdminSandboxKillResult
+from .assign_template_tag_request import AssignTemplateTagRequest
from .aws_registry import AWSRegistry
from .aws_registry_type import AWSRegistryType
from .build_log_entry import BuildLogEntry
@@ -16,6 +18,9 @@ from .general_registry_type import GeneralRegistryType
from .identifier_masking_details import IdentifierMaskingDetails
from .listed_sandbox import ListedSandbox
from .log_level import LogLevel
+from .logs_direction import LogsDirection
+from .logs_source import LogsSource
+from .machine_info import MachineInfo
from .max_team_metric import MaxTeamMetric
from .mcp_type_0 import McpType0
from .new_access_token import NewAccessToken
@@ -46,9 +51,11 @@ from .team_api_key import TeamAPIKey
from .team_metric import TeamMetric
from .team_user import TeamUser
from .template import Template
+from .template_alias_response import TemplateAliasResponse
from .template_build import TemplateBuild
from .template_build_file_upload import TemplateBuildFileUpload
from .template_build_info import TemplateBuildInfo
+from .template_build_logs_response import TemplateBuildLogsResponse
from .template_build_request import TemplateBuildRequest
from .template_build_request_v2 import TemplateBuildRequestV2
from .template_build_request_v3 import TemplateBuildRequestV3
@@ -57,11 +64,14 @@ from .template_build_status import TemplateBuildStatus
from .template_legacy import TemplateLegacy
from .template_request_response_v3 import TemplateRequestResponseV3
from .template_step import TemplateStep
+from .template_tag import TemplateTag
from .template_update_request import TemplateUpdateRequest
from .template_with_builds import TemplateWithBuilds
from .update_team_api_key import UpdateTeamAPIKey
__all__ = (
+ "AdminSandboxKillResult",
+ "AssignTemplateTagRequest",
"AWSRegistry",
"AWSRegistryType",
"BuildLogEntry",
@@ -78,6 +88,9 @@ __all__ = (
"IdentifierMaskingDetails",
"ListedSandbox",
"LogLevel",
+ "LogsDirection",
+ "LogsSource",
+ "MachineInfo",
"MaxTeamMetric",
"McpType0",
"NewAccessToken",
@@ -106,9 +119,11 @@ __all__ = (
"TeamMetric",
"TeamUser",
"Template",
+ "TemplateAliasResponse",
"TemplateBuild",
"TemplateBuildFileUpload",
"TemplateBuildInfo",
+ "TemplateBuildLogsResponse",
"TemplateBuildRequest",
"TemplateBuildRequestV2",
"TemplateBuildRequestV3",
@@ -117,6 +132,7 @@ __all__ = (
"TemplateLegacy",
"TemplateRequestResponseV3",
"TemplateStep",
+ "TemplateTag",
"TemplateUpdateRequest",
"TemplateWithBuilds",
"UpdateTeamAPIKey",
diff --git a/packages/python-sdk/e2b/api/client/models/admin_sandbox_kill_result.py b/packages/python-sdk/e2b/api/client/models/admin_sandbox_kill_result.py
new file mode 100644
index 000000000..ac1df8911
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/admin_sandbox_kill_result.py
@@ -0,0 +1,67 @@
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="AdminSandboxKillResult")
+
+
+@_attrs_define
+class AdminSandboxKillResult:
+ """
+ Attributes:
+ failed_count (int): Number of sandboxes that failed to kill
+ killed_count (int): Number of sandboxes successfully killed
+ """
+
+ failed_count: int
+ killed_count: int
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ failed_count = self.failed_count
+
+ killed_count = self.killed_count
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "failedCount": failed_count,
+ "killedCount": killed_count,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ failed_count = d.pop("failedCount")
+
+ killed_count = d.pop("killedCount")
+
+ admin_sandbox_kill_result = cls(
+ failed_count=failed_count,
+ killed_count=killed_count,
+ )
+
+ admin_sandbox_kill_result.additional_properties = d
+ return admin_sandbox_kill_result
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/assign_template_tag_request.py b/packages/python-sdk/e2b/api/client/models/assign_template_tag_request.py
new file mode 100644
index 000000000..10d6fee99
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/assign_template_tag_request.py
@@ -0,0 +1,67 @@
+from collections.abc import Mapping
+from typing import Any, TypeVar, cast
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="AssignTemplateTagRequest")
+
+
+@_attrs_define
+class AssignTemplateTagRequest:
+ """
+ Attributes:
+ names (list[str]): Names of the template
+ target (str): Target template name in 'alias:tag' format
+ """
+
+ names: list[str]
+ target: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ names = self.names
+
+ target = self.target
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "names": names,
+ "target": target,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ names = cast(list[str], d.pop("names"))
+
+ target = d.pop("target")
+
+ assign_template_tag_request = cls(
+ names=names,
+ target=target,
+ )
+
+ assign_template_tag_request.additional_properties = d
+ return assign_template_tag_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/logs_direction.py b/packages/python-sdk/e2b/api/client/models/logs_direction.py
new file mode 100644
index 000000000..3aa9bbd77
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/logs_direction.py
@@ -0,0 +1,9 @@
+from enum import Enum
+
+
+class LogsDirection(str, Enum):
+ BACKWARD = "backward"
+ FORWARD = "forward"
+
+ def __str__(self) -> str:
+ return str(self.value)
diff --git a/packages/python-sdk/e2b/api/client/models/logs_source.py b/packages/python-sdk/e2b/api/client/models/logs_source.py
new file mode 100644
index 000000000..f27a64151
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/logs_source.py
@@ -0,0 +1,9 @@
+from enum import Enum
+
+
+class LogsSource(str, Enum):
+ PERSISTENT = "persistent"
+ TEMPORARY = "temporary"
+
+ def __str__(self) -> str:
+ return str(self.value)
diff --git a/packages/python-sdk/e2b/api/client/models/machine_info.py b/packages/python-sdk/e2b/api/client/models/machine_info.py
new file mode 100644
index 000000000..cd63ef0cb
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/machine_info.py
@@ -0,0 +1,83 @@
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="MachineInfo")
+
+
+@_attrs_define
+class MachineInfo:
+ """
+ Attributes:
+ cpu_architecture (str): CPU architecture of the node
+ cpu_family (str): CPU family of the node
+ cpu_model (str): CPU model of the node
+ cpu_model_name (str): CPU model name of the node
+ """
+
+ cpu_architecture: str
+ cpu_family: str
+ cpu_model: str
+ cpu_model_name: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ cpu_architecture = self.cpu_architecture
+
+ cpu_family = self.cpu_family
+
+ cpu_model = self.cpu_model
+
+ cpu_model_name = self.cpu_model_name
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "cpuArchitecture": cpu_architecture,
+ "cpuFamily": cpu_family,
+ "cpuModel": cpu_model,
+ "cpuModelName": cpu_model_name,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ cpu_architecture = d.pop("cpuArchitecture")
+
+ cpu_family = d.pop("cpuFamily")
+
+ cpu_model = d.pop("cpuModel")
+
+ cpu_model_name = d.pop("cpuModelName")
+
+ machine_info = cls(
+ cpu_architecture=cpu_architecture,
+ cpu_family=cpu_family,
+ cpu_model=cpu_model,
+ cpu_model_name=cpu_model_name,
+ )
+
+ machine_info.additional_properties = d
+ return machine_info
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/node.py b/packages/python-sdk/e2b/api/client/models/node.py
index d50936958..af839117c 100644
--- a/packages/python-sdk/e2b/api/client/models/node.py
+++ b/packages/python-sdk/e2b/api/client/models/node.py
@@ -7,6 +7,7 @@ from attrs import field as _attrs_field
from ..models.node_status import NodeStatus
if TYPE_CHECKING:
+ from ..models.machine_info import MachineInfo
from ..models.node_metrics import NodeMetrics
@@ -22,6 +23,7 @@ class Node:
create_fails (int): Number of sandbox create fails
create_successes (int): Number of sandbox create successes
id (str): Identifier of the node
+ machine_info (MachineInfo):
metrics (NodeMetrics): Node metrics
node_id (str): Identifier of the nomad node
sandbox_count (int): Number of sandboxes running on the node
@@ -36,6 +38,7 @@ class Node:
create_fails: int
create_successes: int
id: str
+ machine_info: "MachineInfo"
metrics: "NodeMetrics"
node_id: str
sandbox_count: int
@@ -56,6 +59,8 @@ class Node:
id = self.id
+ machine_info = self.machine_info.to_dict()
+
metrics = self.metrics.to_dict()
node_id = self.node_id
@@ -79,6 +84,7 @@ class Node:
"createFails": create_fails,
"createSuccesses": create_successes,
"id": id,
+ "machineInfo": machine_info,
"metrics": metrics,
"nodeID": node_id,
"sandboxCount": sandbox_count,
@@ -93,6 +99,7 @@ class Node:
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.machine_info import MachineInfo
from ..models.node_metrics import NodeMetrics
d = dict(src_dict)
@@ -106,6 +113,8 @@ class Node:
id = d.pop("id")
+ machine_info = MachineInfo.from_dict(d.pop("machineInfo"))
+
metrics = NodeMetrics.from_dict(d.pop("metrics"))
node_id = d.pop("nodeID")
@@ -126,6 +135,7 @@ class Node:
create_fails=create_fails,
create_successes=create_successes,
id=id,
+ machine_info=machine_info,
metrics=metrics,
node_id=node_id,
sandbox_count=sandbox_count,
diff --git a/packages/python-sdk/e2b/api/client/models/node_detail.py b/packages/python-sdk/e2b/api/client/models/node_detail.py
index 352ead6d5..41b32a09f 100644
--- a/packages/python-sdk/e2b/api/client/models/node_detail.py
+++ b/packages/python-sdk/e2b/api/client/models/node_detail.py
@@ -8,6 +8,7 @@ from ..models.node_status import NodeStatus
if TYPE_CHECKING:
from ..models.listed_sandbox import ListedSandbox
+ from ..models.machine_info import MachineInfo
from ..models.node_metrics import NodeMetrics
@@ -24,6 +25,7 @@ class NodeDetail:
create_fails (int): Number of sandbox create fails
create_successes (int): Number of sandbox create successes
id (str): Identifier of the node
+ machine_info (MachineInfo):
metrics (NodeMetrics): Node metrics
node_id (str): Identifier of the nomad node
sandboxes (list['ListedSandbox']): List of sandboxes running on the node
@@ -38,6 +40,7 @@ class NodeDetail:
create_fails: int
create_successes: int
id: str
+ machine_info: "MachineInfo"
metrics: "NodeMetrics"
node_id: str
sandboxes: list["ListedSandbox"]
@@ -59,6 +62,8 @@ class NodeDetail:
id = self.id
+ machine_info = self.machine_info.to_dict()
+
metrics = self.metrics.to_dict()
node_id = self.node_id
@@ -84,6 +89,7 @@ class NodeDetail:
"createFails": create_fails,
"createSuccesses": create_successes,
"id": id,
+ "machineInfo": machine_info,
"metrics": metrics,
"nodeID": node_id,
"sandboxes": sandboxes,
@@ -98,6 +104,7 @@ class NodeDetail:
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.listed_sandbox import ListedSandbox
+ from ..models.machine_info import MachineInfo
from ..models.node_metrics import NodeMetrics
d = dict(src_dict)
@@ -113,6 +120,8 @@ class NodeDetail:
id = d.pop("id")
+ machine_info = MachineInfo.from_dict(d.pop("machineInfo"))
+
metrics = NodeMetrics.from_dict(d.pop("metrics"))
node_id = d.pop("nodeID")
@@ -137,6 +146,7 @@ class NodeDetail:
create_fails=create_fails,
create_successes=create_successes,
id=id,
+ machine_info=machine_info,
metrics=metrics,
node_id=node_id,
sandboxes=sandboxes,
diff --git a/packages/python-sdk/e2b/api/client/models/template_alias_response.py b/packages/python-sdk/e2b/api/client/models/template_alias_response.py
new file mode 100644
index 000000000..7c9106197
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/template_alias_response.py
@@ -0,0 +1,67 @@
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="TemplateAliasResponse")
+
+
+@_attrs_define
+class TemplateAliasResponse:
+ """
+ Attributes:
+ public (bool): Whether the template is public or only accessible by the team
+ template_id (str): Identifier of the template
+ """
+
+ public: bool
+ template_id: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ public = self.public
+
+ template_id = self.template_id
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "public": public,
+ "templateID": template_id,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ public = d.pop("public")
+
+ template_id = d.pop("templateID")
+
+ template_alias_response = cls(
+ public=public,
+ template_id=template_id,
+ )
+
+ template_alias_response.additional_properties = d
+ return template_alias_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/template_build_logs_response.py b/packages/python-sdk/e2b/api/client/models/template_build_logs_response.py
new file mode 100644
index 000000000..6f3f70998
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/template_build_logs_response.py
@@ -0,0 +1,73 @@
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+if TYPE_CHECKING:
+ from ..models.build_log_entry import BuildLogEntry
+
+
+T = TypeVar("T", bound="TemplateBuildLogsResponse")
+
+
+@_attrs_define
+class TemplateBuildLogsResponse:
+ """
+ Attributes:
+ logs (list['BuildLogEntry']): Build logs structured
+ """
+
+ logs: list["BuildLogEntry"]
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ logs = []
+ for logs_item_data in self.logs:
+ logs_item = logs_item_data.to_dict()
+ logs.append(logs_item)
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "logs": logs,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.build_log_entry import BuildLogEntry
+
+ d = dict(src_dict)
+ logs = []
+ _logs = d.pop("logs")
+ for logs_item_data in _logs:
+ logs_item = BuildLogEntry.from_dict(logs_item_data)
+
+ logs.append(logs_item)
+
+ template_build_logs_response = cls(
+ logs=logs,
+ )
+
+ template_build_logs_response.additional_properties = d
+ return template_build_logs_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/template_build_request_v3.py b/packages/python-sdk/e2b/api/client/models/template_build_request_v3.py
index 0c14ad5d8..3c9106d39 100644
--- a/packages/python-sdk/e2b/api/client/models/template_build_request_v3.py
+++ b/packages/python-sdk/e2b/api/client/models/template_build_request_v3.py
@@ -1,5 +1,5 @@
from collections.abc import Mapping
-from typing import Any, TypeVar, Union
+from typing import Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
@@ -13,15 +13,17 @@ T = TypeVar("T", bound="TemplateBuildRequestV3")
class TemplateBuildRequestV3:
"""
Attributes:
- alias (str): Alias of the template
+ alias (Union[Unset, str]): Alias of the template. Deprecated, use names instead.
cpu_count (Union[Unset, int]): CPU cores for the sandbox
memory_mb (Union[Unset, int]): Memory for the sandbox in MiB
+ names (Union[Unset, list[str]]): Names of the template
team_id (Union[Unset, str]): Identifier of the team
"""
- alias: str
+ alias: Union[Unset, str] = UNSET
cpu_count: Union[Unset, int] = UNSET
memory_mb: Union[Unset, int] = UNSET
+ names: Union[Unset, list[str]] = UNSET
team_id: Union[Unset, str] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
@@ -32,19 +34,23 @@ class TemplateBuildRequestV3:
memory_mb = self.memory_mb
+ names: Union[Unset, list[str]] = UNSET
+ if not isinstance(self.names, Unset):
+ names = self.names
+
team_id = self.team_id
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
- field_dict.update(
- {
- "alias": alias,
- }
- )
+ field_dict.update({})
+ if alias is not UNSET:
+ field_dict["alias"] = alias
if cpu_count is not UNSET:
field_dict["cpuCount"] = cpu_count
if memory_mb is not UNSET:
field_dict["memoryMB"] = memory_mb
+ if names is not UNSET:
+ field_dict["names"] = names
if team_id is not UNSET:
field_dict["teamID"] = team_id
@@ -53,18 +59,21 @@ class TemplateBuildRequestV3:
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
- alias = d.pop("alias")
+ alias = d.pop("alias", UNSET)
cpu_count = d.pop("cpuCount", UNSET)
memory_mb = d.pop("memoryMB", UNSET)
+ names = cast(list[str], d.pop("names", UNSET))
+
team_id = d.pop("teamID", UNSET)
template_build_request_v3 = cls(
alias=alias,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ names=names,
team_id=team_id,
)
diff --git a/packages/python-sdk/e2b/api/client/models/template_tag.py b/packages/python-sdk/e2b/api/client/models/template_tag.py
new file mode 100644
index 000000000..52072f77a
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/template_tag.py
@@ -0,0 +1,68 @@
+from collections.abc import Mapping
+from typing import Any, TypeVar, cast
+from uuid import UUID
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="TemplateTag")
+
+
+@_attrs_define
+class TemplateTag:
+ """
+ Attributes:
+ build_id (UUID): Identifier of the build associated with this tag
+ tags (list[str]): Tags of the template
+ """
+
+ build_id: UUID
+ tags: list[str]
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ build_id = str(self.build_id)
+
+ tags = self.tags
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "buildID": build_id,
+ "tags": tags,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ build_id = UUID(d.pop("buildID"))
+
+ tags = cast(list[str], d.pop("tags"))
+
+ template_tag = cls(
+ build_id=build_id,
+ tags=tags,
+ )
+
+ template_tag.additional_properties = d
+ return template_tag
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/template_async/build_api.py b/packages/python-sdk/e2b/template_async/build_api.py
index 13ff984d8..f8f9924d1 100644
--- a/packages/python-sdk/e2b/template_async/build_api.py
+++ b/packages/python-sdk/e2b/template_async/build_api.py
@@ -10,6 +10,7 @@ from e2b.api.client.api.templates import (
get_templates_template_id_files_hash,
post_v_2_templates_template_id_builds_build_id,
get_templates_template_id_builds_build_id_status,
+ get_templates_aliases_alias,
)
from e2b.api.client.client import AuthenticatedClient
from e2b.api.client.models import (
@@ -200,3 +201,35 @@ async def wait_for_build_finish(
await asyncio.sleep(logs_refresh_frequency)
raise BuildException("Unknown build error occurred.")
+
+
+async def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool:
+ """
+ Check if a template with the given alias exists.
+
+ Args:
+ client: Authenticated API client
+ alias: Template alias to check
+
+ Returns:
+ True if the alias exists, False otherwise
+ """
+ res = await get_templates_aliases_alias.asyncio_detailed(
+ alias=alias,
+ client=client,
+ )
+
+ # If we get a NotFound, the alias doesn't exist
+ if res.status_code == 404:
+ return False
+
+ # If we get a Forbidden, alias exists, but you are not owner
+ if res.status_code == 403:
+ return True
+
+ # Handle other errors
+ if res.status_code >= 300:
+ raise handle_api_exception(res, BuildException)
+
+ # If we get Ok with data, you are owner and the alias exists
+ return res.parsed is not None
diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.py
index 52ecdcce2..e561c2b9e 100644
--- a/packages/python-sdk/e2b/template_async/main.py
+++ b/packages/python-sdk/e2b/template_async/main.py
@@ -1,9 +1,10 @@
-import os
from datetime import datetime
from typing import Callable, Optional
+from typing_extensions import Unpack
+
from e2b.api.client.client import AuthenticatedClient
-from e2b.connection_config import ConnectionConfig
+from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.template.consts import RESOLVE_SYMLINKS
from e2b.template.logger import LogEntry, LogEntryEnd, LogEntryStart
from e2b.template.main import TemplateBase, TemplateClass
@@ -11,6 +12,7 @@ from e2b.template.types import BuildInfo, InstructionType
from e2b.template.utils import read_dockerignore
from .build_api import (
+ check_alias_exists,
get_build_status,
get_file_upload_link,
request_build,
@@ -176,8 +178,7 @@ class AsyncTemplate(TemplateBase):
memory_mb: int = 1024,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
+ **opts: Unpack[ApiParams],
) -> BuildInfo:
"""
Build and deploy a template to E2B infrastructure.
@@ -188,8 +189,6 @@ class AsyncTemplate(TemplateBase):
:param memory_mb: Amount of memory in MB allocated to the sandbox
:param skip_cache: If True, forces a complete rebuild ignoring cache
:param on_build_logs: Callback function to receive build logs during the build process
- :param api_key: E2B API key for authentication
- :param domain: Domain of the E2B API
Example
```python
@@ -219,10 +218,7 @@ class AsyncTemplate(TemplateBase):
)
)
- domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
- config = ConnectionConfig(
- domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
- )
+ config = ConnectionConfig(**opts)
api_client = get_api_client(
config,
require_api_key=True,
@@ -275,8 +271,7 @@ class AsyncTemplate(TemplateBase):
memory_mb: int = 1024,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
+ **opts: Unpack[ApiParams],
) -> BuildInfo:
"""
Build and deploy a template to E2B infrastructure without waiting for completion.
@@ -286,8 +281,6 @@ class AsyncTemplate(TemplateBase):
:param cpu_count: Number of CPUs allocated to the sandbox
:param memory_mb: Amount of memory in MB allocated to the sandbox
:param skip_cache: If True, forces a complete rebuild ignoring cache
- :param api_key: E2B API key for authentication
- :param domain: Domain of the E2B API
:return: BuildInfo containing the template ID and build ID
Example
@@ -309,10 +302,7 @@ class AsyncTemplate(TemplateBase):
)
```
"""
- domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
- config = ConnectionConfig(
- domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
- )
+ config = ConnectionConfig(**opts)
api_client = get_api_client(
config,
require_api_key=True,
@@ -333,16 +323,13 @@ class AsyncTemplate(TemplateBase):
async def get_build_status(
build_info: BuildInfo,
logs_offset: int = 0,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
+ **opts: Unpack[ApiParams],
):
"""
Get the status of a build.
:param build_info: Build identifiers returned from build_in_background
:param logs_offset: Offset for fetching logs
- :param api_key: E2B API key for authentication
- :param domain: Domain of the E2B API
:return: TemplateBuild containing the build status and logs
Example
@@ -353,14 +340,44 @@ class AsyncTemplate(TemplateBase):
status = await AsyncTemplate.get_build_status(build_info, logs_offset=0)
```
"""
- domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
- config = ConnectionConfig(
- domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(
+ config,
+ require_api_key=True,
+ require_access_token=False,
)
- api_client = get_api_client(config)
return await get_build_status(
api_client,
build_info.template_id,
build_info.build_id,
logs_offset,
)
+
+ @staticmethod
+ async def alias_exists(
+ alias: str,
+ **opts: Unpack[ApiParams],
+ ) -> bool:
+ """
+ Check if a template with the given alias exists.
+
+ :param alias: Template alias to check
+ :return: True if the alias exists, False otherwise
+
+ Example
+ ```python
+ from e2b import AsyncTemplate
+
+ exists = await AsyncTemplate.alias_exists('base')
+ if exists:
+ print('Template exists!')
+ ```
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(
+ config,
+ require_api_key=True,
+ require_access_token=False,
+ )
+
+ return await check_alias_exists(api_client, alias)
diff --git a/packages/python-sdk/e2b/template_sync/build_api.py b/packages/python-sdk/e2b/template_sync/build_api.py
index 392737cd4..4d560b21d 100644
--- a/packages/python-sdk/e2b/template_sync/build_api.py
+++ b/packages/python-sdk/e2b/template_sync/build_api.py
@@ -10,6 +10,7 @@ from e2b.api.client.api.templates import (
get_templates_template_id_files_hash,
post_v_2_templates_template_id_builds_build_id,
get_templates_template_id_builds_build_id_status,
+ get_templates_aliases_alias,
)
from e2b.api.client.client import AuthenticatedClient
from e2b.api.client.models import (
@@ -197,3 +198,35 @@ def wait_for_build_finish(
time.sleep(logs_refresh_frequency)
raise BuildException("Unknown build error occurred.")
+
+
+def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool:
+ """
+ Check if a template with the given alias exists.
+
+ Args:
+ client: Authenticated API client
+ alias: Template alias to check
+
+ Returns:
+ True if the alias exists, False otherwise
+ """
+ res = get_templates_aliases_alias.sync_detailed(
+ alias=alias,
+ client=client,
+ )
+
+ # If we get a NotFound, the alias doesn't exist
+ if res.status_code == 404:
+ return False
+
+ # If we get a Forbidden, alias exists, but you are not owner
+ if res.status_code == 403:
+ return True
+
+ # Handle other errors
+ if res.status_code >= 300:
+ raise handle_api_exception(res, BuildException)
+
+ # If we get Ok with data, you are owner and the alias exists
+ return res.parsed is not None
diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.py
index fe41afdfd..b173b050c 100644
--- a/packages/python-sdk/e2b/template_sync/main.py
+++ b/packages/python-sdk/e2b/template_sync/main.py
@@ -1,9 +1,10 @@
-import os
from datetime import datetime
from typing import Callable, Optional
+from typing_extensions import Unpack
+
from e2b.api.client.client import AuthenticatedClient
-from e2b.connection_config import ConnectionConfig
+from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.api.client_sync import get_api_client
from e2b.template.consts import RESOLVE_SYMLINKS
@@ -11,6 +12,7 @@ from e2b.template.logger import LogEntry, LogEntryEnd, LogEntryStart
from e2b.template.main import TemplateBase, TemplateClass
from e2b.template.types import BuildInfo, InstructionType
from e2b.template_sync.build_api import (
+ check_alias_exists,
get_build_status,
get_file_upload_link,
request_build,
@@ -176,8 +178,7 @@ class Template(TemplateBase):
memory_mb: int = 1024,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
+ **opts: Unpack[ApiParams],
) -> BuildInfo:
"""
Build and deploy a template to E2B infrastructure.
@@ -188,8 +189,6 @@ class Template(TemplateBase):
:param memory_mb: Amount of memory in MB allocated to the sandbox
:param skip_cache: If True, forces a complete rebuild ignoring cache
:param on_build_logs: Callback function to receive build logs during the build process
- :param api_key: E2B API key for authentication
- :param domain: Domain of the E2B API
Example
```python
@@ -219,10 +218,7 @@ class Template(TemplateBase):
)
)
- domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
- config = ConnectionConfig(
- domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
- )
+ config = ConnectionConfig(**opts)
api_client = get_api_client(
config,
require_api_key=True,
@@ -275,8 +271,7 @@ class Template(TemplateBase):
memory_mb: int = 1024,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
+ **opts: Unpack[ApiParams],
) -> BuildInfo:
"""
Build and deploy a template to E2B infrastructure without waiting for completion.
@@ -286,8 +281,6 @@ class Template(TemplateBase):
:param cpu_count: Number of CPUs allocated to the sandbox
:param memory_mb: Amount of memory in MB allocated to the sandbox
:param skip_cache: If True, forces a complete rebuild ignoring cache
- :param api_key: E2B API key for authentication
- :param domain: Domain of the E2B API
:return: BuildInfo containing the template ID and build ID
Example
@@ -309,10 +302,7 @@ class Template(TemplateBase):
)
```
"""
- domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
- config = ConnectionConfig(
- domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
- )
+ config = ConnectionConfig(**opts)
api_client = get_api_client(
config,
require_api_key=True,
@@ -333,16 +323,13 @@ class Template(TemplateBase):
def get_build_status(
build_info: BuildInfo,
logs_offset: int = 0,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
+ **opts: Unpack[ApiParams],
):
"""
Get the status of a build.
:param build_info: Build identifiers returned from build_in_background
:param logs_offset: Offset for fetching logs
- :param api_key: E2B API key for authentication
- :param domain: Domain of the E2B API
:return: TemplateBuild containing the build status and logs
Example
@@ -353,10 +340,7 @@ class Template(TemplateBase):
status = Template.get_build_status(build_info, logs_offset=0)
```
"""
- domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
- config = ConnectionConfig(
- domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
- )
+ config = ConnectionConfig(**opts)
api_client = get_api_client(
config,
require_api_key=True,
@@ -369,3 +353,32 @@ class Template(TemplateBase):
build_info.build_id,
logs_offset,
)
+
+ @staticmethod
+ def alias_exists(
+ alias: str,
+ **opts: Unpack[ApiParams],
+ ) -> bool:
+ """
+ Check if a template with the given alias exists.
+
+ :param alias: Template alias to check
+ :return: True if the alias exists, False otherwise
+
+ Example
+ ```python
+ from e2b import Template
+
+ exists = Template.alias_exists('base')
+ if exists:
+ print('Template exists!')
+ ```
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(
+ config,
+ require_api_key=True,
+ require_access_token=False,
+ )
+
+ return check_alias_exists(api_client, alias)
diff --git a/packages/python-sdk/tests/async/template_async/test_alias_exists.py b/packages/python-sdk/tests/async/template_async/test_alias_exists.py
new file mode 100644
index 000000000..da2b7093d
--- /dev/null
+++ b/packages/python-sdk/tests/async/template_async/test_alias_exists.py
@@ -0,0 +1,20 @@
+import uuid
+
+import pytest
+
+from e2b import AsyncTemplate
+
+
+async def test_check_base_template_alias_exists():
+ """Test that the base template alias exists."""
+ exists = await AsyncTemplate.alias_exists("base")
+ assert exists is True
+
+
+async def test_check_non_existing_alias():
+ """Test that a non-existing alias returns False."""
+ non_existing_alias = f"nonexistent-{uuid.uuid4()}"
+ exists = await AsyncTemplate.alias_exists(non_existing_alias)
+ assert exists is False
diff --git a/packages/python-sdk/tests/sync/template_sync/test_alias_exists.py b/packages/python-sdk/tests/sync/template_sync/test_alias_exists.py
new file mode 100644
index 000000000..43397db90
--- /dev/null
+++ b/packages/python-sdk/tests/sync/template_sync/test_alias_exists.py
@@ -0,0 +1,20 @@
+import uuid
+
+import pytest
+
+from e2b import Template
+
+
+def test_check_base_template_alias_exists():
+ """Test that the base template alias exists."""
+ exists = Template.alias_exists("base")
+ assert exists is True
+
+
+def test_check_non_existing_alias():
+ """Test that a non-existing alias returns False."""
+ non_existing_alias = f"nonexistent-{uuid.uuid4()}"
+ exists = Template.alias_exists(non_existing_alias)
+ assert exists is False
diff --git a/spec/openapi.yml b/spec/openapi.yml
index e05bf641f..faa19b956 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -75,6 +75,13 @@ components:
required: true
schema:
type: string
+ tag:
+ name: tag
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Tag name
paginationLimit:
name: limit
in: query
@@ -582,6 +589,18 @@ components:
type: number
description: The maximum value of the requested metric in the given interval
+ AdminSandboxKillResult:
+ required:
+ - killedCount
+ - failedCount
+ properties:
+ killedCount:
+ type: integer
+ description: Number of sandboxes successfully killed
+ failedCount:
+ type: integer
+ description: Number of sandboxes that failed to kill
+
Template:
required:
- templateID
@@ -818,6 +837,18 @@ components:
items:
$ref: '#/components/schemas/TemplateBuild'
+ TemplateAliasResponse:
+ required:
+ - templateID
+ - public
+ properties:
+ templateID:
+ type: string
+ description: Identifier of the template
+ public:
+ type: boolean
+ description: Whether the template is public or only accessible by the team
+
TemplateBuildRequest:
required:
- dockerfile
@@ -865,12 +896,16 @@ components:
description: Whether the step should be forced to run regardless of the cache
TemplateBuildRequestV3:
- required:
- - alias
properties:
alias:
- description: Alias of the template
+ description: Alias of the template. Deprecated, use names instead.
type: string
+ deprecated: true
+ names:
+ type: array
+ description: Names of the template
+ items:
+ type: string
teamID:
type: string
description: Identifier of the team
@@ -1084,6 +1119,37 @@ components:
reason:
$ref: '#/components/schemas/BuildStatusReason'
+ TemplateBuildLogsResponse:
+ required:
+ - logs
+ properties:
+ logs:
+ default: []
+ description: Build logs structured
+ type: array
+ items:
+ $ref: '#/components/schemas/BuildLogEntry'
+
+ LogsDirection:
+ type: string
+ description: Direction of the logs that should be returned
+ enum:
+ - forward
+ - backward
+ x-enum-varnames:
+ - LogsDirectionForward
+ - LogsDirectionBackward
+
+ LogsSource:
+ type: string
+ description: Source of the logs that should be returned
+ enum:
+ - temporary
+ - persistent
+ x-enum-varnames:
+ - LogsSourceTemporary
+ - LogsSourcePersistent
+
NodeStatus:
type: string
description: Status of the node
@@ -1175,6 +1241,25 @@ components:
description: Detailed metrics for each disk/mount point
items:
$ref: '#/components/schemas/DiskMetrics'
+ MachineInfo:
+ required:
+ - cpuFamily
+ - cpuModel
+ - cpuModelName
+ - cpuArchitecture
+ properties:
+ cpuFamily:
+ type: string
+ description: CPU family of the node
+ cpuModel:
+ type: string
+ description: CPU model of the node
+ cpuModelName:
+ type: string
+ description: CPU model name of the node
+ cpuArchitecture:
+ type: string
+ description: CPU architecture of the node
Node:
required:
@@ -1190,6 +1275,7 @@ components:
- sandboxStartingCount
- version
- commit
+ - machineInfo
properties:
version:
type: string
@@ -1210,6 +1296,8 @@ components:
clusterID:
type: string
description: Identifier of the cluster
+ machineInfo:
+ $ref: '#/components/schemas/MachineInfo'
status:
$ref: '#/components/schemas/NodeStatus'
sandboxCount:
@@ -1245,6 +1333,7 @@ components:
- version
- commit
- metrics
+ - machineInfo
properties:
clusterID:
type: string
@@ -1265,6 +1354,8 @@ components:
type: string
deprecated: true
description: Identifier of the nomad node
+ machineInfo:
+ $ref: '#/components/schemas/MachineInfo'
status:
$ref: '#/components/schemas/NodeStatus'
sandboxes:
@@ -1401,6 +1492,35 @@ components:
type: string
description: New name for the API key
+ TemplateTag:
+ required:
+ - tags
+ - buildID
+ properties:
+ tags:
+ type: array
+ items:
+ type: string
+ description: Tags of the template
+ buildID:
+ type: string
+ format: uuid
+ description: Identifier of the build associated with this tag
+
+ AssignTemplateTagRequest:
+ required:
+ - target
+ - names
+ properties:
+ target:
+ type: string
+ description: Target template name in 'alias:tag' format
+ names:
+ description: Names of the template
+ type: array
+ items:
+ type: string
+
Error:
required:
- code
@@ -1440,6 +1560,7 @@ tags:
- name: auth
- name: access-tokens
- name: api-keys
+ - name: tags
paths:
/health:
@@ -1573,7 +1694,7 @@ paths:
parameters:
- name: metadata
in: query
- description: Metadata query used to filter the sandboxes (e.g. "user=abc&app=prod"). Each key and values must be URL encoded.
+ description: Metadata query used to filter the sandboxes (e.g. 'user=abc&app=prod'). Each key and values must be URL encoded.
required: false
schema:
type: string
@@ -1631,7 +1752,7 @@ paths:
parameters:
- name: metadata
in: query
- description: Metadata query used to filter the sandboxes (e.g. "user=abc&app=prod"). Each key and values must be URL encoded.
+ description: Metadata query used to filter the sandboxes (e.g. 'user=abc&app=prod'). Each key and values must be URL encoded.
required: false
schema:
type: string
@@ -2279,6 +2400,15 @@ paths:
format: int32
minimum: 0
description: Index of the starting build log that should be returned with the template
+ - in: query
+ name: limit
+ schema:
+ default: 100
+ type: integer
+ format: int32
+ minimum: 0
+ maximum: 100
+ description: Maximum number of logs that should be returned
- in: query
name: level
schema:
@@ -2297,6 +2427,147 @@ paths:
'500':
$ref: '#/components/responses/500'
+ /templates/{templateID}/builds/{buildID}/logs:
+ get:
+ description: Get template build logs
+ tags: [templates]
+ security:
+ - AccessTokenAuth: []
+ - ApiKeyAuth: []
+ - Supabase1TokenAuth: []
+ parameters:
+ - $ref: '#/components/parameters/templateID'
+ - $ref: '#/components/parameters/buildID'
+ - in: query
+ name: cursor
+ schema:
+ type: integer
+ format: int64
+ minimum: 0
+ description: Starting timestamp of the logs that should be returned in milliseconds
+ - in: query
+ name: limit
+ schema:
+ default: 100
+ type: integer
+ format: int32
+ minimum: 0
+ maximum: 100
+ description: Maximum number of logs that should be returned
+ - in: query
+ name: direction
+ schema:
+ $ref: '#/components/schemas/LogsDirection'
+ - in: query
+ name: level
+ schema:
+ $ref: '#/components/schemas/LogLevel'
+ - in: query
+ name: source
+ schema:
+ $ref: '#/components/schemas/LogsSource'
+ description: Source of the logs that should be returned from
+ responses:
+ '200':
+ description: Successfully returned the template build logs
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TemplateBuildLogsResponse'
+ '401':
+ $ref: '#/components/responses/401'
+ '404':
+ $ref: '#/components/responses/404'
+ '500':
+ $ref: '#/components/responses/500'
+
+ /templates/tags:
+ post:
+ description: Assign tag(s) to a template build
+ tags: [tags]
+ security:
+ - ApiKeyAuth: []
+ - Supabase1TokenAuth: []
+ Supabase2TeamAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AssignTemplateTagRequest'
+ responses:
+ '201':
+ description: Tag assigned successfully
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TemplateTag'
+ '400':
+ $ref: '#/components/responses/400'
+ '401':
+ $ref: '#/components/responses/401'
+ '404':
+ $ref: '#/components/responses/404'
+ '500':
+ $ref: '#/components/responses/500'
+ /templates/tags/{name}:
+ parameters:
+ - name: name
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Template name in 'alias:tag' format
+ delete:
+ description: Delete a tag from a template
+ tags: [tags]
+ security:
+ - ApiKeyAuth: []
+ - Supabase1TokenAuth: []
+ Supabase2TeamAuth: []
+ responses:
+ '204':
+ description: Tag deleted successfully
+ '400':
+ $ref: '#/components/responses/400'
+ '401':
+ $ref: '#/components/responses/401'
+ '404':
+ $ref: '#/components/responses/404'
+ '500':
+ $ref: '#/components/responses/500'
+
+ /templates/aliases/{alias}:
+ get:
+ description: Check if template with given alias exists
+ tags: [templates]
+ security:
+ - ApiKeyAuth: []
+ - Supabase1TokenAuth: []
+ Supabase2TeamAuth: []
+ parameters:
+ - name: alias
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Template alias
+ responses:
+ '200':
+ description: Successfully queried template by alias
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TemplateAliasResponse'
+ '400':
+ $ref: '#/components/responses/400'
+ '403':
+ $ref: '#/components/responses/403'
+ '404':
+ $ref: '#/components/responses/404'
+ '500':
+ $ref: '#/components/responses/500'
+
/nodes:
get:
description: List all nodes
@@ -2368,6 +2639,35 @@ paths:
'500':
$ref: '#/components/responses/500'
+ /admin/teams/{teamID}/sandboxes/kill:
+ post:
+ summary: Kill all sandboxes for a team
+ description: Kills all sandboxes for the specified team
+ tags: [admin]
+ security:
+ - AdminTokenAuth: []
+ parameters:
+ - name: teamID
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ description: Team ID
+ responses:
+ '200':
+ description: Successfully killed sandboxes
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AdminSandboxKillResult'
+ '401':
+ $ref: '#/components/responses/401'
+ '404':
+ $ref: '#/components/responses/404'
+ '500':
+ $ref: '#/components/responses/500'
+
/access-tokens:
post:
description: Create a new access token