Documentation
¶
Overview ¶
Package msg is otag's durable message outbox (phase 4, docs/MESSAGES.md): messages, their per-recipient deliveries and the delivery state machine.
Mutating functions take a *sql.Tx opened with BEGIN IMMEDIATE (db.DB.Tx); every state change is a compare-and-swap on message_deliveries.version (or messages.closed_at) plus an events row in that tx. A lost CAS means another path won; it is a no-op, never an error. The package never talks to a harness: P3's dispatcher and the hook bridge claim attempts here, deliver outside the transaction and settle them here.
Index ¶
- Constants
- func AddressedTo(ctx context.Context, q db.Querier, r Reader, id int64) (bool, error)
- func AwaitsAnswer(ctx context.Context, q db.Querier, taskID, runID string) (bool, error)
- func CloseAsks(ctx context.Context, tx *sql.Tx, taskID, reason string, a Actor) error
- func Due(ctx context.Context, q db.Querier, now time.Time, limit int) ([]string, error)
- func DueRuns(ctx context.Context, q db.Querier, in DueInput) ([]string, error)
- func HasOpenAsk(ctx context.Context, q db.Querier, taskID string) (bool, error)
- func HasOpenAskBy(ctx context.Context, q db.Querier, taskID, runID string) (bool, error)
- func Headline(m Message) string
- func MarkRead(ctx context.Context, tx *sql.Tx, ids []int64, reader Reader, a Actor) ([]int64, error)
- func MarkUnknown(ctx context.Context, tx *sql.Tx, runID, channel, nonce, reason string, a Actor) ([]int64, error)
- func Marker(deliveryID int64) string
- func NewNonce() string
- func ProofTimeout(ctx context.Context, tx *sql.Tx, before time.Time, channel string, limit int, ...) ([]int64, error)
- func Prove(ctx context.Context, tx *sql.Tx, in ProveInput, a Actor) ([]int64, error)
- func Render(items []Item, maxChars int) string
- func ScanMarkers(payload []byte) []int64
- type Actor
- type AskFilter
- type AskInput
- type Attempt
- type AttemptResult
- type ClaimInput
- type Delivery
- type Dispatcher
- type DueInput
- type ExpireResult
- type From
- type Item
- type Message
- func Ask(ctx context.Context, tx *sql.Tx, in AskInput, a Actor) (*Message, bool, error)
- func Get(ctx context.Context, q db.Querier, id int64) (*Message, error)
- func Reply(ctx context.Context, tx *sql.Tx, in ReplyInput, a Actor) (*Message, bool, error)
- func Send(ctx context.Context, tx *sql.Tx, in SendInput, a Actor) (*Message, bool, error)
- type NeedAnswer
- type NeedBlocked
- type NeedDelivery
- type NeedIdle
- type NeedQuestion
- type Needs
- type OpenAsk
- type ProveInput
- type Reader
- type Recipient
- type ReplyInput
- type RunDispatcher
- type SendInput
- type Sender
- type SettleInput
- type SettleResult
- type To
Constants ¶
const ( DefaultMaxItems = 10 // deliveries one attempt carries DefaultMaxChars = 9000 // rendered text of one attempt (Claude caps hook context near 10k) DefaultMaxAttempts = 5 // definite not-sent failures before dead )
Defaults of Claim and Settle.
const ( Sent = "sent" // the harness accepted the text; proof still to come NotSent = "not_sent" // definitely not delivered (adapter.ErrNotSent): queued again, or dead NotReady = "not_ready" // definitely not delivered, only "not now" (adapter.ErrNotReady): queued again soon, the attempt given back, never dead Unknown = "unknown" // ambiguous: outcome_unknown, never re-sent automatically ChannelProved = "delivered" // the channel itself proves delivery (hook output produced in time) )
Settle outcomes.
const ( KindQuestion = "question" KindInfo = "info" KindAnswer = "answer" KindCommand = "command" )
Message kinds.
const ( SenderRun = "run" // verified with the run's token SenderHuman = "human" // a person (or a plain coordinator session) at the CLI SenderSystem = "system" // the daemon )
Sender kinds.
const ( ToRun = "run" // a run; follows its task to the next run if it ends undelivered ToTask = "task" // whichever run of the task takes it first (its next run when none is live) ToRole = "role" // the project's live coordinator, else the human ToHuman = "human" // read with `otag inbox` outside a run )
Recipient kinds.
const ( Queued = "queued" // waiting for a channel Dispatched = "dispatched" // an attempt (nonce) is in flight or sent without proof Delivered = "delivered" // proven: in the session Read = "read" // read with otag inbox, or the recipient replied OutcomeUnknown = "outcome_unknown" // may or may not have arrived; never re-sent automatically Expired = "expired" // its time passed, or the question was answered or closed Dead = "dead" // undeliverable: target gone, or too many definite failures )
Delivery states.
const ( ProofMarker = "marker" // the delivery's marker in a hook payload of its run ProofReceipt = "receipt" // a harness ref matching the attempt's receipt ProofChannel = "channel" // the channel itself proved it (hook output produced, Stop continued) ProofCLI = "cli" // the recipient read it with otag inbox (or replied) )
Proof kinds (message_deliveries.proof).
const ( ClosedAnswered = "answered" ClosedAskerDone = "asker_done" ClosedAskerFailed = "asker_failed" ClosedSuperseded = "superseded" // a later run of the task asked anew ClosedCancelled = "cancelled" )
Close reasons of a question.
const MaxBody = 32 * 1024
MaxBody is the largest message body in bytes.
const ReasonProofTimeout = "no proof of delivery after the timeout"
ReasonProofTimeout is the last_error of a delivery ProofTimeout made unknown. A late correlated proof of the same attempt still delivers it (Prove: Channel with Nonce).
const RoleCoordinator = "coordinator"
RoleCoordinator is the only role recipient: the coordinator of the project.
Variables ¶
This section is empty.
Functions ¶
func AddressedTo ¶
AddressedTo reports whether message id has a delivery for reader in any state: one bound or addressed to its run, or addressed to its task (a child replies only to those). For the human: a human or coordinator-role delivery.
func AwaitsAnswer ¶
AwaitsAnswer reports whether run runID of task taskID still waits for an answer: its ask is open, or its latest ask is answered but no copy of the answer has been delivered or read yet (queued, in flight, unknown, expired or dead: `otag needs` shows the last three). A closing harness dialog of runID leaves the task waiting then; the answer reaching the run moves it (received).
func CloseAsks ¶
CloseAsks closes the open ask of task taskID (P4: the asker finished with done or fail: ClosedAskerDone, ClosedAskerFailed; a cancelled task: ClosedCancelled). Its queued deliveries expire. No open ask is a no-op.
func Due ¶
Due returns the runs that have queued deliveries an injected channel could take now (run idle or running, no injected attempt in flight), fairly ordered: least recently served by an injected attempt first, then by the oldest due delivery. P3's daemon step walks them in this order within its time budget. limit 0 = 50.
func HasOpenAsk ¶
HasOpenAsk reports whether task taskID has an open ask. P3: a closing harness dialog must leave such a task waiting.
func HasOpenAskBy ¶
HasOpenAskBy reports whether task taskID has an open ask from run runID. A closing harness dialog of runID leaves the task waiting only for its own ask: an ask of an earlier run of the task that has gone does not hold the new run's task.
func MarkRead ¶
func MarkRead(ctx context.Context, tx *sql.Tx, ids []int64, reader Reader, a Actor) ([]int64, error)
MarkRead marks deliveries ids as read by reader (`otag inbox`): queued ones are taken directly (channel cli); delivered, outcome_unknown and hook-channel dispatched ones too. A dispatched injected delivery is skipped: its attempt holds the run's injected slot until it is settled or proven. Deliveries the reader may not read, or that are read or closed already, are skipped too. It returns the ids it marked.
A run reader must still be live, checked in tx: a stopping, parked or ended run takes nothing (CONFLICT), so its messages stay queued for the task's next run (a parked run's answer must stay queued for the resume).
func MarkUnknown ¶
func MarkUnknown(ctx context.Context, tx *sql.Tx, runID, channel, nonce, reason string, a Actor) ([]int64, error)
MarkUnknown moves the run's dispatched deliveries on channel (only attempt nonce, when set) to outcome_unknown. P3: a Stop without stop_hook_active means the previous Stop block was not continued (Esc, kill): MarkUnknown(run, adapter.ChanStopBlock, "").
func ProofTimeout ¶
func ProofTimeout(ctx context.Context, tx *sql.Tx, before time.Time, channel string, limit int, a Actor) ([]int64, error)
ProofTimeout moves deliveries dispatched before `before` without proof to outcome_unknown (never re-sent automatically; `otag needs` shows them). channel "" = every channel. It returns the ids it moved.
func Prove ¶
Prove delivers the run's deliveries that the input proves; it returns their ids. Only the run's own deliveries are proven: a marker of another run's delivery is ignored. A marker proves a delivery that is dispatched or outcome_unknown (late proof), or queued after an attempt reported not sent. A ref that matches nothing yet is kept (message_proofs) so the attempt's Settle(Sent) with that receipt proves it.
func Render ¶
Render renders items for a session, oldest first, each starting with its marker:
[otag#d130] answer #57 to question #42, from the coordinator (run OTAG-coord-r1): <body> --- [otag#d131] question #44 from run OTAG-9-r1 (task OTAG-9): <body> Reply with: otag reply 44 "<answer>"
When the text would exceed maxChars (0 = no limit), bodies are cut evenly; the markers and headers always stay. Pure.
func ScanMarkers ¶
ScanMarkers returns the delivery ids whose markers appear in payload (a raw hook payload: the UserPromptSubmit prompt, a turn input), sorted and without duplicates.
Types ¶
type Actor ¶
type Actor struct {
Name string // user:<name> | run:<id> | daemon
Source string // events.source: cli | hook:<harness> | daemon
}
Actor is who changes messages; recorded on events.
type AskInput ¶
type AskInput struct {
RunID string // the asking run (verified by the caller)
ClientMsgID string
Body string
To Recipient // zero = the coordinator (the human when none is live)
Park bool // `otag ask --park`: P4 parks the run once it is idle
}
AskInput describes `otag ask`.
type Attempt ¶
Attempt is a claimed delivery attempt: its deliveries are dispatched with Nonce.
func Claim ¶
Claim takes the run's due queued deliveries (oldest first) into one attempt: queued -> dispatched with a fresh nonce, the channel and attempts+1, binding them to the run. It returns nil when there is nothing to claim or the run cannot take this channel now: a gone run; an injected channel (other than the launch prompt) unless the run is idle or running; the launch prompt unless it is queued or starting; and an injected channel while another injected attempt of the run is still dispatched (one in flight per run). Hook channels take any run that is not gone.
type AttemptResult ¶
type AttemptResult struct {
Delivery int64 `json:"delivery"`
Result string `json:"result"` // dispatched | delivered | queued | skipped | failed
Reason string `json:"reason,omitempty"`
}
AttemptResult is the outcome of one Dispatcher.Attempt.
type ClaimInput ¶
type ClaimInput struct {
RunID string
Channel string // adapter.Chan*; adapter.Injected decides serialization
Max int // deliveries in this attempt; 0 = DefaultMaxItems
MaxChars int // rendered text budget; 0 = DefaultMaxChars (the first item always fits; Render truncates it)
Now time.Time // zero = now
IDs []int64 // only these deliveries (still subject to every other rule); nil = any
// Status, when set, is the run status the caller planned the attempt for (say idle
// for a Claude mod submit): the claim takes nothing unless the run is still in it,
// checked in the claim's own transaction.
Status string
}
ClaimInput describes one delivery attempt into a run.
type Delivery ¶
type Delivery struct {
ID int64 `json:"id"`
MessageID int64 `json:"message"`
ProjectID int64 `json:"-"`
To To `json:"to"`
State string `json:"state"`
Channel *string `json:"channel"`
Injected bool `json:"injected"`
Nonce *string `json:"nonce"`
Attempts int `json:"attempts"`
Receipt *string `json:"receipt"`
Proof *string `json:"proof"`
ProofRef *string `json:"proof_ref"`
NextAttemptAt *string `json:"next_attempt_at"`
LastError *string `json:"last_error"`
DispatchedAt *string `json:"dispatched_at"`
DeliveredAt *string `json:"delivered_at"`
ReadAt *string `json:"read_at"`
ClosedAt *string `json:"closed_at"`
Version int64 `json:"version"`
CreatedAt string `json:"created_at"`
}
Delivery is one recipient's copy of a message.
func GetDelivery ¶
GetDelivery returns one delivery.
type Dispatcher ¶
type Dispatcher interface {
Attempt(ctx context.Context, deliveryID int64) AttemptResult
}
Dispatcher makes one synchronous delivery attempt of a queued delivery: Claim, the adapter call outside any transaction, Settle. P3 implements it (run package); the CLI calls it after send, reply and ask commit, the daemon once per due delivery.
type DueInput ¶
type DueInput struct {
Now time.Time // zero = now
Limit int // 0 = 50
// Eligible, when set, drops the runs no injected channel can serve now (a busy
// Claude run, Codex in hooks mode, a harness without injected delivery) before
// the order and the limit: such a run is never served by an injected attempt, so
// it would sort first forever and, past the limit, starve the others. It is asked
// only about runs that have due deliveries.
Eligible func(runID string) bool
}
DueInput selects the runs of DueRuns.
type ExpireResult ¶
type ExpireResult struct {
Expired int `json:"expired"`
Dead int `json:"dead"`
Proofs int `json:"proofs"` // unmatched early proofs dropped
}
ExpireResult counts what Expire changed.
func Expire ¶
func Expire(ctx context.Context, tx *sql.Tx, now time.Time, limit int, a Actor) (ExpireResult, error)
Expire sweeps queued deliveries: past their message's expires_at -> expired; whose target can never take them -> dead (a task that is done or cancelled, a task-less run that has gone). It also drops early proofs nobody claimed within an hour.
type From ¶
type From struct {
Kind string `json:"kind"`
Run *string `json:"run"`
Task *string `json:"task"` // the sender run's task
Role *string `json:"role"` // the sender run's role
Actor string `json:"actor"`
}
From describes the sender.
type Item ¶
Item is a message as one recipient sees it: inbox entries and claimed attempts.
func Inbox ¶
Inbox returns what reader may read, oldest first: the unread deliveries (queued, dispatched, delivered, outcome_unknown), or with all the latest limit of any state. limit 0 = 50.
func Take ¶
Take selects reader's unread deliveries (as Inbox, oldest first, up to limit) and marks them read in the same transaction: it returns only the items it took, with their deliveries as they are now. A delivery a dispatcher claimed in the meantime is never returned, so an agent never sees a message twice (`otag inbox`).
type Message ¶
type Message struct {
ID int64 `json:"id"`
ClientMsgID string `json:"client_msg_id"`
Project string `json:"project"`
ProjectID int64 `json:"-"`
Kind string `json:"kind"`
From From `json:"from"`
Task *string `json:"task"`
ReplyTo *int64 `json:"reply_to"`
Body string `json:"body"`
Ask bool `json:"ask"`
Park bool `json:"park"`
ClosedAt *string `json:"closed_at"`
ClosedReason *string `json:"closed_reason"`
AnswerID *int64 `json:"answer_id"`
ExpiresAt *string `json:"expires_at"`
CreatedAt string `json:"created_at"`
Deliveries []Delivery `json:"deliveries,omitempty"`
}
Message is one message with its deliveries (JSON shape of docs/MESSAGES.md).
func Ask ¶
Ask stores a question from a run about its task and moves the task running -> waiting in the same transaction. A task has at most one open ask: the same question again from the same run returns the open one (replayed); an open ask of an earlier run of the task that has gone is closed as superseded; anything else is CONFLICT.
func Reply ¶
Reply answers (or follows up on) message in.To. The reply goes to its sender: a run that can still take messages, else that run's open task, else (a coordinator run) the coordinator role; a human's message to the human, the daemon's to the coordinator. Answering a question closes it in the same transaction and expires its other queued copies; the replier's own copy becomes read. The asking task goes back to running only when the answer reaches its run (see Prove, Settle, MarkRead).
type NeedAnswer ¶
type NeedAnswer struct {
Task string `json:"task"`
Title string `json:"title"`
Question int64 `json:"question"`
Answer int64 `json:"answer"`
Delivery Delivery `json:"delivery"`
Action string `json:"action"`
}
NeedAnswer is a waiting task whose ask is answered but whose answer is neither delivered nor read and will not get there by itself: no run of the task can take it (the asker ended or parked), or its delivery is expired, outcome_unknown or dead.
type NeedBlocked ¶
type NeedBlocked struct {
Task string `json:"task"`
Title string `json:"title"`
Reason string `json:"reason"`
Action string `json:"action"`
}
NeedBlocked is a blocked task.
type NeedDelivery ¶
type NeedDelivery struct {
Delivery Delivery `json:"delivery"`
Message int64 `json:"message"`
Body string `json:"body"`
Action string `json:"action"`
}
NeedDelivery is a delivery whose outcome needs a person.
type NeedIdle ¶
type NeedIdle struct {
Run string `json:"run"`
Task string `json:"task"`
Title string `json:"title"`
IdleSince string `json:"idle_since"`
IdleS int64 `json:"idle_s"`
Action string `json:"action"`
}
NeedIdle is a child or review run that is idle without an open ask.
type NeedQuestion ¶
type NeedQuestion struct {
Message *Message `json:"message"`
To string `json:"to"` // human | coordinator <run> | coordinator (none live: human)
AgeS int64 `json:"age_s"`
Action string `json:"action"`
}
NeedQuestion is an open question to the human or the coordinator.
type Needs ¶
type Needs struct {
Questions []NeedQuestion `json:"questions"` // open questions to the human or the coordinator
Deliveries []NeedDelivery `json:"deliveries"` // outcome_unknown or dead deliveries
Blocked []NeedBlocked `json:"blocked"` // blocked tasks
Idle []NeedIdle `json:"idle"` // idle child/review runs without an open ask
Answers []NeedAnswer `json:"answers"` // waiting tasks whose answer has not reached a run
}
Needs is what waits for the human or the coordinator (`otag needs`).
type OpenAsk ¶
type OpenAsk struct {
Message *Message `json:"message"`
Asker string `json:"asker"` // the run that asked
AskerStatus string `json:"asker_status"`
AskerEndedReason *string `json:"asker_ended_reason"` // "parked" once P4 parked it
TaskStatus string `json:"task_status"`
AgeS int64 `json:"age_s"`
}
OpenAsk is an open `otag ask` question with its asker.
type ProveInput ¶
type ProveInput struct {
RunID string
Markers []int64 // delivery ids whose marker the payload carries (ScanMarkers)
Refs []string // harness refs (HookResult.Refs), matched with receipt_ref or the nonce
// Channel proves every dispatched delivery of the run on this channel (a Stop with
// stop_hook_active proves the Stop block). The caller checks the session.
Channel string
EventID int64 // the event carrying the proof, 0 = none
// Nonce, when set, limits every proof above to that attempt (e.g. the Stop block
// whose continuation this Stop is).
Nonce string
}
ProveInput is what a hook (or sidecar) event of a run shows about deliveries.
type Reader ¶
type Reader struct {
ProjectID int64 // the human: 0 = every project
RunID string
TaskID string
Role string
}
Reader is whoever reads deliveries: a run (RunID, its TaskID and Role, see ReaderFor) or, with RunID "", the human.
type Recipient ¶
type Recipient struct {
Kind string // ToRun | ToTask | ToRole | ToHuman
Ref string // run id | task id | RoleCoordinator | "human"
}
Recipient is an address resolved in a project.
type ReplyInput ¶
type ReplyInput struct {
ClientMsgID string
From Sender
To int64 // the message replied to
Body string
Kind string // "" = answer to an open question, info otherwise; KindInfo for a follow-up
ExpiresAt string
}
ReplyInput describes `otag reply`.
type RunDispatcher ¶
type RunDispatcher interface {
AttemptRun(ctx context.Context, runID string) []AttemptResult
}
RunDispatcher is optionally implemented by a Dispatcher that attempts per run (one attempt, ClaimInput{RunID}, may carry several of the run's queued deliveries). The CLI prefers it: one AttemptRun per run the new message's deliveries are bound to. It returns one result per delivery of the run it looked at.
type SendInput ¶
type SendInput struct {
ProjectID int64
// ClientMsgID is the durable request identity ("req:<request-id>"); "" = random. A
// second Send with the same id returns the first message (replayed) when it matches,
// REQUEST_ID_REUSED otherwise.
ClientMsgID string
Kind string // default KindInfo; KindAnswer only through Reply
From Sender
TaskID string // the task it is about; "" = the sender run's task
Body string
To []Recipient
ExpiresAt string // "" = never; queued deliveries expire after it
// contains filtered or unexported fields
}
SendInput describes a new message.
type Sender ¶
type Sender struct {
Kind string // SenderRun | SenderHuman | SenderSystem
RunID string // SenderRun
Actor string // run:<id> | user:<name> | daemon
}
Sender is who sends a message. The CLI verifies a run sender with its token before it gets here; msg trusts it.
type SettleInput ¶
type SettleInput struct {
Nonce string
Outcome string // Sent | NotSent | NotReady | Unknown | ChannelProved
Receipt adapter.Receipt // Sent: Ref is stored (and matched with early proofs); Channel replaces the claimed one
Error string
RetryAt time.Time // NotSent: zero = exponential backoff from 10s up to 5m; NotReady: zero = 5s
MaxAttempts int // NotSent: 0 = DefaultMaxAttempts; reaching it makes the delivery dead
}
SettleInput is the outcome of the attempt with Nonce.
type SettleResult ¶
type SettleResult struct {
Changed []int64 `json:"changed"` // deliveries whose state changed
// Stale: no delivery carries Nonce (any more). A late settle of a proven delivery
// (proof before receipt) is not stale: its receipt is still stored.
Stale bool `json:"stale"`
}
SettleResult reports what Settle changed.
func Settle ¶
func Settle(ctx context.Context, tx *sql.Tx, in SettleInput, a Actor) (SettleResult, error)
Settle records the outcome of attempt Nonce for the deliveries that carry it. dispatched: Sent keeps it dispatched with the receipt (delivered at once when the receipt's proof arrived first); NotSent requeues it (dead after MaxAttempts); NotReady requeues it soon and gives the attempt back (never dead); Unknown -> outcome_unknown; ChannelProved -> delivered. outcome_unknown (a proof timeout passed during the call): Sent stores the receipt for a late proof, NotSent and NotReady requeue, ChannelProved delivers. delivered or read: only a missing receipt is stored. Other states are left alone.