models

package
v0.23.5 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 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 models is the family model library (spec §7): the Hugging Face cache ($HUB) shared by every family app, with claims ("I use repo@commit, keep it"), flock locks compatible with huggingface_hub's .locks/ directory, the deletion rules that keep one app from deleting another's models, the family pins table and model licence acceptances.

It does not download: hfhub (or an app's own downloader) does, holding the locks of this package and claiming what it downloaded.

Typical use:

s := &models.Store{Family: family.Default(), Hub: hub, BundleID: "dev.hehehai.dicta", AppID: "dicta", Apps: presence}
s.Claim(ctx, models.Claim{Repo: r, Revision: c, Model: "qwen3-asr-0.6b-4bit", Role: "asr", Origin: models.OriginMigrated})
d, _ := s.Decide(models.Ref{Repo: r, Revision: c}) // who else uses it
res, err := s.Delete(ctx, ref, models.ThisApp)    // only removes files nobody else claims

Index

Constants

View Source
const (
	OriginDownloaded = "downloaded" // this app downloaded it
	OriginReused     = "reused"     // it was there (another app's), this app uses it
	OriginMigrated   = "migrated"   // registered at the first start with the spec (§15.2)
)

Origins of a claim.

View Source
const (
	RoleASR     = "asr"
	RoleTTS     = "tts"
	RoleLLM     = "llm"
	RoleVAD     = "vad"
	RoleAlign   = "align"
	RoleDiarize = "diarize"
	RoleEnhance = "enhance"
	RoleEmbed   = "embed" // embedding models (search by meaning)
	RoleVLM     = "vlm"   // vision language models used only for images
	RoleOther   = "other"
)

Roles of a claimed model.

View Source
const (
	ImportImported = "imported"
	ImportPresent  = "present"
	ImportAbsent   = "absent"
	ImportBusy     = "busy"
	ImportNoSpace  = "no-space"
	ImportError    = "error"
)

Actions of ImportResult.

View Source
const (
	OpDownload = "download"
	OpVerify   = "verify"
	OpDelete   = "delete"
	OpClaim    = "claim"
	OpFinish   = "finish" // completing a snapshot (rename, refs)
)

Operations named in lock owner files.

View Source
const BackupExcludeXattr = "com.apple.metadata:com_apple_backup_excludeItem"

BackupExcludeXattr is the extended attribute Time Machine honours to skip an item and everything under it ("sticky" exclusion: it moves with the folder). NSURLIsExcludedFromBackupKey and `tmutil addexclusion` (without -p) set the same attribute.

View Source
const EngineCopyMinAge = 10 * time.Minute

EngineCopyMinAge: empty mlx-audio directories younger than this may be another app's engine at work (spec §7.8).

View Source
const HubDirName = "hub"

HubDirName is the default hub's directory under $FAMILY/models.

View Source
const ImportReserve int64 = 2e9

ImportReserve is the free space a copy across volumes leaves.

View Source
const KindBlobs = "models.blobs"

KindBlobs is the schema kind of a repo's blob sizes file.

View Source
const KindClaims = "models.claims"

KindClaims is the schema kind of models/claims/<bundle id>.json.

View Source
const KindImported = "models.imported"

KindImported is the schema kind of models/imported/<bundle id>.json.

View Source
const KindLicences = "models.licences"

KindLicences is the schema kind of models/licences.json.

View Source
const KindRemoved = "models.removed"

KindRemoved is the schema kind of models/removed.json.

View Source
const OpImport = "import"

OpImport names the lock owner of an import.

View Source
const OriginImported = "imported"

OriginImported marks a claim made by Import.

View Source
const RepoLockName = "actnow-repo.lock"

RepoLockName is the repo lock's file name.

View Source
const SizesDirName = ".actnow"

SizesDirName is the family's folder inside a repo folder (models--owner--name/.actnow). huggingface_hub reads only blobs/, snapshots/ and refs/ of a repo folder, so tools ignore it.

View Source
const TombstoneTTL = 90 * 24 * time.Hour

TombstoneTTL is how long a "deleted for all apps" record is kept (spec §7.6).

Variables

View Source
var (
	// TextReuseTitle / TextReuseBy: the first-run reuse card (§7.10.1).
	TextReuseTitle = family.Text{EN: "{count} models are already on this Mac", ZH: "已在这台 Mac 上找到 {count} 个模型"}
	TextReuseBy    = family.Text{EN: "Installed by {app} · {size} · no download needed", ZH: "由 {app} 安装 · {size} · 无需下载"}
	// TextReuseShared: the reuse card's line without app names (v0.22.1),
	// for when several apps installed the models.
	TextReuseShared = family.Text{EN: "Shared across ActNow · {size} · no download needed", ZH: "ActNow 共用 · {size} · 无需下载"}
	TextUseThem     = family.Text{EN: "Use them", ZH: "直接使用"}
	TextChooseModel = family.Text{EN: "Choose models…", ZH: "选择模型…"}
	TextStillToGet  = family.Text{EN: "{size} still to download", ZH: "还需下载 {size}"}
	TextInstalledBy = family.Text{EN: "Installed · from {app}", ZH: "已安装 · 来自 {app}"}
	// TextInstalledShared: a model's state when only other apps use it,
	// without naming them (v0.22.1; preferred over TextInstalledBy).
	TextInstalledShared = family.Text{EN: "Installed · Shared across ActNow", ZH: "已安装 · ActNow 共用"}
	// TextAlternative: the recommended model is missing, a lighter one of
	// the same series is there (§7.10.1). Default button: download.
	TextAlternative = family.Text{
		EN: "{want} isn't installed, but {have} (from {app}) is. Use it for now?",
		ZH: "未安装 {want},但已有 {have}(来自 {app})。先用它吗?",
	}
	TextUseAlternative = family.Text{EN: "Use {have}", ZH: "先用 {have}"}
	TextDownloadWanted = family.Text{EN: "Download {want}", ZH: "下载 {want}"}

	// Models and storage pages (§7.10.2). A model's state says it is
	// shared, not with whom (v0.22.1): the list grows with the family and
	// names apps that are not public. TextShared replaces TextSharedWith
	// and TextSharedOthers; the delete dialogs still name the apps.
	TextShared = family.Text{EN: "Shared across ActNow", ZH: "ActNow 共用"}
	// TextLoadedElsewhere: another app holds the model in memory now.
	TextLoadedElsewhere = family.Text{EN: "In use by another app", ZH: "其他 App 正在使用"}
	// Deprecated: use TextShared (v0.22.1).
	TextSharedWith   = family.Text{EN: "Shared with {apps}", ZH: "与 {apps} 共用"}
	TextFolderShared = family.Text{EN: "Shared by all ActNow apps", ZH: "由所有 ActNow app 共用"}
	TextOnlyThisApp  = family.Text{EN: "Only {app}", ZH: "仅 {app}"}
	// Deprecated: use TextShared (v0.22.1).
	TextSharedOthers = family.Text{EN: "Shared with other ActNow apps", ZH: "与其他 ActNow app 共享"}
	TextStillUsedBy  = family.Text{EN: "Still used by {app}, kept", ZH: "仍被 {app} 使用,已保留"}
	TextOrphans      = family.Text{
		EN: "{count} models ({size}) are only used by apps that are no longer installed.",
		ZH: "有 {count} 个模型({size})只被已卸载的 app 使用。",
	}
	TextCleanUp = family.Text{EN: "Clean up", ZH: "清理"}

	// The delete dialog when another app uses the model (§7.10.3).
	TextRemoveTitle = family.Text{EN: "Remove \"{model}\" from {app}?", ZH: "从 {app} 移除“{model}”?"}
	TextRemoveBody  = family.Text{
		EN: "{apps} also uses this model, so its files ({size}) stay on this Mac.",
		ZH: "{apps} 也在使用这个模型,文件({size})会保留在这台 Mac 上。",
	}
	TextRemoveFromApp   = family.Text{EN: "Remove from {app}", ZH: "从 {app} 移除"}
	TextDeleteForAll    = family.Text{EN: "Delete for all apps…", ZH: "为所有 app 删除…"}
	TextDeleteForAllMsg = family.Text{
		EN: "{apps} will need to download it again ({size}).",
		ZH: "{apps} 再次使用时需要重新下载({size})。",
	}
	TextDelete = family.Text{EN: "Delete", ZH: "删除"}
	TextCancel = family.Text{EN: "Cancel", ZH: "取消"}
	// TextWipeKeeps: "erase all data" with models, when some are shared (§7.6 step 3).
	TextWipeKeeps = family.Text{
		EN: "These models are also used by other ActNow apps and will be kept: {models} ({size})",
		ZH: "以下模型也被其他 ActNow app 使用,将被保留:{models}({size})",
	}
	// TextDeletedIn: after another app deleted a model for all apps (§7.6).
	TextDeletedIn = family.Text{EN: "Deleted in {app} · Download again", ZH: "已在 {app} 中删除 · 重新下载"}
	// TextBusy: the repo lock is held (§7.4).
	TextBusy = family.Text{
		EN: "{app} is downloading or using this model. Try again later.",
		ZH: "{app} 正在下载或使用这个模型,请稍后再试。",
	}
	// TextDownloadingIn: another app downloads the model (§7.10.4).
	TextDownloadingIn = family.Text{EN: "Downloading in {app}… {percent}%", ZH: "正在由 {app} 下载… {percent}%"}
	// TextLicenceAcceptedIn: a licence accepted in another app (§7.9).
	TextLicenceAcceptedIn = family.Text{
		EN: "You accepted this licence in {app} on {date}.",
		ZH: "你已在 {app} 中接受了此许可({date})。",
	}
	TextContinue = family.Text{EN: "Continue", ZH: "继续"}
	// TextMoveModels: the family keeps models elsewhere (§15.2 step 5).
	TextMoveModels = family.Text{
		EN: "Other ActNow apps keep models in {path}. Move this app's models there to share them?",
		ZH: "其他 ActNow app 把模型放在 {path}。要把本 app 的模型移过去以便共用吗?",
	}
	TextMoveButton   = family.Text{EN: "Move models…", ZH: "移动模型…"}
	TextKeepSeparate = family.Text{EN: "Keep separate", ZH: "保持分开"}

	// TextBackupModels / TextBackupModelsHint: the storage page's switch
	// for models.backup (§7.12), off by default.
	TextBackupModels     = family.Text{EN: "Back up models with Time Machine", ZH: "用 Time Machine 备份模型"}
	TextBackupModelsHint = family.Text{
		EN: "Models can be downloaded again, so they are left out of backups. Applies to all ActNow apps.",
		ZH: "模型可以重新下载,所以默认不放进备份。对所有 ActNow app 生效。",
	}
	// TextImported: once, after Import found models (§7.1.1).
	TextImported = family.Text{
		EN: "Found {count} models downloaded earlier ({size}). They are now in the ActNow model folder; nothing was downloaded again.",
		ZH: "找到之前下载的 {count} 个模型({size}),已放进 ActNow 模型文件夹,无需重新下载。",
	}
	// TextFolderSource: the model folder row's second line (§7.10.2):
	// where the path comes from.
	TextFolderDefault = family.Text{EN: "Default · Shared by all ActNow apps", ZH: "默认位置 · 由所有 ActNow app 共用"}
	TextFolderChosen  = family.Text{EN: "Chosen in {app} · Shared by all ActNow apps", ZH: "在 {app} 中设置 · 由所有 ActNow app 共用"}
	// TextDamaged: Check found files of the wrong size (§7.5).
	TextDamaged = family.Text{
		EN: "Some files are incomplete. Download again to repair (only the damaged files are fetched).",
		ZH: "部分文件不完整。重新下载即可修复(只下载损坏的文件)。",
	}
	// TextUnclaimed: Decide is unsure because an app's claims are missing
	// (§7.6, v1.0.9); the files stay.
	TextUnclaimed = family.Text{
		EN: "{apps} may still use this model, so its files stay. Open {apps} once and try again.",
		ZH: "{apps} 可能还在使用这个模型,文件已保留。打开一次 {apps} 后再试。",
	}
)

Reference texts of the model library (spec §7.10). Apps translate them with their own i18n; placeholders are filled with Text.Fill.

View Source
var ErrBackupUnsupported = errors.New("backup exclusion is only supported on macOS")

ErrBackupUnsupported: the system has no Time Machine (not macOS).

View Source
var ErrNotInstalled = errors.New("model is not installed")

ErrNotInstalled: a claim was asked for a model that is not on disk.

Functions

func AcceptLicence

func AcceptLicence(ctx context.Context, d family.Dir, repo, licence, bundleID string) error

AcceptLicence records that the user accepted repo's licence in the app bundleID. An acceptance of the same repo and licence is replaced.

func AddTombstone

func AddTombstone(ctx context.Context, d family.Dir, hub string, ref Ref, by string, at time.Time) error

AddTombstone records that ref was deleted for all apps from hub.

func ApplyBackup added in v0.8.0

func ApplyBackup(d family.Dir, hub string, backup bool) error

ApplyBackup applies the family setting models.backup to the model library at hub (spec §7.12): with backup false (the default) the models are excluded from Time Machine, with true the marks are cleared.

  • hub is the family's default library (DefaultHubIn(d)): the whole folder is marked, which also covers downloads in progress and the mlx-audio copies;
  • every hub (also a folder the user chose, such as their own Hugging Face cache): each repo folder (models--owner--name) some family app claims is marked, and nothing else — the user's own models there stay as they are.

Every app calls it at launch, after a download or import, and when TopicSettings says models.backup changed; it is idempotent and cheap (one getxattr per claimed repo). Errors are per item and joined.

func BlobLockFile

func BlobLockFile(hub, repo, blob string) string

BlobLockFile is $HUB/.locks/models--owner--name/<blob>.lock, the same file huggingface_hub locks while it downloads that blob.

func CleanEngineCopies

func CleanEngineCopies(hub string, minAge time.Duration) ([]string, error)

CleanEngineCopies removes the empty directories under $HUB/mlx-audio that are older than minAge (EngineCopyMinAge): mlx-audio-swift leaves them after failed loads, and its next load would then delete the hub snapshot. It returns their names.

func ClearTombstone

func ClearTombstone(ctx context.Context, d family.Dir, hub string, ref Ref) error

ClearTombstone forgets that ref was deleted from hub: it is on disk again (downloaded or claimed).

func DefaultHub added in v0.8.0

func DefaultHub() string

DefaultHub is the family's default model library (spec §7.1, v1.0.9): $FAMILY/models/hub, i.e. ~/Library/Application Support/ActNow/models/hub (it follows ACTNOW_FAMILY_DIR). The layout inside is Hugging Face's (models--owner--name/{blobs,snapshots,refs}), so engines and hfhub only change their root.

func DefaultHubIn added in v0.8.0

func DefaultHubIn(d family.Dir) string

DefaultHubIn is the default hub of a family directory.

func DeleteSnapshot

func DeleteSnapshot(hub string, ref Ref) (int64, error)

DeleteSnapshot removes ref's files (spec §7.6 step 1.5): the snapshot (and an unfinished one), the refs naming it, the blobs no remaining snapshot links (with their partial downloads, except blobs whose lock someone holds); the repo directory and its mlx-audio copy when no snapshot is left. The caller holds the repo lock exclusively and has decided (Decide) that the files may go. It returns the bytes removed.

func EngineCopiesDir

func EngineCopiesDir(hub string) string

EngineCopiesDir is $HUB/mlx-audio, mlx-audio-swift's flat copies.

func EngineCopy

func EngineCopy(hub, repo string) string

EngineCopy is $HUB/mlx-audio/<owner>_<name> (spec §7.8).

func EnsureHub added in v0.8.0

func EnsureHub(d family.Dir, hub string) error

EnsureHub creates the model library folder. The default one is inside $FAMILY, whose folders are 0700 (spec §4): they are created first with that mode, then hub itself (0755, Hugging Face's usual mode).

func HFDefaultHub added in v0.8.0

func HFDefaultHub() string

HFDefaultHub is ~/.cache/huggingface/hub.

func ImportedFile added in v0.8.0

func ImportedFile(d family.Dir, bundleID string) string

ImportedFile is $FAMILY/models/imported/<bundle id>.json: what this app already brought over into which $HUB, so that a model the user deletes afterwards is not imported again at the next launch. Only that app writes it.

func IsBackupExcluded added in v0.8.0

func IsBackupExcluded(path string) (bool, error)

IsBackupExcluded reports whether path itself carries the mark.

func IsCommit

func IsCommit(rev string) bool

IsCommit reports a 40-hex commit id.

func LegacyHubs added in v0.8.0

func LegacyHubs(hub string) []string

LegacyHubs are the Hugging Face caches models may be imported from (Store.Import): $HF_HUB_CACHE, $HF_HOME/hub and ~/.cache/huggingface/hub, each once, those that exist and are not hub itself.

func LocksDir

func LocksDir(hub, repo string) string

LocksDir is $HUB/.locks/models--owner--name, huggingface_hub's lock directory for the repo (spec §7.4).

func MarkRepoBackup added in v0.8.0

func MarkRepoBackup(hub, repo string, backup bool) error

MarkRepoBackup marks (backup false) or unmarks one repo folder; a repo that is not on disk is skipped. Downloaders and Import call it for the repos they finish, with the family setting.

func ReadAllClaims

func ReadAllClaims(d family.Dir) (all map[string]Claims, errs []error)

ReadAllClaims reads every app's claims file, keyed by the bundle id of the file name. Files that cannot be read are reported in errs and left out; callers that delete must treat errs as "someone may use anything" (Decide does).

func ReadBlobSizes added in v0.8.0

func ReadBlobSizes(hub, repo string) map[string]int64

ReadBlobSizes reads a repo's blob sizes; nil when there are none (a download by an older app or a Python tool) or the file is unreadable.

func RecordBlobSizes added in v0.8.0

func RecordBlobSizes(hub, repo string, sizes map[string]int64) error

RecordBlobSizes adds blob sizes to a repo's file, for a downloader that verified them (hfhub does; an app's own downloader should). The caller holds the repo lock exclusively (finishing a snapshot), so writers do not race. Blob names that are not hashes are skipped.

func RepoDir

func RepoDir(hub, repo string) string

RepoDir is $HUB/models--owner--name.

func RepoFolder

func RepoFolder(repo string) string

RepoFolder is a repo's directory name: "models--owner--name".

func RepoLockFile

func RepoLockFile(hub, repo string) string

RepoLockFile is $HUB/.locks/models--owner--name/actnow-repo.lock.

func SameHub

func SameHub(a, b string) bool

SameHub reports whether two hub paths are the same directory (as written in claims: cleaned, symlinks resolved when they exist).

func SetBackupExcluded added in v0.8.0

func SetBackupExcluded(path string, excluded bool) error

SetBackupExcluded marks path (a folder: everything under it) as excluded from Time Machine backups, or clears the mark. It changes only that item, never its parents. On other systems it returns ErrBackupUnsupported.

func SizesFile added in v0.8.0

func SizesFile(hub, repo string) string

SizesFile is $HUB/models--owner--name/.actnow/blobs.json: the size of each blob of the repo (blob name → bytes) as verified by whoever wrote it. A blob's name is its hash, so its size never changes: entries are only added.

func SnapshotDir

func SnapshotDir(hub string, r Ref) string

SnapshotDir is $HUB/models--owner--name/snapshots/<commit>, the path an engine is given (spec §7.1: never let it pick a snapshot itself).

func ValidRepo

func ValidRepo(repo string) bool

ValidRepo reports whether repo is "owner/name" with the characters the Hub allows, so that paths built from it stay inside $HUB (spec §13).

Types

type Acceptance

type Acceptance struct {
	Repo    string       `json:"repo"`
	Licence string       `json:"licence"` // SPDX-like: "CC-BY-NC-4.0"
	By      string       `json:"by"`      // bundle id
	At      time.Time    `json:"at"`
	Extra   family.Extra `json:"-"`
}

Acceptance is the user accepting a model's licence in one app (spec §7.9).

func LicenceAccepted

func LicenceAccepted(d family.Dir, repo, licence string) (Acceptance, bool)

LicenceAccepted finds an acceptance of repo's licence (any app). The app still shows the licence, worded TextLicenceAcceptedIn, with a "Continue" button.

func ReadLicences

func ReadLicences(d family.Dir) ([]Acceptance, error)

ReadLicences reads every acceptance.

func (Acceptance) MarshalJSON

func (a Acceptance) MarshalJSON() ([]byte, error)

func (*Acceptance) UnmarshalJSON

func (a *Acceptance) UnmarshalJSON(b []byte) error

type AppState

type AppState struct {
	BundleID  string
	AppID     string
	Name      string
	Installed bool
	Running   bool
	// ModelsRoot is the $HUB the app's manifest names (manifest
	// models.root): the app keeps models there. An installed app with a
	// ModelsRoot equal to this app's $HUB but no claims file makes
	// deletions unsure (spec §7.6, v1.0.9: the claims may have been lost).
	ModelsRoot string
}

AppState is what the registry knows of an app (registry.States).

type BusyError

type BusyError struct {
	Lock  string
	Owner *Owner
}

BusyError: a lock is held by another process (or another open in this one). Owner is what its owner file says, nil when unknown. It matches family.ErrLocked.

func (*BusyError) Error

func (e *BusyError) Error() string

func (*BusyError) Is

func (e *BusyError) Is(target error) bool

type Claim

type Claim struct {
	Repo     string `json:"repo"`
	Revision string `json:"revision"`
	Model    string `json:"model,omitempty"` // the app's catalogue id (the first model that claimed it)
	// Models are every catalogue entry of the app that uses the repo:
	// an auxiliary repo (a tokenizer) shared by two models of one app is
	// one claim with both. Removing one model releases only its name
	// (Store.Release, Store.DeleteModel); the claim goes with the last.
	// Absent in files of older writers: Model alone counts.
	Models []string `json:"models,omitempty"`
	Family string   `json:"family,omitempty"` // model series: "qwen3-asr"
	Role   string   `json:"role,omitempty"`
	Bytes  int64    `json:"bytes,omitempty"`
	// Files lists the files used when only part of the repo is (globs
	// allowed: "v3/*"); nil = the whole snapshot.
	Files  []string  `json:"files"`
	Aux    bool      `json:"aux"`
	Since  time.Time `json:"since"`
	Origin string    `json:"origin,omitempty"`
	// Sizes are the expected sizes of files (path → bytes), from the
	// app's catalogue, for Check; not written to the claims file.
	Sizes map[string]int64 `json:"-"`
	Extra family.Extra     `json:"-"`
}

Claim is "this app uses repo@revision, keep it" (spec §7.3).

func (Claim) MarshalJSON

func (c Claim) MarshalJSON() ([]byte, error)

func (Claim) Ref

func (c Claim) Ref() Ref

Ref is the claim's identity.

func (*Claim) UnmarshalJSON

func (c *Claim) UnmarshalJSON(b []byte) error

func (Claim) Users added in v0.2.0

func (c Claim) Users() []string

Users are the app's models using the claimed repo: Models and Model, each once, sorted; empty when the claim names none.

type Claims

type Claims struct {
	Schema   string       `json:"schema"`
	App      string       `json:"app"`
	BundleID string       `json:"bundleId"`
	Updated  time.Time    `json:"updated"`
	Root     string       `json:"root"` // the $HUB these claims protect
	Claims   []Claim      `json:"claims"`
	Extra    family.Extra `json:"-"`
}

Claims is one app's claims file, models/claims/<bundle id>.json. Only that app writes it.

func ReadClaims

func ReadClaims(d family.Dir, bundleID string) (Claims, error)

ReadClaims reads one app's claims; a missing file is no claims.

func (Claims) Find

func (c Claims) Find(ref Ref) (Claim, bool)

Find returns the claim on ref.

func (Claims) MarshalJSON

func (c Claims) MarshalJSON() ([]byte, error)

func (*Claims) UnmarshalJSON

func (c *Claims) UnmarshalJSON(b []byte) error

type Decision

type Decision struct {
	Ref    Ref
	Status Status // the snapshot on disk
	// Mine: this app claims it (MyClaim), for the models MyModels.
	Mine     bool
	MyClaim  Claim
	MyModels []string
	// Users are the other apps with a valid claim: same $HUB, installed.
	Users []User
	// Orphans are the claims of uninstalled apps.
	Orphans []User
	// LoadedBy are the other running apps that hold it in memory.
	LoadedBy []User
	// Unsure: some claims files could not be read, or an installed app
	// that keeps models in this $HUB has no claims file (Unclaimed), so
	// anyone may use it.
	Unsure bool
	// Unclaimed are the installed apps whose manifest names this $HUB but
	// whose claims file is missing (lost with the family folder): they
	// will claim their models again when they start (Store.Heal).
	Unclaimed []User
	// FreeBytes is what deleting the snapshot frees: its blobs that no
	// other snapshot of the repo links.
	FreeBytes int64
	// LastSnapshot: no other snapshot of the repo is left after it, so
	// the repo directory and its engine copy (mlx-audio/) go too.
	LastSnapshot bool
}

Decision is what deleting a model would do (spec §7.6), computed from the disk, every app's claims and the running apps' runtime files.

func (Decision) InUse

func (d Decision) InUse() bool

InUse reports whether another app needs the files: deleting "from this app" then keeps them (spec §7.6 step 1.4).

func (Decision) UserNames

func (d Decision) UserNames() []string

UserNames are the names of Users, LoadedBy and Unclaimed, each once, for the dialogs ("AudioSmith also uses this model").

type Found

type Found struct {
	Want   Claim
	Status Status
	// By are the other apps claiming it (the card says "Installed by
	// <first>"); empty when no app claims it (an older app or a Python
	// tool fetched it).
	By []User
}

Found is a wanted model found on disk, for the first-run reuse card (spec §7.10.1).

type HeldLock

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

HeldLock is a repo or blob lock this process holds.

func LockBlob

func LockBlob(ctx context.Context, hub, repo, blob string, who Owner) (*HeldLock, error)

LockBlob is TryLockBlob waiting until the lock is free or ctx ends.

func LockRepo

func LockRepo(ctx context.Context, hub, repo string, mode family.LockMode, who Owner) (*HeldLock, error)

LockRepo is TryLockRepo waiting until the lock is free or ctx ends.

func TryLockBlob

func TryLockBlob(hub, repo, blob string, who Owner) (*HeldLock, error)

TryLockBlob takes a blob's lock (exclusive) without waiting. A *BusyError means another app (or a Python tool) is downloading the same blob: wait for it (LockBlob), then check whether the blob is complete.

func TryLockRepo

func TryLockRepo(hub, repo string, mode family.LockMode, who Owner) (*HeldLock, error)

TryLockRepo takes the repo lock without waiting: *BusyError when held. Downloads and claims take it Shared; finishing a snapshot and deleting take it Exclusive (spec §7.4). Deleting never waits: tell the user to try again (TextBusy).

func (*HeldLock) Downgrade added in v0.2.0

func (l *HeldLock) Downgrade(ctx context.Context, op string) error

Downgrade turns an exclusive repo lock into a shared one, e.g. to keep holding a repo (against deletion) while waiting for others, after finishing its snapshot. Not atomic either (family.Lock.Convert): re-check afterwards. On error the lock is no longer held; Release it.

func (*HeldLock) Mode

func (l *HeldLock) Mode() family.LockMode

Mode is the lock's current mode.

func (*HeldLock) Path

func (l *HeldLock) Path() string

Path is the lock file.

func (*HeldLock) Release

func (l *HeldLock) Release() error

Release drops the lock (and its owner file, when it is still this process's). Safe on nil and twice.

func (*HeldLock) Upgrade

func (l *HeldLock) Upgrade(ctx context.Context, op string) error

Upgrade turns a shared repo lock into an exclusive one, waiting for the other holders to finish (spec §7.4: release SH, then take EX; the caller re-checks the state afterwards, since others may have acted in between).

type HubSource

type HubSource string

Sources of the hub directory (ResolveHub).

const (
	FromFamily  HubSource = "family"  // settings.json models.root
	FromApp     HubSource = "app"     // the app's own folder, when it does not follow the family
	FromDefault HubSource = "default" // $FAMILY/models/hub (DefaultHub)
	// FromEnvHub and FromEnvHome name Hugging Face caches found through
	// the environment: since v0.8.0 they are import sources only
	// (LegacyHubs), never $HUB.
	FromEnvHub  HubSource = "HF_HUB_CACHE"
	FromEnvHome HubSource = "HF_HOME"
	// FromHFDefault is ~/.cache/huggingface/hub, huggingface_hub's default
	// and the family's $HUB before v0.8.0 (spec v1.0.8 and older).
	FromHFDefault HubSource = "hf-default"
)

func EnvHub

func EnvHub() (string, HubSource)

EnvHub is the Hugging Face cache huggingface_hub would use, from the environment alone: $HF_HUB_CACHE, else $HF_HOME/hub, else ~/.cache/huggingface/hub. It was $HUB's fallback before v0.8.0; now it is the first of LegacyHubs.

func ResolveHub

func ResolveHub(follow bool, familyRoot, own string) (string, HubSource)

ResolveHub finds $HUB (spec §7.1), the first that is set of:

  1. familyRoot, settings.json models.root, when the app follows the family;
  2. own, the app's private folder, when it does not;
  3. DefaultHub: $FAMILY/models/hub.

HF_HUB_CACHE and HF_HOME no longer choose it (spec v1.0.9): an app started from Finder and one started from a shell would use different folders. The Hugging Face caches they name are where Import looks for models to bring over (LegacyHubs); a user who wants the family to share one of them picks it as the model folder (models.root).

type ImportResult added in v0.8.0

type ImportResult struct {
	Ref  Ref
	From string // the source hub; "" when nothing was brought over
	// Action: "imported", "present" (already in $HUB), "absent" (in no
	// source), "busy" (a lock is held: tried again next time), "no-space"
	// (a copy across volumes would not fit), "error".
	Action string
	Linked int64 // bytes hard-linked (no new disk space)
	Copied int64 // bytes copied (another volume)
	Err    error
}

ImportResult is what Import did with one model.

type Imported added in v0.8.0

type Imported struct {
	Schema   string        `json:"schema"`
	BundleID string        `json:"bundleId"`
	Updated  time.Time     `json:"updated"`
	Hubs     []ImportedHub `json:"hubs"`
	Extra    family.Extra  `json:"-"`
}

Imported is the content of ImportedFile.

func (Imported) MarshalJSON added in v0.8.0

func (i Imported) MarshalJSON() ([]byte, error)

func (*Imported) UnmarshalJSON added in v0.8.0

func (i *Imported) UnmarshalJSON(b []byte) error

type ImportedHub added in v0.8.0

type ImportedHub struct {
	Root string   `json:"root"`
	Refs []string `json:"refs"`
}

ImportedHub is what was handled for one destination $HUB: refs ("repo@commit") imported, already there, or found in no source.

type Licences

type Licences struct {
	Schema   string       `json:"schema"`
	Accepted []Acceptance `json:"accepted"`
	Extra    family.Extra `json:"-"`
}

Licences is models/licences.json (multi-writer, locks/licences.lock).

func (Licences) MarshalJSON

func (l Licences) MarshalJSON() ([]byte, error)

func (*Licences) UnmarshalJSON

func (l *Licences) UnmarshalJSON(b []byte) error

type Orphan

type Orphan struct {
	User
	Claims []Claim
	// Bytes is what cleaning up would free: the claimed snapshots no
	// installed app claims.
	Bytes int64
}

Orphan is an uninstalled app's claims (spec §7.6 step 4).

type Owner

type Owner struct {
	BundleID string       `json:"bundleId"`
	PID      int          `json:"pid"`
	Since    time.Time    `json:"since"`
	Op       string       `json:"op"`
	Extra    family.Extra `json:"-"`
}

Owner says who holds a lock: written beside it as <lock file>.owner so that other apps can show "Downloading in AudioSmith…" (spec §7.4). Only a hint: flock decides.

func Activity

func Activity(hub, repo, self string) (Owner, bool)

Activity is what another app is doing with a repo, from the owner files of its locks (the repo lock's, else any blob lock's), skipping self (a bundle id). ok is false when nobody is, or the owners are gone. Use it for "Downloading in AudioSmith… 43%" (TextDownloadingIn); the progress can be estimated from the size of the .incomplete blobs.

func ReadOwner

func ReadOwner(lockPath string) (Owner, bool)

ReadOwner reads the owner file of a lock; false when there is none or its process is gone.

func (Owner) MarshalJSON

func (o Owner) MarshalJSON() ([]byte, error)

func (*Owner) UnmarshalJSON

func (o *Owner) UnmarshalJSON(b []byte) error

type Pin

type Pin struct {
	Repo     string   `json:"repo"`
	Revision string   `json:"revision"`
	Family   string   `json:"family"`          // model series: "qwen3-asr"
	Quant    string   `json:"quant,omitempty"` // "4bit", "fp16", "Q4_K_M"…
	Role     string   `json:"role"`
	Bytes    int64    `json:"bytes,omitempty"`
	Files    []string `json:"files,omitempty"` // the files used, when not the whole repo
	Apps     []string `json:"apps"`            // app ids whose catalogue has it
	Aux      []Ref    `json:"aux,omitempty"`   // auxiliary repos it needs
	Note     string   `json:"note,omitempty"`
}

Pin is a row of the family pins table (spec §7.2): the commit every app should use for a repo. To move a repo to another commit, change the table first (an actnowkit release); the apps follow in their next versions, keeping the old commit in their catalogue's accept list meanwhile.

func PinOf

func PinOf(repo string) (Pin, bool)

PinOf finds a repo's pin.

func Pins

func Pins() []Pin

Pins is the family pins table (a copy).

func PinsOfApp

func PinsOfApp(appID string) []Pin

PinsOfApp lists the pins whose Apps include appID: for the phase-0 rule "do not delete what another installed app may use", until every app writes claims.

func PinsOfFamily

func PinsOfFamily(family string) []Pin

PinsOfFamily lists the pins of a model series ("gemma4"): the candidates for a catalogue entry's alternatives.

func (Pin) Ref

func (p Pin) Ref() Ref

Ref is the pin's identity.

type Ref

type Ref struct {
	Repo     string `json:"repo"`
	Revision string `json:"revision"`
}

Ref is a model's identity: repo@commit (spec §7.2).

func ParseRef

func ParseRef(s string) (Ref, error)

ParseRef parses "owner/name@commit".

func (Ref) String

func (r Ref) String() string

type Removed

type Removed struct {
	Schema  string       `json:"schema"`
	Removed []Tombstone  `json:"removed"`
	Extra   family.Extra `json:"-"`
}

Removed is models/removed.json (multi-writer, locks/removed.lock).

func (Removed) MarshalJSON

func (r Removed) MarshalJSON() ([]byte, error)

func (*Removed) UnmarshalJSON

func (r *Removed) UnmarshalJSON(b []byte) error

type Result

type Result struct {
	Decision Decision // as decided holding the lock
	Deleted  bool     // the files went
	Freed    int64    // bytes removed
	// Tombstoned: other apps' claims were overridden (AllApps).
	Tombstoned bool
	// OwnModels are this app's other models that still use the repo
	// (DeleteModel): with ThisApp the claim and files stay for them; with
	// AllApps they lost it too.
	OwnModels []string
}

Result is what Delete did.

type Scope

type Scope int

Scope of a deletion.

const (
	// ThisApp removes the model from this app; the files go only when no
	// other app needs them (the default button).
	ThisApp Scope = iota
	// AllApps deletes the files whoever uses them, and records a tombstone
	// so that the other apps drop their claims ("Delete for all apps…",
	// after a second confirmation).
	AllApps
)

type State

type State string

State is how much of a model is on disk.

const (
	Missing   State = "missing"   // nothing of the snapshot
	Partial   State = "partial"   // a repo directory, an unfinished snapshot or missing files
	Installed State = "installed" // complete (spec §7.5)
)

type Status

type Status struct {
	State    State
	Snapshot string   // snapshots/<commit>, when it exists
	Bytes    int64    // bytes of the blobs the snapshot links (each counted once)
	Missing  []string // files listed but absent, or links without a blob
	// Damaged are files whose size is not the size their blob was
	// verified with (a truncated weights file): the model is Partial,
	// and a download or Verify repairs it (spec §7.5).
	Damaged []string
	// Incomplete bytes of unfinished downloads of the repo (blobs/*.incomplete).
	Incomplete int64
}

Status is what Check found.

func Check

func Check(hub string, c Claim) Status

Check says whether c's snapshot is installed, from the files alone (no hashing, no network; spec §7.5): the snapshot directory exists, every link reaches its blob, every file c.Files lists is there, each file has the size recorded for its blob (SizesFile) and the size c.Sizes gives, and a main repo has a weights file. Hashes are checked when downloading and when the user asks (hfhub Verify).

func FindInstalled

func FindInstalled(hub string, c Claim, accept []string) (rev string, st Status, ok bool)

FindInstalled picks the snapshot an app should use for a catalogue entry (spec §7.2): the pinned commit when installed, else the first of accept (other commits the app's engine has validated) that is. ok is false when none is: download the pinned one.

type Store

type Store struct {
	Family   family.Dir
	Hub      string // $HUB in use (ResolveHub)
	BundleID string // this app's bundle id
	AppID    string // this app's id: "dicta"
	// Apps reports the family apps by bundle id (registry.States). An app
	// with claims but missing from the map counts as installed: when in
	// doubt, keep (spec §3.4). nil = every app counts as installed.
	Apps func() map[string]AppState
	// Now is the clock (tests); nil = time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

Store is one app's view of the model library: its claims, and the decisions and deletions that respect the other apps' claims.

func (*Store) ApplyTombstones

func (s *Store) ApplyTombstones() ([]Tombstone, error)

ApplyTombstones drops this app's claims on models another app deleted for all apps after this app claimed them, and returns those tombstones (for "Deleted in Dicta · Download again", TextDeletedIn). Call it at start-up and on TopicModels.

func (*Store) Claim

func (s *Store) Claim(ctx context.Context, claims ...Claim) error

Claim adds (or refreshes) claims (spec §7.3): after a download, when reusing a model another app installed, or at migration. Each is added holding the repo's shared lock, and checked to be installed afterwards (a racing delete either finished before, and the check fails, or waits for the lock and then sees the claim). A model that is not installed is not claimed: ErrNotInstalled. Tombstones of claimed models are cleared.

func (*Store) ClaimLocked

func (s *Store) ClaimLocked(ctx context.Context, c Claim) error

ClaimLocked is Claim for a caller that already holds c's repo lock (shared or exclusive), such as a downloader finishing a snapshot: taking it again from the same process would wait for itself.

func (*Store) Claims

func (s *Store) Claims() (Claims, error)

Claims reads this app's claims.

func (*Store) CleanOrphans

func (s *Store) CleanOrphans(ctx context.Context, bundleID string) ([]Result, error)

CleanOrphans deletes the models only the uninstalled app bundleID claimed (each as Delete would, skipping busy repos), then removes that app's claims, manifest and runtime files. It returns what happened to each claim.

func (*Store) Decide

func (s *Store) Decide(ref Ref) (Decision, error)

Decide computes what deleting ref would do. It takes no lock: Delete calls it again holding the repo lock.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, ref Ref, scope Scope) (Result, error)

Delete removes ref from this app, following spec §7.6 step 1:

  1. this app's claim goes first (whatever happens next);
  2. the repo lock is taken exclusively without waiting: when another app downloads or claims, the claim is restored and a *BusyError returned (TextBusy: "try again later");
  3. the claims and runtime files are read again;
  4. ThisApp: when another app uses the model, the files stay;
  5. otherwise the snapshot goes (DeleteSnapshot);
  6. AllApps with other users also writes a tombstone.

Auxiliary repos (a tokenizer) are separate refs: delete them the same way.

func (*Store) DeleteModel added in v0.2.0

func (s *Store) DeleteModel(ctx context.Context, ref Ref, model string, scope Scope) (Result, error)

DeleteModel removes one of this app's models (a catalogue id) from ref: the model's main repo, or one of its auxiliary repos. When other models of this app still use ref, ThisApp only releases model from the claim (Release) and keeps everything, reporting them in Result.OwnModels; AllApps deletes anyway, as Delete does. Otherwise it is Delete. Call it for the model's repo and for each of its auxiliary repos.

func (*Store) Heal added in v0.8.0

func (s *Store) Heal(ctx context.Context, installed ...Claim) (bool, error)

Heal recreates this app's claims file when it is missing (spec §7.6, v1.0.9): the family folder or its models/claims were deleted (a cleaner, a migration script, the user) and with them the protection of this app's models. installed are the app's catalogue models that are on disk; each that is installed is claimed again (OriginMigrated), and an empty file is written when none is, so that the others see this app keeps no models rather than "claims lost". Call it at launch and when the app becomes active; with the file present it only stats it. It reports whether it wrote the file.

func (*Store) Import added in v0.8.0

func (s *Store) Import(ctx context.Context, from []string, backup bool, want ...Claim) ([]ImportResult, error)

Import brings this app's models into s.Hub from the Hugging Face caches in from (usually LegacyHubs(s.Hub)), so that moving the library (spec v1.0.9) downloads nothing again:

  • the models are want (the app's catalogue entries, main and auxiliary repos as separate claims, with Files/Aux/Sizes as for Check) and the claims of this app's claims file when it names one of from as root (the app's previous library);
  • each is looked up in s.Hub first (another app imported or downloaded it), then in each source in turn, and taken from the first where it is installed (Check);
  • files are hard-linked (same volume: no space used, and the source stays untouched for the tools and older app versions that use it); across volumes they are copied when the copy leaves ImportReserve free, else the model is skipped ("no-space");
  • the snapshot is built as snapshots/<commit>.incomplete and renamed, holding the destination repo's lock exclusively and the source repo's shared (a busy lock skips the model: "busy"); the refs of the source that name the commit are copied when the destination lacks them; blob sizes are recorded, and the repo is marked for Time Machine as backup (models.backup) says;
  • the app's previous claims are claimed again here (OriginImported); want is not claimed: the app claims what it uses as before (its migration when set up, its first-run reuse card on a fresh install);
  • nothing in the sources is changed or deleted, and models that no family app wants (the user's own) are not looked at.

Handled refs (imported, present, absent) are recorded in ImportedFile and skipped next time, so that a model deleted after the import does not come back; busy, no-space and failed ones are tried again at the next call. Call it at launch before showing model states, and after the model folder changed. It is safe to run from several apps at once.

func (*Store) Orphans

func (s *Store) Orphans() ([]Orphan, error)

Orphans lists the claims of apps the registry says are uninstalled (needs Store.Apps), for "N models (X GB) are only used by apps that are no longer installed" (TextOrphans).

func (*Store) Rehome

func (s *Store) Rehome() error

Rehome moves this app's claims to the hub s.Hub after the app's model folder changed (spec §15.2 step 5): claims whose model is installed under the new hub are kept, the others dropped.

func (*Store) Release added in v0.2.0

func (s *Store) Release(ref Ref, model string) (remaining []string, err error)

Release removes one model (a catalogue id) from this app's claim on ref: the claim stays while other models of the app still use the repo (remaining lists them) and goes with the last one. A claim naming no model at all, or model "", goes at once. Files are not touched: see DeleteModel.

func (*Store) Remove

func (s *Store) Remove() error

Remove deletes this app's claims file (e.g. the app wipes its data and its models).

func (*Store) Survey

func (s *Store) Survey(want ...Claim) []Found

Survey checks which of the wanted models (this app's recommended pack) are already installed, and by whom. Claiming the installed ones with OriginReused is "Use them".

func (*Store) Unclaim

func (s *Store) Unclaim(refs ...Ref) error

Unclaim removes this app's claims on refs (the user removed the model from this app, or the catalogue dropped it). Files are not touched: see Delete.

func (*Store) Usage

func (s *Store) Usage() (Usage, error)

Usage computes it.

type Tombstone

type Tombstone struct {
	Repo      string    `json:"repo"`
	Revision  string    `json:"revision"`
	RemovedBy string    `json:"removedBy"` // bundle id
	At        time.Time `json:"at"`
	// Root is the $HUB the files were deleted from; claims of another
	// root are unaffected. "" (older writers) = any root.
	Root  string       `json:"root,omitempty"`
	Extra family.Extra `json:"-"`
}

Tombstone records that a model was deleted for all apps: the other apps drop their claims on it and show "Deleted in Dicta · Download again".

func ReadTombstones

func ReadTombstones(d family.Dir) ([]Tombstone, error)

ReadTombstones reads models/removed.json (none when missing).

func (Tombstone) MarshalJSON

func (t Tombstone) MarshalJSON() ([]byte, error)

func (Tombstone) Ref

func (t Tombstone) Ref() Ref

Ref is the tombstone's model.

func (*Tombstone) UnmarshalJSON

func (t *Tombstone) UnmarshalJSON(b []byte) error

type Usage

type Usage struct {
	Mine, Shared int64
}

Usage splits the disk space of this app's claimed models (blobs counted once): Mine only this app uses, Shared other apps use too (spec §7.6 step 6).

type User

type User struct {
	BundleID string
	AppID    string // "audiosmith"; "" for an app outside the family table
	Name     string // "AudioSmith", "AudioSmith (dev)"
	Claim    Claim
	// Orphan: the app is uninstalled (spec §7.7); its claim protects
	// nothing, but is listed so that the user can clean it up.
	Orphan bool
}

User is an app that claims a model.

Jump to

Keyboard shortcuts

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