artifact

package
v0.1.4875 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 37 Imported by: 0 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 artifact keeps Magpie Artifacts: pages an agent makes for the user to look at or use (a report, a chart, a small app), kept on this computer with every version, and served by the gateway at /a/<id>/.

Claude Code's own Artifact tool keeps its pages with the claude.ai account that made them, so a page made before magpie switched the Claude account doesn't open under the next one. These are magpie's, whichever account or agent made them.

An artifact is a folder under Dir named by its id, a random, unguessable name: meta.json says what it is and lists its versions, and v<N>/ holds version N's files, the page as index.html beside the files it uses. A version is written whole into a folder of its own and never changed after; a publish that leaves a file out keeps the one before (linked, or copied where links can't be made).

Index

Examples

Constants

View Source
const (

	// MaxAsset is the most an asset may be; an SVG MaxSVGAsset, a
	// stylesheet or script MaxCodeAsset
	MaxAsset     = 20 << 20
	MaxSVGAsset  = 2 << 20
	MaxCodeAsset = 16 << 20
	// MaxAssets and MaxAssetBytes are an artifact's budget
	MaxAssets     = 1000
	MaxAssetBytes = 1 << 30
)
View Source
const (

	// MaxPage is the most a page may hold, MaxFile a file beside it, and
	// MaxVersion a version's files together (the page included)
	MaxPage    = 16 << 20
	MaxFile    = 16 << 20
	MaxVersion = 64 << 20
	// MaxFiles is the most files a version holds besides its page
	MaxFiles = 255
)
View Source
const BlobPath = "/_blob/"

BlobPath is where an asset is served, by its id alone.

View Source
const MaxShared = 32 << 20

MaxShared is the most a shared version's files hold together, as usemagpie.ai takes (site/shares.js MAX_BYTES).

View Source
const Page = "index.html"

Page is the name a version's page is kept and served under.

View Source
const PageAgent = "page"

PageAgent is the Agent of a version the page published itself (the artifact capability), as the user viewing it.

Variables

View Source
var (
	ErrAssetRequest = errors.New("not an asset")
	ErrAssetType    = errors.New("not a type an asset may be")
	ErrAssetQuota   = errors.New("the artifact's assets are full")
)

the asset refusals, by the code the page reads (ErrTooLarge is too_large)

View Source
var (
	ErrNotFound = errors.New("no such artifact")
	// ErrConflict: the artifact has a version newer than the one the
	// publish was built on
	ErrConflict = errors.New("the artifact has a newer version than the one read")
	// ErrTooLarge and ErrInvalid are a publish refused for its size and
	// for what it holds (a page that isn't text, a bad path): its error
	// Is one of them, with its own words
	ErrTooLarge = errors.New("too large to publish")
	ErrInvalid  = errors.New("not publishable")
)
View Source
var AssetTypes = []string{
	"image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml",
	"video/mp4", "video/webm", "application/pdf",
	"font/woff2", "font/woff", "font/ttf", "font/otf",
	"text/csv", "text/markdown", "application/json", "text/plain", "text/css", "text/javascript",
}

AssetTypes are the types an asset may be, exactly as spelled: no parameters, no aliases.

View Source
var Dir = func() string { return appdir.Join(appdir.Config(), "artifacts") }

Dir is the folder artifacts are kept in; a variable for tests.

View Source
var ErrSharedGone = errors.New("its shared link was taken down on usemagpie.ai")

ErrSharedGone is a shared link usemagpie.ai took down on its side (a page reported): the artifact isn't shared any more.

View Source
var ServedCaps = []string{"artifact", "assets", "db", "self", "user"}

ServedCaps are the capabilities the page runtime gives a page that declares them; permissions is built in and never declared. self is artifact's former name, and resolves the same namespace.

View Source
var ShareSite = func() string {
	if s := os.Getenv("MAGPIE_SHARE_SITE"); s != "" {
		return strings.TrimRight(s, "/")
	}
	if testing.Testing() {
		return ""
	}
	return "https://usemagpie.ai"
}

ShareSite is where artifacts are shared. MAGPIE_SHARE_SITE moves it, and a test names its own: a test never shares on the real site.

Functions

func AssetLimit

func AssetLimit(t string) int

AssetLimit is the most an asset of type t may be.

func Assets

func Assets(id string) ([]Asset, AssetUsage, error)

Assets is artifact id's assets, oldest first, and its budget.

func CheckAsset

func CheckAsset(body []byte, t string) ([]byte, error)

CheckAsset is body as it is stored under type t (an SVG sanitized), or why it can't be.

func CheckPath

func CheckPath(p string, doc bool) ([]string, error)

CheckPath is a store path's segments; doc says whether it names a document (an even number of segments) or a collection (odd).

Example
_, err := CheckPath("tasks", true)
fmt.Println(err)
Output:
invalid_argument: "tasks" has 1 segments, so it is a collection: a document's path has an even number

func CleanPath

func CleanPath(p string) (string, error)

CleanPath is a published path as kept: forward slashes, relative, nothing that climbs out or names the page; an error says why not.

func Collections

func Collections(id string) (map[string]int, error)

Collections are the store's collections, with how many documents each holds, for an agent finding its way.

func DataVersion

func DataVersion(id string) int64

DataVersion changes when another connection, in this process or another, has written artifact id's store; 0 when it has none.

func Delete

func Delete(id string) error

Delete takes the artifact and every version of it away, its shared link first: one that can't be taken down keeps the artifact, so its token isn't lost with it.

func DeleteAsset

func DeleteAsset(id, aid string) (deleted bool, err error)

DeleteAsset takes asset aid away from artifact id for good; deleted is false when it holds none by that id.

func FileSHA

func FileSHA(id string, n int, name string) (sum string, ok bool, err error)

FileSHA is the sha256, in hex, of version n's (0: the newest) file name (Page or "" for the page); ok is false when it has none.

func PageTitle

func PageTitle(page []byte) string

PageTitle is the text of the page's <title>, "" when it has none.

func PageToken

func PageToken(id string) (string, error)

PageToken is what artifact id's page sends to reach its store: only the page magpie served knows it, so another page on this computer, or another artifact's, can't read or write it.

func PageTokenOK

func PageTokenOK(id, t string) bool

PageTokenOK is whether t is artifact id's page token.

func SanitizeSVG

func SanitizeSVG(body []byte) ([]byte, error)

SanitizeSVG is an SVG upload as it is stored, as claude.ai's assets keep one: scripts, event handlers, <foreignObject>, <style> and <link>, animation, a <use> of another file, and javascript: and data: URLs are taken out, and what is left is written out again. It is served as an image, so nothing is left in it that runs or reaches out once it is opened as a document.

func Served

func Served(page []byte) []byte

Served is the page as a browser is given it: one written as a fragment, with no doctype, is put in a document of its own with a charset, a viewport and the base styles a page without them lacks, so it doesn't render in quirks mode with the browser's defaults. A page with its doctype is given as written.

func Stats

func Stats(id string) (docs int, bytes int64, err error)

Stats is how much artifact id's store holds.

func Unshare

func Unshare(ctx context.Context, id string) error

Unshare takes the artifact's shared link down; one not shared, or taken down on usemagpie.ai already, is done.

func ValidAssetID

func ValidAssetID(s string) bool

ValidAssetID is whether s is one an asset can have.

func ValidID

func ValidID(id string) bool

ValidID is whether id is one an artifact can have.

func Watch

func Watch(id string) (<-chan Change, func())

Watch gives the store's writes to artifact id as they are made in this process; another process's (the CLI's) show in DataVersion.

func Whole

func Whole(page []byte) bool

Whole is whether page is a whole document, its doctype first, as a page that publishes itself sends it.

func WithRuntime

func WithRuntime(page []byte, c *RuntimeConfig) []byte

WithRuntime is the served page with the runtime in it, ahead of the page's own scripts: right after <head>, else <html>, else the doctype, else first.

Types

type Artifact

type Artifact struct {
	ID          string    `json:"id"`
	Title       string    `json:"title"`
	Description string    `json:"description,omitempty"`
	Created     time.Time `json:"created"`
	Updated     time.Time `json:"updated"`
	Versions    []Version `json:"versions"`
}

Artifact is one artifact as meta.json keeps it.

func File

func File(id string, n int, name string) (string, *Artifact, error)

File is where version n's (0: the newest) file name is on disk; name "" or Page is the page.

func Get

func Get(id string) (*Artifact, error)

Get is the artifact id.

func List

func List() ([]*Artifact, error)

List is every artifact, the most recently updated first. One whose meta.json can't be read is left out, and said in the error beside the rest.

func PublishPage

func PublishPage(p Publish) (*Artifact, error)

PublishPage writes a new artifact, or a new version of one.

func (*Artifact) Latest

func (a *Artifact) Latest() *Version

Latest is the newest version.

func (*Artifact) Version

func (a *Artifact) Version(n int) *Version

Version is version n, nil when there is none; 0 is the newest.

type ArtifactConfig

type ArtifactConfig struct {
	Publish *bool `json:"publish,omitempty"`
}

ArtifactConfig is the artifact capability's declaration (and self's, its former name): {publish: false} keeps the page from saving itself.

func ParseArtifactConfig

func ParseArtifactConfig(raw json.RawMessage) (*ArtifactConfig, error)

ParseArtifactConfig reads the artifact capability's declaration.

type Asset

type Asset struct {
	ID          string    `json:"id"`
	ContentType string    `json:"contentType"`
	Size        int64     `json:"sizeBytes"`
	Created     time.Time `json:"createdAt"`
}

Asset is one stored asset, as assets.json keeps it.

func BlobFile

func BlobFile(aid string) (string, *Asset, error)

BlobFile is asset aid's file and record, whichever artifact holds it: an asset's address names it alone.

func UploadAsset

func UploadAsset(id string, body []byte, t string) (*Asset, error)

UploadAsset stores body, checked (CheckAsset), as one of artifact id's assets.

type AssetUsage

type AssetUsage struct {
	Files    int   `json:"files"`
	Bytes    int64 `json:"bytes"`
	MaxFiles int   `json:"maxFiles"`
	MaxBytes int64 `json:"maxBytes"`
}

AssetUsage is how much of an artifact's budget its assets take.

type AssetsConfig

type AssetsConfig struct {
	Upload string `json:"upload,omitempty"`
}

AssetsConfig is the assets capability's declaration: upload "interact" lets people who can't edit upload too, on claude.ai; here the page's one viewer is its owner, who always may.

func ParseAssetsConfig

func ParseAssetsConfig(raw json.RawMessage) (*AssetsConfig, error)

ParseAssetsConfig reads the assets capability's declaration.

type Capabilities

type Capabilities map[string]json.RawMessage

Capabilities is a version's declaration, by name.

func ParseCapabilities

func ParseCapabilities(raw json.RawMessage) (Capabilities, error)

ParseCapabilities reads a declaration as a publish gives it: nil for none given (the one before is kept), an empty map for {} (cleared).

func (Capabilities) Has

func (c Capabilities) Has(name string) bool

Has is whether the declaration names capability name.

func (Capabilities) PagePublishes

func (c Capabilities) PagePublishes() (publishes, declared bool)

PagePublishes is whether the version's page may publish itself: it declares artifact (or self) without {publish: false}. declared is whether it declares either at all.

type Change

type Change struct {
	Artifact string
	Paths    []string
	// Version, when set, is a new version published: no data changed
	Version int
}

Change is a write the store made: the paths it touched.

type ConflictPath

type ConflictPath struct {
	Path     string  `json:"path"`
	Expected *string `json:"expected"`
	Actual   *string `json:"actual"`
}

ConflictPath is a file whose IfMatch no longer held: Actual is its sha256 now, nil when it isn't there.

type DB

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

DB is one artifact's store, as one viewer reaches it.

func OpenDB

func OpenDB(id string, n int, who Viewer) (*DB, error)

OpenDB is artifact id's store as viewer who reaches it from version n (0: the newest), under the rules the db declaration in force there sets (DBRules). It needs no db declaration: an agent reads and seeds the store of a page that declares one later.

func (*DB) Acquire

func (db *DB) Acquire(p, holder string, ttl time.Duration, data map[string]any) (*Lease, error)

Acquire takes a short lease on the document at p for holder, when no one else holds it, merging data into the document then.

func (*DB) Batch

func (db *DB) Batch(ops []Op) error

Batch makes the writes together, or none of them.

func (*DB) Delete

func (db *DB) Delete(p string) error

Delete takes the document at p away; one not there is done. Documents nested below it stay.

func (*DB) Get

func (db *DB) Get(p string) (*Doc, error)

Get is the document at p, nil when there is none or the viewer can't see it: the two are the same to the viewer.

func (*DB) Run

func (db *DB) Run(q Query) ([]*Doc, error)

Run is the documents q matches that the viewer can see, in its order.

func (*DB) Set

func (db *DB) Set(p string, data map[string]any) error

Set writes the whole document at p, making it if there is none.

func (*DB) Update

func (db *DB) Update(p string, data map[string]any) error

Update merges data into the document at p, which must be there.

type DBConfig

type DBConfig struct {
	Rules []Rule `json:"rules,omitempty"`
}

DBConfig is the db capability's declaration.

func DBRules

func DBRules(a *Artifact, n int) *DBConfig

DBRules is the db declaration in force for artifact a's version n (0: the newest): that version's, or the newest's when it declares none.

func ParseDBConfig

func ParseDBConfig(raw json.RawMessage) (*DBConfig, error)

ParseDBConfig reads and checks the db capability's declaration, as claude.ai checks it at publish.

type DBError

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

DBError is a store call's failure, by the code claude.ai's runtime gives a page (invalid_argument, resource_exhausted, quota_exceeded, unavailable).

func (*DBError) Error

func (e *DBError) Error() string

type Doc

type Doc struct {
	Path    string         `json:"path"`
	ID      string         `json:"id"`
	Data    map[string]any `json:"data"`
	Version int64          `json:"version"`
	Updated time.Time      `json:"updated"`
}

Doc is one document as the store gives it.

type FileConflict

type FileConflict struct {
	Newest int
	Paths  []ConflictPath
}

FileConflict refuses a publish whose IfMatch didn't hold; it is an ErrConflict.

func (*FileConflict) Error

func (c *FileConflict) Error() string

func (*FileConflict) Is

func (c *FileConflict) Is(err error) bool

type FileLimit

type FileLimit struct{ Max, Would int }

FileLimit refuses a version that would hold more than Max files besides its page; it is an ErrInvalid.

func (*FileLimit) Error

func (l *FileLimit) Error() string

func (*FileLimit) Is

func (l *FileLimit) Is(err error) bool

type Filter

type Filter struct {
	Field string `json:"field"`
	Op    string `json:"op"`
	Value any    `json:"value"`
}

Filter is one where() of a query.

type Lease

type Lease struct {
	Acquired  bool      `json:"acquired"`
	Version   int64     `json:"version,omitempty"`
	ExpiresAt time.Time `json:"expiresAt,omitzero"`
	Holder    string    `json:"holder,omitempty"`
}

Lease is an acquire's answer.

type Level

type Level int

Level is how far a viewer reaches into an artifact's data.

const (
	LevelView Level = iota
	LevelInteract
	LevelAdmin
	LevelOwner
	// LevelSelf is held by nobody, the owner included
	LevelSelf
)

func (Level) String

func (l Level) String() string

type Op

type Op struct {
	Op   string         `json:"op"`
	Path string         `json:"path"`
	Data map[string]any `json:"data,omitempty"`
}

Op is one write of a batch: set, update or delete.

type Publish

type Publish struct {
	ID          string
	Title       string // used when the page has no <title> of its own
	Description string
	Label       string
	Agent       string
	// Page is the page itself; on an update nil keeps the one before
	Page []byte
	// Files are the files beside the page, by published path; on an
	// update the files left out are kept, and a nil value removes one
	Files map[string][]byte
	// Base, when set, is the version the publisher last read: a publish
	// over a newer one is refused (ErrConflict)
	Base int
	// IfMatch holds files to what the publisher last read, by published
	// path (Page for the page): the sha256 (FileSHA) each still has, nil
	// for one that isn't there yet. A file that no longer matches
	// refuses the publish with a *FileConflict.
	IfMatch map[string]*string
	// Capabilities: nil keeps the version before's, an empty map
	// clears them, any other is the whole set (ParseCapabilities)
	Capabilities Capabilities
}

Publish is what a publish asks for. With ID empty a new artifact is made; with it, the artifact gets a new version.

type Query

type Query struct {
	Collection string   `json:"collection"`
	Where      []Filter `json:"where,omitempty"`
	OrderBy    string   `json:"orderBy,omitempty"`
	Desc       bool     `json:"desc,omitempty"`
	Limit      int      `json:"limit,omitempty"`
}

Query is a read of one collection.

type Rule

type Rule struct {
	Path  string `json:"path"`
	Read  string `json:"read,omitempty"`
	Write string `json:"write,omitempty"`
}

Rule is one access rule of the db capability: the least level that reads and that writes at Path and below.

type RuntimeConfig

type RuntimeConfig struct {
	// API is where the page's store calls go: <page's folder>_api
	API   string `json:"api"`
	Token string `json:"token"`
	// Caps are the served capabilities the version declares, by name,
	// with their declarations
	Caps   map[string]any `json:"caps"`
	Viewer struct {
		ID string `json:"id"`
	} `json:"viewer"`
	// Version is the version the page is; Pinned, that its address names
	// it (<id>@<n>/), so a newer one doesn't reload it. Home is the
	// artifact's own address, where a publish from a pinned view goes.
	Version int    `json:"version,omitempty"`
	Pinned  bool   `json:"pinned,omitempty"`
	Home    string `json:"home,omitempty"`
	// Shared: the page is a shared copy, on usemagpie.ai, where nothing
	// is served and every capability resolves null
	Shared bool `json:"shared,omitempty"`
}

RuntimeConfig is what the page runtime is given about its page.

func PageRuntime

func PageRuntime(a *Artifact, n int, api string) (*RuntimeConfig, error)

PageRuntime is the runtime config for artifact a's version n (0: the newest), its store calls going to api.

func SharedRuntime

func SharedRuntime() *RuntimeConfig

SharedRuntime is the runtime a shared copy's pages run: window.claude is there, so a page written for it runs, and each capability is null, so the page shows what it shows without them.

type Share

type Share struct {
	ID    string `json:"id"`
	URL   string `json:"url"`
	Token string `json:"token"`
	// Version is the artifact's version the link shows
	Version int       `json:"version"`
	At      time.Time `json:"at"`
}

Share is an artifact's shared link, as share.json keeps it.

func ShareLatest

func ShareLatest(ctx context.Context, id string) (*Share, error)

ShareLatest shares the artifact's newest version: at a new link, or, shared already, at its link in place of the version it showed.

func Shared

func Shared(id string) (*Share, error)

Shared is the artifact id's shared link, or nil when it isn't shared.

type UserConfig

type UserConfig struct {
	Scopes []string `json:"scopes,omitempty"`
}

UserConfig is the user capability's declaration.

func ParseUserConfig

func ParseUserConfig(raw json.RawMessage) (*UserConfig, error)

ParseUserConfig reads the user capability's declaration.

type Version

type Version struct {
	N     int       `json:"n"`
	At    time.Time `json:"at"`
	Label string    `json:"label,omitempty"`
	// Agent is who published it, as the gateway knew the caller
	Agent string `json:"agent,omitempty"`
	// Files are the version's files besides the page, by published path
	Files []string `json:"files,omitempty"`
	Size  int64    `json:"size"`
	// Capabilities are what the page may do beyond static HTML (caps.go)
	Capabilities Capabilities `json:"capabilities,omitempty"`
}

Version is one publish of an artifact.

type Viewer

type Viewer struct {
	ID    string
	Level Level
	Agent bool
}

Viewer is who reaches into an artifact's data: the person viewing its page, at their level, or an agent, which reaches everything.

func LocalViewer

func LocalViewer() (Viewer, error)

LocalViewer is the person at this computer, as the store knows them: every artifact's owner.

Jump to

Keyboard shortcuts

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