run9

package module
v0.18.2 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 30 Imported by: 0

README

run9-sdk-go

run9-sdk-go is the public Go SDK for the run9 control-plane API.

The module path is github.com/sys9-ai/run9-sdk-go. The package name is run9.

Documentation

If the public API changes, README, doc comments, and examples are updated in the same change.

Install

go get github.com/sys9-ai/run9-sdk-go@latest

The SDK uses semantic version tags. For reproducible builds, pin one released tag in your go.mod instead of an unpublished commit.

Quick Start

package main

import (
	"context"
	"log"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
		AK: "ak-...",
		SK: "sk-...",
	})
	if err != nil {
		log.Fatal(err)
	}

	project := client.WithProject("default")
	boxes, err := project.ListBoxes(context.Background(), run9.ListBoxesRequest{})
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("loaded %d boxes", len(boxes))
}

Calling Model

This SDK is intentionally opinionated. It uses one stable calling style across the package:

  1. Create one client from endpoint and credentials.
  2. Use the base client for global APIs such as account, org, shared snaps, and project discovery.
  3. Use client.WithProject(...) before calling any project-scoped API.
  4. Keep simple identity inputs positional, and use request structs for optional filters or mutable payloads.
  5. Use typed streaming helpers instead of raw NDJSON bodies or websocket frames.

The SDK models the public control-plane contract. It does not include local config persistence, terminal rendering, shell completion, or local cursor persistence.

Common Workflows

Create a Box with independent persistent Volumes:

For a non-root guest user, set InitialPermissions: &run9.VolumeInitialPermissions{UID: 1000, GID: 1000, Mode: "0700"} on its VolumeConfig. This initializes only the new volume's top directory. UID/GID are numeric guest IDs (0–4294967294); omitted IDs mean 0. Mode is an octal string from 0000 through 7777, default 0755. Omitting the entire option preserves the existing empty-volume defaults. Parent directories must already allow guest traversal. Later guest chmod/chown survives Stop and remount; these are creation defaults, not an enforced policy.

box, err := client.WithProject("default").CreateBox(ctx, run9.CreateBoxRequest{
    SourceImageRef: "alpine:3.20",
    Volumes: []run9.VolumeConfig{
        {MountPath: "/state"},
        {MountPath: "/cache"},
    },
})

The mount must be absent or empty in the source filesystem. The disk survives Stop and runtime replacement, but is deleted with the Box. Root Snap forks do not include its contents or mount configuration. Each derived Box must opt in again to receive fresh empty Volumes. The disks and mounts cannot be changed after creation. Mount paths must be distinct and must not nest inside one another.

Volumes is optional: omit it or use an empty slice to create no Volumes. A Box supports at most nine Volumes in either Normal or Managed networking. Paths are Linux paths inside the Box, not directories on the caller's machine. Use a canonical absolute path such as /state, with no trailing slash or . / .. components. Symlinks and runtime-managed paths are rejected by the server. The same option works with CreateBoxFromSharedSnapRequest, for both a pinned version and the latest version. BoxView.Volumes reports each SnapID and MountPath in create, get, list, and stop responses; it is not a runtime readiness signal.

Use the existing Box exec, upload/download, and BoxFileSystem methods to access data under the mount path, including read-only access while stopped. There is no separate attachment API. Each Volume is an attached Snap and appears in ListSnaps with Attached: true, its owning Box, and its mount path. SnapFileSystem reads that Volume's own filesystem, without other Box mounts. Fork a Volume by its Snap ID, including while its healthy Box is running:

project := client.WithProject("default")
snapID, err := box.SnapIDAtMount("/state")
if err != nil {
    return err
}
saved, err := project.ForkSnap(ctx, snapID)
// saved is an independent detached Snap; deleting the Box does not delete it.

SnapIDAtMount is a local lookup on a BoxView, not a network request. It accepts an exact configured mount path or / for the original Attached Snap. It does not normalize paths or select a containing Volume for a subdirectory. Missing mounts return an error. Reuse the selected ID with GetSnap, SnapFileSystem, or ForkSnap; the server checks current readiness and ownership for each operation. Online Fork briefly pauses the VM, resumes its existing processes, then waits for the new Snap to become ready. Use a caller context to bound the full wait. It includes synchronized filesystem writes, but excludes VM memory and application-private buffers and does not guarantee application-level transactions. Parent lifecycle hooks do not run. New boxes start fresh processes from the saved files. CreateBox with a source Snap uses the same online capture behavior.

ListSnaps defaults to detached Snaps; set Attached to a pointer to true to list the original Attached Snaps and Volumes instead.

Volumes cannot be deleted independently or initialized from a Snap in this MVP. A saved Snap may contain only application files, not a bootable root filesystem. A failed mount does not fall back to writing the Root directory. The disk uses Run9's existing durability contract; it adds no cross-disk transaction or zero-loss host-crash guarantee.

Load the current authenticated identity:

identity, err := client.WhoAmI(ctx)

List accessible projects:

projects, err := client.ListProjects(ctx)

Create one box in a project:

project := client.WithProject("sandbox")

box, err := project.CreateBox(ctx, run9.CreateBoxRequest{
	BoxID:          "devbox",
	DesiredShape:   "2c4g",
	SourceImageRef: "public.ecr.aws/docker/library/alpine:3.20",
})
if err == nil {
	log.Printf("browse box files at %s", box.FileAccessURL)
}

Resolve a reusable read-only filesystem and stream files without transfer jobs:

files, err := project.BoxFileSystem(ctx, "devbox")
if err != nil {
	return err
}
files, err = files.RootedAt("/workspace")
if err != nil {
	return err
}

page, err := files.ReadDir(ctx, "/site", run9.ReadDirRequest{Limit: 100})
if err != nil {
	return err
}

matches, err := files.GlobFiles(ctx, "/", run9.GlobFilesRequest{
	Pattern:            "**/*index*",
	Limit:              20,
	ExcludeDirectories: []string{".git", "node_modules"},
	RankingQuery:       "index",
	RespectGitIgnore:   true,
})
if err != nil {
	return err
}

reader, err := files.Open(ctx, "/site/index.html", run9.OpenFileOptions{})
if err != nil {
	return err
}
defer reader.Close()
_, err = io.Copy(os.Stdout, reader)

Use project.SnapFileSystem(ctx, snapID) for the same operations on a snap. A detached snap reads its immutable settled generation; a Volume reads only its own filesystem, excluding other mounts. The original root Attached Snap retains its owning Box's composed view. RootedAt makes the selected directory the filesystem root, including for symlink resolution. Resolve FileSystem once and reuse it for concurrent Open, Stat, GlobFiles, and paginated ReadDir calls. GlobFiles applies one case-sensitive doublestar pattern to regular-file paths relative to the requested directory; brace alternatives are not supported. Results are lexically ordered by default. RankingQuery instead applies VS Code File Quick Open-style relevance before the limit. RespectGitIgnore applies the requested directory's root and nested .gitignore files before matching, ranking, and limiting. Both options keep the operation to one bounded request rather than recursively listing remote directories.

Run one foreground exec and stream its output:

result, err := project.RunExec(ctx, "devbox", run9.ExecRequest{
	Command: []string{"/bin/sh", "-lc", "echo hello"},
}, run9.ExecOutputWriters{
	Stdout: os.Stdout,
	Stderr: os.Stderr,
})

result tells you whether the exec exited, was cancelled, or failed. When you need direct event control, StartExecStream(...) and ReadEvent() are still available.

Run one foreground exec and wait for the final merged transcript:

capture, err := project.RunExecCapture(ctx, "devbox", run9.ExecRequest{
	Command: []string{"/bin/sh", "-lc", "echo hello"},
})
if err != nil {
	return err
}
if capture.TranscriptUnavailableReason != "" {
	return fmt.Errorf("exec finished but its final transcript is unavailable: %s", capture.TranscriptUnavailableReason)
}
fmt.Printf("exit=%d transcript=%s", *capture.Terminal.ExitCode, capture.Transcript)

RunExecCapture(...) is the stable completion helper. It uses the live foreground stream to start the command, then falls back to durable exec truth plus log-download when the stream transport breaks near terminal. The returned transcript always follows the merged log-download view, so it does not preserve stdout and stderr as separate streams. If the exec finished but the transcript archive is unavailable, the helper still returns the terminal result and reports the transcript problem through TranscriptUnavailableReason.

Start one background exec and follow its output with an internal cursor:

execView, err := project.StartBackgroundExec(ctx, "devbox", run9.ExecRequest{
	Command:        []string{"/bin/sh", "-lc", "long task"},
	StdinEnabled:   true,
	IdempotencyKey: "daemon-generation-42",
})
if err != nil {
	return err
}

follower := project.FollowBackgroundExec(execView.ExecID)
result, err := follower.Pump(ctx, 2*time.Second, run9.ExecOutputWriters{
	Stdout: os.Stdout,
	Stderr: os.Stderr,
})

Persist one stable IdempotencyKey for each logical daemon generation and reuse it when retrying after an uncertain response. The same key and request return the original exec; changing the request while reusing the key returns a conflict. If omitted, the SDK generates a new key for that StartBackgroundExec call.

result.NextCursor is still exposed for explicit replay use cases, but callers that only want to keep tailing can let the follower manage it.

Record and manage a low-latency workload profile for an exact base snap:

recording, err := project.StartPrewarmRecording(ctx, run9.RecordPrewarmProfileRequest{
	Name:       "typescript",
	BaseSnapID: "snap-base",
	Command:    []string{"npx", "tsc", "--version"},
	MaxRuntime: time.Minute,
})
if err != nil {
	return err
}
result, err := recording.Stream.Pump(ctx, run9.ExecOutputWriters{Stdout: os.Stdout, Stderr: os.Stderr})
profile, err := project.GetPrewarmProfile(context.Background(), recording.ProfileID)

MaxRuntime limits only the user workload and defaults to one minute; runtime preparation and artifact finalization are outside that interval. Reaching the limit, or cancelling the recording context, stops the workload but does not discard blocks already observed. Use a fresh context to poll the profile until it becomes ready or error. Ready profiles are enabled by default; SetPrewarmProfileEnabled changes automatic selection and enabling also converges already-running tenant hosts.

A ready, enabled profile is selected automatically for boxes created from its base snap or any descendant. If several profiles are present on that ancestor chain, the nearest ready, enabled profile wins.

If you want one merged transcript in event order, call Read(...) and then WriteMergedOutput(...):

result, err := follower.Read(ctx, 2*time.Second)
if err != nil {
	return err
}
if err := result.WriteMergedOutput(os.Stdout, os.Stderr); err != nil {
	return err
}

API Surface

Global APIs live on the base client:

  • account identity and SSH keys
  • org metadata, members, invitations, API keys, and org hosts
  • project list, inspect, and create
  • shared snap catalog list, inspect, publish, and delete

Project-scoped APIs require WithProject(...):

  • boxes
  • snaps
  • execs
  • recorded prewarm profiles
  • file archive upload and download
  • reusable read-only box and snap filesystems
  • project members
  • project and box secrets
  • create-from-shared-snap flows

If a project-scoped method is called without WithProject(...), the SDK returns an explicit error instead of guessing a default project.

Errors

Non-2xx responses are returned as *run9.Error.

if err != nil {
	var apiErr *run9.Error
	if errors.As(err, &apiErr) {
		log.Printf("run9 request failed: status=%d message=%q", apiErr.StatusCode, apiErr.Message)
	}
}

The SDK avoids silent fallbacks. Missing credentials, invalid endpoints, and missing project scope are returned as direct errors.

Compatibility

Before v1.0.0, breaking API cleanup is allowed when it materially improves clarity or ergonomics. Every exported API change must land together with:

  • updated doc comments
  • updated README examples
  • passing go test ./...

Documentation

Overview

Package run9 provides the public Go SDK for the run9 control-plane API.

The package follows one consistent calling model:

  • Create one Client with NewClient by binding the API endpoint and API key once.
  • Use the base client for account, organization, shared-snap, and project-discovery APIs.
  • Use Client.WithProject to derive a project-scoped client for boxes, snaps, execs, archives, and secrets.
  • Pass request structs when a call has optional filters or mutable payload.
  • Use high-level helpers such as Client.RunExec, Client.RunExecCapture, and Client.FollowBackgroundExec when you want terminal results plus live output or one merged transcript.
  • Drop down to typed stream helpers such as ExecStream and ExecAttachSocket only when you need direct event control.

The module path is github.com/sys9-ai/run9-sdk-go, while the package name is run9:

client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
	AK: "ak-...",
	SK: "sk-...",
})
if err != nil {
	return
}

project := client.WithProject("default")
_, _ = project.ListBoxes(context.Background(), run9.ListBoxesRequest{})

Non-2xx responses are returned as *Error. When the control plane returns a structured error message, it is exposed through Error.Message.

Index

Examples

Constants

View Source
const MaxPrewarmRecordingRuntime = 12 * time.Hour

MaxPrewarmRecordingRuntime is the largest workload duration accepted for one recording.

View Source
const PrewarmRecordingStopReasonMaxRuntime = "prewarm_max_runtime_reached"

PrewarmRecordingStopReasonMaxRuntime identifies a recording workload stopped by its configured limit.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIKeyView

type APIKeyView struct {
	APIKeyID          string    `json:"api_key_id"`
	OrgID             string    `json:"org_id"`
	UserID            string    `json:"user_id"`
	OwnerPrimaryEmail string    `json:"owner_primary_email"`
	OwnerDisplayName  string    `json:"owner_display_name,omitempty"`
	Description       string    `json:"description,omitempty"`
	AK                string    `json:"ak"`
	DisplayPrefix     string    `json:"display_prefix"`
	DisplaySuffix     string    `json:"display_suffix"`
	CreatedAt         time.Time `json:"created_at"`
	ExpiresAt         time.Time `json:"expires_at,omitempty"`
	NoExpire          bool      `json:"no_expire"`
}

APIKeyView describes one API key without secret key material.

type BackgroundExecFollower added in v0.2.0

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

BackgroundExecFollower tracks one background exec cursor and hides repeated pull-output polling.

func (*BackgroundExecFollower) Cursor added in v0.2.0

func (f *BackgroundExecFollower) Cursor() string

Cursor returns the current replay cursor.

func (*BackgroundExecFollower) Pump added in v0.2.0

Pump reads one meaningful output window and writes stdout to Stdout and stderr plus notices to Stderr.

func (*BackgroundExecFollower) Read added in v0.2.0

Read waits for the next meaningful output window.

When wait is positive, Read skips empty and started-only polls while the exec stays active.

func (*BackgroundExecFollower) Reset added in v0.2.0

func (f *BackgroundExecFollower) Reset()

Reset clears the current replay cursor so the next read starts from the beginning once.

func (*BackgroundExecFollower) SetCursor added in v0.2.0

func (f *BackgroundExecFollower) SetCursor(cursor string)

SetCursor overwrites the current replay cursor.

type BackgroundExecOutputEvent added in v0.2.0

type BackgroundExecOutputEvent struct {
	// Seq is the durable event sequence number for incremental replay.
	Seq uint64
	// Type identifies whether this event is stdout, stderr, gap, truncated, or terminal.
	Type BackgroundExecOutputEventType
	// Data carries stdout or stderr bytes on output events.
	Data []byte
	// GapBytes reports how many bytes were omitted on gap events.
	GapBytes uint64
	// ExitCode is set on exit events.
	ExitCode *int
	// Reason is set on cancelled and error events.
	Reason string
}

BackgroundExecOutputEvent describes one decoded background exec output event.

type BackgroundExecOutputEventType added in v0.2.0

type BackgroundExecOutputEventType string

BackgroundExecOutputEventType identifies one event decoded from a background exec output window.

const (
	// BackgroundExecOutputEventStarted reports the durable exec start marker.
	BackgroundExecOutputEventStarted BackgroundExecOutputEventType = "started"
	// BackgroundExecOutputEventStdout reports one stdout chunk.
	BackgroundExecOutputEventStdout BackgroundExecOutputEventType = "stdout"
	// BackgroundExecOutputEventStderr reports one stderr chunk.
	BackgroundExecOutputEventStderr BackgroundExecOutputEventType = "stderr"
	// BackgroundExecOutputEventGap reports that older bytes were omitted around the current cursor.
	BackgroundExecOutputEventGap BackgroundExecOutputEventType = "gap"
	// BackgroundExecOutputEventTruncated reports that the service truncated retained output at its hard limit.
	BackgroundExecOutputEventTruncated BackgroundExecOutputEventType = "truncated"
	// BackgroundExecOutputEventExit reports a terminal process exit.
	BackgroundExecOutputEventExit BackgroundExecOutputEventType = "exit"
	// BackgroundExecOutputEventCancelled reports a terminal cancellation.
	BackgroundExecOutputEventCancelled BackgroundExecOutputEventType = "cancelled"
	// BackgroundExecOutputEventError reports a terminal runtime or control-plane failure.
	BackgroundExecOutputEventError BackgroundExecOutputEventType = "error"
)

type BackgroundExecPullOutput

type BackgroundExecPullOutput struct {
	// Events carries the decoded output and terminal events returned by this poll.
	Events []BackgroundExecOutputEvent
	// NextCursor is the cursor to use on the next incremental poll.
	NextCursor string
	// State is the current durable exec state.
	State string
	// ExitCode is set after terminal exit when the exec produced one.
	ExitCode *int
	// Reason carries the durable terminal reason when one is available.
	Reason string
	// IdleDeadlineAt is the current idle lease deadline when the control plane reports it.
	IdleDeadlineAt *time.Time
}

BackgroundExecPullOutput describes one decoded background exec output window.

func (BackgroundExecPullOutput) TerminalResult added in v0.2.0

func (r BackgroundExecPullOutput) TerminalResult() *ExecTerminalResult

TerminalResult returns the terminal outcome carried by this output window when one is available.

func (BackgroundExecPullOutput) WriteMergedOutput added in v0.2.0

func (r BackgroundExecPullOutput) WriteMergedOutput(output io.Writer, notices io.Writer) error

WriteMergedOutput writes stdout and stderr chunks to output in event order and writes gap or truncation notices to notices.

Example
package main

import (
	"io"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	result := run9.BackgroundExecPullOutput{
		Events: []run9.BackgroundExecOutputEvent{
			{Type: run9.BackgroundExecOutputEventStdout, Data: []byte("hello\n")},
			{Type: run9.BackgroundExecOutputEventStderr, Data: []byte("warn\n")},
		},
	}

	if err := result.WriteMergedOutput(io.Discard, io.Discard); err != nil {
		panic(err)
	}
}

func (BackgroundExecPullOutput) WriteOutput added in v0.2.0

func (r BackgroundExecPullOutput) WriteOutput(writers ExecOutputWriters) error

WriteOutput writes stdout events to Stdout, stderr events to Stderr, and gap or truncation notices to Stderr.

type BoxNetworkMode

type BoxNetworkMode string

BoxNetworkMode represents the requested networking mode for a box.

const (
	// BoxNetworkModeNormal requests the default non-managed network path.
	BoxNetworkModeNormal BoxNetworkMode = "normal"
	// BoxNetworkModeManaged requests the managed network path.
	BoxNetworkModeManaged BoxNetworkMode = "managed"
)

Box network modes accepted by box create and update APIs.

type BoxState

type BoxState string

BoxState represents the current box state.

type BoxView

type BoxView struct {
	BoxID       string            `json:"box_id"`
	OrgID       string            `json:"org_id"`
	ProjectID   string            `json:"project_id"`
	Creator     string            `json:"creator"`
	CreatedAt   time.Time         `json:"created_at"`
	LastUsedAt  time.Time         `json:"last_used_at"`
	Description string            `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	State       BoxState          `json:"state"`
	Reason      string            `json:"reason,omitempty"`
	// BoxSnapID identifies this Box's writable Attached Snap, not its source.
	BoxSnapID string `json:"box_snap_id"`
	// Volumes lists the fixed Box-owned Snap mounts; empty means none.
	// It describes configuration, not whether a runtime is currently mounted.
	Volumes                   []VolumeView   `json:"volumes,omitempty"`
	FileAccessURL             string         `json:"file_access_url,omitempty"`
	DesiredShape              string         `json:"desired_shape"`
	NetworkMode               BoxNetworkMode `json:"network_mode"`
	CurrentHostID             string         `json:"current_host_id,omitempty"`
	CurrentRuntimeShape       string         `json:"current_runtime_shape,omitempty"`
	CurrentRuntimeNetworkMode BoxNetworkMode `json:"current_runtime_network_mode,omitempty"`
	PendingShapeChange        bool           `json:"pending_shape_change"`
	PendingNetworkModeChange  bool           `json:"pending_network_mode_change"`
}

BoxView describes one box. FileAccessURL is its stable read-only filesystem capability URL.

func (BoxView) SnapIDAtMount added in v0.17.0

func (b BoxView) SnapIDAtMount(mountPath string) (string, error)

SnapIDAtMount resolves an exact mount path in this Box view to its Snap ID. Use "/" for the original Attached Snap, or a Volume's configured MountPath. It does not normalize paths, match subdirectories, or make a network request. This lookup does not establish readiness; Snap operations check current state on the server; a healthy running Box can Fork with a brief pause.

type CacheAccessStats added in v0.11.0

type CacheAccessStats struct {
	PrivateCacheHits     uint64 `json:"private_cache_hits"`
	PrivateCacheHitBytes uint64 `json:"private_cache_hit_bytes"`
	PrewarmCacheHits     uint64 `json:"prewarm_cache_hits"`
	PrewarmCacheHitBytes uint64 `json:"prewarm_cache_hit_bytes"`
	PrewarmCacheMisses   uint64 `json:"prewarm_cache_misses"`
	PrewarmCacheErrors   uint64 `json:"prewarm_cache_errors"`
	ObjectGets           uint64 `json:"object_gets"`
	ObjectGetBytes       uint64 `json:"object_get_bytes"`
	UnavailableReason    string `json:"unavailable_reason,omitempty"`
}

CacheAccessStats reports per-exec JuiceFS access counter deltas.

type Client

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

Client is the public run9 control-plane HTTP client.

func NewClient

func NewClient(endpoint string, creds Credentials) (*Client, error)

NewClient creates one authenticated run9 control-plane HTTP client rooted at the given endpoint.

Example
package main

import (
	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
		AK: "ak-...",
		SK: "sk-...",
	})
	if err != nil {
		panic(err)
	}

	projectClient := client.WithProject("default")
	_, _ = client, projectClient
}

func (*Client) BoxFileSystem added in v0.5.0

func (c *Client) BoxFileSystem(ctx context.Context, boxID string) (*FileSystem, error)

BoxFileSystem resolves one Box filesystem capability.

Example
package main

import (
	"context"
	"io"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
		AK: "ak-...",
		SK: "sk-...",
	})
	if err != nil {
		panic(err)
	}

	files, err := client.WithProject("sandbox").BoxFileSystem(context.Background(), "devbox")
	if err != nil {
		panic(err)
	}
	files, err = files.RootedAt("/workspace")
	if err != nil {
		panic(err)
	}
	_, err = files.GlobFiles(context.Background(), "/", run9.GlobFilesRequest{
		Pattern:            "**/*index*",
		Limit:              20,
		ExcludeDirectories: []string{".git", "node_modules"},
	})
	if err != nil {
		panic(err)
	}
	reader, err := files.Open(context.Background(), "/site/index.html", run9.OpenFileOptions{})
	if err != nil {
		panic(err)
	}
	defer reader.Close()
	_, _ = io.Copy(io.Discard, reader)
}

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(ctx context.Context, req CreateAPIKeyRequest) (CreatedAPIKeyView, error)

CreateAPIKey creates one API key in the current organization.

func (*Client) CreateBox

func (c *Client) CreateBox(ctx context.Context, req CreateBoxRequest) (BoxView, error)

CreateBox creates one project-scoped box with its own root Snap. A source Snap may belong to a healthy running Box; that Box pauses briefly for capture and continues while the new root Snap prepares.

Example
package main

import (
	"context"
	"log"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{AK: "ak-example", SK: "sk-example"})
	if err != nil {
		log.Fatal(err)
	}
	box, err := client.WithProject("default").CreateBox(context.Background(), run9.CreateBoxRequest{
		SourceImageRef: "alpine:3.20",
		Volumes: []run9.VolumeConfig{{
			MountPath:          "/state",
			InitialPermissions: &run9.VolumeInitialPermissions{UID: 1000, GID: 1000, Mode: "0700"},
		}, {MountPath: "/cache"}},
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Box %s has persistent Volumes %v", box.BoxID, box.Volumes)
}

func (*Client) CreateBoxFromSharedSnap

func (c *Client) CreateBoxFromSharedSnap(ctx context.Context, name string, req CreateBoxFromSharedSnapRequest) (BoxView, error)

CreateBoxFromSharedSnap creates a box from one shared snap.

Example
package main

import (
	"context"
	"log"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{AK: "ak-example", SK: "sk-example"})
	if err != nil {
		log.Fatal(err)
	}
	// The latest shared version supplies Root only. This Box gets its own
	// empty Volume; neither the data nor this option is inherited from a Snap.
	box, err := client.WithProject("default").CreateBoxFromSharedSnap(context.Background(), "python-dev", run9.CreateBoxFromSharedSnapRequest{
		Volumes: []run9.VolumeConfig{{MountPath: "/state"}, {MountPath: "/cache"}},
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Box %s has persistent Volumes %v", box.BoxID, box.Volumes)
}

func (*Client) CreateBoxSecret

func (c *Client) CreateBoxSecret(ctx context.Context, boxID string, req CreateProjectSecretRequest) (ProjectSecretView, error)

CreateBoxSecret creates one box-scoped secret.

func (*Client) CreateInvitation

func (c *Client) CreateInvitation(ctx context.Context, orgID string, req CreateInvitationRequest) (InvitationView, error)

CreateInvitation creates one invitation in an organization.

func (*Client) CreateProject

func (c *Client) CreateProject(ctx context.Context, req CreateProjectRequest) (ProjectView, error)

CreateProject creates one project.

func (*Client) CreateProjectSecret

func (c *Client) CreateProjectSecret(ctx context.Context, req CreateProjectSecretRequest) (ProjectSecretView, error)

CreateProjectSecret creates one project-scoped secret.

func (*Client) CreateSSHKey

func (c *Client) CreateSSHKey(ctx context.Context, req CreateSSHKeyRequest) (SSHKeyView, error)

CreateSSHKey registers one SSH public key on the caller's account.

func (*Client) CreateSnapFromSharedSnap

func (c *Client) CreateSnapFromSharedSnap(ctx context.Context, name string, req CreateSnapFromSharedSnapRequest) (SnapView, error)

CreateSnapFromSharedSnap creates a snap from one shared snap.

func (*Client) DeleteBox

func (c *Client) DeleteBox(ctx context.Context, boxID string) (BoxView, error)

DeleteBox deletes one box. It also deletes the Attached Snap and all Volumes. Detached Snaps previously forked from them survive. Use StopBox to retain data while releasing compute.

func (*Client) DeleteBoxSecret

func (c *Client) DeleteBoxSecret(ctx context.Context, boxID string, secretID string) error

DeleteBoxSecret deletes one box-scoped secret.

func (*Client) DeleteOrg

func (c *Client) DeleteOrg(ctx context.Context, orgID string) (DeleteOrgResult, error)

DeleteOrg deletes one organization.

func (*Client) DeleteOrgMember

func (c *Client) DeleteOrgMember(ctx context.Context, orgID string, userID string) error

DeleteOrgMember removes one member from an organization.

func (*Client) DeleteProject

func (c *Client) DeleteProject(ctx context.Context) (DeleteProjectResult, error)

DeleteProject deletes the current project.

func (*Client) DeleteProjectMember

func (c *Client) DeleteProjectMember(ctx context.Context, userID string) error

DeleteProjectMember removes one member from the current project.

func (*Client) DeleteProjectSecret

func (c *Client) DeleteProjectSecret(ctx context.Context, secretID string) error

DeleteProjectSecret deletes one project-scoped secret.

func (*Client) DeleteSSHKey

func (c *Client) DeleteSSHKey(ctx context.Context, sshKeyID string) (SSHKeyView, error)

DeleteSSHKey removes one SSH key from the caller's account.

func (*Client) DeleteSharedSnap

func (c *Client) DeleteSharedSnap(ctx context.Context, name string) error

DeleteSharedSnap deletes one shared snap name and all of its versions.

func (*Client) DeleteSharedSnapVersion

func (c *Client) DeleteSharedSnapVersion(ctx context.Context, name string, version int) error

DeleteSharedSnapVersion deletes one shared snap version.

func (*Client) DeleteSnap

func (c *Client) DeleteSnap(ctx context.Context, snapID string) (SnapView, error)

DeleteSnap deletes one snap.

func (*Client) DownloadArchive

func (c *Client) DownloadArchive(ctx context.Context, boxID string, boxAbsPath string) (io.ReadCloser, error)

DownloadArchive downloads one box path as a tar archive.

func (*Client) DownloadExecLog

func (c *Client) DownloadExecLog(ctx context.Context, execID string) (io.ReadCloser, error)

DownloadExecLog downloads the stored log for one exec.

func (*Client) FollowBackgroundExec added in v0.2.0

func (c *Client) FollowBackgroundExec(execID string) *BackgroundExecFollower

FollowBackgroundExec returns a cursor-tracking follower for one background exec.

Example
package main

import (
	"context"
	"io"
	"time"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
		AK: "ak-...",
		SK: "sk-...",
	})
	if err != nil {
		panic(err)
	}

	project := client.WithProject("sandbox")
	follower := project.FollowBackgroundExec("exec-123")
	result, err := follower.Pump(context.Background(), 2*time.Second, run9.ExecOutputWriters{
		Stdout: io.Discard,
		Stderr: io.Discard,
	})
	if err != nil {
		panic(err)
	}

	_ = result.TerminalResult()
}

func (*Client) ForkSnap

func (c *Client) ForkSnap(ctx context.Context, snapID string) (SnapView, error)

ForkSnap creates an independent detached Snap from the selected Snap's contents. A healthy running source Box pauses briefly, then resumes its existing processes. The call waits until the new Snap is ready; ctx bounds the entire request. Only the selected filesystem is captured, excluding other mounts, mount configuration, VM memory, and application-private buffers. Application-level transactions are not guaranteed, and the parent's lifecycle hooks do not run.

Example
package main

import (
	"context"
	"log"
	"time"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{AK: "ak-example", SK: "sk-example"})
	if err != nil {
		log.Fatal(err)
	}
	project := client.WithProject("default")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()
	box, err := project.GetBox(ctx, "stateful-box")
	if err != nil {
		log.Fatal(err)
	}
	// Select an exact mount, not an array position or a directory inside a Volume.
	snapID, err := box.SnapIDAtMount("/state")
	if err != nil {
		log.Fatal(err)
	}
	saved, err := project.ForkSnap(ctx, snapID)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Saved independent detached Snap %s", saved.SnapID)
}

func (*Client) GetBox

func (c *Client) GetBox(ctx context.Context, boxID string) (BoxView, error)

GetBox loads one project-scoped box by ID.

func (*Client) GetExec

func (c *Client) GetExec(ctx context.Context, execID string) (ExecView, error)

GetExec loads one exec by ID from the current project.

func (*Client) GetOrgHosts

func (c *Client) GetOrgHosts(ctx context.Context) (OrgHostsView, error)

GetOrgHosts loads runtime hosts assigned to the current organization.

func (*Client) GetPrewarmProfile added in v0.11.0

func (c *Client) GetPrewarmProfile(ctx context.Context, nameOrID string) (PrewarmProfileView, error)

GetPrewarmProfile loads one recorded prewarm profile by name or id.

func (*Client) GetProject

func (c *Client) GetProject(ctx context.Context, projectCID string) (ProjectView, error)

GetProject loads one project by CID.

func (*Client) GetSharedSnap

func (c *Client) GetSharedSnap(ctx context.Context, name string) (SharedSnapDetailView, error)

GetSharedSnap loads one shared snap and its versions.

func (*Client) GetSnap

func (c *Client) GetSnap(ctx context.Context, snapID string) (SnapView, error)

GetSnap loads one project-scoped snap by ID.

func (*Client) GetSnapTree

func (c *Client) GetSnapTree(ctx context.Context, snapID string) (SnapTreeView, error)

GetSnapTree loads the ancestry tree for one snap.

func (*Client) ImportSnap

func (c *Client) ImportSnap(ctx context.Context, req ImportSnapRequest) (SnapView, error)

ImportSnap imports a snap from an image reference into the current project.

func (*Client) KillBackgroundExec

func (c *Client) KillBackgroundExec(ctx context.Context, execID string) error

KillBackgroundExec requests termination of one background exec.

func (*Client) ListAPIKeys

func (c *Client) ListAPIKeys(ctx context.Context) ([]APIKeyView, error)

ListAPIKeys lists API keys visible to the caller in the current organization.

func (*Client) ListBoxSecrets

func (c *Client) ListBoxSecrets(ctx context.Context, boxID string) ([]ProjectSecretView, error)

ListBoxSecrets lists box-scoped secrets for one box.

func (*Client) ListBoxes

func (c *Client) ListBoxes(ctx context.Context, req ListBoxesRequest) ([]BoxView, error)

ListBoxes lists project-scoped boxes with optional creator, label, and state filters.

func (*Client) ListExecs

func (c *Client) ListExecs(ctx context.Context, req ListExecsRequest) (ListExecsResult, error)

ListExecs lists execs in the current project with optional filters.

func (*Client) ListInvitations

func (c *Client) ListInvitations(ctx context.Context, orgID string) ([]InvitationView, error)

ListInvitations lists invitations in one organization.

func (*Client) ListOrgMembers

func (c *Client) ListOrgMembers(ctx context.Context, orgID string) ([]MembershipView, error)

ListOrgMembers lists members in one organization.

func (*Client) ListPrewarmProfiles added in v0.11.0

func (c *Client) ListPrewarmProfiles(ctx context.Context) ([]PrewarmProfileView, error)

ListPrewarmProfiles lists recorded prewarm profiles in the selected project.

func (*Client) ListProjectMembers

func (c *Client) ListProjectMembers(ctx context.Context) ([]ProjectMembershipView, error)

ListProjectMembers lists members in the current project.

func (*Client) ListProjectSecrets

func (c *Client) ListProjectSecrets(ctx context.Context) ([]ProjectSecretView, error)

ListProjectSecrets lists project-scoped secrets for the current project.

func (*Client) ListProjects

func (c *Client) ListProjects(ctx context.Context) ([]ProjectView, error)

ListProjects lists projects visible to the caller.

func (*Client) ListSSHKeys

func (c *Client) ListSSHKeys(ctx context.Context) ([]SSHKeyView, error)

ListSSHKeys lists SSH keys registered on the caller's account.

func (*Client) ListSharedSnaps

func (c *Client) ListSharedSnaps(ctx context.Context) ([]SharedSnapLineView, error)

ListSharedSnaps lists shared snaps visible to the caller.

func (*Client) ListSnaps

func (c *Client) ListSnaps(ctx context.Context, req ListSnapsRequest) ([]SnapView, error)

ListSnaps lists project-scoped snaps with an optional attached filter.

func (*Client) OpenExecAttach

func (c *Client) OpenExecAttach(ctx context.Context, attachURL string) (*ExecAttachSocket, error)

OpenExecAttach dials one exec attach websocket returned by the control plane.

func (*Client) PublishSharedSnap

func (c *Client) PublishSharedSnap(ctx context.Context, req PublishSharedSnapRequest) (SharedSnapVersionView, error)

PublishSharedSnap publishes one snap into the shared snap catalog.

func (*Client) PullBackgroundExecOutput

func (c *Client) PullBackgroundExecOutput(ctx context.Context, execID string, req PullBackgroundExecOutputRequest) (BackgroundExecPullOutput, error)

PullBackgroundExecOutput polls output and state transitions for one background exec.

func (*Client) RevokeAPIKey

func (c *Client) RevokeAPIKey(ctx context.Context, apiKeyID string) (APIKeyView, error)

RevokeAPIKey revokes one API key in the current organization.

func (*Client) RevokeInvitation

func (c *Client) RevokeInvitation(ctx context.Context, orgID string, invitationID string) (DeleteInvitationResult, error)

RevokeInvitation revokes one organization invitation.

func (*Client) RunExec added in v0.2.0

func (c *Client) RunExec(ctx context.Context, boxID string, req ExecRequest, writers ExecOutputWriters) (ExecTerminalResult, error)

RunExec starts one foreground exec, pumps its output, and returns the terminal result.

Example
package main

import (
	"context"
	"io"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
		AK: "ak-...",
		SK: "sk-...",
	})
	if err != nil {
		panic(err)
	}

	project := client.WithProject("sandbox")
	_, err = project.RunExec(context.Background(), "devbox", run9.ExecRequest{
		Command: []string{"/bin/sh", "-lc", "echo hello"},
	}, run9.ExecOutputWriters{
		Stdout: io.Discard,
		Stderr: io.Discard,
	})
	if err != nil {
		panic(err)
	}

	_ = project
}

func (*Client) RunExecCapture added in v0.3.0

func (c *Client) RunExecCapture(ctx context.Context, boxID string, req ExecRequest) (ExecCapture, error)

RunExecCapture starts one foreground exec, waits for a terminal result, and loads the final merged log snapshot.

The helper uses the normal foreground live stream to start the command. If that transport breaks after the exec has been accepted, it polls the durable exec record and still returns a terminal result when one becomes visible. It does not change foreground exec disconnect semantics, and the returned Transcript intentionally follows the merged log-download view instead of preserving stdout and stderr as separate streams.

Example
package main

import (
	"context"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
		AK: "ak-...",
		SK: "sk-...",
	})
	if err != nil {
		panic(err)
	}

	project := client.WithProject("sandbox")
	capture, err := project.RunExecCapture(context.Background(), "devbox", run9.ExecRequest{
		Command: []string{"/bin/sh", "-lc", "echo hello"},
	})
	if err != nil {
		panic(err)
	}

	_, _ = capture.Transcript, capture.Terminal
}

func (*Client) SetPrewarmProfileEnabled added in v0.11.0

func (c *Client) SetPrewarmProfileEnabled(ctx context.Context, nameOrID string, enabled bool) (PrewarmProfileView, error)

SetPrewarmProfileEnabled enables or disables automatic selection of one profile.

func (*Client) SnapFileSystem added in v0.5.0

func (c *Client) SnapFileSystem(ctx context.Context, snapID string) (*FileSystem, error)

SnapFileSystem resolves a Snap's read-only filesystem capability. A detached Snap reads its immutable view; a Volume reads only its own contents. The original root Attached Snap retains the owning Box's composed view.

func (*Client) StartBackgroundExec

func (c *Client) StartBackgroundExec(ctx context.Context, boxID string, req ExecRequest) (ExecView, error)

StartBackgroundExec starts one background exec in a box.

Example
package main

import (
	"context"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
		AK: "ak-...",
		SK: "sk-...",
	})
	if err != nil {
		panic(err)
	}

	project := client.WithProject("sandbox")
	_, err = project.StartBackgroundExec(context.Background(), "devbox", run9.ExecRequest{
		Command:        []string{"/bin/sh", "-lc", "long task"},
		IdempotencyKey: "daemon-generation-42",
	})
	if err != nil {
		panic(err)
	}
}

func (*Client) StartExec

func (c *Client) StartExec(ctx context.Context, boxID string, req ExecRequest) (ExecView, error)

StartExec starts one foreground exec and returns its initial view.

func (*Client) StartExecStream

func (c *Client) StartExecStream(ctx context.Context, boxID string, req ExecRequest) (*ExecStream, error)

StartExecStream starts a streaming exec and returns one event reader.

func (*Client) StartPrewarmRecording added in v0.11.0

func (c *Client) StartPrewarmRecording(ctx context.Context, req RecordPrewarmProfileRequest) (*PrewarmRecordingStream, error)

StartPrewarmRecording creates an enabled profile and starts its standard workload stream. Closing or cancelling the stream cancels only the workload; the service still finalizes collected blocks.

Example
package main

import (
	"context"
	"time"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, _ := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{AK: "ak-example", SK: "sk-example"})
	project := client.WithProject("sandbox")
	recording, err := project.StartPrewarmRecording(context.Background(), run9.RecordPrewarmProfileRequest{
		Name:       "typescript",
		BaseSnapID: "snap-base",
		Command:    []string{"npx", "tsc", "--version"},
		MaxRuntime: time.Minute,
	})
	if err != nil {
		return
	}
	defer recording.Stream.Close()
	_ = recording.ProfileID
}

func (*Client) StopBox

func (c *Client) StopBox(ctx context.Context, boxID string) (BoxView, error)

StopBox requests a graceful stop for one box. It finalizes and retains the Attached Snap and all Volumes for subsequent execution.

func (*Client) UpdateAccount

func (c *Client) UpdateAccount(ctx context.Context, req UpdateMeRequest) (MeView, error)

UpdateAccount updates mutable fields on the caller's user account.

func (*Client) UpdateBox

func (c *Client) UpdateBox(ctx context.Context, boxID string, req UpdateBoxRequest) (BoxView, error)

UpdateBox updates mutable fields on one box.

func (*Client) UpdateBoxSecret

func (c *Client) UpdateBoxSecret(ctx context.Context, boxID string, secretID string, req UpdateProjectSecretRequest) (ProjectSecretView, error)

UpdateBoxSecret updates one box-scoped secret.

func (*Client) UpdateOrg

func (c *Client) UpdateOrg(ctx context.Context, orgID string, req UpdateOrgRequest) (OrgView, error)

UpdateOrg updates mutable fields on one organization.

func (*Client) UpdateOrgMember

func (c *Client) UpdateOrgMember(ctx context.Context, orgID string, userID string, req UpdateMembershipRequest) (MembershipView, error)

UpdateOrgMember updates one organization member.

func (*Client) UpdateProject

func (c *Client) UpdateProject(ctx context.Context, req UpdateProjectRequest) (ProjectView, error)

UpdateProject updates mutable fields on the current project.

func (*Client) UpdateProjectMember

func (c *Client) UpdateProjectMember(ctx context.Context, userID string, req UpdateProjectMembershipRequest) (ProjectMembershipView, error)

UpdateProjectMember updates one member in the current project.

func (*Client) UpdateProjectSecret

func (c *Client) UpdateProjectSecret(ctx context.Context, secretID string, req UpdateProjectSecretRequest) (ProjectSecretView, error)

UpdateProjectSecret updates one project-scoped secret.

func (*Client) UploadArchive

func (c *Client) UploadArchive(ctx context.Context, boxID string, boxAbsPath string, source io.Reader) (RuntimeRequestView, error)

UploadArchive uploads one tar archive into a box path.

func (*Client) WhoAmI

WhoAmI loads the current authenticated user and organization identity.

func (*Client) WithProject

func (c *Client) WithProject(projectCID string) *Client

WithProject returns a shallow client clone pinned to one project CID.

Example
package main

import (
	"context"

	run9 "github.com/sys9-ai/run9-sdk-go"
)

func main() {
	client, err := run9.NewClient("https://api.run.sys9.ai", run9.Credentials{
		AK: "ak-...",
		SK: "sk-...",
	})
	if err != nil {
		panic(err)
	}

	project := client.WithProject("sandbox")
	_, _ = project.ListBoxes(context.Background(), run9.ListBoxesRequest{})
}

func (*Client) WriteBackgroundExecStdin

func (c *Client) WriteBackgroundExecStdin(ctx context.Context, execID string, req WriteBackgroundExecStdinRequest) (*time.Time, error)

WriteBackgroundExecStdin writes stdin bytes into one background exec.

type CreateAPIKeyRequest

type CreateAPIKeyRequest struct {
	// Description is optional operator-facing API key text.
	Description string `json:"description,omitempty"`
	// ExpiresAt requests one explicit expiry time when non-nil.
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	// NoExpire requests a non-expiring API key.
	NoExpire bool `json:"no_expire"`
}

CreateAPIKeyRequest creates one API key for the current organization.

type CreateBoxFromSharedSnapRequest

type CreateBoxFromSharedSnapRequest struct {
	// Volumes creates independent empty Volumes, not inherited from the shared
	// snap. Rules match CreateBoxRequest.Volumes, including latest versions.
	Volumes []VolumeConfig `json:"volumes,omitempty"`
	// Version selects one published version. When nil, the latest version is used.
	Version *int `json:"version,omitempty"`
	// BoxID requests one specific box identifier. When empty, the control plane generates one.
	BoxID string `json:"box_id,omitempty"`
	// DesiredShape requests the compute shape for the box.
	DesiredShape string `json:"desired_shape,omitempty"`
	// NetworkMode requests the durable network mode for the box.
	NetworkMode BoxNetworkMode `json:"network_mode,omitempty"`
	// Description is optional free-form box text.
	Description string `json:"description,omitempty"`
	// Labels sets durable box labels.
	Labels map[string]string `json:"labels,omitempty"`
}

CreateBoxFromSharedSnapRequest creates a box from a published shared snap.

type CreateBoxRequest

type CreateBoxRequest struct {
	// Volumes creates up to nine independent empty Volumes. Omit to create none.
	// Mount paths must not overlap, including ancestor/descendant paths.
	Volumes []VolumeConfig `json:"volumes,omitempty"`
	// BoxID requests one specific box identifier. When empty, the control plane generates one.
	BoxID string `json:"box_id,omitempty"`
	// DesiredShape requests the compute shape for the box.
	DesiredShape string `json:"desired_shape,omitempty"`
	// NetworkMode requests the durable network mode for the box.
	NetworkMode BoxNetworkMode `json:"network_mode,omitempty"`
	// Description is optional free-form box text.
	Description string `json:"description,omitempty"`
	// Labels sets durable box labels.
	Labels map[string]string `json:"labels,omitempty"`
	// SourceSnapID creates the box from one existing snap when non-empty.
	SourceSnapID string `json:"source_snap_id,omitempty"`
	// SourceImageRef imports directly from one image reference when non-empty.
	SourceImageRef string `json:"source_image_ref,omitempty"`
}

CreateBoxRequest creates a new box from an image or snap.

type CreateInvitationRequest

type CreateInvitationRequest struct {
	// InviteeEmail is the target email address.
	InviteeEmail string `json:"invitee_email"`
	// Role is the organization role to grant on acceptance.
	Role MembershipRole `json:"role"`
}

CreateInvitationRequest invites one user into an organization.

type CreateProjectRequest

type CreateProjectRequest struct {
	// DisplayName is the human-readable project name.
	DisplayName string `json:"display_name"`
	// Description is optional free-form project text.
	Description string `json:"description,omitempty"`
}

CreateProjectRequest creates a new project.

type CreateProjectSecretRequest

type CreateProjectSecretRequest struct {
	// Name is an optional human-readable secret name.
	Name string `json:"name,omitempty"`
	// Value is the raw secret value to store.
	Value string `json:"value"`
	// Placeholder is the literal marker that managed egress will replace.
	Placeholder string `json:"placeholder"`
	// AllowedHosts lists the destination hosts where placeholder substitution is allowed.
	AllowedHosts []string `json:"allowed_hosts"`
	// InjectHeaderName selects which HTTP header names are eligible for substitution.
	InjectHeaderName string `json:"inject_header_name"`
}

CreateProjectSecretRequest creates a new project or box secret.

type CreateSSHKeyRequest

type CreateSSHKeyRequest struct {
	// Label is the human-readable SSH key label.
	Label string `json:"label"`
	// PublicKey is the authorized_keys-formatted SSH public key.
	PublicKey string `json:"public_key"`
}

CreateSSHKeyRequest creates one account SSH key.

type CreateSnapFromSharedSnapRequest

type CreateSnapFromSharedSnapRequest struct {
	// Version selects one published version. When nil, the latest version is used.
	Version *int `json:"version,omitempty"`
}

CreateSnapFromSharedSnapRequest creates a new snap from a shared snap version.

type CreatedAPIKeyView

type CreatedAPIKeyView struct {
	APIKeyID          string    `json:"api_key_id"`
	OrgID             string    `json:"org_id"`
	UserID            string    `json:"user_id"`
	OwnerPrimaryEmail string    `json:"owner_primary_email"`
	OwnerDisplayName  string    `json:"owner_display_name,omitempty"`
	Description       string    `json:"description,omitempty"`
	AK                string    `json:"ak"`
	SK                string    `json:"sk"`
	DisplayPrefix     string    `json:"display_prefix"`
	DisplaySuffix     string    `json:"display_suffix"`
	CreatedAt         time.Time `json:"created_at"`
	ExpiresAt         time.Time `json:"expires_at,omitempty"`
	NoExpire          bool      `json:"no_expire"`
}

CreatedAPIKeyView describes a newly created API key, including its secret key.

type Credentials

type Credentials struct {
	// AK is the access-key identifier.
	AK string
	// SK is the secret-key value paired with AK.
	SK string
}

Credentials are the org-scoped API key credentials used by run9 clients.

type CurrentOrgIdentityView

type CurrentOrgIdentityView struct {
	User     MeView  `json:"user"`
	Org      OrgView `json:"org"`
	AuthKind string  `json:"auth_kind"`
}

CurrentOrgIdentityView describes the current authenticated user and org.

type CurrentSubscriptionView

type CurrentSubscriptionView struct {
	Tier      string    `json:"tier"`
	StartDate time.Time `json:"start_date,omitempty"`
	EndDate   time.Time `json:"end_date,omitempty"`
}

CurrentSubscriptionView describes the caller's current subscription snapshot.

type DeleteInvitationResult

type DeleteInvitationResult struct {
	InvitationID string `json:"invitation_id"`
	Status       string `json:"status"`
}

DeleteInvitationResult describes the accepted result of revoking an invitation.

type DeleteOrgResult

type DeleteOrgResult struct {
	OrgID  string `json:"org_id"`
	Status string `json:"status"`
}

DeleteOrgResult describes the accepted result of deleting an organization.

type DeleteProjectResult

type DeleteProjectResult struct {
	ProjectID string `json:"project_id"`
	Status    string `json:"status"`
}

DeleteProjectResult describes the accepted result of deleting a project.

type Error

type Error struct {
	// StatusCode is the HTTP status returned by the control plane.
	StatusCode int
	// Message is the structured control-plane error message when one is available.
	Message string
}

Error represents one run9 control-plane request failure.

func (*Error) Error

func (e *Error) Error() string

Error returns the control-plane message when present.

type ExecAttachInput

type ExecAttachInput struct {
	// Type identifies the input frame kind. Supported values are stdin, close_stdin, and resize.
	Type string `json:"type"`
	// Data carries stdin bytes when Type is stdin.
	Data []byte `json:"data,omitempty"`
	// Rows carries the new terminal height when Type is resize.
	Rows uint32 `json:"rows,omitempty"`
	// Cols carries the new terminal width when Type is resize.
	Cols uint32 `json:"cols,omitempty"`
}

ExecAttachInput describes one input message sent over exec attach.

type ExecAttachSocket

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

ExecAttachSocket wraps one exec attach websocket connection.

func (*ExecAttachSocket) Close

func (s *ExecAttachSocket) Close() error

Close closes the underlying websocket connection.

func (*ExecAttachSocket) CloseStdin added in v0.2.0

func (s *ExecAttachSocket) CloseStdin() error

CloseStdin closes remote stdin for the attached exec session.

func (*ExecAttachSocket) Pump added in v0.2.0

Pump writes stdout and stderr events to the given writers until the attached stream reaches a terminal event or ctx ends.

func (*ExecAttachSocket) ReadEvent

func (s *ExecAttachSocket) ReadEvent() (ExecStreamEvent, error)

ReadEvent reads the next exec stream event from the websocket.

func (*ExecAttachSocket) ResizeTTY added in v0.2.0

func (s *ExecAttachSocket) ResizeTTY(rows uint32, cols uint32) error

ResizeTTY sends one terminal resize event for the attached exec session.

func (*ExecAttachSocket) WriteInput

func (s *ExecAttachSocket) WriteInput(input ExecAttachInput) error

WriteInput writes one exec attach input frame to the websocket.

func (*ExecAttachSocket) WriteStdin added in v0.2.0

func (s *ExecAttachSocket) WriteStdin(data []byte) error

WriteStdin writes one stdin chunk into the attached exec session.

type ExecCapture added in v0.3.0

type ExecCapture struct {
	// ExecID is the durable foreground exec identifier.
	ExecID string
	// Terminal is the normalized terminal outcome.
	Terminal ExecTerminalResult
	// Transcript is the final merged transcript when log-download is available.
	Transcript []byte
	// TranscriptUnavailableReason explains why Transcript could not be loaded after the exec reached a terminal state.
	TranscriptUnavailableReason string
}

ExecCapture describes one foreground exec after the SDK has observed a terminal result.

Transcript is the final merged log-download snapshot when it is available. It follows the control-plane log-download contract, so stdout and stderr are already merged and the body may include omission or truncation markers for bounded retention.

type ExecOutputWriters added in v0.2.0

type ExecOutputWriters struct {
	Stdout io.Writer
	Stderr io.Writer
}

ExecOutputWriters selects where exec stdout, stderr, and output notices are written.

Nil writers are treated as io.Discard.

type ExecRequest

type ExecRequest struct {
	// IdempotencyKey identifies one logical background exec creation. Reusing the key
	// with the same request returns the existing exec; reusing it with a different
	// request fails. StartBackgroundExec generates a key when this field is empty.
	IdempotencyKey string `json:"-"`
	// DeadlineAt requests a hard deadline. When nil, the target exec API applies its default.
	DeadlineAt *time.Time `json:"deadline_at,omitempty"`
	// Command is the argv array executed in the target box.
	Command []string `json:"command"`
	// EnvOverrides replaces or adds environment variables for this exec.
	EnvOverrides map[string]string `json:"env_overrides,omitempty"`
	// User selects the target user account inside the box when non-empty.
	User string `json:"user,omitempty"`
	// Workdir selects the target working directory when non-empty.
	Workdir string `json:"workdir,omitempty"`
	// StdinEnabled keeps stdin available for this exec when true.
	StdinEnabled bool `json:"stdin_enabled,omitempty"`
	// TTY requests one PTY-backed exec session.
	TTY bool `json:"tty,omitempty"`
	// TTYSize provides the initial PTY size when TTY is true.
	TTYSize *TTYSize `json:"tty_size,omitempty"`
}

ExecRequest starts one foreground or background exec in a box.

type ExecStream

type ExecStream struct {
	// ExecID is the durable exec identifier assigned by the control plane.
	ExecID string
	// contains filtered or unexported fields
}

ExecStream reads one foreground exec event stream.

func (*ExecStream) Close

func (s *ExecStream) Close() error

Close closes the underlying stream body.

func (*ExecStream) Pump added in v0.2.0

Pump writes stdout and stderr events to the given writers until the stream reaches a terminal event or ctx ends.

func (*ExecStream) ReadEvent

func (s *ExecStream) ReadEvent() (ExecStreamEvent, error)

ReadEvent reads the next foreground exec event.

type ExecStreamEvent

type ExecStreamEvent struct {
	// Type identifies the event kind. Common values include started, keepalive, stdout,
	// stderr, finalizing, exit, error, and cancelled.
	Type string `json:"type"`
	// ExecID carries the durable exec identifier on events that include it.
	ExecID string `json:"exec_id,omitempty"`
	// Data carries stdout or stderr bytes for stream output events.
	Data []byte `json:"data,omitempty"`
	// ExitCode is set on terminal exit events.
	ExitCode int32 `json:"exit_code,omitempty"`
	// FailureReason is set when the stream terminates with an error event.
	FailureReason string `json:"failure_reason,omitempty"`
	// CancelReason is set when the stream terminates with a cancelled event.
	CancelReason string `json:"cancel_reason,omitempty"`
	// CacheAccess reports JuiceFS cache and object-store deltas for this exec.
	CacheAccess *CacheAccessStats `json:"cache_access,omitempty"`
	// PrewarmProfileID identifies the profile selected for this exec.
	PrewarmProfileID string `json:"prewarm_profile_id,omitempty"`
	// PrewarmProfileName is the user-visible profile name selected for this exec.
	PrewarmProfileName string `json:"prewarm_profile_name,omitempty"`
	// PrewarmRecording describes the immutable artifact produced by a recording exec.
	PrewarmRecording *PrewarmRecordingResult `json:"prewarm_recording,omitempty"`
}

ExecStreamEvent describes one event emitted by exec streaming APIs.

type ExecTerminalResult added in v0.2.0

type ExecTerminalResult struct {
	// Status identifies whether the exec exited, was cancelled, or failed.
	Status ExecTerminalStatus
	// ExitCode is set when the terminal outcome includes a process exit code.
	ExitCode *int
	// Reason carries the terminal cancellation or failure reason when one is available.
	Reason string
	// CacheAccess reports JuiceFS cache and object-store deltas when the runtime exposes them.
	CacheAccess *CacheAccessStats
	// PrewarmProfileID identifies the profile selected for this exec.
	PrewarmProfileID string
	// PrewarmProfileName is the profile name selected for this exec.
	PrewarmProfileName string
	// PrewarmRecording describes the artifact finalized by a recording exec.
	PrewarmRecording *PrewarmRecordingResult
}

ExecTerminalResult describes the terminal outcome of one foreground, attached, or background exec stream.

type ExecTerminalStatus added in v0.2.0

type ExecTerminalStatus string

ExecTerminalStatus identifies how one exec stream reached a terminal state.

const (
	// ExecTerminalStatusExited reports a normal process exit with an exit code.
	ExecTerminalStatusExited ExecTerminalStatus = "exited"
	// ExecTerminalStatusCancelled reports a terminal cancellation.
	ExecTerminalStatusCancelled ExecTerminalStatus = "cancelled"
	// ExecTerminalStatusError reports a terminal runtime or control-plane failure.
	ExecTerminalStatusError ExecTerminalStatus = "error"
)

type ExecView

type ExecView struct {
	ExecID         string         `json:"exec_id"`
	BoxID          string         `json:"box_id"`
	OrgID          string         `json:"org_id"`
	ProjectID      string         `json:"project_id"`
	Creator        string         `json:"creator"`
	AcceptedAt     time.Time      `json:"accepted_at"`
	Source         string         `json:"source"`
	CommandSummary string         `json:"command_summary"`
	ShapeSnapshot  string         `json:"shape_snapshot"`
	Mode           string         `json:"mode,omitempty"`
	State          string         `json:"state"`
	ExitCode       *int           `json:"exit_code,omitempty"`
	OutputSummary  string         `json:"output_summary,omitempty"`
	Reason         string         `json:"reason,omitempty"`
	HardDeadlineAt *time.Time     `json:"hard_deadline_at,omitempty"`
	IdleDeadlineAt *time.Time     `json:"idle_deadline_at,omitempty"`
	StdinEnabled   bool           `json:"stdin_enabled,omitempty"`
	AttachURL      string         `json:"attach_url,omitempty"`
	Diagnostics    map[string]any `json:"diagnostics,omitempty"`
}

ExecView describes one exec request and its current state.

func (ExecView) TerminalResult added in v0.3.0

func (v ExecView) TerminalResult() *ExecTerminalResult

TerminalResult returns the normalized terminal outcome when this exec view is terminal.

type FileEntry added in v0.5.0

type FileEntry struct {
	Name    string    `json:"name"`
	Type    FileType  `json:"type"`
	Size    int64     `json:"size"`
	ModTime time.Time `json:"mod_time"`
	ETag    string    `json:"etag,omitempty"`
}

FileEntry describes one child returned by FileSystem.ReadDir.

type FileGlobMatch added in v0.9.0

type FileGlobMatch struct {
	Path string `json:"path"`
}

FileGlobMatch identifies one regular file relative to the requested directory.

type FileInfo added in v0.5.0

type FileInfo struct {
	Path        string    `json:"path"`
	Type        FileType  `json:"type"`
	Size        int64     `json:"size"`
	ModTime     time.Time `json:"mod_time,omitempty"`
	ETag        string    `json:"etag,omitempty"`
	ContentType string    `json:"content_type,omitempty"`
}

FileInfo describes one path returned by FileSystem.Stat.

type FileReader added in v0.5.0

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

FileReader streams one file response and exposes its metadata.

func (*FileReader) Close added in v0.5.0

func (reader *FileReader) Close() error

Close releases the underlying HTTP response body.

func (*FileReader) Info added in v0.5.0

func (reader *FileReader) Info() FileInfo

Info returns metadata from the file response headers.

func (*FileReader) Read added in v0.5.0

func (reader *FileReader) Read(data []byte) (int, error)

Read reads file content from the gateway response.

type FileSystem added in v0.5.0

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

FileSystem is a reusable read-only Box or Snap filesystem capability. It reuses the parent Client's HTTP transport and does not contact the control plane again after resolution.

func (*FileSystem) GlobFiles added in v0.9.0

func (fileSystem *FileSystem) GlobFiles(ctx context.Context, directoryPath string, request GlobFilesRequest) (GlobFilesResult, error)

GlobFiles matches regular files in one server-side operation. Pattern uses doublestar glob syntax and is relative to directoryPath. Results are case-sensitive. Results are lexical unless RankingQuery requests relevance ordering. Symlinks are not returned or followed. Truncated reports additional matches or a scan stopped by safety bounds.

func (*FileSystem) Open added in v0.5.0

func (fileSystem *FileSystem) Open(ctx context.Context, filePath string, options OpenFileOptions) (*FileReader, error)

Open starts a streamed read of one regular file.

func (*FileSystem) ReadDir added in v0.5.0

func (fileSystem *FileSystem) ReadDir(ctx context.Context, directoryPath string, request ReadDirRequest) (ReadDirPage, error)

ReadDir loads one bounded, name-ordered directory page.

func (*FileSystem) RootedAt added in v0.7.0

func (fileSystem *FileSystem) RootedAt(root string) (*FileSystem, error)

RootedAt returns a filesystem whose "/" is rooted at root inside the Box or Snap. The gateway also resolves symlinks inside that root.

func (*FileSystem) Stat added in v0.5.0

func (fileSystem *FileSystem) Stat(ctx context.Context, filePath string) (FileInfo, error)

Stat loads metadata for one file or directory without reading its content.

type FileType added in v0.5.0

type FileType string

FileType identifies the kind of one filesystem entry.

const (
	// FileTypeFile identifies a regular file.
	FileTypeFile FileType = "file"
	// FileTypeDirectory identifies a directory.
	FileTypeDirectory FileType = "directory"
	// FileTypeSymlink identifies a symbolic link in a directory listing.
	FileTypeSymlink FileType = "symlink"
)

type GlobFilesRequest added in v0.9.0

type GlobFilesRequest struct {
	// Pattern is a case-sensitive doublestar glob relative to the requested directory.
	Pattern string
	// Limit is the maximum number of matches. Zero uses the gateway default.
	Limit int
	// ExcludeDirectories skips directories with these exact names at any depth.
	ExcludeDirectories []string
	// RankingQuery requests VS Code File Quick Open-style relevance ordering
	// before Limit is applied. Empty keeps lexical ordering.
	RankingQuery string
	// RespectGitIgnore applies hierarchical .gitignore files rooted at the
	// requested directory before matching, ranking, and limiting results.
	RespectGitIgnore bool
}

GlobFilesRequest controls one bounded recursive file glob.

type GlobFilesResult added in v0.9.0

type GlobFilesResult struct {
	Matches   []FileGlobMatch `json:"matches"`
	Truncated bool            `json:"truncated"`
}

GlobFilesResult contains ordered matches from one bounded filesystem view.

type HostIssue

type HostIssue struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

HostIssue describes one issue reported for a runtime host.

type HostView

type HostView struct {
	HostID string `json:"host_id"`

	HostClass      string `json:"host_class,omitempty"`
	LifecycleState string `json:"lifecycle_state,omitempty"`
	InstanceID     string `json:"instance_id,omitempty"`
	OwnerOrgID     string `json:"owner_org_id,omitempty"`

	MachineID                 string `json:"machine_id,omitempty"`
	BootID                    string `json:"boot_id,omitempty"`
	Hostname                  string `json:"hostname,omitempty"`
	VmaVersion                string `json:"vma_version,omitempty"`
	ChVersion                 string `json:"ch_version,omitempty"`
	RtVersion                 string `json:"rt_version,omitempty"`
	ForegroundRelayConfigured bool   `json:"foreground_relay_configured,omitempty"`

	Connected       bool      `json:"connected"`
	Ready           bool      `json:"ready"`
	LastHeartbeatAt time.Time `json:"last_heartbeat_at,omitempty"`

	ActiveBoxes                                uint32 `json:"active_boxes"`
	ActiveExecs                                uint32 `json:"active_execs"`
	ActiveTransfers                            uint32 `json:"active_transfers"`
	ActiveBackgroundOwnerExecs                 uint32 `json:"active_background_owner_execs"`
	VMAServiceRestartPreservesBackgroundOwners bool   `json:"vma_service_restart_preserves_background_owners"`

	PlanningReservedCPUMillis   uint32 `json:"planning_reserved_cpu_millis"`
	PlanningReservedMemoryBytes uint64 `json:"planning_reserved_memory_bytes"`

	CPUTotalCores              float64 `json:"cpu_total_cores"`
	MemoryTotalBytes           uint64  `json:"memory_total_bytes"`
	CPUUsedCores               float64 `json:"cpu_used_cores"`
	MemoryUsedBytes            uint64  `json:"memory_used_bytes"`
	RuntimeReservedCPUMillis   uint32  `json:"runtime_reserved_cpu_millis"`
	RuntimeReservedMemoryBytes uint64  `json:"runtime_reserved_memory_bytes"`

	LastIssueSummary string      `json:"last_issue_summary,omitempty"`
	Issues           []HostIssue `json:"issues,omitempty"`
}

HostView describes one runtime host assigned to an organization.

type ImportSnapRequest

type ImportSnapRequest struct {
	// ImageRef is the OCI-style image reference to import.
	ImageRef string `json:"image_ref"`
}

ImportSnapRequest imports a snap from an image reference.

type InvitationState

type InvitationState string

InvitationState represents one invitation lifecycle state.

type InvitationView

type InvitationView struct {
	InvitationID string          `json:"invitation_id"`
	OrgID        string          `json:"org_id"`
	InviteeEmail string          `json:"invitee_email"`
	Role         MembershipRole  `json:"role"`
	InvitedBy    string          `json:"invited_by"`
	State        InvitationState `json:"state"`
	ExpiresAt    time.Time       `json:"expires_at"`
	AcceptedBy   string          `json:"accepted_by,omitempty"`
	CreatedAt    time.Time       `json:"created_at"`
	UpdatedAt    time.Time       `json:"updated_at"`
}

InvitationView describes one organization invitation.

type ListBoxesRequest

type ListBoxesRequest struct {
	// Creator filters by the creator identifier.
	Creator string
	// Label filters by one label selector supported by the control plane.
	Label string
	// State filters by the current box state.
	State BoxState
}

ListBoxesRequest describes optional filters for ListBoxes.

type ListExecsRequest

type ListExecsRequest struct {
	BoxID          string
	State          string
	Creator        string
	AcceptedAfter  *time.Time
	AcceptedBefore *time.Time
	Order          string
	Paged          bool
	Limit          *int
	Cursor         string
}

ListExecsRequest describes optional filters for ListExecs.

type ListExecsResult

type ListExecsResult struct {
	Execs      []ExecView `json:"items"`
	NextCursor string     `json:"next_cursor"`
}

ListExecsResult describes the response returned by ListExecs.

type ListSnapsRequest

type ListSnapsRequest struct {
	// Attached selects attached Snaps (true) or detached Snaps (false).
	// Nil defaults to detached Snaps. Attached includes the original Attached
	// Snap and every Volume, with their owning Box and mount paths.
	Attached *bool
}

ListSnapsRequest describes optional filters for ListSnaps.

type MeView

type MeView struct {
	UserID          string    `json:"user_id"`
	PrimaryEmail    string    `json:"primary_email"`
	DisplayName     string    `json:"display_name,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	IsSystemManager bool      `json:"is_system_manager"`
}

MeView describes one user account.

type MembershipRole

type MembershipRole string

MembershipRole represents one organization membership role.

type MembershipView

type MembershipView struct {
	OrgID        string         `json:"org_id"`
	UserID       string         `json:"user_id"`
	PrimaryEmail string         `json:"primary_email"`
	DisplayName  string         `json:"display_name,omitempty"`
	Role         MembershipRole `json:"role"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	LastLoginAt  time.Time      `json:"last_login_at,omitempty"`
}

MembershipView describes one organization member.

type OpenFileOptions added in v0.5.0

type OpenFileOptions struct {
	// Range is an optional HTTP byte range, for example "bytes=0-1023".
	// Single and multipart ranges supported by the gateway are accepted.
	Range string
}

OpenFileOptions controls one streamed file read.

type OrgHostsView

type OrgHostsView struct {
	OrgID         string     `json:"org_id"`
	AssignedHosts int        `json:"assigned_hosts"`
	Hosts         []HostView `json:"hosts"`
}

OrgHostsView describes runtime host assignment for one organization.

type OrgKind

type OrgKind string

OrgKind represents one organization kind.

const (
	// OrgKindPersonal identifies one personal organization.
	OrgKindPersonal OrgKind = "personal"
	// OrgKindShared identifies one shared organization.
	OrgKindShared OrgKind = "shared"
)

Organization kinds returned by the control plane.

type OrgView

type OrgView struct {
	OrgID               string                  `json:"org_id"`
	OrgCID              string                  `json:"org_cid"`
	DisplayName         string                  `json:"display_name"`
	Kind                OrgKind                 `json:"kind"`
	Role                MembershipRole          `json:"role"`
	CreatedBy           string                  `json:"created_by"`
	CreatedAt           time.Time               `json:"created_at"`
	CurrentSubscription CurrentSubscriptionView `json:"current_subscription"`
}

OrgView describes one organization visible to the caller.

type PrewarmProfileHostState added in v0.11.0

type PrewarmProfileHostState string

PrewarmProfileHostState describes installation of one artifact generation on a host.

const (
	// PrewarmProfileHostStatePending means the current artifact is not installed yet.
	PrewarmProfileHostStatePending PrewarmProfileHostState = "pending"
	// PrewarmProfileHostStateReady means the current artifact is installed and usable.
	PrewarmProfileHostStateReady PrewarmProfileHostState = "ready"
	// PrewarmProfileHostStateError means the latest installation attempt failed.
	PrewarmProfileHostStateError PrewarmProfileHostState = "error"
)

type PrewarmProfileHostView added in v0.11.0

type PrewarmProfileHostView struct {
	HostID      string                  `json:"host_id"`
	State       PrewarmProfileHostState `json:"state"`
	LastError   string                  `json:"last_error,omitempty"`
	InstalledAt *time.Time              `json:"installed_at,omitempty"`
}

PrewarmProfileHostView describes installation of a profile artifact on one target host.

type PrewarmProfileState added in v0.11.0

type PrewarmProfileState string

PrewarmProfileState identifies the recorded artifact lifecycle.

const (
	// PrewarmProfileStateRecording means the standard workload is still running.
	PrewarmProfileStateRecording PrewarmProfileState = "recording"
	// PrewarmProfileStateFinalizing means block collection and upload continue after workload cancellation.
	PrewarmProfileStateFinalizing PrewarmProfileState = "finalizing"
	// PrewarmProfileStateReady means the immutable artifact can be selected by new execs.
	PrewarmProfileStateReady PrewarmProfileState = "ready"
	// PrewarmProfileStateError means artifact finalization failed.
	PrewarmProfileStateError PrewarmProfileState = "error"
)

type PrewarmProfileView added in v0.11.0

type PrewarmProfileView struct {
	ProfileID           string                   `json:"profile_id"`
	Name                string                   `json:"name"`
	OrgID               string                   `json:"org_id"`
	ProjectID           string                   `json:"project_id"`
	BaseSnapID          string                   `json:"base_snap_id"`
	State               PrewarmProfileState      `json:"state"`
	Enabled             bool                     `json:"enabled"`
	Workload            []string                 `json:"workload"`
	MaxRuntimeSeconds   uint64                   `json:"max_runtime_seconds"`
	RecordingStopReason string                   `json:"recording_stop_reason,omitempty"`
	ArtifactGeneration  string                   `json:"artifact_generation,omitempty"`
	ArtifactSHA256      string                   `json:"artifact_sha256,omitempty"`
	ArtifactBlocks      uint64                   `json:"artifact_blocks"`
	ArtifactBytes       uint64                   `json:"artifact_bytes"`
	RecordingExecID     string                   `json:"recording_exec_id,omitempty"`
	UseCount            uint64                   `json:"use_count"`
	LastUsedAt          *time.Time               `json:"last_used_at,omitempty"`
	LastError           string                   `json:"last_error,omitempty"`
	ReadyHosts          int                      `json:"ready_hosts"`
	TargetHosts         int                      `json:"target_hosts"`
	Hosts               []PrewarmProfileHostView `json:"hosts,omitempty"`
	CreatedAt           time.Time                `json:"created_at"`
	UpdatedAt           time.Time                `json:"updated_at"`
}

PrewarmProfileView describes one exact-base recorded prewarm profile.

type PrewarmRecordingResult added in v0.11.0

type PrewarmRecordingResult struct {
	ProfileID  string `json:"profile_id"`
	Generation string `json:"generation"`
	SHA256     string `json:"sha256"`
	VolumeUUID string `json:"volume_uuid"`
	Blocks     uint64 `json:"blocks"`
	Bytes      uint64 `json:"bytes"`
	Error      string `json:"error,omitempty"`
}

PrewarmRecordingResult describes the recorded artifact finalized after a workload exits or is cancelled.

type PrewarmRecordingStream added in v0.11.0

type PrewarmRecordingStream struct {
	ProfileID string
	ExecID    string
	Stream    *ExecStream
}

PrewarmRecordingStream identifies the new profile and exposes its live workload stream.

type ProjectMembershipView

type ProjectMembershipView struct {
	ProjectID    string      `json:"project_id"`
	UserID       string      `json:"user_id"`
	PrimaryEmail string      `json:"primary_email"`
	DisplayName  string      `json:"display_name,omitempty"`
	Role         ProjectRole `json:"role"`
	CreatedAt    time.Time   `json:"created_at"`
	UpdatedAt    time.Time   `json:"updated_at"`
}

ProjectMembershipView describes one project member.

type ProjectRole

type ProjectRole string

ProjectRole represents one project membership role.

type ProjectSecretScope

type ProjectSecretScope string

ProjectSecretScope represents where a secret is attached.

const (
	// ProjectSecretScopeProject attaches one secret to project scope.
	ProjectSecretScopeProject ProjectSecretScope = "project"
	// ProjectSecretScopeBox attaches one secret to one box.
	ProjectSecretScopeBox ProjectSecretScope = "box"
)

Secret scopes accepted by project and box secret APIs.

type ProjectSecretView

type ProjectSecretView struct {
	SecretID         string             `json:"secret_id"`
	OrgID            string             `json:"org_id"`
	ProjectID        string             `json:"project_id"`
	Scope            ProjectSecretScope `json:"scope"`
	BoxID            string             `json:"box_id,omitempty"`
	Name             string             `json:"name,omitempty"`
	Placeholder      string             `json:"placeholder"`
	AllowedHosts     []string           `json:"allowed_hosts"`
	InjectHeaderName string             `json:"inject_header_name"`
	CreatedBy        string             `json:"created_by"`
	UpdatedBy        string             `json:"updated_by"`
	CreatedAt        time.Time          `json:"created_at"`
	UpdatedAt        time.Time          `json:"updated_at"`
}

ProjectSecretView describes one secret attached to project or box scope.

type ProjectView

type ProjectView struct {
	ProjectID   string      `json:"project_id"`
	OrgID       string      `json:"org_id"`
	ProjectCID  string      `json:"project_cid"`
	DisplayName string      `json:"display_name"`
	Description string      `json:"description,omitempty"`
	Role        ProjectRole `json:"role"`
	CreatedBy   string      `json:"created_by"`
	CreatedAt   time.Time   `json:"created_at"`
	UpdatedAt   time.Time   `json:"updated_at"`
}

ProjectView describes one project visible to the caller.

type PublishSharedSnapRequest

type PublishSharedSnapRequest struct {
	// Name is the shared snap catalog name.
	Name string `json:"name"`
	// Description is optional catalog text for this publication.
	Description string `json:"description,omitempty"`
	// SourceSnapID identifies the project-local snap to publish.
	SourceSnapID string `json:"source_snap_id"`
}

PublishSharedSnapRequest publishes one snap into the shared snap catalog.

type PullBackgroundExecOutputRequest

type PullBackgroundExecOutputRequest struct {
	// Cursor resumes from one previously returned cursor. Leave empty to read from the beginning once.
	Cursor string
	// Wait asks the service to short-poll before returning when the cursor is currently at the live tail.
	Wait time.Duration
}

PullBackgroundExecOutputRequest describes one pull-output request.

type ReadDirPage added in v0.5.0

type ReadDirPage struct {
	Entries []FileEntry `json:"entries"`
	Cursor  string      `json:"cursor,omitempty"`
}

ReadDirPage is one name-ordered directory page.

type ReadDirRequest added in v0.5.0

type ReadDirRequest struct {
	// Limit is the maximum number of entries. Zero uses the gateway default.
	Limit int
	// Cursor continues a previous page for the same directory and filesystem view.
	Cursor string
}

ReadDirRequest controls one bounded directory page.

type RecordPrewarmProfileRequest added in v0.11.0

type RecordPrewarmProfileRequest struct {
	Name       string   `json:"name"`
	BaseSnapID string   `json:"base_snap_id"`
	Command    []string `json:"command"`
	// MaxRuntime limits only the recorded workload. Zero uses the service default of one minute.
	MaxRuntime time.Duration `json:"-"`
}

RecordPrewarmProfileRequest starts one standard workload recording for an exact base snap.

type RuntimeRequestView

type RuntimeRequestView struct {
	RuntimeRequestID string `json:"runtime_request_id"`
	State            string `json:"state"`
	SessionID        string `json:"session_id,omitempty"`
	HostID           string `json:"host_id,omitempty"`
}

RuntimeRequestView describes one asynchronous runtime request.

type SSHKeyView

type SSHKeyView struct {
	SSHKeyID    string     `json:"ssh_key_id"`
	Label       string     `json:"label"`
	Fingerprint string     `json:"fingerprint"`
	CreatedAt   time.Time  `json:"created_at"`
	LastUsedAt  *time.Time `json:"last_used_at,omitempty"`
}

SSHKeyView describes one SSH key on the caller's account.

type SharedSnapDetailView

type SharedSnapDetailView struct {
	OrgID         string                  `json:"org_id"`
	Name          string                  `json:"name"`
	LatestVersion int                     `json:"latest_version"`
	Publisher     string                  `json:"publisher"`
	Versions      []SharedSnapVersionView `json:"versions"`
}

SharedSnapDetailView describes one shared snap and its version history.

type SharedSnapLineView

type SharedSnapLineView struct {
	OrgID                    string    `json:"org_id"`
	Name                     string    `json:"name"`
	LatestVersion            int       `json:"latest_version"`
	Publisher                string    `json:"publisher"`
	PublishedBy              string    `json:"published_by"`
	PublishedAt              time.Time `json:"published_at"`
	Description              string    `json:"description,omitempty"`
	SourceProjectID          string    `json:"source_project_id"`
	SourceProjectCID         string    `json:"source_project_cid"`
	SourceProjectDisplayName string    `json:"source_project_display_name"`
}

SharedSnapLineView describes one shared snap in list results.

type SharedSnapVersionView

type SharedSnapVersionView struct {
	OrgID                    string    `json:"org_id"`
	Name                     string    `json:"name"`
	Version                  int       `json:"version"`
	Description              string    `json:"description,omitempty"`
	PublishedBy              string    `json:"published_by"`
	PublishedAt              time.Time `json:"published_at"`
	SourceProjectID          string    `json:"source_project_id"`
	SourceProjectCID         string    `json:"source_project_cid"`
	SourceProjectDisplayName string    `json:"source_project_display_name"`
}

SharedSnapVersionView describes one published shared snap version.

type SnapOwnedStorage

type SnapOwnedStorage struct {
	Bytes      uint64    `json:"bytes"`
	Objects    uint64    `json:"objects"`
	MeasuredAt time.Time `json:"measured_at"`
}

SnapOwnedStorage is the cached first-owner object storage attribution for one snap.

type SnapSize

type SnapSize struct {
	UsedBytes  uint64    `json:"used_bytes"`
	UsedInodes uint64    `json:"used_inodes"`
	MeasuredAt time.Time `json:"measured_at"`
}

SnapSize is the cached filesystem usage measured for one snap.

type SnapState

type SnapState string

SnapState represents the current snap state.

type SnapTreeAttachedBoxView

type SnapTreeAttachedBoxView struct {
	BoxID string `json:"box_id"`
	// MountPath identifies this Snap's mount in the Box, including "/" for root.
	MountPath    string   `json:"mount_path"`
	DesiredShape string   `json:"desired_shape"`
	State        BoxState `json:"state"`
}

SnapTreeAttachedBoxView describes the box attached to one snap tree node.

type SnapTreeNodeView

type SnapTreeNodeView struct {
	SnapID              string                   `json:"snap_id"`
	ParentSnapID        string                   `json:"parent_snap_id,omitempty"`
	Creator             string                   `json:"creator"`
	CreatorDisplayName  string                   `json:"creator_display_name,omitempty"`
	CreatorPrimaryEmail string                   `json:"creator_primary_email,omitempty"`
	CreatedAt           time.Time                `json:"created_at"`
	State               SnapState                `json:"state"`
	Reason              string                   `json:"reason,omitempty"`
	SourceImageRef      string                   `json:"source_image_ref,omitempty"`
	SourceImageDigest   string                   `json:"source_image_digest,omitempty"`
	SourceImagePlatform string                   `json:"source_image_platform,omitempty"`
	AttachedBox         *SnapTreeAttachedBoxView `json:"attached_box,omitempty"`
}

SnapTreeNodeView describes one node inside a snap ancestry tree.

type SnapTreeView

type SnapTreeView struct {
	Supported  bool               `json:"supported"`
	RootSnapID string             `json:"root_snap_id,omitempty"`
	Nodes      []SnapTreeNodeView `json:"nodes,omitempty"`
}

SnapTreeView describes the ancestry tree returned for one snap.

type SnapView

type SnapView struct {
	SnapID              string    `json:"snap_id"`
	OrgID               string    `json:"org_id"`
	ProjectID           string    `json:"project_id"`
	Creator             string    `json:"creator"`
	CreatedAt           time.Time `json:"created_at"`
	LastUsedAt          time.Time `json:"last_used_at"`
	State               SnapState `json:"state"`
	InUseReason         string    `json:"inuse_reason,omitempty"`
	Reason              string    `json:"reason,omitempty"`
	ParentChain         []string  `json:"parent_chain,omitempty"`
	SourceImageRef      string    `json:"source_image_ref,omitempty"`
	SourceImageDigest   string    `json:"source_image_digest,omitempty"`
	SourceImagePlatform string    `json:"source_image_platform,omitempty"`
	Attached            bool      `json:"attached"`
	AttachedBoxID       string    `json:"attached_box_id,omitempty"`
	// MountPath is the fixed path in the owning Box; root is "/".
	// Detached Snaps omit it.
	MountPath     string            `json:"mount_path,omitempty"`
	FileAccessURL string            `json:"file_access_url,omitempty"`
	Size          *SnapSize         `json:"size,omitempty"`
	OwnedStorage  *SnapOwnedStorage `json:"owned_storage,omitempty"`
}

SnapView describes one snap. FileAccessURL reads a detached Snap's immutable filesystem or a Volume's own filesystem. The original root Attached Snap retains the owning Box's composed filesystem view.

type TTYSize

type TTYSize struct {
	// Rows is the terminal height in character cells.
	Rows uint32 `json:"rows,omitempty"`
	// Cols is the terminal width in character cells.
	Cols uint32 `json:"cols,omitempty"`
}

TTYSize describes terminal size in rows and columns.

type UpdateBoxRequest

type UpdateBoxRequest struct {
	// Description replaces the durable box description when non-nil.
	Description *string `json:"description,omitempty"`
	// Labels replaces the full durable label map when non-nil.
	Labels *map[string]string `json:"labels,omitempty"`
	// DesiredShape replaces the durable target shape when non-nil.
	DesiredShape *string `json:"desired_shape,omitempty"`
	// NetworkMode replaces the durable network mode when non-nil.
	NetworkMode *BoxNetworkMode `json:"network_mode,omitempty"`
}

UpdateBoxRequest updates mutable box fields.

type UpdateMeRequest

type UpdateMeRequest struct {
	// DisplayName replaces the current account display name when non-nil.
	DisplayName *string `json:"display_name,omitempty"`
}

UpdateMeRequest updates caller profile fields.

type UpdateMembershipRequest

type UpdateMembershipRequest struct {
	// Role is the desired organization role.
	Role MembershipRole `json:"role"`
}

UpdateMembershipRequest updates one organization membership.

type UpdateOrgRequest

type UpdateOrgRequest struct {
	// DisplayName replaces the current organization display name when non-nil.
	DisplayName *string `json:"display_name,omitempty"`
	// OrgCID replaces the durable organization CID when non-nil.
	OrgCID *string `json:"org_cid,omitempty"`
}

UpdateOrgRequest updates mutable organization fields.

type UpdateProjectMembershipRequest

type UpdateProjectMembershipRequest struct {
	// Role is the desired project role.
	Role ProjectRole `json:"role"`
}

UpdateProjectMembershipRequest updates one project membership.

type UpdateProjectRequest

type UpdateProjectRequest struct {
	// DisplayName replaces the current project display name when non-nil.
	DisplayName *string `json:"display_name,omitempty"`
	// Description replaces the current project description when non-nil.
	Description *string `json:"description,omitempty"`
}

UpdateProjectRequest updates mutable project fields.

type UpdateProjectSecretRequest

type UpdateProjectSecretRequest struct {
	// Name replaces the stored human-readable secret name when non-nil.
	Name *string `json:"name,omitempty"`
	// Value replaces the stored secret value when non-nil.
	Value *string `json:"value,omitempty"`
	// AllowedHosts replaces the full allowed-host set when non-nil.
	AllowedHosts *[]string `json:"allowed_hosts,omitempty"`
	// InjectHeaderName replaces the header selector when non-nil.
	InjectHeaderName *string `json:"inject_header_name,omitempty"`
}

UpdateProjectSecretRequest updates one existing project or box secret.

type VolumeConfig added in v0.16.0

type VolumeConfig struct {
	// MountPath is a fixed directory inside the Box.
	// Use a canonical absolute Linux path other than root, without a trailing
	// slash or dot components. The source directory must be absent or empty,
	// must not traverse symlinks, and must not overlap runtime-managed paths.
	// The mount is fixed at creation. Data survives Stop and runtime replacement,
	// is deleted with the Box, and is excluded from Root Snap forks along with
	// its mount configuration. The server validates the path and source contents.
	MountPath string `json:"mount_path"`
	// InitialPermissions applies only to the new volume's top directory.
	// Omit to keep default guest ownership and permissions. Later guest chmod
	// and chown persist; mounting or restarting never resets them.
	InitialPermissions *VolumeInitialPermissions `json:"initial_permissions,omitempty"`
}

VolumeConfig creates one independent, empty, Box-owned persistent Snap.

type VolumeInitialPermissions added in v0.18.0

type VolumeInitialPermissions struct {
	// UID is the guest owner, from 0 through 4294967294; zero means guest root.
	UID uint32 `json:"uid"`
	// GID is the guest group, from 0 through 4294967294; zero means guest root.
	GID uint32 `json:"gid"`
	// Mode is three or four octal digits, 0000 through 7777. Empty means 0755.
	Mode string `json:"mode,omitempty"`
}

VolumeInitialPermissions sets guest ownership and mode once at creation. It does not resolve image user names or recursively change existing files.

type VolumeView added in v0.16.0

type VolumeView struct {
	SnapID    string `json:"snap_id"`
	MountPath string `json:"mount_path"`
}

VolumeView describes a Box-owned writable Snap and its fixed mount. Stop preserves it; deleting the Box deletes it. ForkSnap saves an independent detached Snap while the Box is stopped and storage has settled.

type WriteBackgroundExecStdinRequest

type WriteBackgroundExecStdinRequest struct {
	// Data is the raw stdin chunk to send in this request.
	Data []byte
	// CloseStdin requests EOF immediately after Data is written.
	CloseStdin bool
}

WriteBackgroundExecStdinRequest describes one background exec stdin write.

Directories

Path Synopsis
cmd
internal
codegenpatch
Package codegenpatch provides external schema types injected into the generated swagger client to preserve PATCH request semantics.
Package codegenpatch provides external schema types injected into the generated swagger client to preserve PATCH request semantics.

Jump to

Keyboard shortcuts

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