process

package
v0.54.3 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ModeFollowUp queues the message for the turn after the one running right
	// now; a client that sends no mode at all asks for this.
	ModeFollowUp = "follow_up"
	// ModeSteer asks the server to insert the message into the turn running right
	// now, and to queue it for the next turn when there is none (design
	// "send:--steer").
	ModeSteer = "steer"
)

Delivery modes of a Request (Request.Mode).

View Source
const (
	// StateQueued is a message waiting for the next turn of the receiver.
	StateQueued = "queued"
	// StateSteered is a message inserted into the turn running right now.
	StateSteered = "steered"
	// StateProcessed is a message whose turn completed: it ran exactly once.
	StateProcessed = "processed"
	// StateFailed is a message whose turn failed or was cancelled: it did not run
	// and is not retried automatically (design D2).
	StateFailed = "failed"
	// StateHeld is a message a failed turn moved to the person's next turn.
	StateHeld = "held"
	// StateDiscarded is a message the receiver dropped at exit: it never ran.
	StateDiscarded = "discarded"
)

States of one message in its receiving process (Response.State and the status query; design session-message-delivery D2/D3).

View Source
const FeatureHops = "hops"

FeatureHops is the Record.Features entry of a process whose chat understands Request.Hops: it holds a message that arrived at the automatic-reply limit instead of starting a turn. A record without it belongs to an older version, which ignores the field and starts a turn every time (design session_message "兼容").

View Source
const FeatureImages = "images"

FeatureImages is the Record.Features entry of a process that accepts Request.Images (`suga send --image`).

View Source
const MaxQueue = 8
View Source
const SessionFromPrefix = "session:"

SessionFromPrefix starts Request.From of a message one suga session sends to another ("session:<full session ID>"): the receiver shows it as a message of a peer session, not as a person's instruction.

View Source
const TypeStatus = "status"

TypeStatus is the Request.Type that asks for the state of one message ID (`session_message action=status`, design session-message-delivery D3).

Variables

View Source
var ErrAmbiguous = errors.New("session selector matches multiple processes")
View Source
var ErrDiscarded = errors.New("message discarded before it ran")

ErrDiscarded is the error a deliver func reports on a settled channel for a message dropped at exit.

View Source
var ErrFailed = errors.New("the turn carrying the message failed")

ErrFailed is the error a deliver func reports on a settled channel for a message whose turn failed or was cancelled: it did not run and is not retried (design session-message-delivery D2).

View Source
var ErrHeld = errors.New("message held for the person's next turn")

ErrHeld is the error a deliver func reports on a settled channel for a message a failed turn moved to the person's next turn (StateHeld): it runs there once the person writes, never on its own.

View Source
var ErrImageRejected = errors.New("delivered image rejected")

ErrImageRejected is what a receiver reports when it refuses the images of a request (a missing file, a sha256 that does not match what the sender named): the whole message is refused, nothing is delivered.

View Source
var ErrImagesUnsupported = errors.New("receiving process does not support images")

ErrImagesUnsupported is what Send returns when the receiving process cannot take the request's images (an older version): nothing was delivered.

View Source
var ErrNotOnline = errors.New("session process is not online")
View Source
var ErrQueueFull = errors.New("delivery queue is full")

ErrQueueFull reports a full delivery queue (of the running turn's steers, or of the messages waiting for the next turn): the sender is told to try again later instead of queueing without bound.

View Source
var ErrSessionClosed = errors.New("session is closing")

ErrSessionClosed is returned by a deliver func that no longer accepts messages (chat is exiting).

View Source
var ErrSessionLocked = errors.New("session is locked by another Suga process")
View Source
var ErrUnknownMessage = errors.New("message ID unknown to the receiving process")

ErrUnknownMessage is what Status reports for an ID the receiving process does not know: the message belongs to another process, or its chat restarted.

Functions

func NewShortName

func NewShortName(dir string, taken func(string) bool, suffix SuffixSource) string

NewShortName returns the short name of a chat process working in dir: the cleaned directory part plus a random suffix, retried while taken reports that the candidate is in use by another live chat process (nil taken means nothing is in use). After shortNameAttempts tries it returns a name with a longer suffix: a name is always needed, and two extra characters make a collision practically impossible.

func RandomSuffix

func RandomSuffix() string

RandomSuffix returns shortNameSuffixLen random characters of the short name alphabet: 1296 possible suffixes.

func SecureDir

func SecureDir(dir string) error

SecureDir restricts an existing directory to the current user: 0700 on Unix, a protected inheritable DACL (current user + SYSTEM) on Windows, so files created inside later get the same restriction.

func ShortNamePrefix

func ShortNamePrefix(dir string) string

ShortNamePrefix cleans dir down to the directory part of a short name: the base name, lower cased, everything outside [a-z0-9-] dropped and the result cut to shortNameMaxDirLen characters (without leaving a "-" glued to the suffix). An empty result falls back to shortNameFallback.

func Status

func Status(record Record, id string) (string, error)

Status asks one running process for the state of a message ID (`suga send --id`, session_message action=status). ErrUnknownMessage means the process never saw the ID: it belongs to another process, or the chat restarted (design session-message-delivery D3).

func TakenNames

func TakenNames(records []Record, ownPID int) func(string) bool

TakenNames returns a predicate reporting whether a short name is already used by another live chat process. ownPID's own record (the process that is about to register) is ignored, and so are records without a name (sessions that started before short names existed). Names compare without case, the same way Resolve matches them.

Types

type DeliverFunc

type DeliverFunc func(mode, text, from string) (Delivery, error)

DeliverFunc hands one message to the process the server belongs to. mode is the Request.Mode of the sender (ModeFollowUp when it sent none).

type DeliverImagesFunc

type DeliverImagesFunc func(mode, text, from, fromName string, hops int, images []ImageRef) (Delivery, <-chan error, error)

DeliverImagesFunc is a DeliverWaitFunc that also receives the request's FromName, Hops and images (Record.Features carrying FeatureImages / FeatureHops). A server started without one answers images requests with "images_unsupported", so an old receiver never takes the text and drops the pictures.

type DeliverMessageFunc

type DeliverMessageFunc func(req DeliverRequest) (Delivery, <-chan error, error)

DeliverMessageFunc is what a receiver that knows message IDs registers: it takes the whole DeliverRequest and reports the final fate of an accepted message on the settled channel (nil processed, ErrFailed, ErrHeld, ErrDiscarded).

type DeliverRequest

type DeliverRequest struct {
	Mode, Text, From, FromName string
	Hops                       int
	Images                     []ImageRef
	// ID and WaitProcessed decide which receipt the receiver sends: the ID is
	// recorded in the state table, and WaitProcessed defers the receipt to the end
	// of the message's turn.
	ID            string
	WaitProcessed bool
}

DeliverRequest is one incoming request as a receiver that knows message IDs sees it: the fields of Request a chat reads, including the sender's ID and which receipt it asked for (design session-message-delivery D1).

type DeliverWaitFunc

type DeliverWaitFunc func(mode, text, from string) (Delivery, <-chan error, error)

DeliverWaitFunc is a DeliverFunc that can also report the final fate of an accepted message: settled (may be nil) yields nil once the message is delivered or starts a turn (OK), or an error if it is discarded before it ran.

type Delivery

type Delivery struct {
	Queued  bool
	Steered bool
	// Warning is what the receiver did to accept the message that the sender
	// should show (an empty one says nothing).
	Warning string
}

Delivery is the acknowledgement of one accepted message: exactly one of Queued (it waits for its own turn, the default) and Steered (it went into the turn running right now) is set. A sender may wait on both.

type ImageRef

type ImageRef struct {
	// Ref is the part reference below the session directory, images/<sha256>.<ext>.
	Ref       string `json:"ref"`
	SHA256    string `json:"sha256"`
	MediaType string `json:"media_type,omitempty"`
	Width     int    `json:"width,omitempty"`
	Height    int    `json:"height,omitempty"`
}

ImageRef names one image `suga send --image` delivers: the sender writes the file into the target session's images directory and the request carries the reference only (the request body stays far below the 1 MiB limit, design D1). The receiver checks the file and its sha256 before the picture enters the message.

type Record

type Record struct {
	PID       int    `json:"pid"`
	SessionID string `json:"session_id"`
	// Name is the session's short name ("<workspace directory>-k7"), the address
	// `suga send --session <name>` accepts; empty in records of older versions,
	// which stored the first message as the name.
	Name      string    `json:"name"`
	CWD       string    `json:"cwd"`
	Kind      string    `json:"kind"`
	Socket    string    `json:"socket"`
	StartedAt time.Time `json:"started_at"`
	// ProcStart is the OS start time of PID; it tells a reused PID apart from this process.
	ProcStart string `json:"proc_start,omitempty"`
	Host      string `json:"host"`
	State     string `json:"state"`
	// Features lists what this process accepts beyond plain text (FeatureImages
	// for `suga send --image`). A record written by an older version has no
	// field, and an older receiver would silently drop an images request, so a
	// sender checks the feature before it sends anything (design send --image D2).
	Features []string `json:"features,omitempty"`
}

func List

func List(root string) ([]Record, error)

func Resolve

func Resolve(records []Record, selector string) (Record, error)

Resolve picks the live process a selector names. Three stages, each only ambiguous within itself: an exact session ID, then an exact short name (ignoring case), then a session ID prefix. The order matters, a full ID that is also another session's prefix or short name never turns ambiguous, and a short name that is also a prefix of several IDs still addresses one process.

func (Record) HasFeature

func (r Record) HasFeature(feature string) bool

HasFeature reports whether the record declares feature in its Features.

type Request

type Request struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id,omitempty"`
	Text      string `json:"text,omitempty"`
	From      string `json:"from,omitempty"`
	// FromName is the short name of the sender when From names a session
	// ("session:<id>"): the receiver shows it instead of the raw id. An older
	// server ignores the field.
	FromName string `json:"from_name,omitempty"`
	// Hops is how many automatic replies this message is away from the person who
	// started the exchange: 0 for a message typed at a keyboard or sent by `suga
	// send` on the command line, h+1 for a message a session sent during a turn
	// that a hops-h message started (design session_message D3). An older server
	// ignores it; its Record.Features then lacks FeatureHops.
	Hops int `json:"hops,omitempty"`
	// Wait asks the server to keep the connection open after a "queued"/"steered" acknowledgement and
	// send a second Response once the message is delivered or starts a turn (OK) or is discarded (Error).
	Wait bool `json:"wait,omitempty"`
	// Mode is how the message is delivered: ModeSteer inserts it into the turn running
	// right now, anything else (an absent field included, the shape every older
	// client sends) queues it for the next turn.
	Mode string `json:"mode,omitempty"`
	// Images are the pictures delivered with the text, as references only. An
	// older server ignores the unknown field, which the sender's feature check
	// prevents (Record.Features).
	Images []ImageRef `json:"images,omitempty"`
	// ID is the sender's message ID: a message whose ID the receiver already took
	// is not queued a second time, and the ID names the message in a receipt and in
	// a status query (design session-message-delivery D2). An older server ignores
	// the unknown field, so the message is delivered as before.
	ID string `json:"id,omitempty"`
	// WaitProcessed asks for the receipt of the message's terminal state (processed,
	// failed, held or discarded) instead of the one Wait reports, which is sent when
	// the message starts a turn (design D4: the semantics of Wait do not change).
	WaitProcessed bool `json:"wait_processed,omitempty"`
}

Request is one message or one status query a sender hands to a receiver.

type Response

type Response struct {
	OK bool `json:"ok"`
	// Queued and Steered are the acknowledgement of an accepted message: it waits
	// for the next turn, or it went into the turn running right now (an older
	// server never sets Steered).
	Queued  bool   `json:"queued,omitempty"`
	Steered bool   `json:"steered,omitempty"`
	Error   string `json:"error,omitempty"`
	// Warning reports something the receiver did to accept the message that the
	// sender should show (the model cannot see images, so they became a note).
	Warning string `json:"warning,omitempty"`
	// MessageID echoes Request.ID, and State says what happened to that message:
	// queued or steered in the first answer, processed, failed, held or discarded in
	// the second. Both stay empty for a request that names no ID, so the answers of
	// an older client are byte-identical to the ones this version always sent.
	MessageID string `json:"message_id,omitempty"`
	State     string `json:"state,omitempty"`
}

func Send

func Send(record Record, request Request) (Response, error)

type Server

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

func Start

func Start(root, sessionID, name, cwd string, deliver DeliverFunc) (*Server, error)

func StartFeatures

func StartFeatures(root, sessionID, name, cwd string, features []string, deliver DeliverFunc) (*Server, error)

StartFeatures is Start with the Record.Features the process declares: the features a sender checks before it relies on them (FeatureImages).

func StartMessages

func StartMessages(root, sessionID, name, cwd string, features []string, deliver DeliverMessageFunc, status StatusFunc) (*Server, error)

StartMessages is the receiver of a process that knows message IDs: deliver takes the whole DeliverRequest (so the ID and the receipt choice reach the chat) and status answers Request.Type == TypeStatus for this process (design session-message-delivery D1/D3).

func StartWait

func StartWait(root, sessionID, name, cwd string, deliver DeliverWaitFunc) (*Server, error)

func StartWaitImages

func StartWaitImages(root, sessionID, name, cwd string, features []string, deliver DeliverImagesFunc) (*Server, error)

StartWaitImages is StartWait with the Record.Features the process declares and a deliver func that also takes the request's images (`suga send --image`).

func (*Server) Close

func (s *Server) Close() error

func (*Server) Record

func (s *Server) Record() Record

func (*Server) SetBusy

func (s *Server) SetBusy(busy bool) error

type SessionLock

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

func AcquireSessionLock

func AcquireSessionLock(root, sessionID string, wait time.Duration) (*SessionLock, error)

AcquireSessionLock holds an OS file lock (flock / LockFileEx) on <root>/<session>.lock. The OS releases it when the owner exits, so a crashed owner never needs PID-based reclaiming, and two contenders can never both win. The JSON content is diagnostic only.

func AcquireSessionLockContext

func AcquireSessionLockContext(ctx context.Context, root, sessionID string, wait time.Duration) (*SessionLock, error)

AcquireSessionLockContext is AcquireSessionLock whose wait aborts as soon as ctx is cancelled (Ctrl-C / SIGTERM), returning ctx.Err() instead of sleeping out the timeout.

func (*SessionLock) Close

func (l *SessionLock) Close() error

type StatusFunc

type StatusFunc func(id string) (state string, ok bool)

StatusFunc answers Request.Type == TypeStatus: the state of one message ID in this process, ok=false for an ID it never saw (a restart, or a message of another process; design session-message-delivery D3).

type SuffixSource

type SuffixSource func() string

SuffixSource returns one random name suffix of shortNameSuffixLen characters. It is a parameter so tests can inject a deterministic source.

Jump to

Keyboard shortcuts

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