> ## Documentation Index
> Fetch the complete documentation index at: https://docs.phala.com/llms.txt
> Use this file to discover all available pages before exploring further.

# CVM Configuration

> Functions for updating CVM resources, visibility, OS images, and compose files

<Warning>
  **Every configuration update triggers a CVM restart.** The CVM will be stopped, updated, and restarted automatically. Plan updates accordingly to minimize downtime.
</Warning>

Each `updateXxxx` method targets a single aspect of the CVM and calls a dedicated API endpoint. `patchCvm` is the unified method that can update multiple fields in a single request. Use `patchCvm` when you need to change several settings atomically; use the individual `updateXxxx` methods when you only need to change one thing.

## updateCvmResources

`PATCH /cvms/{cvmId}/resources`

Updates CVM compute resources (vCPU, memory, disk).

**Parameters:**

| Field       | Type     | Required | Description     |
| ----------- | -------- | -------- | --------------- |
| `id`        | `string` | Yes      | CVM identifier  |
| `vcpu`      | `number` | No       | Number of vCPUs |
| `memory`    | `number` | No       | Memory in MB    |
| `disk_size` | `number` | No       | Disk size in GB |

**Returns:** Updated CVM details.

**Example:**

```typescript theme={"system"}
await client.updateCvmResources({
  id: "my-app",
  vcpu: 4,
  memory: 8192,
  disk_size: 100,
});
```

***

## updateCvmVisibility

`PATCH /cvms/{cvmId}/visibility`

Updates CVM visibility settings (public listing, public TCB info).

**Parameters:**

| Field    | Type      | Required | Description              |
| -------- | --------- | -------- | ------------------------ |
| `id`     | `string`  | Yes      | CVM identifier           |
| `listed` | `boolean` | No       | List in public directory |

**Returns:** Updated CVM details.

***

## updatePreLaunchScript

`PATCH /cvms/{cvmId}/pre-launch-script`

Updates the pre-launch script for a CVM.

**Parameters:**

| Field               | Type     | Required | Description                |
| ------------------- | -------- | -------- | -------------------------- |
| `id`                | `string` | Yes      | CVM identifier             |
| `pre_launch_script` | `string` | Yes      | Script content             |
| `compose_hash`      | `string` | No       | For on-chain KMS (Phase 2) |
| `transaction_hash`  | `string` | No       | For on-chain KMS (Phase 2) |

**Returns:** Union type:

* `{ status: "in_progress", message, correlation_id }` — update accepted
* `{ status: "precondition_required", message, compose_hash, app_id, device_id, kms_info }` — on-chain KMS requires compose hash registration first

<Note>
  For CVMs using on-chain KMS, this function may return `precondition_required`. You must register the `compose_hash` on-chain using [`addComposeHash`](/phala-cloud/references/cloud-js-sdk/add-compose-hash) before retrying with the `compose_hash` and `transaction_hash` parameters.
</Note>

***

## updateOsImage

`PATCH /cvms/{cvmId}/os-image`

Updates the OS image for a CVM. The CVM will restart with the new image.

**Parameters:**

| Field   | Type     | Required | Description    |
| ------- | -------- | -------- | -------------- |
| `id`    | `string` | Yes      | CVM identifier |
| `image` | `string` | Yes      | OS image name  |

**Returns:** Updated CVM details.

***

## getAvailableOsImages

`GET /os-images`

Returns the list of available OS images.

**Parameters:** None (optional filters).

**Returns:** `GetAvailableOSImagesResponse` — array of OS image variants with version info.

**Example:**

```typescript theme={"system"}
const images = await client.getAvailableOsImages();
images.forEach(img => console.log(img.name, img.version));
```

***

<Note>
  `refreshCvmInstanceId` is unreleased — added after `@phala/cloud` v0.2.4. It will be available in a future release.
</Note>

## refreshCvmInstanceId

`POST /cvms/{cvmId}/refresh-instance-id`

Generates a new instance ID for a CVM. This invalidates the old instance ID.

**Parameters:**

| Field | Type     | Required | Description    |
| ----- | -------- | -------- | -------------- |
| `id`  | `string` | Yes      | CVM identifier |

**Returns:** `InstanceIdRefreshResult` with the new `instance_id`.

***

<Note>
  `refreshCvmInstanceIds` is unreleased — added after `@phala/cloud` v0.2.4. It will be available in a future release.
</Note>

## refreshCvmInstanceIds

`POST /cvms/refresh-instance-ids`

Generates new instance IDs for multiple CVMs in a single request.

**Parameters:**

| Field | Type       | Required | Description              |
| ----- | ---------- | -------- | ------------------------ |
| `ids` | `string[]` | Yes      | Array of CVM identifiers |

**Returns:** `RefreshCvmInstanceIdsResponse` — batch results.

***

## provisionCvmComposeFileUpdate

`POST /cvms/{cvmId}/compose_file/provision`

Provisions a compose file update — the first phase of a two-phase compose file change. Returns a `compose_hash` needed for the commit step.

**Parameters:**

| Field         | Type     | Required | Description                          |
| ------------- | -------- | -------- | ------------------------------------ |
| `id`          | `string` | Yes      | CVM identifier (also accepts `uuid`) |
| `app_compose` | `object` | Yes      | Updated compose file object          |

**Returns:** `ProvisionCvmComposeFileUpdateResult`

| Field                     | Type             | Description                                                                                                                                                                                                                      |
| ------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `compose_hash`            | `string`         | Hash of the provisioned compose file. Pass it to `commitCvmComposeFileUpdate`.                                                                                                                                                   |
| `compose_hash_registered` | `boolean`        | On-chain KMS only: `true` if the hash is already registered on the AppAuth contract. When `true`, skip [`addComposeHash`](/phala-cloud/references/cloud-js-sdk/add-compose-hash) and call `commitCvmComposeFileUpdate` directly. |
| `app_id`                  | `string \| null` | App identifier of the target CVM.                                                                                                                                                                                                |
| `device_id`               | `string \| null` | Device identifier of the target CVM.                                                                                                                                                                                             |
| `kms_info`                | `object \| null` | KMS metadata for the target CVM. Present for on-chain KMS CVMs.                                                                                                                                                                  |

**Example:**

```typescript theme={"system"}
import { addComposeHash } from "@phala/cloud";

const compose = await client.getCvmComposeFile({ id: "my-app" });
compose.docker_compose_file = newYaml;

const provision = await client.provisionCvmComposeFileUpdate({
  uuid: "my-app",
  app_compose: compose,
});

if (provision.kms_info && !provision.compose_hash_registered) {
  // On-chain KMS: register the new hash before commit.
  // See addComposeHash docs for the full parameter set.
  await addComposeHash({
    chain: provision.kms_info.chain,
    kmsContractAddress: provision.kms_info.kms_contract_address,
    appId: provision.app_id as `0x${string}`,
    composeHash: provision.compose_hash,
    privateKey: process.env.ETH_PRIVATE_KEY as `0x${string}`,
  });
}

await client.commitCvmComposeFileUpdate({
  id: "my-app",
  compose_hash: provision.compose_hash,
});
```

***

## commitCvmComposeFileUpdate

`POST /cvms/{cvmId}/compose_file/commit`

Commits a compose file update — the second phase. For on-chain KMS, the `compose_hash` must be registered on-chain before calling this.

**Parameters:**

| Field              | Type       | Required | Description                          |
| ------------------ | ---------- | -------- | ------------------------------------ |
| `id`               | `string`   | Yes      | CVM identifier                       |
| `compose_hash`     | `string`   | Yes      | From `provisionCvmComposeFileUpdate` |
| `encrypted_env`    | `string`   | No       | Hex-encoded encrypted env vars       |
| `env_keys`         | `string[]` | No       | Allowed env variable keys            |
| `transaction_hash` | `string`   | No       | On-chain transaction hash            |

**Returns:** `CommitCvmComposeFileUpdate` — update details.

***

## patchCvm

`PATCH /cvms/{cvmId}`

Applies partial updates to a CVM via the unified PATCH endpoint. Only fields present in the request body are applied, giving you true PATCH semantics. You can update compose files, environment variables, resources, visibility, and OS images all in a single call.

For CVMs with on-chain KMS (ETHEREUM/BASE), any change that affects the compose hash triggers a two-phase flow. The first call returns `{ requiresOnChainHash: true, composeHash, ... }` with the hash you need to register on-chain. After registration, call [`confirmCvmPatch`](#confirmcvmpatch) with the transaction proof.

**Parameters:**

| Field                 | Type       | Required | Description                              |
| --------------------- | ---------- | -------- | ---------------------------------------- |
| `id`                  | `string`   | Yes      | CVM identifier                           |
| `docker_compose_file` | `string`   | No       | New Docker Compose YAML                  |
| `pre_launch_script`   | `string`   | No       | New pre-launch script                    |
| `allowed_envs`        | `string[]` | No       | Allowed env variable keys                |
| `public_logs`         | `boolean`  | No       | Make logs publicly accessible            |
| `public_sysinfo`      | `boolean`  | No       | Make system info public                  |
| `public_tcbinfo`      | `boolean`  | No       | Make TCB info public                     |
| `encrypted_env`       | `string`   | No       | Hex-encoded encrypted env vars           |
| `user_config`         | `string`   | No       | User configuration string                |
| `gpus`                | `object`   | No       | GPU config: `{ count, product_name? }`   |
| `vcpu`                | `number`   | No       | Number of vCPUs                          |
| `memory`              | `number`   | No       | Memory in MB                             |
| `disk_size`           | `number`   | No       | Disk size in GB                          |
| `image`               | `string`   | No       | OS image name                            |
| `shutdown_timeout`    | `number`   | No       | Shutdown timeout in seconds              |
| `allow_force_stop`    | `boolean`  | No       | Allow force stop on timeout              |
| `prepareOnly`         | `boolean`  | No       | Prepare-only mode for multisig workflows |

**Returns:** Discriminated union on `requiresOnChainHash`:

**Accepted (`requiresOnChainHash: false`):**

| Field                 | Type     | Description              |
| --------------------- | -------- | ------------------------ |
| `requiresOnChainHash` | `false`  | Update accepted directly |
| `correlationId`       | `string` | Tracking ID              |

**Hash required (`requiresOnChainHash: true`):**

| Field                 | Type      | Description                        |
| --------------------- | --------- | ---------------------------------- |
| `requiresOnChainHash` | `true`    | On-chain registration needed       |
| `composeHash`         | `string`  | Hash to register on-chain          |
| `appId`               | `string`  | App ID for contract interaction    |
| `deviceId`            | `string`  | Device ID                          |
| `kmsInfo`             | `KmsInfo` | KMS details for chain interaction  |
| `commitToken`         | `string?` | One-time token for multisig commit |
| `commitUrl`           | `string?` | Commit URL                         |
| `onchainStatus`       | `object?` | Current on-chain allowance status  |

**Example — simple update (PHALA KMS):**

```typescript theme={"system"}
const result = await client.patchCvm({
  id: "my-app",
  vcpu: 4,
  memory: 8192,
});
console.log(result.correlationId);
```

**Example — on-chain KMS compose update (two-phase):**

```typescript theme={"system"}
import { addComposeHash } from "@phala/cloud";

const result = await client.patchCvm({
  id: "my-app",
  docker_compose_file: newComposeYaml,
});

if (result.requiresOnChainHash) {
  const tx = await addComposeHash({
    chain: result.kmsInfo.chain,
    kmsContractAddress: result.kmsInfo.kms_contract_address,
    appId: result.appId as `0x${string}`,
    composeHash: result.composeHash,
    privateKey: privateKey,
  });

  await client.confirmCvmPatch({
    id: "my-app",
    composeHash: result.composeHash,
    transactionHash: tx.transactionHash,
  });
}
```

***

## confirmCvmPatch

`PATCH /cvms/{cvmId}` (with `X-Compose-Hash` and `X-Transaction-Hash` headers)

Completes the second phase of an on-chain KMS CVM update. Call this after `patchCvm` returns `{ requiresOnChainHash: true }` and you have registered the compose hash on-chain via [`addComposeHash`](/phala-cloud/references/cloud-js-sdk/add-compose-hash).

**Parameters:**

| Field             | Type     | Required | Description                                    |
| ----------------- | -------- | -------- | ---------------------------------------------- |
| `id`              | `string` | Yes      | CVM identifier                                 |
| `composeHash`     | `string` | Yes      | Compose hash from `patchCvm` Phase 1 response  |
| `transactionHash` | `string` | Yes      | Transaction hash proving on-chain registration |

**Returns:** `ConfirmCvmPatchResult`

| Field           | Type     | Description |
| --------------- | -------- | ----------- |
| `correlationId` | `string` | Tracking ID |

**Example:**

```typescript theme={"system"}
const confirmed = await client.confirmCvmPatch({
  id: "my-app",
  composeHash: patchResult.composeHash,
  transactionHash: txReceipt.transactionHash,
});
console.log(`Update started: ${confirmed.correlationId}`);
```

***

## commitCvmUpdate

`POST /cvms/{cvmId}/commit-update`

Completes a two-phase CVM update using a one-time commit token. This enables multisig workflows where the on-chain signer is different from the original API caller. The token is generated when you call `patchCvm` with `prepareOnly: true`.

**Parameters:**

| Field             | Type     | Required | Description                                    |
| ----------------- | -------- | -------- | ---------------------------------------------- |
| `id`              | `string` | Yes      | CVM identifier                                 |
| `token`           | `string` | Yes      | One-time commit token from prepare-only flow   |
| `composeHash`     | `string` | Yes      | Compose hash from Phase 1 response             |
| `transactionHash` | `string` | Yes      | Transaction hash proving on-chain registration |

**Returns:** `CommitCvmUpdateResult`

| Field           | Type     | Description   |
| --------------- | -------- | ------------- |
| `correlationId` | `string` | Tracking ID   |
| `status`        | `string` | Update status |

**Example:**

```typescript theme={"system"}
// Phase 1: prepare-only
const result = await client.patchCvm({
  id: "my-app",
  docker_compose_file: newComposeYaml,
  prepareOnly: true,
});

if (result.requiresOnChainHash && result.commitToken) {
  // ... multisig approval and on-chain registration happen externally ...

  // Phase 2: commit with token
  const committed = await client.commitCvmUpdate({
    id: "my-app",
    token: result.commitToken,
    composeHash: result.composeHash,
    transactionHash: "0x...",
  });
  console.log(`Update started: ${committed.correlationId}`);
}
```
