The open-source agent harness - the runtime layer that turns an LLM into a working agent.
fix: reject duplicate sandbox environment names on create (#1015)
Sujai Kumar Gupta694a5722afa0
diff --git a/.changeset/sandbox-env-create-name-conflict.md b/.changeset/sandbox-env-create-name-conflict.mdnew file mode 100644index 000000000..fc5267da2--- /dev/null+++ b/.changeset/sandbox-env-create-name-conflict.md@@ -0,0 +1,8 @@+---+'@truefoundry/trueforge': patch+'@truefoundry/trueforge-ui': patch+'@truefoundry/trueforge-assistant-ui-runtime': patch+'@truefoundry/trueforge-sdk': patch+---++Reject duplicate sandbox environment names on create (POST) instead of overwriting via upsert.diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex 1e51b16ff..40a8100b3 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -1047,6 +1047,18 @@],"type": "object"},+ "CreateSandboxEnvironmentRequest": {+ "additionalProperties": false,+ "properties": {+ "manifest": {+ "$ref": "#/components/schemas/SandboxEnvironmentManifestRequest"+ }+ },+ "required": [+ "manifest"+ ],+ "type": "object"+ },"CreateScheduleRequest": {"additionalProperties": false,"properties": {@@ -8506,6 +8518,89 @@],"x-fern-sdk-method-name": "list"},+ "post": {+ "description": "Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateSandboxEnvironmentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetSandboxEnvironmentResponse"+ }+ }+ },+ "description": "The created sandbox environment."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid request body, resource allocation, or missing secret value."+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Unauthenticated."+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "A sandbox environment with this name already exists."+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Sandbox provider is missing, credentials are invalid, or rejected the secret."+ },+ "502": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Sandbox provider secret synchronization failed."+ }+ },+ "summary": "Create a sandbox environment",+ "tags": [+ "Sandboxes"+ ],+ "x-fern-sdk-group-name": [+ "sandboxEnvironments"+ ],+ "x-fern-sdk-method-name": "create"+ },"put": {"description": "Create or replace by `manifest.name`. Requires a configured sandbox provider.","requestBody": {diff --git a/docs/openapi.json b/docs/openapi.jsonindex 1e51b16ff..40a8100b3 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -1047,6 +1047,18 @@],"type": "object"},+ "CreateSandboxEnvironmentRequest": {+ "additionalProperties": false,+ "properties": {+ "manifest": {+ "$ref": "#/components/schemas/SandboxEnvironmentManifestRequest"+ }+ },+ "required": [+ "manifest"+ ],+ "type": "object"+ },"CreateScheduleRequest": {"additionalProperties": false,"properties": {@@ -8506,6 +8518,89 @@],"x-fern-sdk-method-name": "list"},+ "post": {+ "description": "Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateSandboxEnvironmentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetSandboxEnvironmentResponse"+ }+ }+ },+ "description": "The created sandbox environment."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid request body, resource allocation, or missing secret value."+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Unauthenticated."+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "A sandbox environment with this name already exists."+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Sandbox provider is missing, credentials are invalid, or rejected the secret."+ },+ "502": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Sandbox provider secret synchronization failed."+ }+ },+ "summary": "Create a sandbox environment",+ "tags": [+ "Sandboxes"+ ],+ "x-fern-sdk-group-name": [+ "sandboxEnvironments"+ ],+ "x-fern-sdk-method-name": "create"+ },"put": {"description": "Create or replace by `manifest.name`. Requires a configured sandbox provider.","requestBody": {diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.tsindex ae09d2ddc..6d194b78d 100644--- a/packages/assistant-ui-runtime/src/server/types.ts+++ b/packages/assistant-ui-runtime/src/server/types.ts@@ -1118,6 +1118,8 @@ export type ListSandboxEnvironmentsParams = Pick<PageParams, 'limit' | 'pageTokeexport interface SandboxEnvironmentServer<TEnvironment extends SandboxEnvironment = SandboxEnvironment> {listEnvironments(req?: ListSandboxEnvironmentsParams): Promise<ListResult<TEnvironment>>;getEnvironment(req: { name: string }): Promise<TEnvironment>;+ /** Create only β fails if `manifest.name` is already taken. */+ createEnvironment(req: { manifest: SandboxEnvironmentManifest }): Promise<TEnvironment>;createOrUpdateEnvironment(req: { manifest: SandboxEnvironmentManifest }): Promise<TEnvironment>;deleteEnvironment(req: { name: string }): Promise<void>;}diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.mdindex 6a22bb7fa..0ff033d2d 100644--- a/packages/trueforge-sdk/reference.md+++ b/packages/trueforge-sdk/reference.md@@ -972,6 +972,73 @@ const response = page.response;</dl>+</dd>+</dl>+</details>++<details><summary><code>client.sandboxEnvironments.<a href="/src/api/resources/sandboxEnvironments/client/Client.ts">create</a>({ ...params }) -> TrueForge.GetSandboxEnvironmentResponse</code></summary>+<dl>+<dd>++#### π Description++<dl>+<dd>++<dl>+<dd>++Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.+</dd>+</dl>+</dd>+</dl>++#### π Usage++<dl>+<dd>++<dl>+<dd>++```typescript+await client.sandboxEnvironments.create({+ manifest: {+ name: "name"+ }+});++```+</dd>+</dl>+</dd>+</dl>++#### βοΈ Parameters++<dl>+<dd>++<dl>+<dd>++**request:** `TrueForge.CreateSandboxEnvironmentRequest`++</dd>+</dl>++<dl>+<dd>++**requestOptions:** `SandboxEnvironmentsClient.RequestOptions`++</dd>+</dl>+</dd>+</dl>++</dd></dl></details>diff --git a/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/Client.ts b/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/Client.tsindex 1ceb2ac6f..8d72f37b0 100644--- a/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/Client.ts+++ b/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/Client.ts@@ -141,6 +141,152 @@ export class SandboxEnvironmentsClient {});}+ /**+ * Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.+ *+ * @param {TrueForge.CreateSandboxEnvironmentRequest} request+ * @param {SandboxEnvironmentsClient.RequestOptions} requestOptions - Request-specific configuration.+ *+ * @throws {@link TrueForge.BadRequestError}+ * @throws {@link TrueForge.UnauthorizedError}+ * @throws {@link TrueForge.ConflictError}+ * @throws {@link TrueForge.UnprocessableEntityError}+ * @throws {@link TrueForge.BadGatewayError}+ * @throws {@link errors.TrueForgeError}+ * @throws {@link errors.TrueForgeTimeoutError}+ *+ * @example+ * await client.sandboxEnvironments.create({+ * manifest: {+ * name: "name"+ * }+ * })+ */+ public create(+ request: TrueForge.CreateSandboxEnvironmentRequest,+ requestOptions?: SandboxEnvironmentsClient.RequestOptions,+ ): core.HttpResponsePromise<TrueForge.GetSandboxEnvironmentResponse> {+ return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));+ }++ private async __create(+ request: TrueForge.CreateSandboxEnvironmentRequest,+ requestOptions?: SandboxEnvironmentsClient.RequestOptions,+ ): Promise<core.WithRawResponse<TrueForge.GetSandboxEnvironmentResponse>> {+ const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(+ _authRequest.headers,+ this._options?.headers,+ requestOptions?.headers,+ );+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ "api/v1/sandbox-environments",+ ),+ method: "POST",+ headers: _headers,+ contentType: "application/json",+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),+ requestType: "json",+ body: mergeAdditionalBodyParameters(+ serializers.CreateSandboxEnvironmentRequest.jsonOrThrow(request, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ omitUndefined: true,+ }),+ requestOptions?.additionalBodyParameters,+ ),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.GetSandboxEnvironmentResponse.parseOrThrow(_response.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ rawResponse: _response.rawResponse,+ };+ }++ if (_response.error.reason === "status-code") {+ switch (_response.error.statusCode) {+ case 400:+ throw new TrueForge.BadRequestError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 401:+ throw new TrueForge.UnauthorizedError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 409:+ throw new TrueForge.ConflictError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 422:+ throw new TrueForge.UnprocessableEntityError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 502:+ throw new TrueForge.BadGatewayError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ default:+ throw new errors.TrueForgeError({+ statusCode: _response.error.statusCode,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }+ }++ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/api/v1/sandbox-environments");+ }+/*** Create or replace by `manifest.name`. Requires a configured sandbox provider.*diff --git a/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/requests/CreateSandboxEnvironmentRequest.ts b/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/requests/CreateSandboxEnvironmentRequest.tsnew file mode 100644index 000000000..e22241942--- /dev/null+++ b/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/requests/CreateSandboxEnvironmentRequest.ts@@ -0,0 +1,15 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../../../index.js";++/**+ * @example+ * {+ * manifest: {+ * name: "name"+ * }+ * }+ */+export interface CreateSandboxEnvironmentRequest {+ manifest: TrueForge.SandboxEnvironmentManifestRequest;+}diff --git a/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/requests/index.ts b/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/requests/index.tsindex bf9f82c2a..f20f36488 100644--- a/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/requests/index.ts+++ b/packages/trueforge-sdk/src/api/resources/sandboxEnvironments/client/requests/index.ts@@ -1,2 +1,3 @@+export type { CreateSandboxEnvironmentRequest } from "./CreateSandboxEnvironmentRequest.js";export type { ListSandboxEnvironmentsRequest } from "./ListSandboxEnvironmentsRequest.js";export type { UpdateSandboxEnvironmentRequest } from "./UpdateSandboxEnvironmentRequest.js";diff --git a/packages/trueforge-sdk/src/serialization/resources/sandboxEnvironments/client/requests/CreateSandboxEnvironmentRequest.ts b/packages/trueforge-sdk/src/serialization/resources/sandboxEnvironments/client/requests/CreateSandboxEnvironmentRequest.tsnew file mode 100644index 000000000..e91d4e660--- /dev/null+++ b/packages/trueforge-sdk/src/serialization/resources/sandboxEnvironments/client/requests/CreateSandboxEnvironmentRequest.ts@@ -0,0 +1,19 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../../../../api/index.js";+import * as core from "../../../../../core/index.js";+import type * as serializers from "../../../../index.js";+import { SandboxEnvironmentManifestRequest } from "../../../../types/SandboxEnvironmentManifestRequest.js";++export const CreateSandboxEnvironmentRequest: core.serialization.Schema<+ serializers.CreateSandboxEnvironmentRequest.Raw,+ TrueForge.CreateSandboxEnvironmentRequest+> = core.serialization.object({+ manifest: SandboxEnvironmentManifestRequest,+});++export declare namespace CreateSandboxEnvironmentRequest {+ export interface Raw {+ manifest: SandboxEnvironmentManifestRequest.Raw;+ }+}diff --git a/packages/trueforge-sdk/src/serialization/resources/sandboxEnvironments/client/requests/index.ts b/packages/trueforge-sdk/src/serialization/resources/sandboxEnvironments/client/requests/index.tsindex ab09842a3..77023ee76 100644--- a/packages/trueforge-sdk/src/serialization/resources/sandboxEnvironments/client/requests/index.ts+++ b/packages/trueforge-sdk/src/serialization/resources/sandboxEnvironments/client/requests/index.ts@@ -1 +1,2 @@+export { CreateSandboxEnvironmentRequest } from "./CreateSandboxEnvironmentRequest.js";export { UpdateSandboxEnvironmentRequest } from "./UpdateSandboxEnvironmentRequest.js";diff --git a/packages/trueforge-sdk/tests/wire/sandboxEnvironments.test.ts b/packages/trueforge-sdk/tests/wire/sandboxEnvironments.test.tsindex 67e838a88..caf67b14f 100644--- a/packages/trueforge-sdk/tests/wire/sandboxEnvironments.test.ts+++ b/packages/trueforge-sdk/tests/wire/sandboxEnvironments.test.ts@@ -116,6 +116,198 @@ describe("SandboxEnvironmentsClient", () => {}).rejects.toThrow(TrueForgeTypes.UnauthorizedError);});+ test("create (1)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { manifest: { name: "name" } };+ const rawResponseBody = {+ data: {+ created_at: "2024-01-15T09:30:00Z",+ created_by_subject: {+ subject_display_name: "subject_display_name",+ subject_id: "subject_id",+ subject_type: "subject_type",+ },+ description: "description",+ id: "id",+ lifecycle_stage: "active",+ manifest: {+ description: "description",+ environment_variables: { key: "value" },+ image: { build_script: "set -ex\npip install httpx\n", type: "build" },+ name: "name",+ },+ name: "name",+ status: "pending",+ status_reason: "status_reason",+ updated_at: "2024-01-15T09:30:00Z",+ },+ };++ server+ .mockEndpoint()+ .post("/api/v1/sandbox-environments")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(200)+ .jsonBody(rawResponseBody)+ .build();++ const response = await client.sandboxEnvironments.create({+ manifest: {+ name: "name",+ },+ });+ expect(response).toEqual({+ data: {+ createdAt: new Date("2024-01-15T09:30:00.000Z"),+ createdBySubject: {+ subjectDisplayName: "subject_display_name",+ subjectId: "subject_id",+ subjectType: "subject_type",+ },+ description: "description",+ id: "id",+ lifecycleStage: "active",+ manifest: {+ description: "description",+ environmentVariables: {+ key: "value",+ },+ image: {+ buildScript: "set -ex\npip install httpx\n",+ type: "build",+ },+ name: "name",+ },+ name: "name",+ status: "pending",+ statusReason: "status_reason",+ updatedAt: new Date("2024-01-15T09:30:00.000Z"),+ },+ });+ });++ test("create (2)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { manifest: { name: "xy" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/sandbox-environments")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(400)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.sandboxEnvironments.create({+ manifest: {+ name: "xy",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);+ });++ test("create (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { manifest: { name: "xy" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/sandbox-environments")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(401)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.sandboxEnvironments.create({+ manifest: {+ name: "xy",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.UnauthorizedError);+ });++ test("create (4)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { manifest: { name: "xy" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/sandbox-environments")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(409)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.sandboxEnvironments.create({+ manifest: {+ name: "xy",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.ConflictError);+ });++ test("create (5)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { manifest: { name: "xy" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/sandbox-environments")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(422)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.sandboxEnvironments.create({+ manifest: {+ name: "xy",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);+ });++ test("create (6)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { manifest: { name: "xy" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/sandbox-environments")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(502)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.sandboxEnvironments.create({+ manifest: {+ name: "xy",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.BadGatewayError);+ });+test("create_or_update (1)", async () => {const server = mockServerPool.createServer();const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });diff --git a/packages/trueforge-ui/src/atoms/environments/EnvironmentFormDrawer.tsx b/packages/trueforge-ui/src/atoms/environments/EnvironmentFormDrawer.tsxindex 8bc040ba6..e3a158b69 100644--- a/packages/trueforge-ui/src/atoms/environments/EnvironmentFormDrawer.tsx+++ b/packages/trueforge-ui/src/atoms/environments/EnvironmentFormDrawer.tsx@@ -57,7 +57,11 @@ export function EnvironmentFormDrawer({ open, onOpenChange, mode, environment, osetSaving(true);try {- const saved = await environmentServer.createOrUpdateEnvironment({ manifest: formValuesToManifest(form) });+ const manifest = formValuesToManifest(form);+ const saved =+ mode === 'create'+ ? await environmentServer.createEnvironment({ manifest })+ : await environmentServer.createOrUpdateEnvironment({ manifest });track(mode === 'create' ? AnalyticsEvents.Environment.CREATED : AnalyticsEvents.Environment.EDITED, {environment_name: saved.name,environment_id: saved.id,diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/sandboxEnvironments/sandboxEnvironmentServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/sandboxEnvironments/sandboxEnvironmentServer.tsindex 091329703..fda55aaf6 100644--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/sandboxEnvironments/sandboxEnvironmentServer.ts+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/sandboxEnvironments/sandboxEnvironmentServer.ts@@ -145,6 +145,13 @@ export function createSandboxEnvironmentServer(options: { client: TrueForge }):return toUiEnvironment(data);},+ async createEnvironment({ manifest }): Promise<SandboxEnvironment> {+ const { data } = await client.sandboxEnvironments.create({+ manifest: toWireManifest(manifest),+ });+ return toUiEnvironment(data);+ },+async createOrUpdateEnvironment({ manifest }): Promise<SandboxEnvironment> {const { data } = await client.sandboxEnvironments.createOrUpdate({manifest: toWireManifest(manifest),diff --git a/packages/trueforge-ui/test/atoms/environments/EnvironmentFormDrawer.test.tsx b/packages/trueforge-ui/test/atoms/environments/EnvironmentFormDrawer.test.tsxindex a9b6ccb1e..ff2d910ff 100644--- a/packages/trueforge-ui/test/atoms/environments/EnvironmentFormDrawer.test.tsx+++ b/packages/trueforge-ui/test/atoms/environments/EnvironmentFormDrawer.test.tsx@@ -72,7 +72,7 @@ function renderDrawer({onSaved?: () => void;track?: TrackAnalytics;} = {}) {- const createOrUpdateEnvironment = vi.fn(async ({ manifest }) => ({+ const savedEnvironment = async ({ manifest }: { manifest: SandboxEnvironment['manifest'] }) => ({id: 'e1',name: manifest.name,description: manifest.description ?? '',@@ -86,8 +86,11 @@ function renderDrawer({},createdAt: '2024-01-01T00:00:00.000Z',updatedAt: '2024-01-01T00:00:00.000Z',- }));+ });+ const createEnvironment = vi.fn(savedEnvironment);+ const createOrUpdateEnvironment = vi.fn(savedEnvironment);const environmentServer = createMockSandboxEnvironmentServer({+ createEnvironment,createOrUpdateEnvironment,...environmentOverrides,});@@ -109,21 +112,22 @@ function renderDrawer({);render(track != null ? <AnalyticsProvider track={track}>{tree}</AnalyticsProvider> : tree);- return { createOrUpdateEnvironment, onOpenChange, onSaved, track };+ return { createEnvironment, createOrUpdateEnvironment, onOpenChange, onSaved, track };}describe('EnvironmentFormDrawer', () => {it('saves UI form values', async () => {const track = vi.fn();- const { createOrUpdateEnvironment, onSaved } = renderDrawer({ track });+ const { createEnvironment, createOrUpdateEnvironment, onSaved } = renderDrawer({ track });expect(screen.queryByRole('button', { name: 'YAML' })).not.toBeInTheDocument();const nameInput = screen.getByPlaceholderText('my-environment');fireEvent.change(nameInput, { target: { value: 'node-web' } });fireEvent.click(screen.getByRole('button', { name: 'Create' }));await waitFor(() => {- expect(createOrUpdateEnvironment).toHaveBeenCalled();+ expect(createEnvironment).toHaveBeenCalled();});- expect(createOrUpdateEnvironment.mock.calls[0]?.[0]?.manifest.name).toBe('node-web');+ expect(createEnvironment.mock.calls[0]?.[0]?.manifest.name).toBe('node-web');+ expect(createOrUpdateEnvironment).not.toHaveBeenCalled();expect(onSaved).toHaveBeenCalled();expect(track).toHaveBeenCalledWith(AnalyticsEvents.Environment.CREATED, {environment_name: 'node-web',@@ -132,7 +136,10 @@ describe('EnvironmentFormDrawer', () => {});it('saves UI form values in edit without a YAML switch', async () => {- const { createOrUpdateEnvironment, onSaved } = renderDrawer({ mode: 'edit', environment: editEnvironment });+ const { createEnvironment, createOrUpdateEnvironment, onSaved } = renderDrawer({+ mode: 'edit',+ environment: editEnvironment,+ });expect(screen.queryByRole('button', { name: 'YAML' })).not.toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('write description ...'), {target: { value: 'updated description' },@@ -142,6 +149,7 @@ describe('EnvironmentFormDrawer', () => {expect(createOrUpdateEnvironment).toHaveBeenCalled();});expect(createOrUpdateEnvironment.mock.calls[0]?.[0]?.manifest.description).toBe('updated description');+ expect(createEnvironment).not.toHaveBeenCalled();expect(onSaved).toHaveBeenCalled();});@@ -153,7 +161,7 @@ describe('EnvironmentFormDrawer', () => {});renderDrawer({environmentOverrides: {- createOrUpdateEnvironment: vi.fn(async () => {+ createEnvironment: vi.fn(async () => {throw httpError;}),},diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/sandboxEnvironmentServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/sandboxEnvironmentServer.test.tsindex ee20207d7..e21b52717 100644--- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/sandboxEnvironmentServer.test.ts+++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/sandboxEnvironmentServer.test.ts@@ -3,9 +3,29 @@ import { describe, expect, it, vi } from 'vitest';import { createSandboxEnvironmentServer } from '@/plugins/trueforge-agent-server-adapter/sandboxEnvironments/sandboxEnvironmentServer.js';import type { TrueForge } from '@truefoundry/trueforge-sdk';+const savedEnvResponse = {+ data: {+ id: 'e2',+ name: 'node-web',+ description: '',+ lifecycleStage: 'active' as const,+ status: 'pending' as const,+ statusReason: null,+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ updatedAt: new Date('2024-01-01T00:00:00.000Z'),+ createdBySubject: {+ subjectId: 'user-1',+ subjectType: 'user' as const,+ subjectDisplayName: '[email protected]',+ },+ manifest: { name: 'node-web', resources: { cpu: 1, memory: 1, disk: 3 } },+ },+};+function mockClient(overrides: {list?: ReturnType<typeof vi.fn>;+ create?: ReturnType<typeof vi.fn>;createOrUpdate?: ReturnType<typeof vi.fn>;delete?: ReturnType<typeof vi.fn>;} = {},@@ -45,26 +65,8 @@ function mockClient(sandboxEnvironments: {list,get: vi.fn(),- createOrUpdate:- overrides.createOrUpdate ??- vi.fn(async () => ({- data: {- id: 'e2',- name: 'node-web',- description: '',- lifecycleStage: 'active' as const,- status: 'pending' as const,- statusReason: null,- createdAt: new Date('2024-01-01T00:00:00.000Z'),- updatedAt: new Date('2024-01-01T00:00:00.000Z'),- createdBySubject: {- subjectId: 'user-1',- subjectType: 'user',- subjectDisplayName: '[email protected]',- },- manifest: { name: 'node-web', resources: { cpu: 1, memory: 1, disk: 3 } },- },- })),+ create: overrides.create ?? vi.fn(async () => savedEnvResponse),+ createOrUpdate: overrides.createOrUpdate ?? vi.fn(async () => savedEnvResponse),delete: overrides.delete ?? vi.fn(async () => ({})),},} as unknown as TrueForge;@@ -85,28 +87,19 @@ describe('createSandboxEnvironmentServer', () => {expect(client.sandboxEnvironments.list).toHaveBeenCalledWith({ limit: 1000 });});- it('createOrUpdate and delete call SDK methods', async () => {- const createOrUpdate = vi.fn(async () => ({- data: {- id: 'e2',- name: 'node-web',- description: '',- lifecycleStage: 'active' as const,- status: 'pending' as const,- statusReason: null,- createdAt: new Date('2024-01-01T00:00:00.000Z'),- updatedAt: new Date('2024-01-01T00:00:00.000Z'),- createdBySubject: {- subjectId: 'user-1',- subjectType: 'user',- subjectDisplayName: '[email protected]',- },- manifest: { name: 'node-web' },- },- }));+ it('create, createOrUpdate, and delete call SDK methods', async () => {+ const create = vi.fn(async () => savedEnvResponse);+ const createOrUpdate = vi.fn(async () => savedEnvResponse);const del = vi.fn(async () => ({}));- const client = mockClient({ createOrUpdate, delete: del });+ const client = mockClient({ create, createOrUpdate, delete: del });const server = createSandboxEnvironmentServer({ client });+ const created = await server.createEnvironment({+ manifest: { name: 'node-web', resources: { cpu: 1, memory: 1, disk: 3 } },+ });+ expect(created.name).toBe('node-web');+ expect(create).toHaveBeenCalledWith({+ manifest: { name: 'node-web', resources: { cpu: 1, memory: 1, disk: 3 } },+ });const saved = await server.createOrUpdateEnvironment({manifest: { name: 'node-web', resources: { cpu: 1, memory: 1, disk: 3 } },});diff --git a/packages/trueforge-ui/test/server/mockServer.ts b/packages/trueforge-ui/test/server/mockServer.tsindex 4922d473a..b8b986e7f 100644--- a/packages/trueforge-ui/test/server/mockServer.ts+++ b/packages/trueforge-ui/test/server/mockServer.ts@@ -64,6 +64,7 @@ export function createMockSandboxEnvironmentServer(return {listEnvironments: async () => ({ data: [] }),getEnvironment: unavailable,+ createEnvironment: unavailable,createOrUpdateEnvironment: unavailable,deleteEnvironment: unavailable,...overrides,diff --git a/packages/trueforge/src/apis/sandboxEnvironments.ts b/packages/trueforge/src/apis/sandboxEnvironments.tsindex 88397c817..9401c164f 100644--- a/packages/trueforge/src/apis/sandboxEnvironments.ts+++ b/packages/trueforge/src/apis/sandboxEnvironments.ts@@ -1,7 +1,7 @@/*** Sandbox environments API (mounted at /api/v1/sandbox-environments).* Snapshot builds are not started here β versions land in `pending` for a future controller.- * Networking secrets sync to Daytona on PUT (plaintext is never persisted).+ * Networking secrets sync to Daytona on create/update (plaintext is never persisted).*/import { DaytonaError } from '@daytona/sdk';import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';@@ -13,11 +13,13 @@ import type { IAgentStore } from '../db/agentStore';import {SandboxEnvironmentNameConflictError,SandboxEnvironmentVersionConflictError,+ type ExistingSandboxEnvironmentVersion,type ISandboxEnvironmentStore,type SandboxEnvironmentWithVersion,} from '../db/sandboxEnvironmentStore';import type { ISandboxProviderStore, SandboxProviderRecord } from '../db/sandboxProviderStore';import {+ createSandboxEnvironmentRoute,deleteSandboxEnvironmentRoute,getSandboxEnvironmentRoute,listSandboxEnvironmentsRoute,@@ -30,7 +32,12 @@ import {SandboxEnvironmentSecretSyncError,syncSandboxEnvironmentSecrets,} from '../sandbox/syncSandboxEnvironmentSecrets';-import { DEFAULT_SANDBOX_ENVIRONMENT_NAME, type SandboxEnvironment } from '../schemas/sandboxEnvironment';+import {+ DEFAULT_SANDBOX_ENVIRONMENT_NAME,+ type CreateSandboxEnvironmentRequest,+ type SandboxEnvironment,+ type UpdateSandboxEnvironmentRequest,+} from '../schemas/sandboxEnvironment';import { MissingStoredSecretError } from '../utils/secretRedaction';export interface SandboxEnvironmentsRouterDeps<TTransaction> {@@ -122,19 +129,44 @@ export function createSandboxEnvironmentsRouter<TTransaction>(return c.json({ data: toSandboxEnvironment(loaded) }, 200);};- // Create-or-update keyed by manifest.name.- const putHandler: RouteHandler<typeof putSandboxEnvironmentRoute> = async c => {- const body = c.req.valid('json');+ type WriteSandboxEnvironmentOutcome =+ | { kind: 'saved'; environment: SandboxEnvironment }+ | { kind: 'error'; status: 400 | 409 | 422 | 502; message: string };++ async function writeSandboxEnvironment({+ c,+ body,+ mode,+ }: {+ c: Context;+ body: CreateSandboxEnvironmentRequest | UpdateSandboxEnvironmentRequest;+ mode: 'create' | 'upsert';+ }): Promise<WriteSandboxEnvironmentOutcome> {const requestContext = resolveRequestContext(c);const { manifest } = body;const provider = await resolveSandboxProviderRecord(deps.resolveSandboxProviderStore(c), requestContext.tenant_id);if (provider === undefined) {- return c.json({ error: { message: 'No sandbox provider configured' } }, 422);+ return { kind: 'error', status: 422, message: 'No sandbox provider configured' };}const created_by_subject = createdBySubjectFromRequestContext(requestContext);try {+ // Tenant-wide name check before secret sync so create cannot mutate another env's secrets.+ if (mode === 'create') {+ const taken = await store.getEnvironment({+ tenant_id: requestContext.tenant_id,+ name: manifest.name,+ });+ if (taken) {+ return {+ kind: 'error',+ status: 409,+ message: `Sandbox environment with name ${manifest.name} already exists`,+ };+ }+ }+const existing = await store.getEnvironment({tenant_id: requestContext.tenant_id,name: manifest.name,@@ -155,13 +187,17 @@ export function createSandboxEnvironmentsRouter<TTransaction>(description: `Secret value of environment ${manifest.name}`,});- const result = await store.upsertEnvironment({+ const writeInput = {tenant_id: requestContext.tenant_id,name: manifest.name,description: manifest.description ?? '',created_by_subject,synced_secrets,- buildVersion: ({ existing_version, existing_manifest, existing_external_ref }) =>+ buildVersion: ({+ existing_version,+ existing_manifest,+ existing_external_ref,+ }: ExistingSandboxEnvironmentVersion) =>Promise.resolve({...buildNextVersion({...(existing_version !== undefined ? { existing_version } : {}),@@ -172,25 +208,44 @@ export function createSandboxEnvironmentsRouter<TTransaction>(}),created_by_subject,}),- });+ };+ const result =+ mode === 'create' ? await store.createEnvironment(writeInput) : await store.upsertEnvironment(writeInput);- return c.json({ data: toSandboxEnvironment(result) }, 200);+ return { kind: 'saved', environment: toSandboxEnvironment(result) };} catch (error) {if (error instanceof SandboxEnvironmentNameConflictError) {- return c.json({ error: { message: error.message } }, 409);+ return { kind: 'error', status: 409, message: error.message };}if (error instanceof SandboxEnvironmentVersionConflictError) {- return c.json({ error: { message: 'Sandbox environment was updated concurrently; retry' } }, 409);+ return { kind: 'error', status: 409, message: 'Sandbox environment was updated concurrently; retry' };}if (error instanceof MissingStoredSecretError) {- return c.json({ error: { message: 'Secret value is required' } }, 400);+ return { kind: 'error', status: 400, message: 'Secret value is required' };}const secretError = sandboxEnvironmentSecretHttpError(error);if (secretError !== undefined) {- return c.json({ error: { message: secretError.message } }, secretError.status);+ return { kind: 'error', status: secretError.status, message: secretError.message };}throw error;}+ }++ const createHandler: RouteHandler<typeof createSandboxEnvironmentRoute> = async c => {+ const outcome = await writeSandboxEnvironment({ c, body: c.req.valid('json'), mode: 'create' });+ if (outcome.kind === 'error') {+ return c.json({ error: { message: outcome.message } }, outcome.status);+ }+ return c.json({ data: outcome.environment }, 201);+ };++ // Create-or-update keyed by manifest.name.+ const putHandler: RouteHandler<typeof putSandboxEnvironmentRoute> = async c => {+ const outcome = await writeSandboxEnvironment({ c, body: c.req.valid('json'), mode: 'upsert' });+ if (outcome.kind === 'error') {+ return c.json({ error: { message: outcome.message } }, outcome.status);+ }+ return c.json({ data: outcome.environment }, 200);};const deleteHandler: RouteHandler<typeof deleteSandboxEnvironmentRoute> = async c => {@@ -251,6 +306,7 @@ export function createSandboxEnvironmentsRouter<TTransaction>(const router = new OpenAPIHono();router.openapi(listSandboxEnvironmentsRoute, listHandler);router.openapi(getSandboxEnvironmentRoute, getHandler);+ router.openapi(createSandboxEnvironmentRoute, createHandler);router.openapi(putSandboxEnvironmentRoute, putHandler);router.openapi(deleteSandboxEnvironmentRoute, deleteHandler);return router;diff --git a/packages/trueforge/src/db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore.ts b/packages/trueforge/src/db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore.tsindex 55ac67eb1..2eef94574 100644--- a/packages/trueforge/src/db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore.ts+++ b/packages/trueforge/src/db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore.ts@@ -17,6 +17,7 @@ import {parseStoredSandboxEnvironmentManifest,SandboxEnvironmentNameConflictError,SandboxEnvironmentVersionConflictError,+ type CreateSandboxEnvironmentInput,type DeleteSandboxEnvironmentInput,type GetSandboxEnvironmentInput,type GetSandboxEnvironmentVersionInput,@@ -303,20 +304,33 @@ export class PostgresSandboxEnvironmentStore implements ISandboxEnvironmentStore};}+ async createEnvironment(+ input: CreateSandboxEnvironmentInput,+ transaction?: Transaction<Database>,+ ): Promise<SandboxEnvironmentWithVersion> {+ if (transaction) {+ return this.#writeEnvironment(input, transaction, { mode: 'create' });+ }+ return this.#db.transaction().execute(db => this.#writeEnvironment(input, db, { mode: 'create' }));+ }+async upsertEnvironment(input: UpsertSandboxEnvironmentInput,transaction?: Transaction<Database>,): Promise<SandboxEnvironmentWithVersion> {if (transaction) {- return this.#upsertEnvironment(input, transaction);+ return this.#writeEnvironment(input, transaction, { mode: 'upsert' });}- return this.#db.transaction().execute(db => this.#upsertEnvironment(input, db));+ return this.#db.transaction().execute(db => this.#writeEnvironment(input, db, { mode: 'upsert' }));}- async #upsertEnvironment(+ async #writeEnvironment(input: UpsertSandboxEnvironmentInput,db: Transaction<Database>,+ options: { mode: 'create' | 'upsert' },): Promise<SandboxEnvironmentWithVersion> {+ // `"default"` is tenant-wide (no owner filter); public CRUD rejects that name in the request schema.+ // Store still allows it so ensureDefaultSandboxEnvironment can upsert the system tip.const isDefault = input.name === DEFAULT_SANDBOX_ENVIRONMENT_NAME;let environmentQuery = db.selectFrom('sandbox_environment')@@ -333,6 +347,10 @@ export class PostgresSandboxEnvironmentStore implements ISandboxEnvironmentStore}const environmentRow = await environmentQuery.forUpdate().executeTakeFirst();+ if (environmentRow && options.mode === 'create') {+ throw new SandboxEnvironmentNameConflictError({ tenant_id: input.tenant_id, name: input.name });+ }+if (!environmentRow) {const environment_id = newId();// Parent first so secret FKs can resolve in this transaction.diff --git a/packages/trueforge/src/db/sandboxEnvironmentStore.ts b/packages/trueforge/src/db/sandboxEnvironmentStore.tsindex bafd4023d..788ef7dde 100644--- a/packages/trueforge/src/db/sandboxEnvironmentStore.ts+++ b/packages/trueforge/src/db/sandboxEnvironmentStore.ts@@ -129,17 +129,20 @@ export interface ExistingSandboxEnvironmentVersion {existing_external_ref?: string;}-export interface UpsertSandboxEnvironmentInput {+export interface CreateSandboxEnvironmentInput {tenant_id: string;name: ResourceName;description: string;created_by_subject: CreatedBySubject;- /** Complete provider refs from a successful secret sync before upsert. */+ /** Complete provider refs from a successful secret sync before write. */synced_secrets: SyncedSandboxEnvironmentSecret[];/** Called after parent lock/create; store upserts secrets from the returned manifest. */buildVersion: (input: ExistingSandboxEnvironmentVersion) => Promise<UpsertSandboxEnvironmentVersion>;}+/** Same fields as create β create-or-replace by `(tenant_id, name)`. */+export type UpsertSandboxEnvironmentInput = CreateSandboxEnvironmentInput;+export interface MarkSandboxEnvironmentVersionReadyInput {environment_version_id: string;}@@ -162,7 +165,7 @@ export class SandboxEnvironmentNameConflictError extends Error {readonly environment_name: string;constructor({ tenant_id, name }: { tenant_id: string; name: string }, options?: ErrorOptions) {- super(`Sandbox environment name already exists: ${name}`, options);+ super(`Sandbox environment with name ${name} already exists`, options);this.name = 'SandboxEnvironmentNameConflictError';this.tenant_id = tenant_id;this.environment_name = name;@@ -202,6 +205,15 @@ export interface ISandboxEnvironmentStore<TTransaction = never> {input: GetSandboxEnvironmentInput,transaction?: TTransaction,): Promise<SandboxEnvironmentWithVersion | undefined>;+ /**+ * Create by `(tenant_id, name)` β parent + version row.+ * Throws {@link SandboxEnvironmentNameConflictError} if an active environment already+ * uses the name. Uses `transaction` when passed; otherwise opens its own.+ */+ createEnvironment(+ input: CreateSandboxEnvironmentInput,+ transaction?: TTransaction,+ ): Promise<SandboxEnvironmentWithVersion>;/*** Create or replace by `(tenant_id, name)` β parent + version row.* Updates insert a new version; parent `active_version` advances only when status isdiff --git a/packages/trueforge/src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore.ts b/packages/trueforge/src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore.tsindex df854e4cc..707566344 100644--- a/packages/trueforge/src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore.ts+++ b/packages/trueforge/src/db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore.ts@@ -22,6 +22,7 @@ import {parseStoredSandboxEnvironmentManifest,SandboxEnvironmentNameConflictError,SandboxEnvironmentVersionConflictError,+ type CreateSandboxEnvironmentInput,type DeleteSandboxEnvironmentInput,type GetSandboxEnvironmentInput,type GetSandboxEnvironmentVersionInput,@@ -374,20 +375,33 @@ export class SqliteSandboxEnvironmentStore implements ISandboxEnvironmentStore<T};}+ async createEnvironment(+ input: CreateSandboxEnvironmentInput,+ transaction?: Transaction<Database>,+ ): Promise<SandboxEnvironmentWithVersion> {+ if (transaction) {+ return this.#writeEnvironment(input, transaction, { mode: 'create' });+ }+ return this.#db.transaction().execute(db => this.#writeEnvironment(input, db, { mode: 'create' }));+ }+async upsertEnvironment(input: UpsertSandboxEnvironmentInput,transaction?: Transaction<Database>,): Promise<SandboxEnvironmentWithVersion> {if (transaction) {- return this.#upsertEnvironment(input, transaction);+ return this.#writeEnvironment(input, transaction, { mode: 'upsert' });}- return this.#db.transaction().execute(db => this.#upsertEnvironment(input, db));+ return this.#db.transaction().execute(db => this.#writeEnvironment(input, db, { mode: 'upsert' }));}- async #upsertEnvironment(+ async #writeEnvironment(input: UpsertSandboxEnvironmentInput,db: Transaction<Database>,+ options: { mode: 'create' | 'upsert' },): Promise<SandboxEnvironmentWithVersion> {+ // `"default"` is tenant-wide (no owner filter); public CRUD rejects that name in the request schema.+ // Store still allows it so ensureDefaultSandboxEnvironment can upsert the system tip.const isDefault = input.name === DEFAULT_SANDBOX_ENVIRONMENT_NAME;let environmentQuery = db.selectFrom('sandbox_environment')@@ -414,6 +428,10 @@ export class SqliteSandboxEnvironmentStore implements ISandboxEnvironmentStore<T}const environmentRow = await environmentQuery.executeTakeFirst();+ if (environmentRow && options.mode === 'create') {+ throw new SandboxEnvironmentNameConflictError({ tenant_id: input.tenant_id, name: input.name });+ }+if (!environmentRow) {const environment_id = newId();const created_at = nowIso();diff --git a/packages/trueforge/src/routes/sandboxEnvironmentRoutes.ts b/packages/trueforge/src/routes/sandboxEnvironmentRoutes.tsindex 3e1738011..ba901a7bf 100644--- a/packages/trueforge/src/routes/sandboxEnvironmentRoutes.ts+++ b/packages/trueforge/src/routes/sandboxEnvironmentRoutes.ts@@ -6,6 +6,7 @@ import { createRoute, z } from '@hono/zod-openapi';import { NameSchema, PAGE_LIMIT } from '../schemas/common';import { RequestErrorResponseSchema } from '../schemas/errors';import {+ CreateSandboxEnvironmentRequestSchema,DeleteSandboxEnvironmentResponseSchema,GetSandboxEnvironmentResponseSchema,ListSandboxEnvironmentsResponseSchema,@@ -90,6 +91,49 @@ export const getSandboxEnvironmentRoute = createRoute({},});+export const createSandboxEnvironmentRoute = createRoute({+ method: 'post',+ path: '/',+ tags: [OpenApiTag.SANDBOXES],+ summary: 'Create a sandbox environment',+ description:+ 'Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.',+ 'x-fern-sdk-group-name': ['sandboxEnvironments'],+ 'x-fern-sdk-method-name': 'create',+ request: {+ body: {+ content: { 'application/json': { schema: CreateSandboxEnvironmentRequestSchema } },+ required: true,+ },+ },+ responses: {+ 201: {+ content: { 'application/json': { schema: GetSandboxEnvironmentResponseSchema } },+ description: 'The created sandbox environment.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid request body, resource allocation, or missing secret value.',+ },+ 401: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Unauthenticated.',+ },+ 409: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'A sandbox environment with this name already exists.',+ },+ 422: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Sandbox provider is missing, credentials are invalid, or rejected the secret.',+ },+ 502: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Sandbox provider secret synchronization failed.',+ },+ },+});+export const putSandboxEnvironmentRoute = createRoute({method: 'put',path: '/',diff --git a/packages/trueforge/src/schemas/sandboxEnvironment.ts b/packages/trueforge/src/schemas/sandboxEnvironment.tsindex 74f8118f2..9cc9f3974 100644--- a/packages/trueforge/src/schemas/sandboxEnvironment.ts+++ b/packages/trueforge/src/schemas/sandboxEnvironment.ts@@ -182,26 +182,40 @@ export const SandboxEnvironmentVersionInternalMetadataSchema = z}).strict();-/** PUT create-or-update body (single write API). */-export const UpdateSandboxEnvironmentRequestSchema = z+function refineSandboxEnvironmentResources(+ body: { manifest: { resources: { cpu: number; memory: number; disk: number } } },+ ctx: z.RefinementCtx,+): void {+ const { cpu, memory, disk } = body.manifest.resources;+ if (+ cpu > configuration.SANDBOX_ENVIRONMENT_CPU_MAX ||+ memory > configuration.SANDBOX_ENVIRONMENT_MEMORY_GIB_MAX ||+ disk > configuration.SANDBOX_ENVIRONMENT_DISK_GIB_MAX+ ) {+ ctx.addIssue({+ code: 'custom',+ path: ['manifest', 'resources'],+ message: 'Sandbox environment resources exceed configured limits',+ });+ }+}++/** POST create body. */+export const CreateSandboxEnvironmentRequestSchema = z.object({manifest: SandboxEnvironmentManifestRequestSchema,}).strict()- .superRefine((body, ctx) => {- const { cpu, memory, disk } = body.manifest.resources;- if (- cpu > configuration.SANDBOX_ENVIRONMENT_CPU_MAX ||- memory > configuration.SANDBOX_ENVIRONMENT_MEMORY_GIB_MAX ||- disk > configuration.SANDBOX_ENVIRONMENT_DISK_GIB_MAX- ) {- ctx.addIssue({- code: 'custom',- path: ['manifest', 'resources'],- message: 'Sandbox environment resources exceed configured limits',- });- }+ .superRefine(refineSandboxEnvironmentResources)+ .openapi('CreateSandboxEnvironmentRequest');++/** PUT create-or-update body. */+export const UpdateSandboxEnvironmentRequestSchema = z+ .object({+ manifest: SandboxEnvironmentManifestRequestSchema,})+ .strict()+ .superRefine(refineSandboxEnvironmentResources).openapi('UpdateSandboxEnvironmentRequest');const IsoTimestamp = z.iso.datetime().openapi({ type: 'string', format: 'date-time' });@@ -241,5 +255,6 @@ export type SandboxEnvironmentSecret = z.infer<typeof SandboxEnvironmentSecretScexport type SandboxEnvironmentManifest = z.infer<typeof SandboxEnvironmentManifestSchema>;export type StoredSandboxEnvironmentManifest = z.infer<typeof StoredSandboxEnvironmentManifestSchema>;export type SandboxEnvironmentVersionInternalMetadata = z.infer<typeof SandboxEnvironmentVersionInternalMetadataSchema>;+export type CreateSandboxEnvironmentRequest = z.infer<typeof CreateSandboxEnvironmentRequestSchema>;export type UpdateSandboxEnvironmentRequest = z.infer<typeof UpdateSandboxEnvironmentRequestSchema>;export type SandboxEnvironment = z.infer<typeof SandboxEnvironmentSchema>;diff --git a/packages/trueforge/src/truefoundry/TrueFoundrySandboxEnvironmentStore.ts b/packages/trueforge/src/truefoundry/TrueFoundrySandboxEnvironmentStore.tsindex b99b2140c..ac06336f1 100644--- a/packages/trueforge/src/truefoundry/TrueFoundrySandboxEnvironmentStore.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundrySandboxEnvironmentStore.ts@@ -8,19 +8,21 @@import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';import { encodeOffsetPageToken } from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';import { createLogger } from 'winston';-import type {- DeleteSandboxEnvironmentInput,- GetSandboxEnvironmentInput,- GetSandboxEnvironmentVersionInput,- ISandboxEnvironmentStore,- ListSandboxEnvironmentsInput,- MarkSandboxEnvironmentVersionFailedInput,- MarkSandboxEnvironmentVersionReadyInput,- SandboxEnvironmentSecretRecord,- SandboxEnvironmentVersionForProgress,- SandboxEnvironmentVersionRecord,- SandboxEnvironmentWithVersion,- UpsertSandboxEnvironmentInput,+import {+ SandboxEnvironmentNameConflictError,+ type CreateSandboxEnvironmentInput,+ type DeleteSandboxEnvironmentInput,+ type GetSandboxEnvironmentInput,+ type GetSandboxEnvironmentVersionInput,+ type ISandboxEnvironmentStore,+ type ListSandboxEnvironmentsInput,+ type MarkSandboxEnvironmentVersionFailedInput,+ type MarkSandboxEnvironmentVersionReadyInput,+ type SandboxEnvironmentSecretRecord,+ type SandboxEnvironmentVersionForProgress,+ type SandboxEnvironmentVersionRecord,+ type SandboxEnvironmentWithVersion,+ type UpsertSandboxEnvironmentInput,} from '../db/sandboxEnvironmentStore';import { DEFAULT_SANDBOX_ENVIRONMENT_NAME } from '../schemas/sandboxEnvironment';import { trueFoundryManaged } from './errors';@@ -122,6 +124,23 @@ export class TrueFoundrySandboxEnvironmentStore<return this.#persistence.getActiveEnvironment(input, transaction);}+ createEnvironment(+ input: CreateSandboxEnvironmentInput,+ transaction?: TTransaction,+ ): Promise<SandboxEnvironmentWithVersion> {+ if (!this.#envSupported) {+ logger.info('Skipping sandbox environment create (provider does not support environments)', {+ name: input.name,+ tenant_id: input.tenant_id,+ });+ return trueFoundryManaged();+ }+ if (input.name === DEFAULT_SANDBOX_ENVIRONMENT_NAME) {+ return Promise.reject(new SandboxEnvironmentNameConflictError({ tenant_id: input.tenant_id, name: input.name }));+ }+ return this.#persistence.createEnvironment(input, transaction);+ }+upsertEnvironment(input: UpsertSandboxEnvironmentInput,transaction?: TTransaction,diff --git a/packages/trueforge/tests/unit/apis/sandboxEnvironments.test.ts b/packages/trueforge/tests/unit/apis/sandboxEnvironments.test.tsindex c7ac12c8e..a387aaf79 100644--- a/packages/trueforge/tests/unit/apis/sandboxEnvironments.test.ts+++ b/packages/trueforge/tests/unit/apis/sandboxEnvironments.test.ts@@ -165,6 +165,57 @@ describe('sandbox environments API β build controller path', () => {expect(putRes.status).toBe(400);});+ it('POST creates an environment and returns 409 on name clash', async () => {+ const { publicRouter } = await setup();+ jest.mocked(providerUtils.toDaytonaSandboxProvider).mockReturnValue({+ createSecret: jest.fn(),+ updateSecret: jest.fn(),+ deleteSecret: jest.fn(),+ getBuildStatus: jest.fn(),+ build: jest.fn(),+ } as never);++ const createBody = {+ manifest: {+ name: 'create-only-env',+ description: 'first',+ image: { type: 'build', build_script: 'pip install httpx' },+ },+ };+ const created = await publicRouter.request('/', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(createBody),+ });+ expect(created.status).toBe(201);+ const createdBody = (await created.json()) as { data: { name: string; description: string } };+ expect(createdBody.data).toMatchObject({ name: 'create-only-env', description: 'first' });++ const clash = await publicRouter.request('/', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ manifest: {+ name: 'create-only-env',+ description: 'overwrite attempt',+ image: { type: 'build', build_script: 'pip install requests' },+ },+ }),+ });+ expect(clash.status).toBe(409);+ expect(await clash.json()).toEqual({+ error: { message: 'Sandbox environment with name create-only-env already exists' },+ });++ const getRes = await publicRouter.request('/create-only-env');+ expect(getRes.status).toBe(200);+ const getBody = (await getRes.json()) as {+ data: { description: string; manifest: { image?: { build_script?: string } } };+ };+ expect(getBody.data.description).toBe('first');+ expect(getBody.data.manifest.image?.build_script).toBe('pip install httpx');+ });+it('lists environments for the caller without error when none exist yet', async () => {const { publicRouter } = await setup();const listRes = await publicRouter.request('/');diff --git a/python/trueforge_sdk/reference.md b/python/trueforge_sdk/reference.mdindex 8d6fc7d1e..7ebef4ab3 100644--- a/python/trueforge_sdk/reference.md+++ b/python/trueforge_sdk/reference.md@@ -1124,6 +1124,80 @@ client.sandbox_environments.list()</dl>+</dd>+</dl>+</details>++<details><summary><code>client.sandbox_environments.<a href="src/trueforge_sdk/sandbox_environments/client.py">create</a>(...) -> GetSandboxEnvironmentResponse</code></summary>+<dl>+<dd>++#### π Description++<dl>+<dd>++<dl>+<dd>++Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.+</dd>+</dl>+</dd>+</dl>++#### π Usage++<dl>+<dd>++<dl>+<dd>++```python+from trueforge_sdk import TrueForge, SandboxEnvironmentManifestRequest++client = TrueForge(+ token="<token>",+ base_url="https://yourhost.com/path/to/api",+)++client.sandbox_environments.create(+ manifest=SandboxEnvironmentManifestRequest(+ name="name",+ ),+)++```+</dd>+</dl>+</dd>+</dl>++#### βοΈ Parameters++<dl>+<dd>++<dl>+<dd>++**manifest:** `SandboxEnvironmentManifestRequest`++</dd>+</dl>++<dl>+<dd>++**request_options:** `typing.Optional[RequestOptions]` β Request-specific configuration.++</dd>+</dl>+</dd>+</dl>++</dd></dl></details>diff --git a/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/client.py b/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/client.pyindex 4b2c65a10..85188dad1 100644--- a/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/client.py+++ b/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/client.py@@ -74,6 +74,41 @@ class SandboxEnvironmentsClient:"""return self._raw_client.list(limit=limit, page_token=page_token, request_options=request_options)+ def create(+ self, *, manifest: SandboxEnvironmentManifestRequest, request_options: typing.Optional[RequestOptions] = None+ ) -> GetSandboxEnvironmentResponse:+ """+ Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.++ Parameters+ ----------+ manifest : SandboxEnvironmentManifestRequest++ request_options : typing.Optional[RequestOptions]+ Request-specific configuration.++ Returns+ -------+ GetSandboxEnvironmentResponse+ The created sandbox environment.++ Examples+ --------+ from trueforge_sdk import SandboxEnvironmentManifestRequest, TrueForge++ client = TrueForge(+ token="YOUR_TOKEN",+ base_url="https://yourhost.com/path/to/api",+ )+ client.sandbox_environments.create(+ manifest=SandboxEnvironmentManifestRequest(+ name="name",+ ),+ )+ """+ _response = self._raw_client.create(manifest=manifest, request_options=request_options)+ return _response.data+def create_or_update(self, *, manifest: SandboxEnvironmentManifestRequest, request_options: typing.Optional[RequestOptions] = None) -> GetSandboxEnvironmentResponse:@@ -245,6 +280,49 @@ class AsyncSandboxEnvironmentsClient:"""return await self._raw_client.list(limit=limit, page_token=page_token, request_options=request_options)+ async def create(+ self, *, manifest: SandboxEnvironmentManifestRequest, request_options: typing.Optional[RequestOptions] = None+ ) -> GetSandboxEnvironmentResponse:+ """+ Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.++ Parameters+ ----------+ manifest : SandboxEnvironmentManifestRequest++ request_options : typing.Optional[RequestOptions]+ Request-specific configuration.++ Returns+ -------+ GetSandboxEnvironmentResponse+ The created sandbox environment.++ Examples+ --------+ import asyncio++ from trueforge_sdk import AsyncTrueForge, SandboxEnvironmentManifestRequest++ client = AsyncTrueForge(+ token="YOUR_TOKEN",+ base_url="https://yourhost.com/path/to/api",+ )+++ async def main() -> None:+ await client.sandbox_environments.create(+ manifest=SandboxEnvironmentManifestRequest(+ name="name",+ ),+ )+++ asyncio.run(main())+ """+ _response = await self._raw_client.create(manifest=manifest, request_options=request_options)+ return _response.data+async def create_or_update(self, *, manifest: SandboxEnvironmentManifestRequest, request_options: typing.Optional[RequestOptions] = None) -> GetSandboxEnvironmentResponse:diff --git a/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/raw_client.py b/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/raw_client.pyindex 3473cc049..d899d072f 100644--- a/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/raw_client.py+++ b/python/trueforge_sdk/src/trueforge_sdk/sandbox_environments/raw_client.py@@ -121,6 +121,112 @@ class RawSandboxEnvironmentsClient:)raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)+ def create(+ self, *, manifest: SandboxEnvironmentManifestRequest, request_options: typing.Optional[RequestOptions] = None+ ) -> HttpResponse[GetSandboxEnvironmentResponse]:+ """+ Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.++ Parameters+ ----------+ manifest : SandboxEnvironmentManifestRequest++ request_options : typing.Optional[RequestOptions]+ Request-specific configuration.++ Returns+ -------+ HttpResponse[GetSandboxEnvironmentResponse]+ The created sandbox environment.+ """+ _response = self._client_wrapper.httpx_client.request(+ "api/v1/sandbox-environments",+ method="POST",+ json={+ "manifest": convert_and_respect_annotation_metadata(+ object_=manifest, annotation=SandboxEnvironmentManifestRequest, direction="write"+ ),+ },+ headers={+ "content-type": "application/json",+ },+ request_options=request_options,+ omit=OMIT,+ )+ try:+ if 200 <= _response.status_code < 300:+ _data = typing.cast(+ GetSandboxEnvironmentResponse,+ construct_type(+ type_=GetSandboxEnvironmentResponse, # type: ignore+ object_=_response.json(),+ ),+ )+ return HttpResponse(response=_response, data=_data)+ if _response.status_code == 400:+ raise BadRequestError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ if _response.status_code == 401:+ raise UnauthorizedError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ if _response.status_code == 409:+ raise ConflictError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ if _response.status_code == 422:+ raise UnprocessableEntityError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ if _response.status_code == 502:+ raise BadGatewayError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ _response_json = _response.json()+ except JSONDecodeError:+ raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)+ except ValidationError as e:+ raise ParsingError(+ status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e+ )+ raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)+def create_or_update(self, *, manifest: SandboxEnvironmentManifestRequest, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[GetSandboxEnvironmentResponse]:@@ -485,6 +591,112 @@ class AsyncRawSandboxEnvironmentsClient:)raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)+ async def create(+ self, *, manifest: SandboxEnvironmentManifestRequest, request_options: typing.Optional[RequestOptions] = None+ ) -> AsyncHttpResponse[GetSandboxEnvironmentResponse]:+ """+ Creates by `manifest.name`. Fails if the name is already taken. Requires a configured sandbox provider.++ Parameters+ ----------+ manifest : SandboxEnvironmentManifestRequest++ request_options : typing.Optional[RequestOptions]+ Request-specific configuration.++ Returns+ -------+ AsyncHttpResponse[GetSandboxEnvironmentResponse]+ The created sandbox environment.+ """+ _response = await self._client_wrapper.httpx_client.request(+ "api/v1/sandbox-environments",+ method="POST",+ json={+ "manifest": convert_and_respect_annotation_metadata(+ object_=manifest, annotation=SandboxEnvironmentManifestRequest, direction="write"+ ),+ },+ headers={+ "content-type": "application/json",+ },+ request_options=request_options,+ omit=OMIT,+ )+ try:+ if 200 <= _response.status_code < 300:+ _data = typing.cast(+ GetSandboxEnvironmentResponse,+ construct_type(+ type_=GetSandboxEnvironmentResponse, # type: ignore+ object_=_response.json(),+ ),+ )+ return AsyncHttpResponse(response=_response, data=_data)+ if _response.status_code == 400:+ raise BadRequestError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ if _response.status_code == 401:+ raise UnauthorizedError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ if _response.status_code == 409:+ raise ConflictError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ if _response.status_code == 422:+ raise UnprocessableEntityError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ if _response.status_code == 502:+ raise BadGatewayError(+ headers=dict(_response.headers),+ body=typing.cast(+ RequestErrorResponse,+ construct_type(+ type_=RequestErrorResponse, # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ _response_json = _response.json()+ except JSONDecodeError:+ raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)+ except ValidationError as e:+ raise ParsingError(+ status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e+ )+ raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)+async def create_or_update(self, *, manifest: SandboxEnvironmentManifestRequest, request_options: typing.Optional[RequestOptions] = None) -> AsyncHttpResponse[GetSandboxEnvironmentResponse]: