workspace

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package workspace keeps a thread's /workspace history: a local Git repository with an automatic checkpoint before every AI turn, per-file history, diffs and restores, persisted across sandbox expiry (the .git directory is archived into the blob store after each run and restored into every new sandbox of the thread), plus the workspace status / explicit restore of the files panel.

Index

Constants

View Source
const (
	KindAutomatic = "automatic"
	KindAgent     = "agent"
)

Checkpoint kinds (the commit subject prefix, like Work).

View Source
const (
	AvailabilityReady    = "ready"
	AvailabilityStopped  = "stopped"
	AvailabilityMissing  = "missing"
	AvailabilityStarting = "starting"
)

Availability values of the workspace status (Work's vocabulary).

View Source
const DefaultArchiveMaxBytes = 50 << 20

DefaultArchiveMaxBytes is the default Options.ArchiveMaxBytes.

View Source
const GitPrompt = GitPromptHeading + `

This conversation's /workspace has a local private Git repository used only for organizing and reviewing workspace file changes. You may use local git commands such as status, diff, add, and commit to group meaningful file changes with clear commit messages when helpful. Do not push, fetch, pull, create remotes, or treat this as a user repository. Keep commits small and descriptive so the user can inspect or roll back file changes later.`

GitPrompt is the local Git prompt section.

View Source
const GitPromptHeading = "## Local Git Checkpoints"

GitPromptHeading heads the local Git section of the system prompt.

View Source
const LabelBeforeTurn = "Before AI turn"

LabelBeforeTurn is the checkpoint taken before every run that uses the sandbox.

View Source
const RestoreBlockedReason = "Workspace restore is unavailable while the conversation is still preparing or running."

RestoreBlockedReason is Work's message while a run is active.

Variables

View Source
var (
	ErrPathRequired = errors.New("Path is required.")
	ErrPathOutside  = errors.New("Path must stay within /workspace.")
	ErrPathGit      = errors.New("Path cannot target Git metadata.")
	ErrPathControl  = errors.New("Path cannot contain ASCII control characters.")
	ErrInvalidSHA   = errors.New("Invalid checkpoint id.")
	// Paths a file restore refuses (400 invalid_path), checked before any change.
	ErrRestoreDirectory = errors.New("Only files can be restored, not directories.")
	ErrRestoreIgnored   = errors.New("This path is excluded from the checkpoints and cannot be restored.")
	ErrRestoreUntracked = errors.New("This path is not part of the checkpoint or the workspace history.")
)

Validation errors (400 invalid_path / invalid_checkpoint), Work's messages.

View Source
var (
	// ErrNotReady means the thread has no live sandbox (409 workspace_not_ready).
	ErrNotReady = errors.New("Workspace is not ready.")
	// ErrUnknownCheckpoint means the sha is not a commit of the repository (404).
	ErrUnknownCheckpoint = errors.New("Unknown checkpoint.")
	// ErrNoRepository means /workspace has no checkpoint repository yet.
	ErrNoRepository = errors.New("No checkpoint repository.")
)

Errors of the checkpoint operations.

View Source
var ErrRestoreBlocked = errors.New(RestoreBlockedReason)

ErrRestoreBlocked means a run of the thread is active (409).

Functions

func AbsPath

func AbsPath(rel string) string

AbsPath is the sandbox path of a path relative to /workspace.

func NormalizePath

func NormalizePath(raw string) (string, error)

NormalizePath validates a file path of the workspace: absolute under /workspace or relative to it, no "..", not inside .git, no control characters. It returns the path relative to /workspace (the git pathspec).

func ValidSHA

func ValidSHA(raw string) (string, error)

ValidSHA validates a checkpoint id: 7 to 64 hexadecimal digits.

Types

type Checkpoint

type Checkpoint struct {
	SHA          string   `json:"sha"`
	ShortSHA     string   `json:"shortSha"`
	CreatedAt    string   `json:"createdAt"`
	Kind         string   `json:"kind"`
	Label        string   `json:"label"`
	ChangedFiles []string `json:"changedFiles"`
}

Checkpoint is one commit of the workspace history.

type CheckpointResult

type CheckpointResult struct {
	Created bool
	SHA     string
	// Reason is "no_changes", "no_git" (git missing in the image) or "disabled".
	Reason string
}

CheckpointResult is the outcome of a checkpoint.

type Diff

type Diff struct {
	Path      string `json:"path"`
	SHA       string `json:"sha"`
	Diff      string `json:"diff"`
	Truncated bool   `json:"truncated,omitempty"`
}

Diff is a file's diff between a checkpoint and the working tree.

type EndOfRunHook

type EndOfRunHook struct{ Svc *Service }

EndOfRunHook archives the thread's checkpoint history when a run ends (register it after artifacts.EndOfRunHook), in the background: the run's terminal status and event do not wait for the upload.

func (EndOfRunHook) Finishing

func (h EndOfRunHook) Finishing(ctx context.Context, f *runtime.Finish) func(context.Context)

Finishing implements runtime.Hook.

type GitError

type GitError struct{ Detail string }

GitError is a failed git script (502 workspace_git_failed).

func (*GitError) Error

func (e *GitError) Error() string

type HistoryIssue

type HistoryIssue struct {
	// Reason is too_large (over HARNESS_GIT_ARCHIVE_MAX_BYTES) or failed.
	Reason    string `json:"reason"`
	SizeBytes int64  `json:"sizeBytes,omitempty"`
	At        string `json:"at"`
}

HistoryIssue explains an unsaved checkpoint history.

type Locker

type Locker interface {
	AdvisoryLock(ctx context.Context, name string, wait time.Duration) (func(), error)
}

Locker is the cluster-wide lock of the store (store.ArtifactStore.AdvisoryLock).

type Options

type Options struct {
	// Disabled turns checkpoints off (HARNESS_WORKSPACE_CHECKPOINTS=false): no
	// repository, no archive; the endpoints answer from an absent history.
	Disabled bool
	// ArchiveMaxBytes caps the archived .git (tar.gz; default 50 MiB, also
	// bounded by the blob backend's cap). A larger history is not archived
	// (the previous archive is kept).
	ArchiveMaxBytes int64
	// MaxFileBytes keeps larger files out of the checkpoints (≤ 0: no limit;
	// HARNESS_WORKSPACE_CHECKPOINT_MAX_FILE_BYTES).
	MaxFileBytes int64
	// Timeout bounds one git script (default 30 s, like Work).
	Timeout time.Duration
	// LockWait bounds the wait for a thread's Git lock (default 1 min).
	LockWait time.Duration
}

Options configure the service.

type RestoreDiagnostic

type RestoreDiagnostic struct {
	Status  string `json:"status"`
	Reason  string `json:"reason"`
	Message string `json:"message"`
}

RestoreDiagnostic explains an explicit restore (Work's restore_diagnostic).

type RestoreOutcome

type RestoreOutcome struct {
	*Status
	Restored          bool              `json:"restored"`
	RestoreDiagnostic RestoreDiagnostic `json:"restoreDiagnostic"`
}

RestoreOutcome is the answer of POST …/workspace/restore.

type RestoreResult

type RestoreResult struct {
	Restored bool   `json:"restored"`
	Reason   string `json:"reason,omitempty"`
	Path     string `json:"path"`
	SHA      string `json:"sha"`
	// Deleted is set when the file did not exist at the checkpoint (removed).
	Deleted bool `json:"deleted,omitempty"`
	// Change is the artifact change recorded for the file (nil when none).
	Change *artifacts.Change `json:"-"`
}

RestoreResult is the outcome of a file restore.

type Service

type Service struct {
	Sandbox   sandbox.Manager
	Store     store.WorkspaceGitStore
	Locks     Locker
	Artifacts *artifacts.Service
	Opts      Options
	// contains filtered or unexported fields
}

Service implements the workspace checkpoints, their persistence and the workspace status / restore.

func New

New returns a service with defaults applied.

func (*Service) Archive

func (s *Service) Archive(ctx context.Context, threadID string, sb sandbox.Sandbox)

Archive stores /workspace/.git of sb (tar.gz) as the thread's archive when HEAD moved since the last one. Best effort: errors are logged.

func (*Service) ArchiveAsync

func (s *Service) ArchiveAsync(threadID string, sb sandbox.Sandbox)

ArchiveAsync archives the thread's history in the background (end of run: the run's completion never waits for the upload), serialized per thread — a request made while one runs is coalesced into one more archive afterwards (the cluster-wide git lock also serializes it with other processes).

func (*Service) BeforeRun

func (s *Service) BeforeRun(ctx context.Context, run *store.Run)

BeforeRun implements agent.RunStartHook: a run starting while the thread's sandbox is live checkpoints it first (never creates one; a sandbox created later in the run is checkpointed by OnAcquire).

func (*Service) BeforeTurn

func (s *Service) BeforeTurn(ctx context.Context, threadID, runID string, sb sandbox.Sandbox)

BeforeTurn takes the run's "Before AI turn" checkpoint in sb, once per run and sandbox (a sandbox recreated mid-run gets its own); concurrent callers wait for it. It never fails the run: errors are logged.

func (*Service) Checkpoint

func (s *Service) Checkpoint(ctx context.Context, threadID string, sb sandbox.Sandbox, label string) (CheckpointResult, error)

Checkpoint commits every change of /workspace as "automatic: <label>" (initializing the repository on first use).

func (*Service) Enabled

func (s *Service) Enabled() bool

Enabled reports whether checkpoints are on (a sandbox is configured).

func (*Service) FileDiff

func (s *Service) FileDiff(ctx context.Context, threadID, sha, p string) (*Diff, error)

FileDiff diffs the file p between the checkpoint sha and the working tree.

func (*Service) List

func (s *Service) List(ctx context.Context, threadID, p string) ([]Checkpoint, error)

List returns the checkpoints touching the file p (all when p is ""), newest first.

func (*Service) OnAcquire

func (s *Service) OnAcquire(ctx context.Context, rc tools.RunContext, sb sandbox.Sandbox)

OnAcquire is the sandbox tools' acquisition hook: the first acquisition of a run in a sandbox takes the "Before AI turn" checkpoint (lazily, when the run created the sandbox).

func (*Service) OnCreate

func (s *Service) OnCreate(ctx context.Context, threadID string, sb sandbox.Sandbox)

OnCreate restores the archived history into a new sandbox; call it before the artifacts' workspace restore.

func (*Service) PromptSection

func (s *Service) PromptSection(_ context.Context, in agent.Input) string

PromptSection adds the local Git section to runs with sandbox tools.

func (*Service) Restore

func (s *Service) Restore(ctx context.Context, t *store.Thread) (*RestoreOutcome, error)

Restore recreates the thread's sandbox when it is not running: the new sandbox gets the archived history and the saved files (the OnCreate restore).

func (*Service) RestoreFile

func (s *Service) RestoreFile(ctx context.Context, threadID, login, sha, p string) (*RestoreResult, error)

RestoreFile restores rel as it was at the checkpoint sha (Work's restore_file), records the new artifact version (or the artifact's deletion) and archives the history.

func (*Service) RestoreHistory

func (s *Service) RestoreHistory(ctx context.Context, threadID string, sb sandbox.Sandbox)

RestoreHistory writes the thread's archived .git back into a new sandbox (OnCreate, before the artifacts restore). Best effort: a missing or broken archive leaves /workspace without history (the next checkpoint starts one).

func (*Service) Status

func (s *Service) Status(ctx context.Context, t *store.Thread) (*Status, error)

Status computes the workspace status: ready with a live sandbox, stopped when it expired but files or history are saved, missing otherwise, starting while the sandbox is transiently unavailable.

func (*Service) WaitArchives

func (s *Service) WaitArchives(ctx context.Context) bool

WaitArchives waits for the background archives (shutdown, tests); false when ctx ended first.

type Status

type Status struct {
	Availability string `json:"availability"`
	Status       string `json:"status"`
	Ready        bool   `json:"ready"`
	CanRestore   bool   `json:"canRestore"`
	// RestoreBlockedReason is set while a run of the thread is queued or running.
	RestoreBlockedReason *string `json:"restoreBlockedReason"`
	RootPath             string  `json:"rootPath"`
	// HasHistory reports an archived checkpoint history (restored with the files).
	HasHistory bool `json:"hasHistory"`
	// HistoryNotSaved is set when the latest checkpoint history could not be
	// archived (a new sandbox would get an older history, or none).
	HistoryNotSaved *HistoryIssue `json:"historyNotSaved"`
}

Status is the workspace status of a thread (GET …/workspace/status).

Jump to

Keyboard shortcuts

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