> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.xapi.to/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.xapi.to/_mcp/server.

# 查询审计流

GET https://sandbox.xapi.to/v1/sandboxes/{id}/audit

分别查询 operations、events、usageSegments 或 billingPeriods。

Reference: https://docs.xapi.to/sandbox/api-reference/audit/get-sandbox-audit

## Authentication

- `XAPI-Key` header (required) — 在 xAPI Console 创建的 API Key。只会发送给 *.xapi.to。

## Servers

- `https://sandbox.xapi.to` (Production, default)
- `https://sandbox.test.xapi.to` (Test)

## Request

### Path parameters

- `id` (string, required) — xAPI Sandbox 实例 UUID。

### Query parameters

- `kind` (enum, required) — 审计流类型：operations=用户/系统操作；events=供应商状态事件； usageSegments=按状态切分的用量；billingPeriods=费用预留与最终结算。
  - Allowed values: `operations`, `events`, `usageSegments`, `billingPeriods`
- `page` (integer, optional, default: 1) — 从 1 开始的审计页码。
- `pageSize` (integer, optional, default: 100) — 每页审计记录数，范围 1–100。

## Response

### 200

审计分页结果

- `kind` (enum, required) — 当前页返回的审计类型，也决定 items 中每条记录的 Schema。
  - Allowed values: `operations`, `events`, `usageSegments`, `billingPeriods`
- `items` (list of AuditPageItemsItems, required) — 审计记录：operations 对应 Operation；events 对应 StateEvent； usageSegments 对应 UsageSegment；billingPeriods 对应 BillingPeriod。
- `total` (integer, required) — 该 kind 的审计记录总数。
- `page` (integer, required) — 当前页码，从 1 开始。
- `pageSize` (integer, required) — 本次请求采用的每页最大记录数。
- `totalPages` (integer, required) — 该审计流的总页数。

## Types

### AuditPageItemsItems

- Operation: Operation
- StateEvent: StateEvent
- UsageSegment: UsageSegment
- BillingPeriod: BillingPeriod

### Operation

一次生命周期或数据面调用的持久化审计记录。

- `id` (string, optional) — 操作记录 UUID，用于日志关联，不是实例 ID。
- `idempotencyKey` (string, optional) — 此操作的幂等键；重复请求是否属于同一操作由实例 ID 和该值共同确定。
- `type` (enum, optional) — 操作类型。生命周期操作改变状态；EXEC/FILE/PORT/EXTENSION 是实例内的数据面调用。
  - Allowed values: `CREATE`, `SUSPEND`, `RESUME`, `TERMINATE`, `EXEC`, `EXTENSION`, `FILE_READ`, `FILE_WRITE`, `FILE_LIST`, `PORT_OPEN`
- `status` (enum, optional) — 操作执行状态；HTTP 已接受不代表这里已经 SUCCEEDED。
  - Allowed values: `PENDING`, `RUNNING`, `SUCCEEDED`, `FAILED`, `TIMED_OUT`, `CANCELLED`
- `expectedState` (enum, optional, nullable) — 生命周期操作期望实例最终达到的状态；数据面操作通常为 null。
  - Allowed values: `PROVISIONING`, `RUNNING`, `SUSPENDED`, `TERMINATED`, `FAILED`, `UNKNOWN`
- `error` (string, optional, nullable) — 操作失败、超时或取消时的诊断信息；成功时为 null。
- `input` (map from string to any, optional) — 已脱敏/裁剪的操作输入摘要；文件写入只记录路径、编码和大小，不保存文件内容。
- `requestedAt` (datetime, optional) — Gateway 接受操作请求的时间。
- `startedAt` (datetime, optional, nullable) — 适配器实际开始处理的时间；尚未开始时为 null。
- `completedAt` (datetime, optional, nullable) — 操作进入终态的时间；仍在执行时为 null。
- `durationMs` (integer, optional) — 操作实际执行耗时，单位毫秒；并非实例总运行时长。
- `exitCode` (integer, optional) — EXEC 操作的远端进程退出码；0 通常表示成功，非零表示命令失败但 HTTP 请求可能仍成功。
- `stdoutPreview` (string, optional) — 为审计保存的标准输出前缀，不保证是完整 stdout。
- `stderrPreview` (string, optional) — 为审计保存的标准错误前缀，不保证是完整 stderr。
- `outputTruncated` (boolean, optional) — stdoutPreview 或 stderrPreview 是否因日志大小限制被截断。

### StateEvent

供应商状态变化经 Gateway 规范化后的事件；按 sequence 判断实例状态演进顺序。

- `id` (string, optional) — xAPI 保存的事件 UUID。
- `sequence` (integer, optional) — 当前供应商分配内单调递增的事件序号，用于去重和排序。
- `eventType` (enum, optional) — 规范事件类型；当前为 sandbox.state_changed。
  - Allowed values: `sandbox.state_changed`
- `previousState` (enum, optional) — 变化前状态；首个事件或供应商未提供时可能省略。
  - Allowed values: `PROVISIONING`, `RUNNING`, `SUSPENDED`, `TERMINATED`, `FAILED`, `UNKNOWN`
- `currentState` (enum, optional) — 此事件确认的新状态。
  - Allowed values: `PROVISIONING`, `RUNNING`, `SUSPENDED`, `TERMINATED`, `FAILED`, `UNKNOWN`
- `reason` (string, optional, nullable) — 供应商给出的状态变化原因或失败说明；没有原因时为 null。
- `effectiveAt` (datetime, optional) — 状态变化实际生效时间。
- `observedAt` (datetime, optional) — 供应商或适配器观测到该状态的时间。
- `receivedAt` (datetime, optional) — Gateway 收到并保存该事件的时间；可能晚于 observedAt。
- `timestampSource` (enum, optional) — 时间来源：供应商原生事件、适配器轮询观测或 Gateway 推断。
  - Allowed values: `PROVIDER_NATIVE`, `ADAPTER_OBSERVED`, `INFERRED`
- `resources` (ResourceSnapshot, optional) — 状态变化时确认的资源快照。
- `status` (enum, optional) — Gateway 对事件的处理结果；REJECTED 事件不应被视为有效状态证据。
  - Allowed values: `ACCEPTED`, `PROCESSED`, `REJECTED`

### UsageSegment

实例在同一状态和同一资源快照下的一段连续用量，是费用结算的时间基础。

- `id` (string, optional) — 用量段 UUID。
- `state` (enum, optional) — 此用量段持续期间的规范实例状态。
  - Allowed values: `PROVISIONING`, `RUNNING`, `SUSPENDED`, `TERMINATED`, `FAILED`, `UNKNOWN`
- `startsAt` (datetime, optional) — 用量段开始时间。
- `endsAt` (datetime, optional, nullable) — 用量段结束时间；活动段可能为 null，终态验收时不应存在开放段。
- `durationSeconds` (string, optional, nullable) — 服务端按事件时间计算的持续秒数，以十进制字符串返回以避免精度损失。
- `amount` (string, optional, nullable) — 此用量段最终结算金额（USD）；未结算时可能为 null。
- `resources` (ResourceSnapshot, optional) — 该用量段采用的资源数量快照。
- `timestampSource` (enum, optional) — 开始/结束时间的可信来源。
  - Allowed values: `PROVIDER_NATIVE`, `ADAPTER_OBSERVED`, `INFERRED`
- `status` (enum, optional) — OPEN=仍计量；CLOSED=已结束待结算；SETTLED=已结算；UNVERIFIED=状态时间待确认；VOID=不计费。
  - Allowed values: `OPEN`, `CLOSED`, `SETTLED`, `UNVERIFIED`, `VOID`

### BillingPeriod

一次用量窗口、关机预留或按操作计费的资金预留与结算记录。

- `id` (string, optional) — 账期 UUID。
- `kind` (enum, optional) — USAGE=状态/资源用量；SHUTDOWN=安全销毁预留；OPERATION=按次调用费用。
  - Allowed values: `USAGE`, `SHUTDOWN`, `OPERATION`
- `status` (enum, optional) — RESERVED=已预留未完成；SETTLED=已扣费；RELEASED=未使用并释放；UNVERIFIED=等待人工/系统核对。
  - Allowed values: `RESERVED`, `SETTLED`, `RELEASED`, `UNVERIFIED`
- `startsAt` (datetime, optional) — 账期或资金预留开始时间。
- `endedAt` (datetime, optional, nullable) — 账期终止时间；活动账期可能为 null。
- `amount` (string, optional, nullable) — 最终实际结算金额（USD）；RESERVED 阶段可能尚未确定。
- `breakdown` (BillingBreakdown, optional) — 此账期的计算明细；没有产生费用时可能为空或省略。

### ResourceSnapshot

实例实际分配或 offering 声明的资源快照；供应商可以附加扩展资源字段。

- `cpu` (double, optional) — vCPU 数量。
- `memoryGiB` (double, optional) — 内存容量，单位 GiB。
- `volumeGiB` (double, optional) — 工作卷/持久卷容量，单位 GiB。
- `snapshotGiB` (double, optional) — 快照存储容量或计费基数，单位 GiB。
- `gpu` (list of ResourceSnapshotGpuItems, optional) — 分配的 GPU 型号与数量；CPU-only offering 通常省略。
- `environment` (map from string to any, optional) — 供应商返回的运行环境快照，例如镜像、语言或框架信息。

### BillingBreakdown

账期金额的可审计计算明细。

- `lines` (list of BillingBreakdownLine, optional) — 每项状态、资源或操作费用明细。
- `totalUsd` (string, optional) — 所有明细行金额之和。
- `durationSeconds` (string, optional) — 此账期计入费用的总时长（秒）；操作计费可能为 0。

### ResourceSnapshotGpuItems

- `model` (string, optional) — GPU 型号。
- `count` (integer, optional) — 该型号 GPU 数量。

### BillingBreakdownLine

账期内某一条 rate card 规则产生的费用明细。

- `quantity` (string, optional) — 使用量；按时长规则通常是秒数，按操作规则通常是次数。
- `amountUsd` (string, optional) — 该明细行费用，USD 十进制字符串。
- `component` (RateCardComponent, optional) — 计算该行费用所使用的费率规则快照。

### RateCardComponent

一条计费规则；具体计费基数由 kind 决定。

- `kind` (enum, required) — STATE_TIME=按实例状态时长；RESOURCE_TIME=按资源数量和时长；OPERATION=按调用次数。
  - Allowed values: `STATE_TIME`, `RESOURCE_TIME`, `OPERATION`
- `unit` (enum, required) — 计费单位；时长规则为 SECOND，调用规则为 COUNT。
  - Allowed values: `SECOND`, `COUNT`
- `priceUsd` (string, required) — 每单位价格，USD 十进制字符串。
- `state` (enum, optional) — 该规则适用的实例状态；OPERATION 规则通常省略。
  - Allowed values: `PROVISIONING`, `RUNNING`, `SUSPENDED`, `TERMINATED`, `FAILED`, `UNKNOWN`
- `category` (enum, optional) — 费用分类，用于账单归类。
  - Allowed values: `COMPUTE`, `CAPACITY_RESERVATION`, `STORAGE`, `OTHER`
- `resource` (enum, optional) — RESOURCE_TIME 规则计费的资源类型。
  - Allowed values: `CPU`, `MEMORY_GIB`, `VOLUME_GIB`, `SNAPSHOT_GIB`, `GPU`
- `resourceKey` (string, optional) — 细分资源键，例如具体 GPU 型号；普通 CPU/内存规则通常省略。
- `operation` (string, optional) — OPERATION 规则计费的操作名。

## Examples

**Response**

```json
{
  "kind": "operations",
  "items": [
    {
      "expectedState": "TERMINATED",
      "id": "22222222-2222-4222-8222-222222222224",
      "status": "SUCCEEDED",
      "type": "TERMINATE"
    }
  ],
  "total": 5,
  "page": 1,
  "pageSize": 100,
  "totalPages": 1
}
```

**SDK Code**

```python
import requests

url = "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/audit"

querystring = {"kind":"operations","page":"1","pageSize":"100"}

headers = {"XAPI-Key": "<apiKey>"}

response = requests.get(url, headers=headers, params=querystring)

print(response.json())
```

```javascript
const url = 'https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/audit?kind=operations&page=1&pageSize=100';
const options = {method: 'GET', headers: {'XAPI-Key': '<apiKey>'}};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"net/http"
	"io"
)

func main() {

	url := "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/audit?kind=operations&page=1&pageSize=100"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("XAPI-Key", "<apiKey>")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/audit?kind=operations&page=1&pageSize=100")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Get.new(url)
request["XAPI-Key"] = '<apiKey>'

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.get("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/audit?kind=operations&page=1&pageSize=100")
  .header("XAPI-Key", "<apiKey>")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/audit?kind=operations&page=1&pageSize=100', [
  'headers' => [
    'XAPI-Key' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/audit?kind=operations&page=1&pageSize=100");
var request = new RestRequest(Method.GET);
request.AddHeader("XAPI-Key", "<apiKey>");
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = ["XAPI-Key": "<apiKey>"]

let request = NSMutableURLRequest(url: NSURL(string: "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/audit?kind=operations&page=1&pageSize=100")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```