artifacts

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 31 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 artifacts makes the files the agent produces under /workspace durable: snapshots after file-changing tools (and at run end), versioned and sha256-deduplicated content in a blob store (Postgres or a host-provided Blobs (see artifacts/s3blobs)), workspace restore on sandbox (re)creation, classified downloads, Office → PDF previews and user uploads.

Index

Constants

View Source
const CustomArtifact = "work.artifact"

CustomArtifact is the CUSTOM event announcing an artifact change.

View Source
const CustomArtifactSkipped = "work.artifact_skipped"

CustomArtifactSkipped is the CUSTOM event announcing a workspace file that is not saved as an artifact: {path, sizeBytes, maxBytes, reason: "too_large", toolCallId?}.

View Source
const DefaultBlobGCGrace = 24 * time.Hour

DefaultBlobGCGrace is the default Options.BlobGCGrace.

View Source
const FileReferencePrompt = `` /* 824-byte string literal not displayed */

FileReferencePrompt is the §2.3 instruction (workspace-file: links).

View Source
const PGBlobMax = 50 << 20

PGBlobMax is the Postgres backend cap per blob.

View Source
const UploadDir = sandbox.Workspace

UploadDir is where attachments land in the sandbox by default (the workspace root, e.g. /workspace/<name>, "name (n).ext" when taken).

Variables

View Source
var (
	ErrBlobNotFound = blobs.ErrNotFound
	ErrBlobTooLarge = blobs.ErrTooLarge
)
View Source
var (
	ErrNotPreviewable  = errors.New("this file type cannot be previewed")
	ErrPreviewFailed   = errors.New("the preview could not be generated")
	ErrTypeMismatch    = errors.New("file extension, declared type and content disagree")
	ErrTooLarge        = errors.New("the file exceeds the storage limit")
	ErrSandboxDisabled = errors.New("no sandbox is configured")
)

Errors mapped to HTTP codes by the API.

View Source
var ErrInvalidTargetPath = errors.New("targetPath must be a file path under /workspace")

ErrInvalidTargetPath means an upload's targetPath is not a file path under /workspace.

Functions

func ContentMime

func ContentMime(name string, data []byte) string

ContentMime is the content type recorded for a file: the extension's type, unless the bytes carry a PDF/Office signature the extension does not claim (e.g. a PDF renamed memo.txt), then the signature's type (or application/octet-stream when the signature is a broken one).

func Event

func Event(a *store.Artifact, change, toolCallID string) agui.Event

Event builds the CUSTOM work.artifact event; toolCallID is the call whose result produced the change ("" for end-of-run snapshots, then omitted).

func InSkippedDir

func InSkippedDir(p string) bool

InSkippedDir reports a workspace path inside a directory snapshots skip (uploads and checkpoint restores there would be marked deleted; C-22).

func MessageItems

func MessageItems(changes []Change) []any

MessageItems is the metadata.artifacts form of changes (stored on messages for reloads).

func MimeType

func MimeType(name string) string

MimeType is the content type of a file name (application/octet-stream when unknown).

func Previewable

func Previewable(name string) string

Previewable is the preview kind of a file: pdf (PDF and Office files, converted), image, text, html or none.

func PreviewableAs

func PreviewableAs(name, mimeType string) string

PreviewableAs is Previewable for a file recorded with mimeType: a file whose content type (from its signature, see ContentMime) is not its extension's is never previewed.

func PromptSection

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

PromptSection adds the file-reference instruction when the run has a sandbox (an agent.PromptSection).

func PutReader

func PutReader(ctx context.Context, b Blobs, key string, r io.Reader, size int64) error

PutReader stores size bytes read from r (see blobs.PutReader).

func SanitizeFilename

func SanitizeFilename(name string) string

SanitizeFilename keeps a safe single path component.

func SkippedEvent

func SkippedEvent(s Skipped, toolCallID string) agui.Event

SkippedEvent builds the CUSTOM work.artifact_skipped event.

func UploadTarget

func UploadTarget(target string) (dir, name string, err error)

UploadTarget validates an upload's optional target path: absolute under /workspace or relative to it, no control characters, no "..", not the workspace itself and not inside a directory snapshots skip (.git, node_modules, .venv, __pycache__, the scratch /workspace/.work). It returns the directory and the sanitized file name.

Types

type Blobs

type Blobs = blobs.Blobs

The blob store port lives in core/blobs; these aliases keep the names this package has always had.

type Change

type Change struct {
	Artifact *store.Artifact
	Change   string
}

Change is one artifact change found by a snapshot.

type Delivery

type Delivery struct {
	Data        []byte
	ContentType string
}

Delivery is a file ready to be served.

type EndOfRunHook

type EndOfRunHook struct{ Svc *Service }

EndOfRunHook is the runtime hook that snapshots /workspace when a run ends (any status). Register it before the title and goal hooks: its work.artifact events come before theirs, and the goal evaluator sees the new artifacts.

func (EndOfRunHook) Finishing

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

Finishing implements runtime.Hook (compact runs only compact: no snapshot).

type FallbackBlobs

type FallbackBlobs struct {
	Primary Blobs
	Legacy  Blobs
}

FallbackBlobs writes to Primary and reads a key Primary does not have from Legacy, read-only: switching a deployment from Postgres blobs to S3 (e.g. the dev RustFS) keeps the content stored before readable. Deletes (blob GC of unreferenced keys) go to both, so legacy garbage is collected too.

func (FallbackBlobs) Delete

func (b FallbackBlobs) Delete(ctx context.Context, key string) error

func (FallbackBlobs) Get

func (b FallbackBlobs) Get(ctx context.Context, key string) ([]byte, error)

func (FallbackBlobs) Has

func (b FallbackBlobs) Has(ctx context.Context, key string) (bool, error)

func (FallbackBlobs) MaxBytes

func (b FallbackBlobs) MaxBytes() int64

func (FallbackBlobs) Put

func (b FallbackBlobs) Put(ctx context.Context, key string, data []byte) error

func (FallbackBlobs) PutStream

func (b FallbackBlobs) PutStream(ctx context.Context, key string, r io.Reader, size int64) error

PutStream implements StreamPutter (streamed when Primary supports it).

type FileEntry

type FileEntry struct {
	Name, Path, Type string
	Size             int64
	ModifiedAt       time.Time
}

FileEntry is a v1 files-API entry built from artifacts.

type Images

type Images struct {
	Svc *Service
	// Vision reports whether a model accepts image input (LLM_VISION_MODELS).
	Vision func(model string) bool
}

Images sends attached images (png/jpeg/webp/gif ≤ 5 MiB) to vision models as image parts: the images of the two most recent user messages that have some, at most agent.MaxRequestImages (6) per model call.

func (Images) AttachImages

func (im Images) AttachImages(ctx context.Context, run *store.Run, history []*ai.Message) []*ai.Message

AttachImages implements agent.ImageAttacher.

type Options

type Options struct {
	MaxFileBytes    int64         // snapshot: files above are skipped (default 50 MiB)
	MaxFiles        int           // snapshot: at most this many files (default 500, newest first)
	RestoreMaxFiles int           // workspace restore (default 200)
	RestoreMaxBytes int64         // workspace restore (default 500 MiB)
	PreviewTimeout  time.Duration // soffice conversion (default 120 s)
	// PreviewConcurrency bounds the soffice conversions of this process (default 2).
	PreviewConcurrency int
	// LockWait bounds the wait for a thread's artifact lock (default 2 min).
	LockWait time.Duration
	// BlobGCGrace is how long a content blob must have had no reference before
	// the retention purge deletes it (default 24 h, HARNESS_BLOB_GC_GRACE_HOURS).
	BlobGCGrace time.Duration
}

Options are the limits of the contract (§2).

type PGBlobs

type PGBlobs struct{ S store.BlobStore }

PGBlobs stores blobs in work_blobs (default when no bucket is configured).

func (PGBlobs) CollectUnreferenced

func (b PGBlobs) CollectUnreferenced(ctx context.Context, keys []string, grace time.Duration) ([]string, error)

CollectUnreferenced deletes in one statement the queued keys still unreferenced for grace, with their preview (blob GC of the retention purge).

func (PGBlobs) Delete

func (b PGBlobs) Delete(ctx context.Context, key string) error

func (PGBlobs) Get

func (b PGBlobs) Get(ctx context.Context, key string) ([]byte, error)

func (PGBlobs) Has

func (b PGBlobs) Has(ctx context.Context, key string) (bool, error)

func (PGBlobs) MaxBytes

func (b PGBlobs) MaxBytes() int64

func (PGBlobs) Put

func (b PGBlobs) Put(ctx context.Context, key string, data []byte) error

func (PGBlobs) PutStream

func (b PGBlobs) PutStream(ctx context.Context, key string, r io.Reader, size int64) error

PutStream implements StreamPutter: Postgres stores one bytea value, so the content is read into memory, within the PGBlobMax cap (ErrBlobTooLarge).

type PurgeJob

type PurgeJob struct {
	Svc   *Service
	After time.Duration
}

PurgeJob is the retention job of the runtime sweeper (a runtime.Purger): threads soft-deleted more than After ago are hard-deleted, then the blobs nothing references any more. After ≤ 0 disables it.

func (PurgeJob) Purge

func (j PurgeJob) Purge(ctx context.Context) error

Purge implements runtime.Purger.

type RunRef

type RunRef struct {
	ThreadID string
	RunID    string
	Login    string
}

RunRef identifies the run a snapshot is attributed to.

type Service

type Service struct {
	Store   store.ArtifactStore
	Blobs   Blobs
	Sandbox sandbox.Manager
	Opts    Options
	// contains filtered or unexported fields
}

Service implements artifacts on top of the metadata store, a blob store and the sandbox manager.

func New

func New(st store.ArtifactStore, blobs Blobs, mgr sandbox.Manager, o Options) *Service

New returns a service with defaults applied.

func (*Service) AfterTool

func (s *Service) AfterTool(ctx context.Context, run *store.Run, toolCallID, toolName string) map[string]any

AfterTool implements agent.ToolHook: snapshot after write_file, edit_file and execute_command. The work.artifact events are queued with tools.AfterResult (written right after the call's TOOL_CALL_RESULT, with the tools' own events); the changes go to the tool message metadata.

func (*Service) CheckAnswer

func (s *Service) CheckAnswer(ctx context.Context, run *store.Run, answer string, emit func(agui.Event) error) string

CheckAnswer implements agent.AnswerChecker: when the answer links workspace files, the workspace is snapshotted (the end-of-run snapshot) and the links whose path has no non-deleted artifact (e.g. /workspace/.work/ files, which are never saved) get a corrective note; saved files the answer names without linking them (by absolute path, or by the name of an output of this run) get one too (harness v3 4.6).

func (*Service) Content

func (s *Service) Content(ctx context.Context, a *store.Artifact, version int) ([]byte, *store.ArtifactVersion, error)

Content returns the bytes of an artifact version (0 = latest).

func (*Service) Deliver

func (s *Service) Deliver(_ context.Context, name string, data []byte) (*Delivery, error)

Deliver returns a file as is, with the content type of its name.

func (*Service) ListArtifactVersions

func (s *Service) ListArtifactVersions(ctx context.Context, artifactID string) ([]store.ArtifactVersion, error)

ListArtifactVersions returns the stored versions of an artifact (verify.ArtifactSource).

func (*Service) ListArtifacts

func (s *Service) ListArtifacts(ctx context.Context, threadID string) ([]*store.Artifact, error)

ListArtifacts returns every artifact of a thread, deleted included (verify.ArtifactSource: the originals of decks, the uploaded PDFs).

func (*Service) Preview

func (s *Service) Preview(ctx context.Context, a *store.Artifact, version int) (*Delivery, error)

Preview returns the preview of a version: PDF (Office files converted in the sandbox, cached per source sha256), images as-is and text/html as text/plain.

func (*Service) ProducedPaths

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

ProducedPaths lists the paths of the thread's live output artifacts (the goal evaluator's "files produced").

func (*Service) Purge

func (s *Service) Purge(ctx context.Context, olderThan time.Duration) (threads, blobs int, err error)

Purge hard-deletes the threads soft-deleted more than olderThan ago (with their runs, messages, events, artifacts and versions), then deletes from the blob backend, with its cached preview, every queued content blob that no artifact version references and that had no reference for Opts.BlobGCGrace. The deletion is conditional on both still holding: in the same statement as the queue row for the database backend, after the queue row is removed (and before that removal commits) for an external backend.

func (*Service) RecordPath

func (s *Service) RecordPath(ctx context.Context, sb sandbox.Sandbox, threadID, login, p string) (*Change, error)

RecordPath records the current state of one workspace file of the thread's sandbox after it was changed outside a run (a checkpoint restore): a new version when it exists (created or updated), a deletion of its artifact when it no longer does. It returns the change (nil when there is none, e.g. a file above the snapshot limits or under /workspace/.work).

func (*Service) RestoreVersion

func (s *Service) RestoreVersion(ctx context.Context, a *store.Artifact, version int) (*store.Artifact, error)

RestoreVersion writes a version back into the sandbox (creating it if needed) and records it as a new version.

func (*Service) RestoreWorkspace

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

RestoreWorkspace writes the latest version of every non-deleted artifact back into a new sandbox (files a previous restore skipped first, oldest skipped first, then the newest; ≤ RestoreMaxFiles / RestoreMaxBytes) and returns the notice for the model ("" when there was nothing to restore). Skipped files stay pending: they are never taken for deletions and go first next time.

func (*Service) Snapshot

func (s *Service) Snapshot(ctx context.Context, sb sandbox.Sandbox, ref RunRef) ([]Change, error)

Snapshot diffs /workspace against the thread's artifacts and stores every new or changed file as a new version; files gone from the workspace are marked deleted — only those known to be in this sandbox (seen in a listing or written there) and unchanged since the listing started.

func (*Service) SnapshotEnd

func (s *Service) SnapshotEnd(ctx context.Context, run *store.Run, emit func(agui.Event) error)

SnapshotEnd snapshots the workspace at the end of a run (detached from cancellation); changes are recorded on the run's last assistant message.

func (*Service) SnapshotRun

func (s *Service) SnapshotRun(ctx context.Context, run *store.Run, toolCallID string, emit func(agui.Event) error) []Change

SnapshotRun snapshots the thread's live sandbox (never creates one), emits a work.artifact event per change and returns the changes.

func (*Service) Tree

func (s *Service) Tree(ctx context.Context, threadID, dir string) ([]FileEntry, error)

Tree lists the direct children of dir from the thread's non-deleted artifacts.

func (*Service) Upload

func (s *Service) Upload(ctx context.Context, in UploadInput) (*store.Artifact, error)

Upload validates and stores an attachment as an artifact of kind upload at /workspace/<name> or the validated TargetPath (de-duplicated as "name (2).ext", "name (3).ext"… ), and writes it into the thread's sandbox when one is running.

func (*Service) Version

func (s *Service) Version(ctx context.Context, a *store.Artifact, version int) (*store.ArtifactVersion, error)

Version resolves a version (0 = latest) of an artifact.

type Skipped

type Skipped struct {
	Path      string
	SizeBytes int64
	MaxBytes  int64
	// contains filtered or unexported fields
}

Skipped is a workspace file a snapshot did not save (above MaxFileBytes or the blob backend's cap): files over the limit are refused, not versioned by reference (roadmap 5.8).

type StreamPutter

type StreamPutter = blobs.StreamPutter

The blob store port lives in core/blobs; these aliases keep the names this package has always had.

type UploadInput

type UploadInput struct {
	ThreadID     string
	Login        string
	Filename     string
	DeclaredMIME string
	Data         []byte
	Body         io.ReaderAt
	Size         int64
	// TargetPath is the optional client-chosen path (see UploadTarget); it is
	// de-duplicated like the default one.
	TargetPath string
}

UploadInput is one validated upload: Data, or Size bytes readable from Body (e.g. the request's temporary file; plain files are then streamed to the blob store and the sandbox instead of being held in memory).

Directories

Path Synopsis
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.
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.

Jump to

Keyboard shortcuts

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