sandbox

package
v7.26.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 12, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package sandbox 提供七牛云沙箱服务的 Go SDK,用于管理安全隔离的云端沙箱环境。

沙箱服务是一款专为 AI Agent 场景设计的运行时基础设施,提供安全隔离的云端环境来执行 AI 生成的代码。通过系统级隔离机制,确保代码执行不会对宿主系统造成非法访问或篡改。 沙箱启动时间低于 200 毫秒,默认存活 5 分钟(最长 1 小时),支持暂停/恢复以持久化 文件系统和内存状态。

更多产品信息请参阅: https://developer.qiniu.com/las/13281/sandbox-overview

核心概念

  • Sandbox: 隔离的云端执行环境(轻量级虚拟化),支持 running、paused、killed 三种状态
  • Template: 预构建的沙箱环境定义,包含基础镜像、依赖、文件和启动命令,实现亚秒级启动
  • envd: 运行在沙箱内部的 agent 守护进程,通过 ConnectRPC 提供进程管理、文件系统操作和 PTY 终端服务

快速开始

创建客户端并启动沙箱:

c, err := sandbox.NewClient(&sandbox.Config{
    APIKey: os.Getenv("QINIU_API_KEY"),
})

timeout := int32(120)
sb, _, err := c.CreateAndWait(ctx, sandbox.CreateParams{
    TemplateID: "base",
    Timeout:    &timeout,
}, sandbox.WithPollInterval(2*time.Second))

defer sb.Kill(ctx)

沙箱生命周期

Client 提供沙箱的创建、连接和列表操作:

Sandbox 实例提供生命周期管理:

命令执行

通过 Sandbox.Commands 在沙箱内执行终端命令:

// 同步执行
result, err := sb.Commands().Run(ctx, "echo hello",
    sandbox.WithEnvs(map[string]string{"MY_VAR": "value"}),
    sandbox.WithCwd("/tmp"),
    sandbox.WithTimeout(5*time.Second),
)
fmt.Println(result.Stdout)

// 异步执行(后台命令)
handle, err := sb.Commands().Start(ctx, "sleep 30", sandbox.WithTag("bg"))
handle.WaitPID(ctx)
sb.Commands().Kill(ctx, handle.PID())

Commands 支持实时输出回调(WithOnStdout / WithOnStderr)、后台命令管理 (Commands.Start / Commands.List / Commands.Kill)以及标准输入发送 (Commands.SendStdin)。

文件系统操作

通过 Sandbox.Files 进行文件读写:

// 写入和读取文件
sb.Files().Write(ctx, "/tmp/hello.txt", []byte("Hello!"))
content, err := sb.Files().Read(ctx, "/tmp/hello.txt")

// 批量写入
sb.Files().WriteFiles(ctx, []sandbox.WriteEntry{
    {Path: "/tmp/a.txt", Data: []byte("content A")},
    {Path: "/tmp/b.txt", Data: []byte("content B")},
})

// 目录操作
sb.Files().MakeDir(ctx, "/tmp/mydir")
entries, err := sb.Files().List(ctx, "/tmp")

// 监听目录变更
wh, err := sb.Files().WatchDir(ctx, "/tmp/watch", sandbox.WithRecursive(true))
for ev := range wh.Events() {
    fmt.Printf("event: %s %s\n", ev.Type, ev.Name)
}

Filesystem 还提供 Filesystem.ReadTextFilesystem.ReadStreamFilesystem.ExistsFilesystem.GetInfoFilesystem.RenameFilesystem.Remove 等操作。

PTY 终端

通过 Sandbox.Pty 创建和管理伪终端会话:

ptyHandle, err := sb.Pty().Create(ctx, sandbox.PtySize{Cols: 80, Rows: 24},
    sandbox.WithOnStdout(func(data []byte) { fmt.Print(string(data)) }),
)
sb.Pty().SendInput(ctx, ptyHandle.PID(), []byte("ls -la\n"))
sb.Pty().Resize(ctx, ptyHandle.PID(), sandbox.PtySize{Cols: 120, Rows: 40})
sb.Pty().Kill(ctx, ptyHandle.PID())

模板管理

Client 提供模板的完整生命周期管理:

已有模板的重新构建遵循 Client.RebuildTemplateClient.StartTemplateBuildClient.WaitForBuild 三步流程:先申请一个新的 waiting build,再触发该 build,最后等待完成。

网络访问

沙箱默认允许访问互联网,可通过 CreateParams 的 Network 字段配置出站流量规则。 使用 Sandbox.GetHost 获取外部访问沙箱指定端口的域名。

轮询选项

Client.CreateAndWaitSandbox.WaitForReadyClient.WaitForBuild 支持 通过 PollOption 自定义轮询行为:

Index

Constants

View Source
const DefaultEndpoint = "https://cn-yangzhou-1-sandbox.qiniuapi.com"

DefaultEndpoint 是沙箱 API 的默认服务地址。

View Source
const DefaultUser = "user"

DefaultUser 是沙箱命令执行和文件操作的默认用户名。

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Body       []byte

	// Reqid 是从响应头 X-Reqid 中提取的请求 ID,用于链路追踪和日志排查。
	Reqid string
	// Code 是从响应 body 中解析出的错误码(如果有)。
	Code string
	// Message 是从响应 body 中解析出的错误消息(如果有)。
	Message string
}

APIError 表示 API 返回的非预期 HTTP 响应。

func (*APIError) Error

func (e *APIError) Error() string

Error 实现 error 接口。

type AddOptions added in v7.26.11

type AddOptions struct {
	GitOptions
	// Files 指定要暂存的文件列表,为空时根据 All 决定使用 -A 或 "."。
	Files []string
	// All 控制 Files 为空时是否使用 -A 暂存所有变更。
	// 为 nil 时默认 true(与 E2B 对齐);显式为 false 则使用 "." 仅暂存当前目录。
	All *bool
}

AddOptions 是 git add 操作的选项。

type AnthropicInjection added in v7.26.8

type AnthropicInjection struct {
	// APIKey API 密钥,可选。
	APIKey *string

	// BaseURL 可选 base URL,未指定时使用 api.anthropic.com。
	BaseURL *string
}

AnthropicInjection Anthropic API 注入配置。自动设置 x-api-key 头。 默认 host: api.anthropic.com

type AssignedTemplateTags

type AssignedTemplateTags struct {
	BuildID string
	Tags    []string
}

AssignedTemplateTags 分配的模板标签。

type AuthenticateOptions added in v7.26.11

type AuthenticateOptions struct {
	GitOptions
	// Username 是 HTTPS 认证的用户名,必填。
	Username string
	// Password 是 HTTPS 认证的密码或 token,必填。
	Password string
	// Host 是要认证的主机,缺省为 "github.com"。
	Host string
	// Protocol 是要认证的协议,缺省为 "https"。
	// 出于安全考虑只允许 "https",传入其他值会返回 InvalidArgumentError。
	Protocol string
}

AuthenticateOptions 是 DangerouslyAuthenticate 的选项。

type BuildLogEntry

type BuildLogEntry struct {
	Level     LogLevel
	Message   string
	Step      *string
	Timestamp time.Time
}

BuildLogEntry 构建日志条目。

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client 是沙箱客户端。

func NewClient

func NewClient(config *Config) (*Client, error)

NewClient 创建一个新的沙箱客户端。

func (*Client) AssignTemplateTags

func (c *Client) AssignTemplateTags(ctx context.Context, body ManageTagsParams) (*AssignedTemplateTags, error)

AssignTemplateTags 为模板构建分配标签。

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, sandboxID string, params ConnectParams) (*Sandbox, error)

Connect 连接到一个已有的沙箱,可选择恢复已暂停的沙箱。

func (*Client) Create

func (c *Client) Create(ctx context.Context, params CreateParams) (*Sandbox, error)

Create 根据指定模板创建一个新的沙箱。

func (*Client) CreateAndWait

func (c *Client) CreateAndWait(ctx context.Context, params CreateParams, opts ...PollOption) (*Sandbox, *SandboxInfo, error)

CreateAndWait 创建沙箱并等待其就绪。

func (*Client) CreateInjectionRule added in v7.26.7

func (c *Client) CreateInjectionRule(ctx context.Context, body CreateInjectionRuleParams) (*InjectionRule, error)

CreateInjectionRule 创建一个新的注入规则。

func (*Client) CreateTemplate

func (c *Client) CreateTemplate(ctx context.Context, body CreateTemplateParams) (*TemplateCreateResponse, error)

CreateTemplate 创建一个新模板(v3 API)。

func (*Client) DeleteInjectionRule added in v7.26.7

func (c *Client) DeleteInjectionRule(ctx context.Context, ruleID string) error

DeleteInjectionRule 删除指定的注入规则。

func (*Client) DeleteTemplate

func (c *Client) DeleteTemplate(ctx context.Context, templateID string) error

DeleteTemplate 删除一个模板。

func (*Client) DeleteTemplateTags

func (c *Client) DeleteTemplateTags(ctx context.Context, body DeleteTagsParams) error

DeleteTemplateTags 删除模板的标签。

func (*Client) GetCredentialsOption added in v7.26.8

func (c *Client) GetCredentialsOption() (apis.RequestEditorFn, error)

func (*Client) GetInjectionRule added in v7.26.7

func (c *Client) GetInjectionRule(ctx context.Context, ruleID string) (*InjectionRule, error)

GetInjectionRule 获取指定注入规则的详情。

func (*Client) GetSandboxesMetrics

func (c *Client) GetSandboxesMetrics(ctx context.Context, params *GetSandboxesMetricsParams) (*SandboxesWithMetrics, error)

GetSandboxesMetrics 返回指定沙箱 ID 列表的指标数据。

func (*Client) GetTemplate

func (c *Client) GetTemplate(ctx context.Context, templateID string, params *GetTemplateParams) (*TemplateWithBuilds, error)

GetTemplate 返回模板详情及其构建记录。

func (*Client) GetTemplateBuildLogs

func (c *Client) GetTemplateBuildLogs(ctx context.Context, templateID, buildID string, params *GetBuildLogsParams) (*TemplateBuildLogs, error)

GetTemplateBuildLogs 返回模板的构建日志。

func (*Client) GetTemplateBuildStatus

func (c *Client) GetTemplateBuildStatus(ctx context.Context, templateID, buildID string, params *GetBuildStatusParams) (*TemplateBuildInfo, error)

GetTemplateBuildStatus 返回模板的构建状态。

func (*Client) GetTemplateByAlias

func (c *Client) GetTemplateByAlias(ctx context.Context, alias string) (*TemplateAliasResponse, error)

GetTemplateByAlias 检查指定别名的模板是否存在。

func (*Client) GetTemplateFiles

func (c *Client) GetTemplateFiles(ctx context.Context, templateID, hash string) (*TemplateBuildFileUpload, error)

GetTemplateFiles 返回模板构建文件的上传链接。

func (*Client) List

func (c *Client) List(ctx context.Context, params *ListParams) ([]ListedSandbox, error)

List 列出沙箱,支持分页和状态过滤。

func (*Client) ListInjectionRules added in v7.26.7

func (c *Client) ListInjectionRules(ctx context.Context) ([]InjectionRule, error)

ListInjectionRules 列出当前用户的所有注入规则。

func (*Client) ListTemplates

func (c *Client) ListTemplates(ctx context.Context, params *ListTemplatesParams) ([]Template, error)

ListTemplates 列出所有模板。

func (*Client) RebuildTemplate added in v7.26.10

func (c *Client) RebuildTemplate(ctx context.Context, templateID string, body RebuildTemplateParams) (*TemplateCreateResponse, error)

RebuildTemplate 在已有模板上创建一个新的 waiting build(对应 POST /templates/{templateID})。 返回新 build 的标识(含 BuildID),调用方需随后调用 StartTemplateBuild 触发该 build。 典型流程:RebuildTemplate → StartTemplateBuild → WaitForBuild。

func (*Client) StartTemplateBuild

func (c *Client) StartTemplateBuild(ctx context.Context, templateID, buildID string, body StartTemplateBuildParams) error

StartTemplateBuild 启动模板构建(v2 API)。

func (*Client) UpdateInjectionRule added in v7.26.7

func (c *Client) UpdateInjectionRule(ctx context.Context, ruleID string, body UpdateInjectionRuleParams) (*InjectionRule, error)

UpdateInjectionRule 更新指定的注入规则。

func (*Client) UpdateTemplate

func (c *Client) UpdateTemplate(ctx context.Context, templateID string, body UpdateTemplateParams) error

UpdateTemplate 更新一个模板。

func (*Client) WaitForBuild

func (c *Client) WaitForBuild(ctx context.Context, templateID, buildID string, opts ...PollOption) (*TemplateBuildInfo, error)

WaitForBuild 轮询 GetTemplateBuildStatus 直到构建达到终态("ready" 或 "error")。 默认轮询间隔为 2 秒,可通过 WithPollInterval 等选项自定义。

type CloneOptions added in v7.26.11

type CloneOptions struct {
	GitOptions
	// Path 指定克隆目标路径。
	Path string
	// Branch 指定要检出的分支,设置后会附加 --single-branch。
	Branch string
	// Depth 指定浅克隆深度。
	Depth int
	// Username 是 HTTPS 认证的用户名。
	Username string
	// Password 是 HTTPS 认证的密码或 token。
	Password string
	// DangerouslyStoreCredentials 为 true 时,凭证会持久化在 .git/config 中;
	// 默认会在 clone 完成后通过 remote set-url 清除。
	DangerouslyStoreCredentials bool
}

CloneOptions 是 git clone 操作的选项。

type CommandHandle

type CommandHandle struct {
	// contains filtered or unexported fields
}

CommandHandle 后台命令句柄。

func (*CommandHandle) Kill

func (h *CommandHandle) Kill(ctx context.Context) error

Kill 终止命令。

func (*CommandHandle) PID

func (h *CommandHandle) PID() uint32

PID 返回进程 ID。

func (*CommandHandle) Wait

func (h *CommandHandle) Wait() (*CommandResult, error)

Wait 等待命令完成并返回结果。

func (*CommandHandle) WaitPID

func (h *CommandHandle) WaitPID(ctx context.Context) (uint32, error)

WaitPID 等待进程 PID 被分配。 当进程流收到 Start 事件后返回 PID;若 ctx 取消则返回错误。

type CommandOption

type CommandOption func(*commandOpts)

CommandOption 命令选项。

func WithCommandUser

func WithCommandUser(user string) CommandOption

WithCommandUser 设置执行命令的用户。

func WithCwd

func WithCwd(cwd string) CommandOption

WithCwd 设置命令的工作目录。

func WithEnvs

func WithEnvs(envs map[string]string) CommandOption

WithEnvs 设置命令的环境变量。

func WithOnPtyData

func WithOnPtyData(fn func(data []byte)) CommandOption

WithOnPtyData 设置 PTY 数据回调。用于接收 PTY 会话的输出数据。 若未设置,Pty.Create 会回退使用 WithOnStdout 回调以保持兼容。

func WithOnStderr

func WithOnStderr(fn func(data []byte)) CommandOption

WithOnStderr 设置 stderr 数据回调。

func WithOnStdout

func WithOnStdout(fn func(data []byte)) CommandOption

WithOnStdout 设置 stdout 数据回调。仅用于标准命令的 stdout 输出。 PTY 会话应使用 WithOnPtyData 接收输出。

func WithStdin added in v7.26.4

func WithStdin() CommandOption

WithStdin 启用进程的标准输入。 启用后可通过 Commands.SendStdin 向进程发送数据,通过 Commands.CloseStdin 发送 EOF。

func WithTag

func WithTag(tag string) CommandOption

WithTag 设置进程标签,用于后续通过标签连接进程。

func WithTimeout

func WithTimeout(timeout time.Duration) CommandOption

WithTimeout 设置命令超时时间。

type CommandResult

type CommandResult struct {
	ExitCode int
	Stdout   string
	Stderr   string
	Error    string
}

CommandResult 命令执行结果。

type Commands

type Commands struct {
	// contains filtered or unexported fields
}

Commands 提供沙箱命令执行能力。

func (*Commands) CloseStdin added in v7.26.4

func (c *Commands) CloseStdin(ctx context.Context, pid uint32) error

CloseStdin 关闭进程的标准输入管道,向进程发送 EOF 信号。 仅适用于非 PTY 进程。PTY 进程应通过 SendStdin 发送 Ctrl+D (0x04)。 若服务端尚未支持此 RPC,将返回 Unimplemented 错误,调用方可安全忽略。

func (*Commands) Connect

func (c *Commands) Connect(ctx context.Context, pid uint32) (*CommandHandle, error)

Connect 连接到正在运行的进程。

func (*Commands) Kill

func (c *Commands) Kill(ctx context.Context, pid uint32) error

Kill 终止指定进程。

func (*Commands) List

func (c *Commands) List(ctx context.Context) ([]ProcessInfo, error)

List 列出所有运行中的进程。

func (*Commands) Run

func (c *Commands) Run(ctx context.Context, cmd string, opts ...CommandOption) (*CommandResult, error)

Run 在沙箱中执行命令并等待完成。返回执行结果。 注意: stdout 和 stderr 在内存中累积,长时间运行或大量输出的命令 应使用 Start() + WithOnStdout/WithOnStderr 流式回调处理输出。

func (*Commands) SendStdin

func (c *Commands) SendStdin(ctx context.Context, pid uint32, data []byte) error

SendStdin 向进程发送标准输入。

func (*Commands) Start

func (c *Commands) Start(ctx context.Context, cmd string, opts ...CommandOption) (*CommandHandle, error)

Start 在沙箱中后台启动命令。返回 CommandHandle 可用于等待完成。 cmd 以 /bin/bash -l -c <cmd> 形式执行,支持 shell 语法(管道、重定向等), 会加载登录 shell 环境(/etc/profile 及用户 profile)。

type CommitOptions added in v7.26.11

type CommitOptions struct {
	GitOptions
	// AuthorName 覆盖提交作者名。
	AuthorName string
	// AuthorEmail 覆盖提交作者邮箱。
	AuthorEmail string
	// AllowEmpty 允许空提交。
	AllowEmpty bool
}

CommitOptions 是 git commit 操作的选项。

type Config

type Config struct {
	// APIKey 是用于身份认证的 API 密钥(必填)。
	APIKey string

	// Credentials 是用于身份认证的七牛凭证对象(可选)。
	// InjectionRule 相关接口会使用 Credentials 进行认证。
	Credentials *auth.Credentials

	// Endpoint 是沙箱 API 服务地址(可选,默认值:DefaultEndpoint)。
	Endpoint string

	// HTTPClient 自定义 HTTP 客户端(可选,默认值:http.DefaultClient)。
	HTTPClient *http.Client
}

Config 是沙箱客户端的配置。

type ConfigOptions added in v7.26.11

type ConfigOptions struct {
	GitOptions
	// Scope 是 git config 作用域,缺省为 GitConfigScopeGlobal。
	Scope GitConfigScope
	// Path 是仓库路径,仅在 Scope 为 GitConfigScopeLocal 时必填。
	Path string
}

ConfigOptions 是 git config 操作的选项。 Scope 为 "local" 时必须提供 Path。

type ConnectParams

type ConnectParams struct {
	// Timeout 超时时间(秒)。
	Timeout int32
}

ConnectParams 连接沙箱的请求参数。

type CreateInjectionRuleParams added in v7.26.7

type CreateInjectionRuleParams struct {
	// Name 规则名称(必填),同一用户下唯一。
	Name string

	// Injection 注入配置(必填)。
	Injection InjectionSpec
}

CreateInjectionRuleParams 创建注入规则的请求参数。

type CreateParams

type CreateParams struct {
	// TemplateID 模板 ID(必填)。
	TemplateID string

	// Timeout 沙箱超时时间(秒),可选。
	Timeout *int32

	// AutoPause 超时后自动暂停,可选。
	AutoPause *bool

	// AllowInternetAccess 允许沙箱访问互联网,可选。
	AllowInternetAccess *bool

	// Secure 安全通信模式,可选。
	Secure *bool

	// EnvVars 环境变量,可选。
	EnvVars *map[string]string

	// Metadata 自定义元数据,可选。
	Metadata *Metadata

	// Network 网络配置,可选。
	Network *NetworkConfig

	// Injections 针对出站 HTTPS 请求的注入规则列表,可选。
	// 每项可引用已保存的注入规则 ID,或直接指定注入配置。
	Injections *[]SandboxInjectionSpec

	// Resources 沙箱启动前需挂载的资源列表,可选。
	// 平台会在沙箱启动前完成资源物化(如 GitHub 仓库克隆)。
	Resources *[]SandboxResourceSpec
}

CreateParams 创建沙箱的请求参数。

type CreateTemplateParams

type CreateTemplateParams struct {
	// Alias 模板别名(已废弃,请使用 Name)。
	Alias *string

	// CPUCount 沙箱 CPU 核数。
	CPUCount *int32

	// MemoryMB 沙箱内存大小(MiB)。
	MemoryMB *int32

	// Name 模板名称,可包含标签(如 "my-template" 或 "my-template:v1")。
	Name *string

	// Tags 分配给模板构建的标签列表。
	Tags *[]string

	// TeamID 团队 ID(已废弃)。
	TeamID *string
}

CreateTemplateParams 创建模板的请求参数。

type DeleteBranchOptions added in v7.26.11

type DeleteBranchOptions struct {
	GitOptions
	// Force 为 true 时使用 -D 强制删除分支。
	Force bool
}

DeleteBranchOptions 是 git branch -d/-D 操作的选项。

type DeleteTagsParams

type DeleteTagsParams struct {
	// Name 模板名称。
	Name string

	// Tags 要删除的标签列表。
	Tags []string
}

DeleteTagsParams 删除模板标签的请求参数。

type EntryInfo

type EntryInfo struct {
	Name          string
	Type          FileType
	Path          string
	Size          int64
	Mode          uint32
	Permissions   string
	Owner         string
	Group         string
	ModifiedTime  time.Time
	SymlinkTarget *string
}

EntryInfo 文件或目录的元信息。

type EventType

type EventType string

EventType 文件系统事件类型。

const (
	// EventCreate 文件或目录被创建。
	EventCreate EventType = "create"
	// EventWrite 文件被写入。
	EventWrite EventType = "write"
	// EventRemove 文件或目录被删除。
	EventRemove EventType = "remove"
	// EventRename 文件或目录被重命名。
	EventRename EventType = "rename"
	// EventChmod 文件或目录权限被修改。
	EventChmod EventType = "chmod"
)

type FileType

type FileType string

FileType 文件类型。

const (
	// FileTypeFile 表示普通文件。
	FileTypeFile FileType = "file"
	// FileTypeDirectory 表示目录。
	FileTypeDirectory FileType = "dir"
	// FileTypeUnknown 表示未知文件类型。
	// 当 protobuf 返回了 SDK 尚未识别的新文件类型时使用此值。
	FileTypeUnknown FileType = "unknown"
)

type FileURLOption

type FileURLOption func(*fileURLOpts)

FileURLOption 文件 URL 选项。

func WithFileUser

func WithFileUser(user string) FileURLOption

WithFileUser 设置文件操作的用户。

func WithSignatureExpiration

func WithSignatureExpiration(seconds int) FileURLOption

WithSignatureExpiration 设置签名过期时间(秒)。

type Filesystem

type Filesystem struct {
	// contains filtered or unexported fields
}

Filesystem 提供沙箱文件系统操作。

func (*Filesystem) Exists

func (fs *Filesystem) Exists(ctx context.Context, path string, opts ...FilesystemOption) (bool, error)

Exists 检查文件或目录是否存在。

func (*Filesystem) GetInfo

func (fs *Filesystem) GetInfo(ctx context.Context, path string, opts ...FilesystemOption) (*EntryInfo, error)

GetInfo 返回文件或目录的元信息。

func (*Filesystem) List

func (fs *Filesystem) List(ctx context.Context, path string, opts ...ListOption) ([]EntryInfo, error)

List 列出目录内容。

func (*Filesystem) MakeDir

func (fs *Filesystem) MakeDir(ctx context.Context, path string, opts ...FilesystemOption) (*EntryInfo, error)

MakeDir 创建目录(包含父目录)。

func (*Filesystem) Read

func (fs *Filesystem) Read(ctx context.Context, path string, opts ...FilesystemOption) ([]byte, error)

Read 读取指定路径的文件内容。 通过 envd HTTP API 下载文件。

func (*Filesystem) ReadStream

func (fs *Filesystem) ReadStream(ctx context.Context, path string, opts ...FilesystemOption) (io.ReadCloser, error)

ReadStream 读取指定路径的文件内容,返回 io.ReadCloser 流。 调用方负责关闭返回的 ReadCloser。

func (*Filesystem) ReadText

func (fs *Filesystem) ReadText(ctx context.Context, path string, opts ...FilesystemOption) (string, error)

ReadText 读取指定路径的文件内容,返回 string。

func (*Filesystem) Remove

func (fs *Filesystem) Remove(ctx context.Context, path string, opts ...FilesystemOption) error

Remove 删除文件或目录。

func (*Filesystem) Rename

func (fs *Filesystem) Rename(ctx context.Context, oldPath, newPath string, opts ...FilesystemOption) (*EntryInfo, error)

Rename 重命名或移动文件/目录。

func (*Filesystem) WatchDir

func (fs *Filesystem) WatchDir(ctx context.Context, path string, opts ...WatchOption) (*WatchHandle, error)

WatchDir 监听目录变更。返回 WatchHandle 用于接收事件和停止监听。

func (*Filesystem) Write

func (fs *Filesystem) Write(ctx context.Context, path string, data []byte, opts ...FilesystemOption) (*EntryInfo, error)

Write 写入文件内容。如果文件已存在则覆盖,自动创建父目录。 通过 envd HTTP API 上传文件。

func (*Filesystem) WriteFiles

func (fs *Filesystem) WriteFiles(ctx context.Context, files []WriteEntry, opts ...FilesystemOption) ([]*EntryInfo, error)

WriteFiles 批量写入多个文件。通过单次 multipart POST 请求上传。 单文件时 path 放在 query param(兼容现有 Write 行为); 多文件时每个 part 的 filename 为完整路径,服务端从 part filename 获取路径。 上传成功后逐个调用 GetInfo 获取文件元信息返回。

注意: 当前实现会对每个文件额外发起一次 GetInfo 请求(N+1), 大批量上传时需注意延迟,适合小批量场景。

type FilesystemEvent

type FilesystemEvent struct {
	Name string
	Type EventType
}

FilesystemEvent 文件系统事件。

type FilesystemOption

type FilesystemOption func(*filesystemOpts)

FilesystemOption 文件系统操作选项。

func WithUser

func WithUser(user string) FilesystemOption

WithUser 设置文件系统操作的用户身份。

type FromImageRegistry

type FromImageRegistry = json.RawMessage

FromImageRegistry 镜像仓库认证配置(union 类型,支持 AWS/GCP/General 三种 registry)。 使用 json.RawMessage 保留原始 JSON 格式,由服务端解析具体类型。

type GeminiInjection added in v7.26.8

type GeminiInjection struct {
	// APIKey API 密钥,可选。
	APIKey *string

	// BaseURL 可选 base URL,未指定时使用 generativelanguage.googleapis.com。
	BaseURL *string
}

GeminiInjection Google Gemini API 注入配置。自动设置 x-goog-api-key 头。 默认 host: generativelanguage.googleapis.com

type GetBuildLogsParams

type GetBuildLogsParams struct {
	// Cursor 起始时间戳(毫秒)。
	Cursor *int64

	// Limit 返回的最大日志条数。
	Limit *int32

	// Direction 日志方向。
	Direction *LogsDirection

	// Level 日志级别过滤。
	Level *LogLevel

	// Source 日志来源过滤。
	Source *LogsSource
}

GetBuildLogsParams 获取构建日志的查询参数。

type GetBuildStatusParams

type GetBuildStatusParams struct {
	// LogsOffset 起始构建日志的索引。
	LogsOffset *int32

	// Limit 返回的最大日志条数。
	Limit *int32

	// Level 日志级别过滤。
	Level *LogLevel
}

GetBuildStatusParams 获取构建状态的查询参数。

type GetLogsParams

type GetLogsParams struct {
	// Start 日志起始时间的毫秒级时间戳。
	Start *int64

	// Limit 返回的最大日志条数。
	Limit *int32
}

GetLogsParams 获取沙箱日志的查询参数。

type GetMetricsParams

type GetMetricsParams struct {
	// Start 起始时间的 Unix 时间戳(秒)。
	Start *int64

	// End 结束时间的 Unix 时间戳(秒)。
	End *int64
}

GetMetricsParams 获取沙箱指标的查询参数。

type GetSandboxesMetricsParams

type GetSandboxesMetricsParams struct {
	// SandboxIds 要获取指标的沙箱 ID 列表。
	SandboxIds []string
}

GetSandboxesMetricsParams 批量获取沙箱指标的查询参数。

type GetTemplateParams

type GetTemplateParams struct {
	// NextToken 分页游标。
	NextToken *string

	// Limit 每页最大返回数。
	Limit *int32
}

GetTemplateParams 获取模板详情的查询参数。

type Git added in v7.26.11

type Git struct {
	// contains filtered or unexported fields
}

Git 提供沙箱内的 git 操作接口。

仅支持 HTTPS + username/password (token) 认证,不支持 SSH key。 所有命令都会强制注入 GIT_TERMINAL_PROMPT=0 以禁止交互式输入。

func (*Git) Add added in v7.26.11

func (g *Git) Add(ctx context.Context, path string, opts *AddOptions) (*CommandResult, error)

Add 暂存指定文件,未指定文件时默认 stage 全部变更。

func (*Git) Branches added in v7.26.11

func (g *Git) Branches(ctx context.Context, path string, opts *GitOptions) (*GitBranches, error)

Branches 返回仓库的分支列表。

unborn 仓库(git init 后尚未提交)下 `git branch` 无任何输出,但 HEAD 已经 指向初始分支;此时退化到 `git symbolic-ref --short HEAD` 取出 CurrentBranch, 与 GitBranches.CurrentBranch "仅在 detached HEAD 时为空" 的契约保持一致。

func (*Git) CheckoutBranch added in v7.26.11

func (g *Git) CheckoutBranch(ctx context.Context, path, branch string, opts *GitOptions) (*CommandResult, error)

CheckoutBranch 切换到已存在的分支。

func (*Git) Clone added in v7.26.11

func (g *Git) Clone(ctx context.Context, repoURL string, opts *CloneOptions) (*CommandResult, error)

Clone 克隆远程仓库到沙箱中。 当 opts.Username/Password 提供且 opts.DangerouslyStoreCredentials 为 false 时, SDK 会在 clone 完成后通过 git remote set-url 移除 origin URL 中的凭证。

func (*Git) Commit added in v7.26.11

func (g *Git) Commit(ctx context.Context, path, message string, opts *CommitOptions) (*CommandResult, error)

Commit 在仓库中创建一次提交。

func (*Git) ConfigureUser added in v7.26.11

func (g *Git) ConfigureUser(ctx context.Context, name, email string, opts *ConfigOptions) (*CommandResult, error)

ConfigureUser 设置 git 提交用户名与邮箱(一次 RPC 内完成)。

func (*Git) CreateBranch added in v7.26.11

func (g *Git) CreateBranch(ctx context.Context, path, branch string, opts *GitOptions) (*CommandResult, error)

CreateBranch 创建并切换到新分支。

func (*Git) DangerouslyAuthenticate added in v7.26.11

func (g *Git) DangerouslyAuthenticate(ctx context.Context, opts *AuthenticateOptions) (*CommandResult, error)

DangerouslyAuthenticate 通过 git credential helper 将凭证持久化到磁盘。

该方法会为后续所有 git 操作生效;建议优先使用短生命周期 token,并谨慎使用此方法。

func (*Git) DeleteBranch added in v7.26.11

func (g *Git) DeleteBranch(ctx context.Context, path, branch string, opts *DeleteBranchOptions) (*CommandResult, error)

DeleteBranch 删除分支。

func (*Git) GetConfig added in v7.26.11

func (g *Git) GetConfig(ctx context.Context, key string, opts *ConfigOptions) (string, error)

GetConfig 获取 git config 值,未配置时返回空字符串。

func (*Git) Init added in v7.26.11

func (g *Git) Init(ctx context.Context, path string, opts *InitOptions) (*CommandResult, error)

Init 在指定路径初始化新的 git 仓库。

func (*Git) Pull added in v7.26.11

func (g *Git) Pull(ctx context.Context, path string, opts *PullOptions) (*CommandResult, error)

Pull 从远程拉取变更。 当 opts.Username/Password 提供时,SDK 会临时把凭证写入目标 remote URL,命令完成后立即恢复原 URL。

当未显式指定 Remote 时,SDK 会尝试自动选中仓库唯一的 remote(与"自动选择单一 remote" 契约一致)。当 Remote 与 Branch 都未指定时,SDK 会先检查当前分支是否配置了 upstream, 未配置则直接返回 GitUpstreamError 而不是把模糊错误抛给调用方。

func (*Git) Push added in v7.26.11

func (g *Git) Push(ctx context.Context, path string, opts *PushOptions) (*CommandResult, error)

Push 将提交推送到远程。 当 opts.Username/Password 提供时,SDK 会临时把凭证写入目标 remote URL,命令完成后立即恢复原 URL。

当未显式指定 Remote 时,SDK 会尝试自动选中仓库唯一的 remote(与"自动选择单一 remote" 契约一致);多 remote / 无 remote 时回退到 git 原生行为或返回带凭证场景下的明确错误。

当 SetUpstream=true 且未显式给 Branch 时,仅在 SDK 已确定 target remote 的前提下, 才会通过 git rev-parse 取出当前分支名再拼到 push 命令上(避免 `git push --set-upstream <remote>` 不带分支名被 git 拒绝)。target 未确定(多 remote / 无 remote)时保持原始 `git push` 形态, 让 git 自行报错或走默认语义,避免把分支名误当成 remote 名。

func (*Git) RemoteAdd added in v7.26.11

func (g *Git) RemoteAdd(ctx context.Context, path, name, repoURL string, opts *RemoteAddOptions) (*CommandResult, error)

RemoteAdd 为仓库添加(或在 opts.Overwrite=true 时覆盖)一个 remote。

func (*Git) RemoteGet added in v7.26.11

func (g *Git) RemoteGet(ctx context.Context, path, name string, opts *GitOptions) (string, error)

RemoteGet 获取指定 remote 的 URL,未配置时返回空字符串。

func (*Git) Reset added in v7.26.11

func (g *Git) Reset(ctx context.Context, path string, opts *ResetOptions) (*CommandResult, error)

Reset 重置 HEAD 到指定状态。

func (*Git) Restore added in v7.26.11

func (g *Git) Restore(ctx context.Context, path string, opts *RestoreOptions) (*CommandResult, error)

Restore 恢复工作区文件或取消暂存。

func (*Git) SetConfig added in v7.26.11

func (g *Git) SetConfig(ctx context.Context, key, value string, opts *ConfigOptions) (*CommandResult, error)

SetConfig 设置 git config 值。 使用 GitConfigScopeLocal 时必须同时提供 opts.Path。

func (*Git) Status added in v7.26.11

func (g *Git) Status(ctx context.Context, path string, opts *GitOptions) (*GitStatus, error)

Status 返回仓库状态信息。

type GitAuthError added in v7.26.11

type GitAuthError struct {
	// Msg 是错误消息。
	Msg string
	// Err 是底层原始错误(可能是 errors.Join 聚合后的多个错误),用于 errors.Is/As 解包。
	Err error
}

GitAuthError 表示 git 操作因认证失败而中断。

func (*GitAuthError) Error added in v7.26.11

func (e *GitAuthError) Error() string

Error 实现 error 接口。

func (*GitAuthError) Unwrap added in v7.26.11

func (e *GitAuthError) Unwrap() error

Unwrap 返回底层原始错误,方便调用方使用 errors.Is/As 进一步排查。

type GitBranches added in v7.26.11

type GitBranches struct {
	// Branches 是所有本地分支名。
	Branches []string
	// CurrentBranch 是当前分支名,HEAD 分离时为空。
	CurrentBranch string
}

GitBranches 描述仓库的分支列表。

type GitConfigScope added in v7.26.11

type GitConfigScope string

GitConfigScope 描述 git config 命令的作用域。

const (
	// GitConfigScopeGlobal 表示用户级配置(~/.gitconfig)。
	GitConfigScopeGlobal GitConfigScope = "global"
	// GitConfigScopeLocal 表示仓库级配置(<repo>/.git/config),需要同时提供仓库路径。
	GitConfigScopeLocal GitConfigScope = "local"
	// GitConfigScopeSystem 表示系统级配置(/etc/gitconfig)。
	GitConfigScopeSystem GitConfigScope = "system"
)

type GitFileStatus added in v7.26.11

type GitFileStatus struct {
	// Name 是相对于仓库根目录的路径。
	Name string
	// Status 是归一化后的状态字符串,例如 "modified"、"added"、"deleted"、"untracked"、"conflict" 等。
	Status string
	// IndexStatus 是 porcelain 输出中索引位的字符。
	IndexStatus string
	// WorkingTreeStatus 是 porcelain 输出中工作区位的字符。
	WorkingTreeStatus string
	// Staged 表示该文件是否已暂存。
	Staged bool
	// RenamedFrom 在文件被重命名时记录原路径。
	RenamedFrom string
}

GitFileStatus 描述单个文件的 git 状态条目。

type GitOptions added in v7.26.11

type GitOptions struct {
	// Envs 是额外的环境变量。SDK 会自动注入 GIT_TERMINAL_PROMPT=0 以禁止交互式提示。
	Envs map[string]string
	// User 指定执行命令的用户,缺省使用 DefaultUser。
	User string
	// Cwd 指定工作目录。
	Cwd string
	// Timeout 指定命令超时时间。
	Timeout time.Duration
}

GitOptions 是 git 命令执行的通用选项,可以被各 Options Struct 嵌入复用。

type GitRepositoryResource added in v7.26.11

type GitRepositoryResource struct {
	// Type 仓库托管平台类型(必填)。当前仅支持 GitRepositoryTypeGithub。
	Type GitRepositoryType

	// URL 仓库 URL(HTTPS 或 SSH 形式),如
	// https://github.com/owner/repo.git 或 git@github.com:owner/repo.git。
	URL string

	// MountPath 仓库内容在沙箱内的绝对挂载路径。
	MountPath string

	// AuthorizationToken 用于克隆该仓库的访问 token。
	// 同一沙箱内多个仓库资源当前必须共用同一 token。
	AuthorizationToken *string
}

GitRepositoryResource Git 仓库资源,沙箱启动前由平台拉取并挂载快照到指定路径。 同一沙箱内多个仓库资源当前必须共用同一 token。

type GitRepositoryType added in v7.26.11

type GitRepositoryType string

GitRepositoryType Git 仓库托管平台类型。

const (
	// GitRepositoryTypeGithub GitHub 仓库。
	GitRepositoryTypeGithub GitRepositoryType = "github_repository"
)

Git 仓库托管平台类型常量。后续若服务端扩展更多类型,将在此新增对应常量。

type GitResetMode added in v7.26.11

type GitResetMode string

GitResetMode 是 git reset 的模式。

const (
	// GitResetModeSoft 对应 git reset --soft。
	GitResetModeSoft GitResetMode = "soft"
	// GitResetModeMixed 对应 git reset --mixed。
	GitResetModeMixed GitResetMode = "mixed"
	// GitResetModeHard 对应 git reset --hard。
	GitResetModeHard GitResetMode = "hard"
	// GitResetModeMerge 对应 git reset --merge。
	GitResetModeMerge GitResetMode = "merge"
	// GitResetModeKeep 对应 git reset --keep。
	GitResetModeKeep GitResetMode = "keep"
)

type GitStatus added in v7.26.11

type GitStatus struct {
	// CurrentBranch 是当前分支名,HEAD 分离时为空。
	CurrentBranch string
	// Upstream 是上游分支名,未配置时为空。
	Upstream string
	// Ahead 是当前分支领先上游的提交数。
	Ahead int
	// Behind 是当前分支落后上游的提交数。
	Behind int
	// Detached 表示 HEAD 是否处于分离状态。
	Detached bool
	// FileStatus 是所有有变更的文件状态条目。
	FileStatus []GitFileStatus
}

GitStatus 描述仓库整体状态。

func (*GitStatus) ConflictCount added in v7.26.11

func (s *GitStatus) ConflictCount() int

ConflictCount 返回冲突文件数。

func (*GitStatus) HasChanges added in v7.26.11

func (s *GitStatus) HasChanges() bool

HasChanges 在仓库存在任意文件变更时返回 true。

func (*GitStatus) HasConflicts added in v7.26.11

func (s *GitStatus) HasConflicts() bool

HasConflicts 在存在冲突文件时返回 true。

func (*GitStatus) HasStaged added in v7.26.11

func (s *GitStatus) HasStaged() bool

HasStaged 在至少一个文件存在已暂存变更时返回 true。

func (*GitStatus) HasUntracked added in v7.26.11

func (s *GitStatus) HasUntracked() bool

HasUntracked 在存在未跟踪文件时返回 true。

func (*GitStatus) IsClean added in v7.26.11

func (s *GitStatus) IsClean() bool

IsClean 在仓库无任何文件变更时返回 true。

func (*GitStatus) StagedCount added in v7.26.11

func (s *GitStatus) StagedCount() int

StagedCount 返回已暂存的文件数。

func (*GitStatus) TotalCount added in v7.26.11

func (s *GitStatus) TotalCount() int

TotalCount 返回有变更的文件总数。

func (*GitStatus) UnstagedCount added in v7.26.11

func (s *GitStatus) UnstagedCount() int

UnstagedCount 返回存在未暂存改动的文件数。 同一文件既有 staged 又有 unstaged 改动(如 "MM file")时也会被计入。

func (*GitStatus) UntrackedCount added in v7.26.11

func (s *GitStatus) UntrackedCount() int

UntrackedCount 返回未跟踪的文件数。

type GitUpstreamError added in v7.26.11

type GitUpstreamError struct {
	// Msg 是错误消息。
	Msg string
	// Err 是底层原始错误(可能是 errors.Join 聚合后的多个错误),用于 errors.Is/As 解包。
	Err error
}

GitUpstreamError 表示 git 操作因缺少 upstream 跟踪分支而中断。

func (*GitUpstreamError) Error added in v7.26.11

func (e *GitUpstreamError) Error() string

Error 实现 error 接口。

func (*GitUpstreamError) Unwrap added in v7.26.11

func (e *GitUpstreamError) Unwrap() error

Unwrap 返回底层原始错误,方便调用方使用 errors.Is/As 进一步排查。

type GithubInjection added in v7.26.11

type GithubInjection struct {
	// Token GitHub token,对所有请求的仓库具备访问权限。
	Token *string
}

GithubInjection GitHub 凭证注入。平台用此凭证克隆并校验仓库,且在沙箱运行期间为 匹配 github.com / api.github.com 的 HTTPS 请求自动注入认证;token 不会以明文形式 暴露到沙箱内。

type HTTPInjection added in v7.26.8

type HTTPInjection struct {
	// BaseURL 匹配 HTTPS 请求的 base URL。域名部分用于 host 匹配。
	// 若未指定 scheme 默认为 https。
	BaseURL string

	// Headers 需要注入或覆盖的 HTTP Headers,可选。
	Headers *map[string]string
}

HTTPInjection 自定义 HTTP 注入配置。

type InitOptions added in v7.26.11

type InitOptions struct {
	GitOptions
	// Bare 为 true 时创建 bare 仓库。
	Bare bool
	// InitialBranch 指定初始分支名(例如 "main")。
	InitialBranch string
}

InitOptions 是 git init 操作的选项。

type InjectionRule added in v7.26.7

type InjectionRule struct {
	// RuleID 规则唯一标识。
	RuleID string

	// Name 规则名称,同一用户下唯一。
	Name string

	// Injection 注入配置。
	Injection InjectionSpec

	// CreatedAt 创建时间。
	CreatedAt time.Time

	// UpdatedAt 最后更新时间。
	UpdatedAt time.Time
}

InjectionRule 预定义的请求注入规则。

type InjectionSpec added in v7.26.8

type InjectionSpec struct {
	// OpenAI OpenAI 兼容 API 注入。
	OpenAI *OpenAIInjection

	// Anthropic Anthropic API 注入。
	Anthropic *AnthropicInjection

	// Gemini Google Gemini API 注入。
	Gemini *GeminiInjection

	// Qiniu 七牛 AI API 注入。
	Qiniu *QiniuInjection

	// Github GitHub 凭证注入。
	Github *GithubInjection

	// HTTP 自定义 HTTP 注入。
	HTTP *HTTPInjection
}

InjectionSpec 注入配置(discriminated union),各字段互斥,只能设置一个。

type InvalidArgumentError added in v7.26.11

type InvalidArgumentError struct {
	// Msg 是错误消息。
	Msg string
}

InvalidArgumentError 表示传入的参数非法。

func (*InvalidArgumentError) Error added in v7.26.11

func (e *InvalidArgumentError) Error() string

Error 实现 error 接口。

type ListOption

type ListOption func(*listOpts)

ListOption 列目录选项。

func WithDepth

func WithDepth(depth uint32) ListOption

WithDepth 设置列目录的递归深度,默认为 1。

func WithListUser

func WithListUser(user string) ListOption

WithListUser 设置列目录操作的用户身份。

type ListParams

type ListParams struct {
	// Metadata 用于过滤沙箱的元数据查询(如 "user=abc&app=prod")。
	Metadata *string

	// State 按一个或多个状态过滤沙箱。
	State *[]SandboxState

	// NextToken 分页游标。
	NextToken *string

	// Limit 每页最大返回数。
	Limit *int32
}

ListParams 列出沙箱的查询参数,支持分页和状态过滤。

type ListTemplatesParams

type ListTemplatesParams struct {
	// TeamID 团队 ID。
	TeamID *string
}

ListTemplatesParams 列出模板的查询参数。

type ListedSandbox

type ListedSandbox struct {
	SandboxID   string
	TemplateID  string
	ClientID    string
	Alias       *string
	State       SandboxState
	CPUCount    int32
	MemoryMB    int32
	DiskSizeMB  int32
	EnvdVersion string
	StartedAt   time.Time
	EndAt       time.Time
	Metadata    *Metadata
}

ListedSandbox 沙箱列表中的条目。

type LogLevel

type LogLevel string

LogLevel 日志级别。

const (
	LogLevelDebug LogLevel = "debug"
	LogLevelError LogLevel = "error"
	LogLevelInfo  LogLevel = "info"
	LogLevelWarn  LogLevel = "warn"
)

日志级别常量。

type LogsDirection

type LogsDirection string

LogsDirection 日志方向。

const (
	LogsDirectionBackward LogsDirection = "backward"
	LogsDirectionForward  LogsDirection = "forward"
)

日志方向常量。

type LogsSource

type LogsSource string

LogsSource 日志来源。

const (
	LogsSourcePersistent LogsSource = "persistent"
	LogsSourceTemporary  LogsSource = "temporary"
)

日志来源常量。

type ManageTagsParams

type ManageTagsParams struct {
	// Tags 要分配给模板的标签列表。
	Tags []string

	// Target 目标模板(格式:"name:tag")。
	Target string
}

ManageTagsParams 管理模板标签的请求参数。

type Metadata

type Metadata map[string]string

Metadata 沙箱自定义元数据(key-value)。

type NetworkConfig

type NetworkConfig struct {
	// AllowOut 允许的出站流量 CIDR 列表。
	AllowOut *[]string

	// AllowPublicTraffic 是否允许公共流量访问沙箱 URL。
	AllowPublicTraffic *bool

	// DenyOut 拒绝的出站流量 CIDR 列表。
	DenyOut *[]string

	// MaskRequestHost 用于沙箱请求的 host 掩码。
	MaskRequestHost *string
}

NetworkConfig 沙箱网络配置。

type OpenAIInjection added in v7.26.8

type OpenAIInjection struct {
	// APIKey API 密钥,可选。
	APIKey *string

	// BaseURL 可选 base URL,未指定时使用 api.openai.com。
	BaseURL *string
}

OpenAIInjection OpenAI 兼容 API 注入配置。自动设置 Authorization: Bearer 头。 默认 host: api.openai.com

type PollOption

type PollOption func(*pollOpts)

PollOption 配置轮询行为的选项。

func WithBackoff

func WithBackoff(multiplier float64, maxInterval time.Duration) PollOption

WithBackoff 设置指数退避倍数和最大间隔。 multiplier 为每次轮询后间隔的乘数(如 1.5 表示每次增加 50%), maxInterval 为间隔上限(0 表示不限制)。

func WithOnPoll

func WithOnPoll(fn func(attempt int)) PollOption

WithOnPoll 设置每次轮询时的回调函数。 attempt 从 1 开始递增。

func WithPollInterval

func WithPollInterval(d time.Duration) PollOption

WithPollInterval 设置轮询间隔。

type ProcessInfo

type ProcessInfo struct {
	PID  uint32
	Tag  *string
	Cmd  string
	Args []string
	Envs map[string]string
	Cwd  *string
}

ProcessInfo 进程信息。

type Pty

type Pty struct {
	// contains filtered or unexported fields
}

Pty 提供沙箱 PTY(伪终端)操作。

func (*Pty) Connect

func (p *Pty) Connect(ctx context.Context, pid uint32) (*CommandHandle, error)

Connect 连接到已有的 PTY 会话。

func (*Pty) Create

func (p *Pty) Create(ctx context.Context, size PtySize, opts ...CommandOption) (*CommandHandle, error)

Create 创建一个 PTY 终端会话。 PTY 输出通过 WithOnPtyData 回调接收;若未设置,回退使用 WithOnStdout 以保持兼容。

func (*Pty) Kill

func (p *Pty) Kill(ctx context.Context, pid uint32) error

Kill 终止 PTY 会话。

func (*Pty) Resize

func (p *Pty) Resize(ctx context.Context, pid uint32, size PtySize) error

Resize 调整 PTY 终端大小。

func (*Pty) SendInput

func (p *Pty) SendInput(ctx context.Context, pid uint32, data []byte) error

SendInput 向 PTY 发送输入。

type PtySize

type PtySize struct {
	Cols uint32
	Rows uint32
}

PtySize PTY 终端大小。

type PullOptions added in v7.26.11

type PullOptions struct {
	GitOptions
	// Remote 指定远程名。
	Remote string
	// Branch 指定要拉取的分支名。
	Branch string
	// Username 是 HTTPS 认证的用户名。
	Username string
	// Password 是 HTTPS 认证的密码或 token。
	Password string
}

PullOptions 是 git pull 操作的选项。

type PushOptions added in v7.26.11

type PushOptions struct {
	GitOptions
	// Remote 指定远程名(例如 "origin")。
	Remote string
	// Branch 指定要推送的分支名。
	Branch string
	// SetUpstream 控制是否附加 --set-upstream。
	// 为 nil 时按 SDK 默认(true,与 E2B 对齐);显式设置为 false 可关闭。
	SetUpstream *bool
	// Username 是 HTTPS 认证的用户名。
	Username string
	// Password 是 HTTPS 认证的密码或 token。
	Password string
}

PushOptions 是 git push 操作的选项。

type QiniuInjection added in v7.26.9

type QiniuInjection struct {
	// APIKey API 密钥。
	APIKey *string

	// BaseURL 可选 base URL,未指定时使用 api.qnaigc.com。
	BaseURL *string
}

QiniuInjection 七牛 AI API 注入配置。七牛网关同时兼容 OpenAI 和 Anthropic 协议, api_key 会注入到请求实际携带的认证头(Authorization 或 x-api-key)。 默认 host: api.qnaigc.com

type RebuildTemplateParams added in v7.26.10

type RebuildTemplateParams struct {
	// Dockerfile 必填,模板使用的 Dockerfile 内容。
	Dockerfile string

	// Alias 模板别名。
	Alias *string

	// CPUCount 沙箱 CPU 核数。
	CPUCount *int32

	// MemoryMB 沙箱内存大小(MiB)。
	MemoryMB *int32

	// StartCmd 构建完成后执行的启动命令。
	StartCmd *string

	// ReadyCmd 就绪检查命令。
	ReadyCmd *string

	// TeamID 团队 ID(已废弃)。
	TeamID *string
}

RebuildTemplateParams 重新构建已有模板的请求参数。 对应 POST /templates/{templateID}:在已存在的模板上创建一个新的 waiting build, 返回新的 buildID,后续可通过 StartTemplateBuild 驱动该 build。

type RefreshParams

type RefreshParams struct {
	// Duration 延长的秒数,可选。
	Duration *int
}

RefreshParams 延长沙箱存活时间的请求参数。

type RemoteAddOptions added in v7.26.11

type RemoteAddOptions struct {
	GitOptions
	// Fetch 为 true 时在添加 remote 后立即执行 fetch。
	Fetch bool
	// Overwrite 为 true 时,若 remote 已存在则覆盖其 URL。
	Overwrite bool
}

RemoteAddOptions 是 git remote add 操作的选项。

type ResetOptions added in v7.26.11

type ResetOptions struct {
	GitOptions
	// Mode 是重置模式,缺省时不传 --<mode> 参数。
	Mode GitResetMode
	// Target 是要重置到的提交、分支或引用,缺省为 HEAD。
	Target string
	// Paths 是要重置的路径列表。
	Paths []string
}

ResetOptions 是 git reset 操作的选项。

type RestoreOptions added in v7.26.11

type RestoreOptions struct {
	GitOptions
	// Paths 是要恢复的路径列表,至少一个。
	Paths []string
	// Staged 为非 nil 时显式控制是否恢复索引。
	Staged *bool
	// Worktree 为非 nil 时显式控制是否恢复工作区。
	Worktree *bool
	// Source 指定从该提交或引用恢复。
	Source string
}

RestoreOptions 是 git restore 操作的选项。 当 Staged 与 Worktree 均未显式设置时,默认仅恢复工作区(Worktree=true)。

type Sandbox

type Sandbox struct {
	// contains filtered or unexported fields
}

Sandbox 表示一个运行中的沙箱实例。 持有客户端引用,用于执行生命周期操作和 envd agent 通信。

func (*Sandbox) Alias

func (s *Sandbox) Alias() *string

Alias 返回沙箱的别名。

func (*Sandbox) Commands

func (s *Sandbox) Commands() *Commands

Commands 返回命令执行操作接口。

func (*Sandbox) Domain

func (s *Sandbox) Domain() *string

Domain 返回沙箱的域名。

func (*Sandbox) DownloadURL

func (s *Sandbox) DownloadURL(path string, opts ...FileURLOption) string

DownloadURL 返回从沙箱下载文件的 URL。

func (*Sandbox) Files

func (s *Sandbox) Files() *Filesystem

Files 返回文件系统操作接口。

func (*Sandbox) GetHost

func (s *Sandbox) GetHost(port int) string

GetHost 返回访问沙箱指定端口的外部域名。 格式: {port}-{sandboxID}.{domain}

func (*Sandbox) GetInfo

func (s *Sandbox) GetInfo(ctx context.Context) (*SandboxInfo, error)

GetInfo 返回沙箱的详细信息。

func (*Sandbox) GetLogs

func (s *Sandbox) GetLogs(ctx context.Context, params *GetLogsParams) (*SandboxLogs, error)

GetLogs 返回沙箱日志。

func (*Sandbox) GetMetrics

func (s *Sandbox) GetMetrics(ctx context.Context, params *GetMetricsParams) ([]SandboxMetric, error)

GetMetrics 返回沙箱的资源指标。

func (*Sandbox) Git added in v7.26.11

func (s *Sandbox) Git() *Git

Git 返回 git 操作接口。 沙箱内需预装 git 二进制;当前仅支持 HTTPS + username/password (token) 认证。

func (*Sandbox) ID

func (s *Sandbox) ID() string

ID 返回沙箱 ID。

func (*Sandbox) IsRunning

func (s *Sandbox) IsRunning(ctx context.Context) (bool, error)

IsRunning 通过探测 envd /health 端点检查沙箱是否正在运行且可用。 与 GetInfo(查询控制面状态)不同,此方法直接验证沙箱内部 agent 是否可达。 返回 true 表示沙箱运行中且 envd agent 已就绪;返回 false 表示沙箱不可达(已暂停、已终止等)。

func (*Sandbox) Kill

func (s *Sandbox) Kill(ctx context.Context) error

Kill 终止沙箱。

func (*Sandbox) Pause

func (s *Sandbox) Pause(ctx context.Context) error

Pause 暂停沙箱,以便后续恢复。

func (*Sandbox) Pty

func (s *Sandbox) Pty() *Pty

Pty 返回 PTY 终端操作接口。

func (*Sandbox) Refresh

func (s *Sandbox) Refresh(ctx context.Context, params RefreshParams) error

Refresh 延长沙箱的存活时间。

func (*Sandbox) SetTimeout

func (s *Sandbox) SetTimeout(ctx context.Context, timeout time.Duration) error

SetTimeout 更新沙箱超时时间。 沙箱将在从现在起经过指定时长后过期。 timeout 必须 >= 1 秒。

func (*Sandbox) TemplateID

func (s *Sandbox) TemplateID() string

TemplateID 返回沙箱所属的模板 ID。

func (*Sandbox) UploadURL

func (s *Sandbox) UploadURL(path string, opts ...FileURLOption) string

UploadURL 返回向沙箱上传文件的 URL(POST multipart/form-data)。

func (*Sandbox) WaitForReady

func (s *Sandbox) WaitForReady(ctx context.Context, opts ...PollOption) (*SandboxInfo, error)

WaitForReady 轮询 GetInfo 直到沙箱状态变为 "running" 或上下文被取消。 默认轮询间隔为 1 秒,可通过 WithPollInterval 等选项自定义。

type SandboxInfo

type SandboxInfo struct {
	SandboxID   string
	TemplateID  string
	ClientID    string
	Alias       *string
	Domain      *string
	State       SandboxState
	CPUCount    int32
	MemoryMB    int32
	DiskSizeMB  int32
	EnvdVersion string
	StartedAt   time.Time
	EndAt       time.Time
	Metadata    *Metadata
}

SandboxInfo 沙箱详细信息。

type SandboxInjectionSpec added in v7.26.8

type SandboxInjectionSpec struct {
	// ByID 引用已保存的注入规则 ID。
	ByID *string

	// OpenAI OpenAI 兼容 API 注入。
	OpenAI *OpenAIInjection

	// Anthropic Anthropic API 注入。
	Anthropic *AnthropicInjection

	// Gemini Google Gemini API 注入。
	Gemini *GeminiInjection

	// Qiniu 七牛 AI API 注入。
	Qiniu *QiniuInjection

	// Github GitHub 凭证注入。
	Github *GithubInjection

	// HTTP 自定义 HTTP 注入。
	HTTP *HTTPInjection
}

SandboxInjectionSpec 沙箱注入配置(discriminated union)。 可引用已保存的注入规则 ID,或直接指定注入配置,各字段互斥。

type SandboxLog

type SandboxLog struct {
	Line      string
	Timestamp time.Time
}

SandboxLog 沙箱日志条目。

type SandboxLogEntry

type SandboxLogEntry struct {
	Level     LogLevel
	Message   string
	Fields    map[string]string
	Timestamp time.Time
}

SandboxLogEntry 结构化沙箱日志条目。

type SandboxLogs

type SandboxLogs struct {
	Logs       []SandboxLog
	LogEntries []SandboxLogEntry
}

SandboxLogs 沙箱日志。

type SandboxMetric

type SandboxMetric struct {
	CPUCount      int32
	CPUUsedPct    float32
	MemTotal      int64
	MemUsed       int64
	DiskTotal     int64
	DiskUsed      int64
	Timestamp     time.Time
	TimestampUnix int64
}

SandboxMetric 沙箱资源指标。

type SandboxResourceSpec added in v7.26.11

type SandboxResourceSpec struct {
	// GitRepository GitHub 仓库资源。
	GitRepository *GitRepositoryResource
}

SandboxResourceSpec 沙箱资源规约(discriminated union),各字段互斥,只能设置一个。

type SandboxState

type SandboxState string

SandboxState 沙箱状态。

const (
	StateRunning SandboxState = "running"
	StatePaused  SandboxState = "paused"
)

沙箱状态常量。

type SandboxesWithMetrics

type SandboxesWithMetrics struct {
	Sandboxes map[string]SandboxMetric
}

SandboxesWithMetrics 批量沙箱指标数据。

type StartTemplateBuildParams

type StartTemplateBuildParams struct {
	// Force 是否强制完整构建(忽略缓存)。
	Force *bool

	// FromImage 用作模板构建基础的镜像。
	FromImage *string

	// FromImageRegistry 镜像仓库认证配置。
	FromImageRegistry *FromImageRegistry

	// FromTemplate 用作模板构建基础的模板。
	FromTemplate *string

	// ReadyCmd 构建完成后执行的就绪检查命令。
	ReadyCmd *string

	// StartCmd 构建完成后执行的启动命令。
	StartCmd *string

	// Steps 模板构建步骤列表。
	Steps *[]TemplateStep
}

StartTemplateBuildParams 启动模板构建的请求参数。

type Template

type Template struct {
	TemplateID    string
	Aliases       []string
	BuildID       string
	BuildStatus   TemplateBuildStatus
	BuildCount    int32
	CPUCount      int32
	MemoryMB      int32
	DiskSizeMB    int32
	EnvdVersion   string
	Public        bool
	SpawnCount    int64
	CreatedAt     time.Time
	UpdatedAt     time.Time
	LastSpawnedAt *time.Time
}

Template 模板信息。

type TemplateAliasResponse

type TemplateAliasResponse struct {
	TemplateID string
	Public     bool
}

TemplateAliasResponse 模板别名查询响应。

type TemplateBuild

type TemplateBuild struct {
	BuildID     string
	Status      TemplateBuildStatus
	CPUCount    int32
	MemoryMB    int32
	DiskSizeMB  *int32
	EnvdVersion *string
	CreatedAt   time.Time
	UpdatedAt   time.Time
	FinishedAt  *time.Time
}

TemplateBuild 模板构建记录。

type TemplateBuildFileUpload

type TemplateBuildFileUpload struct {
	// Present 文件是否已存在。
	Present bool
	// URL 上传地址。
	URL *string
}

TemplateBuildFileUpload 模板构建文件上传信息。

type TemplateBuildInfo

type TemplateBuildInfo struct {
	TemplateID string
	BuildID    string
	Status     TemplateBuildStatus
	Logs       []string
}

TemplateBuildInfo 模板构建状态信息。

type TemplateBuildLogs

type TemplateBuildLogs struct {
	Logs []BuildLogEntry
}

TemplateBuildLogs 模板构建日志。

type TemplateBuildStatus

type TemplateBuildStatus string

TemplateBuildStatus 模板构建状态。

const (
	BuildStatusReady    TemplateBuildStatus = "ready"
	BuildStatusError    TemplateBuildStatus = "error"
	BuildStatusBuilding TemplateBuildStatus = "building"
	BuildStatusWaiting  TemplateBuildStatus = "waiting"
	BuildStatusUploaded TemplateBuildStatus = "uploaded"
)

模板构建状态常量。

type TemplateCreateResponse

type TemplateCreateResponse struct {
	TemplateID string
	BuildID    string
	Aliases    []string
	Names      []string
	Tags       []string
	Public     bool
}

TemplateCreateResponse 创建模板的响应。

type TemplateStep

type TemplateStep struct {
	// Args 步骤参数。
	Args *[]string

	// FilesHash 步骤中使用文件的哈希值。
	FilesHash *string

	// Force 是否强制执行(忽略缓存)。
	Force *bool

	// Type 步骤类型。
	Type string
}

TemplateStep 模板构建步骤。

type TemplateWithBuilds

type TemplateWithBuilds struct {
	TemplateID    string
	Aliases       []string
	Public        bool
	SpawnCount    int64
	CreatedAt     time.Time
	UpdatedAt     time.Time
	LastSpawnedAt *time.Time
	Builds        []TemplateBuild
}

TemplateWithBuilds 模板及其构建记录。

type UpdateInjectionRuleParams added in v7.26.7

type UpdateInjectionRuleParams struct {
	// Name 规则名称,可选。
	Name *string

	// Injection 注入配置,可选。
	Injection *InjectionSpec
}

UpdateInjectionRuleParams 更新注入规则的请求参数。

type UpdateTemplateParams

type UpdateTemplateParams struct {
	// Public 模板是否公开。
	Public *bool
}

UpdateTemplateParams 更新模板的请求参数。

type WatchHandle

type WatchHandle struct {
	// contains filtered or unexported fields
}

WatchHandle 目录监听句柄。

func (*WatchHandle) Err

func (w *WatchHandle) Err() error

Err 返回监听过程中发生的错误。应在 Events 通道关闭后调用。 若通过 Stop() 正常停止,Err() 返回 nil;仅在流异常结束时返回错误。

func (*WatchHandle) Events

func (w *WatchHandle) Events() <-chan FilesystemEvent

Events 返回文件系统事件通道。

func (*WatchHandle) Stop

func (w *WatchHandle) Stop()

Stop 停止监听。

type WatchOption

type WatchOption func(*watchOpts)

WatchOption 目录监听选项。

func WithRecursive

func WithRecursive(recursive bool) WatchOption

WithRecursive 设置是否递归监听子目录。

func WithWatchUser

func WithWatchUser(user string) WatchOption

WithWatchUser 设置监听操作的用户身份。

type WriteEntry

type WriteEntry struct {
	Path string
	Data []byte
}

WriteEntry 批量写入的文件条目。

Directories

Path Synopsis
internal
apis
Package apis provides primitives to interact with the openapi HTTP API.
Package apis provides primitives to interact with the openapi HTTP API.
envdapi
Package envdapi provides primitives to interact with the openapi HTTP API.
Package envdapi provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL