chatmove

package
v0.16.521 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 28 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 chatmove carries a conversation to another machine of the same person: the provider-neutral history leaves the source in an encrypted bundle, the target starts a new native session on it in a worktree of its own, and the source is sealed read-only once the cluster has switched. Nothing here names the source's account, provider, model, session or machine: the bundle is the history and where in the repository it was made.

Index

Constants

View Source
const (
	// BundleVersion is the version of the bundle's shape.
	BundleVersion = 1
	// MaxHistory bounds the history a bundle carries; a longer one is refused instead of cut.
	MaxHistory = 32 << 20
	// MaxTitle bounds the title in characters.
	MaxTitle = 300
	// MaxBody bounds an encrypted bundle in the request that carries it.
	MaxBody = MaxHistory + MaxHistory/2 + 1<<16
)
View Source
const (
	CheckProject = "project"
	CheckCommit  = "commit"
	CheckClean   = "clean"
	CheckAuth    = "auth"
	CheckModel   = "model"

	CodeNoProject    = "project_missing"
	CodeCommit       = "commit_missing"
	CodeDirty        = "worktree_dirty"
	CodeAgent        = "agent_unavailable"
	CodeModel        = "model_unavailable"
	CodeDirtySource  = "dirty_source"
	CodeBusy         = "agent_working"
	CodeNoHistory    = "no_history"
	CodeTooBig       = "too_big"
	CodeChanged      = "changed"
	CodeBadBundle    = "bad_bundle"
	CodeNotFound     = "not_found"
	CodeInternal     = "internal"
	CodeAlreadyMoved = "moved"
	// CodeNoSnapshot: the hub keeps no resume snapshot of the chat, or this machine cannot read it.
	CodeNoSnapshot = "no_snapshot"
)

Check ids and the codes of their refusals, as the page reads them.

View Source
const (
	// ResumeVersion is the version of a snapshot file's shape.
	ResumeVersion = 1
	// ResumeKeySecret is the name the person's resume key is kept under in their folder of the hub's safe.
	ResumeKeySecret = "chat-resume-key"
)
View Source
const DefaultResumeEvery = 15 * time.Second

DefaultResumeEvery is how often the uploader looks at the chats.

View Source
const HoldTTL = 5 * time.Minute

HoldTTL is how long a hold stands without a seal: a cluster that died between the two does not freeze the source.

View Source
const MinOpKey = 32

MinOpKey is the shortest one-time key, in bytes.

Variables

View Source
var (
	ErrNoHistory = errors.New("chatmove: no history")
	ErrTooBig    = handoff.ErrArtifactTooBig
	// ErrAgent and ErrModel: the target's agent cannot start (not ready, not that profile) or does not know the model.
	ErrAgent = errors.New("chatmove: the agent is not available")
	ErrModel = errors.New("chatmove: the model is not available")
)

Errors of a Conversations.

View Source
var ErrBundle = errors.New("chatmove: the bundle is not valid")

ErrBundle: the bundle is not one this runtime accepts.

Functions

func AddWorktree

func AddWorktree(ctx context.Context, repo *Repo, name, commit, relDir string) (string, error)

AddWorktree makes the worktree of the move off the repository at the commit, on a branch of its own, and returns the folder the conversation starts in. Making it twice for the same name returns the same folder.

func Decrypt

func Decrypt(secret []byte, opID string, dir Direction, e Envelope) ([]byte, error)

Decrypt opens an envelope made for the operation; any change to it, another key or another operation fails.

func NormalizeRemote

func NormalizeRemote(url string) string

NormalizeRemote makes the same repository the same key whatever way it was cloned: without scheme, user, port and the .git tail, scp-style colons turned into slashes, lower-cased.

func OpKey added in v0.16.154

func OpKey(b64 string) ([]byte, bool)

OpKey reads a one-time key of an operation (base64). A hub that carries a bundle between two machines does not know their secrets: it makes a random key for the operation and gives it to both ends, and the bundle is then made for the target directly, so the hub never reads it. ok is false for a key that is not base64 or too short.

func ResumePath

func ResumePath(machine, conv string) string

ResumePath is where a machine keeps a chat's snapshot in the room: under its own id, the only place the hub lets it write.

Types

type Agent

type Agent struct {
	Provider string  `json:"provider"`
	Profile  string  `json:"profile"`
	Short    string  `json:"short"`
	Models   []Model `json:"models"`
}

Agent is a way to start a conversation on this machine: a CLI, or a profile through it.

type Bundle

type Bundle struct {
	V       int      `json:"v"`
	Title   string   `json:"title"`
	History string   `json:"history"`
	Project *Project `json:"project"`
}

Bundle is everything a move carries. The field set is closed: a bundle with any other field is refused, so an identity cannot ride along by accident.

func DecodeBundle

func DecodeBundle(raw []byte) (Bundle, error)

DecodeBundle reads a bundle's JSON and refuses any field outside the closed set.

func (Bundle) Validate

func (b Bundle) Validate() error

Validate says whether the bundle can be imported.

type Check

type Check struct {
	ID   string `json:"id"`
	OK   bool   `json:"ok"`
	Code string `json:"code,omitempty"`
}

Check is one thing a preflight looked at.

type Conversations

type Conversations interface {
	Info(id string) (Info, bool)
	// Snapshot is the history as neutral JSONL and the fence it was read at; ErrNoHistory, or ErrTooBig past max.
	Snapshot(id string, max int64) ([]byte, string, error)
	Fence(id string) (string, bool)
	Open(in Open) (string, error)
	Delete(id string)
}

Conversations is what a move needs of the conversation runtime.

type DescribeResponse

type DescribeResponse struct {
	Project    *Project `json:"project"`
	Clean      bool     `json:"clean"`
	Busy       bool     `json:"busy"`
	HasHistory bool     `json:"hasHistory"`
	Title      string   `json:"title"`
}

DescribeResponse answers describe.

type Direction

type Direction string

Direction says which end of the transport an envelope is made for; it is part of the key, so what a source wrote cannot be fed back to a source.

const (
	// Export is what a source produces; Import is what a target consumes.
	Export Direction = "export"
	Import Direction = "import"
)

type Envelope

type Envelope struct {
	Enc   string `json:"enc"`
	Nonce string `json:"nonce"`
	CT    string `json:"ct"`
}

Envelope is a bundle in transit: AES-256-GCM under a key derived from the pair's secret and the operation.

func Encrypt

func Encrypt(secret []byte, opID string, dir Direction, plain []byte) (Envelope, error)

Encrypt seals plain for the operation.

type ExportResponse

type ExportResponse struct {
	BundleEnc Envelope `json:"bundleEnc"`
	Fence     string   `json:"fence"`
}

ExportResponse answers export.

type ImportRequest

type ImportRequest struct {
	OpID         string   `json:"opId"`
	BundleEnc    Envelope `json:"bundleEnc"`
	Provider     string   `json:"provider"`
	Profile      string   `json:"profile"`
	Model        ModelRef `json:"model"`
	WithoutFiles bool     `json:"withoutFiles"`
	// Key is the one-time key of the operation (OpKey) the bundle was made under; empty for the pair's secret.
	Key string `json:"key,omitempty"`
}

ImportRequest is a bundle for a target to continue on.

type ImportResponse

type ImportResponse struct {
	ConversationID string `json:"conversationId"`
	Existing       bool   `json:"existing"`
}

ImportResponse answers import.

type Info

type Info struct {
	Title      string
	Cwd        string
	Busy       bool
	HasHistory bool
}

Info is what a move reads of a conversation.

type Match

type Match struct {
	Repo   *Repo
	Checks []Check
}

Match is the target's answer to where a project is: the checkout to branch a worktree off and what was checked.

func Locate

func Locate(ctx context.Context, roots []string, p Project) Match

Locate looks for the project on this machine: the repository by its key, the commit in it and a clean checkout. A move needs all three to bring the files; without any of them it can still go without local files.

func (Match) FilesOK

func (m Match) FilesOK() bool

FilesOK: the project is there, at the commit, clean.

type Model

type Model struct {
	ID      string `json:"id"`
	Label   string `json:"label"`
	Default bool   `json:"default"`
}

Model is a model an agent offers.

type ModelRef

type ModelRef struct {
	ID     string `json:"id"`
	Effort string `json:"effort"`
}

ModelRef is the model a move continues on.

type Open

type Open struct {
	Title    string
	Cwd      string
	History  []byte
	Provider string
	Profile  string
	Model    string
	Effort   string
}

Open is a conversation to start on the target.

type Pointer

type Pointer struct {
	MachineID      string `json:"machineId"`
	Name           string `json:"name"`
	ConversationID string `json:"conversationId"`
}

Pointer is where a sealed conversation went on.

type PreflightRequest

type PreflightRequest struct {
	Project  *Project `json:"project"`
	Provider string   `json:"provider"`
	Profile  string   `json:"profile"`
	Model    string   `json:"model"`
}

PreflightRequest asks a target whether it can take a conversation.

type PreflightResponse

type PreflightResponse struct {
	Checks  []Check `json:"checks"`
	FilesOK bool    `json:"filesOk"`
	Agents  []Agent `json:"agents"`
}

PreflightResponse answers preflight: what was checked, whether the files can come, and the agents to continue with.

type Project

type Project struct {
	RepoKey string `json:"repoKey"`
	RelDir  string `json:"relDir"`
	Commit  string `json:"commit"`
}

Project is where in a repository the conversation worked: the repository by its normalised remote, the folder inside it and the commit its tree was at. It is how a target finds the same files; it carries no path of the source.

type Refusal

type Refusal struct {
	Status  int     `json:"-"`
	Code    string  `json:"code"`
	Message string  `json:"message"`
	Checks  []Check `json:"checks,omitempty"`
}

Refusal is a move that did not happen, with the status and reason the cluster tells the person.

func (*Refusal) Error

func (r *Refusal) Error() string

type Repo

type Repo struct {
	Root    string
	Key     string
	Commit  string
	RelDir  string
	Clean   bool
	IsMain  bool // the main checkout, not a linked worktree
	Project Project
}

Repo is a checkout as the move sees it.

func Find

func Find(ctx context.Context, roots []string, key string) []*Repo

Find lists the main checkouts of the repository under the roots (the roots themselves, and one and two levels below), in a stable order.

func Inspect

func Inspect(ctx context.Context, dir string) *Repo

Inspect reads the checkout dir is in; nil when it is in none, or in one with no remote or no commit to name it by.

type Resume

type Resume struct {
	Store ResumeStore
	Key   func(ctx context.Context) ([]byte, error)
}

Resume is what a machine needs to keep and read snapshots: the person's room and key.

type ResumeKeys

type ResumeKeys struct {
	Safe   Safe
	Folder string
	// contains filtered or unexported fields
}

ResumeKeys finds the person's resume key in their folder of the hub's safe, making one the first time; the key is kept in memory once read. Two machines making it at once settle on what the safe kept: each writes, then reads back.

func (*ResumeKeys) Key

func (k *ResumeKeys) Key(ctx context.Context) ([]byte, error)

Key is the person's resume key.

type ResumeRequest

type ResumeRequest struct {
	SourceMachine  string   `json:"sourceMachine"`
	ConversationID string   `json:"conversationId"`
	Provider       string   `json:"provider"`
	Profile        string   `json:"profile"`
	Model          ModelRef `json:"model"`
	WithoutFiles   bool     `json:"withoutFiles"`
}

ResumeRequest continues on this machine a chat of another machine of the same person from its snapshot, whether that machine is on or not.

type ResumeSnapshot

type ResumeSnapshot struct {
	V         int      `json:"v"`
	OpID      string   `json:"opId"`
	At        int64    `json:"at"`
	BundleEnc Envelope `json:"bundleEnc"`
}

ResumeSnapshot is the file a machine keeps per chat in the resume room, at ResumePath. Only the bundle says anything about the chat, and it is sealed for Import under OpID with the person's key.

type ResumeStore

type ResumeStore interface {
	Current(ctx context.Context, path string) (*filestore.Entry, error)
	GetBlob(ctx context.Context, sha string, w io.Writer) error
	Put(ctx context.Context, path string, data []byte, author string) (filestore.Entry, error)
}

ResumeStore is the person's resume room (filesync.Client of filestore.KindResume).

type ResumeUploader

type ResumeUploader struct {
	Service *Service
	// Machine is this machine's id in the hub: the folder of the room it writes in.
	Machine string
	// List is every conversation of the machine, without waking any.
	List func() []string
	// State is the file that remembers which fence of each chat the store has, so a restart sends only what changed.
	State string
	// Every is the tick (DefaultResumeEvery when 0).
	Every time.Duration
	Log   *slog.Logger
	Now   func() time.Time
	// contains filtered or unexported fields
}

ResumeUploader keeps the resume snapshots of a machine's chats in the hub's store, in the background: a chat whose history grew and that has been at rest for a whole tick (the turn is over, nothing more is coming) is sealed and put once; a chat that did not change since is not sent again. A turn never waits on it.

func (*ResumeUploader) Run

func (u *ResumeUploader) Run(ctx context.Context)

Run ticks until ctx ends.

func (*ResumeUploader) Tick

func (u *ResumeUploader) Tick(ctx context.Context)

Tick is one look at the chats. The first one on a machine with no state only takes note of where every chat is: the chats that were here before the switch was turned on get a snapshot after their next turn, not all at once.

type Safe

type Safe interface {
	Read(ctx context.Context, path string) (map[string]string, error)
	Write(ctx context.Context, path string, data map[string]string) error
}

Safe is the person's folder of the hub's safe (agent.LocalSafe).

type Service

type Service struct {
	Conv   Conversations
	Agents func() []Agent
	Roots  []string
	Secret []byte
	Store  *Store
	// Home is where a move without files gets its folder.
	Home string
	// Resume keeps and reads the chats' resume snapshots in the hub's store; nil when it is off.
	Resume *Resume
	// contains filtered or unexported fields
}

Service is the move of a runtime. Its HTTP face is Handler.

func (*Service) Describe

func (s *Service) Describe(ctx context.Context, conv string) (DescribeResponse, *Refusal)

Describe reads what a source has: where it worked, whether that is clean, whether it is at rest.

func (*Service) Discard

func (s *Service) Discard(ctx context.Context, opID string) *Refusal

Discard undoes an import whose move did not happen. Idempotent.

func (*Service) Export

func (s *Service) Export(ctx context.Context, opID, conv string, withoutFiles bool) (ExportResponse, *Refusal)

Export makes the bundle of a conversation at rest. Nothing changes on the source: it stays active until the cluster switches. A tree with uncommitted changes is refused (they are not carried), unless the move goes without files.

func (*Service) Handler

func (s *Service) Handler() http.Handler

Handler serves POST .../move/<step>: JSON in, JSON out, a refusal as {code, message, checks} with its status.

func (*Service) Hold

func (s *Service) Hold(opID, conv, fence string) *Refusal

Hold stops the source taking messages for a moment, if it is still what was exported: at rest and its transcript unchanged. It is the last look before the cluster switches.

func (*Service) Import

func (s *Service) Import(ctx context.Context, req ImportRequest) (ImportResponse, *Refusal)

Import starts the conversation of a move on this machine, once per operation: a repeated import answers the same conversation. Whatever fails leaves nothing behind.

func (*Service) Preflight

func (s *Service) Preflight(ctx context.Context, req PreflightRequest) PreflightResponse

Preflight is the target's look at a move before anything leaves the source.

func (*Service) Release

func (s *Service) Release(opID, conv string) *Refusal

Release lifts the hold of an operation that did not switch.

func (*Service) ResumeFrom

func (s *Service) ResumeFrom(ctx context.Context, req ResumeRequest) (ImportResponse, *Refusal)

ResumeFrom reads the chat's snapshot from the person's room, opens it with the person's key and imports it like a move. The hub refuses the room to a machine of another person (403), so a snapshot that is not the person's never reaches here.

func (*Service) Seal

func (s *Service) Seal(opID, conv string, to Pointer) *Refusal

Seal makes the source read-only and points it at where the work went on. Idempotent for the same operation.

func (*Service) SealResume

func (s *Service) SealResume(ctx context.Context, machine, conv string, key []byte, at int64) (ResumeSnapshot, string, *Refusal)

SealResume builds the snapshot of a chat of this machine at rest and the fence it was read at. A chat that is working, has no history, moved away or holds more than MaxHistory is refused, as export refuses it. The project is named whether the tree is clean or not: the chat goes on at the last commit, the uncommitted changes stay on the machine.

type Store

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

Store keeps what a runtime must remember across a restart: which operation made which conversation, and which conversations are held or sealed. One small private file.

func OpenStore

func OpenStore(path string) (*Store, error)

OpenStore reads the file at path (none is an empty store).

func (*Store) Blocked

func (s *Store) Blocked(conv string) bool

Blocked says whether the conversation takes no messages: sealed, or held and the hold not run out.

func (*Store) Sealed

func (s *Store) Sealed(conv string) *Pointer

Sealed is where a conversation went, nil when it did not.

Jump to

Keyboard shortcuts

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