Documentation
¶
Index ¶
- Constants
- Variables
- func BudgetFor(ctx int64, p KeepalivePrice) float64
- func BuildIdentity() string
- func BusyCard(supervised bool, status string, idle time.Duration, activity string) bool
- func CapWrapWait(n time.Duration) time.Duration
- func CaptureLine(token string) string
- func CaptureToken(gen uint64) string
- func ClassifyReceipt(r *ForkReceipt, runErr error, ctx int64) string
- func ColdHandoffOff(t *store.Task) bool
- func ColdSpentKey(taskID string) string
- func ContainsID(ids []string, id string) bool
- func FitReasons(head string, whys []string, tail string) string
- func HandoffName(t *store.Task) string
- func HashExecutable() string
- func IsSharedErr(err error) bool
- func KeepFlags(args []string) []string
- func LocalHasHooks(cwd string) bool
- func NcJSON(w http.ResponseWriter, code int, v any)
- func NewContextCaptureText(file, token string) string
- func NewContextLimitPrompt(path, bin string, noShell bool, tokens, limit int64) string
- func NewContextView(c *NewContext) map[string]any
- func NewContextWakeText(path string) string
- func NewHoldID() string
- func ParseSeconds(v string) time.Duration
- func ReceiptCost(r *ForkReceipt, p KeepalivePrice) float64
- func RefreshDueAt(expiry time.Time) time.Time
- func ReplyContent(raw json.RawMessage) (string, bool)
- func RestartWrapNudge(path, bin string) string
- func RestartWrapPrompt(path, bin string) string
- func RestartWrapWake(path string, wrote bool, outcome string) string
- func RunForkProcess(ctx context.Context, spec ForkSpec, ...) ([]byte, error)
- func ScanMainReplies(r io.Reader, fn func(*MainReply)) (int64, error)
- func ScanReplies(r io.Reader, fn func(*MainReply)) (int64, error)
- func StampHandoff(path string, now time.Time) string
- func WakeView(w *store.RestartWake) map[string]any
- type Activity
- type Calls
- type Config
- type ForkReceipt
- type ForkSpec
- type HoldStart
- type HoldState
- type Keepalive
- func (k *Keepalive) Apply(t *store.Task, outcome string, v Verdict)
- func (k *Keepalive) ClearOnRealTurn(t *store.Task, card *store.KeepaliveCard) *store.KeepaliveCard
- func (k *Keepalive) ColdCheck(t *store.Task, card *store.KeepaliveCard, warming bool)
- func (k *Keepalive) ColdDone(taskID string, replyAt time.Time) bool
- func (k *Keepalive) ColdRearm(taskID string)
- func (k *Keepalive) ColdSpent(taskID string) bool
- func (k *Keepalive) ColdSpentAt(taskID string) (time.Time, bool)
- func (k *Keepalive) Decide(t *store.Task, card *store.KeepaliveCard) Verdict
- func (k *Keepalive) EnsureHookFile() error
- func (k *Keepalive) FollowSession(t *store.Task) *store.Task
- func (k *Keepalive) ForkArgs(sessionID, model string) []string
- func (k *Keepalive) ForkEnv(h *store.Harness, t *store.Task) ([]string, error)
- func (k *Keepalive) Loop(ctx context.Context)
- func (k *Keepalive) ModelArg(taskID, model string) string
- func (k *Keepalive) Refresh(ctx context.Context, t *store.Task, v Verdict)
- func (k *Keepalive) Stop(t *store.Task, state string, v Verdict)
- func (k *Keepalive) StretchState(taskID string, card *store.KeepaliveCard, r *LastReply) (anchor time.Time, rows []*store.KeepaliveRefresh, spent float64, ...)
- func (k *Keepalive) Suspend(reason string)
- func (k *Keepalive) Tick(ctx context.Context)
- func (k *Keepalive) View(taskID string) any
- func (k *Keepalive) ViewOf(t *store.Task, card *store.KeepaliveCard, out *KeepaliveCardView) any
- func (k *Keepalive) ViewTask(t *store.Task) any
- type KeepaliveCardView
- type KeepalivePrice
- type LastReplies
- type LastReply
- type LastReplyEntry
- type MainReply
- type NcJournalRow
- type NcTimings
- type NewContext
- type NewContextHooks
- type NewContextSharedError
- type NewContexts
- func (n *NewContexts) Ack(taskID string) bool
- func (n *NewContexts) Advance(taskID string, gen uint64, step string) bool
- func (n *NewContexts) Arm(taskID string, gen uint64) (armed, changed bool)
- func (n *NewContexts) BeginCaptureOnly(taskID, file, conv string) (uint64, bool)
- func (n *NewContexts) BusyCard() string
- func (n *NewContexts) Claim(taskID string, c *NewContext) (uint64, bool)
- func (n *NewContexts) Clear(taskID string) bool
- func (n *NewContexts) DropMarker(taskID string)
- func (n *NewContexts) DroppedHolds(taskID, conv string) bool
- func (n *NewContexts) Fail(taskID string, gen uint64, reason string) bool
- func (n *NewContexts) Finish(taskID string, gen uint64) bool
- func (n *NewContexts) FinishRecorded(taskID string, gen uint64, record func()) bool
- func (n *NewContexts) Get(taskID string) *NewContext
- func (n *NewContexts) Holding(taskID string) bool
- func (n *NewContexts) HoldsInput(taskID string) bool
- func (n *NewContexts) Kick(taskID string)
- func (n *NewContexts) Mine(taskID string, gen uint64) bool
- func (n *NewContexts) NoteCleared(taskID string, gen uint64)
- func (n *NewContexts) NotePrompt(taskID string, gen uint64, turn int, at time.Time) bool
- func (n *NewContexts) ResumeAcked(taskID, conv string) (uint64, bool)
- func (n *NewContexts) Revive(taskID string) (uint64, bool)
- func (n *NewContexts) SameDirBusy(st *store.Store, task *store.Task) string
- func (n *NewContexts) Save()
- func (n *NewContexts) SeedFailed(taskID string, row NcJournalRow, reason string)
- func (n *NewContexts) SessionStarted(taskID, conv string) bool
- func (n *NewContexts) SetTyping(taskID string, gen uint64, on bool) bool
- func (n *NewContexts) SetWaiting(taskID string, gen uint64, why string) bool
- func (n *NewContexts) StopAll()
- func (n *NewContexts) TypingHeld(taskID string) bool
- func (n *NewContexts) TypingNow(taskID string) bool
- func (n *NewContexts) WaitingForAck(taskID string) bool
- func (n *NewContexts) Writing(taskID string) bool
- type RestartWrap
- func (w *RestartWrap) Ack(taskID string) bool
- func (w *RestartWrap) Begin(cancel context.CancelFunc, deadline time.Time) (*WrapRun, bool)
- func (w *RestartWrap) CancelRunning()
- func (w *RestartWrap) End(rep WrapReport)
- func (w *RestartWrap) Expect(taskID string) chan struct{}
- func (w *RestartWrap) Forget(taskID string)
- func (w *RestartWrap) Waiting(taskID string) bool
- type Service
- func (d *Service) AbortWrapWakes()
- func (d *Service) AtIdlePrompt(taskID string) bool
- func (d *Service) CardNamed(name string) *store.Task
- func (d *Service) CardRunning(taskID string) bool
- func (d *Service) ClearWake(taskID, by string) (bool, error)
- func (d *Service) ColdHandoff(t *store.Task) error
- func (d *Service) ConversationOf(t *store.Task) string
- func (d *Service) CycleAwaitAck(taskID string, gen uint64) error
- func (d *Service) CyclePrompt(taskID string, gen uint64, c *NewContext) error
- func (d *Service) CyclePromptDue(taskID string, c *NewContext) bool
- func (d *Service) DeployHeld(taskID string) bool
- func (d *Service) DeployHold() *store.RoomHold
- func (d *Service) DeployHoldMax() time.Duration
- func (d *Service) DeployHoldNote() string
- func (d *Service) DeployRefusal(h *store.RoomHold) string
- func (d *Service) EndAbandonedNewContexts()
- func (d *Service) FrozenForMove(taskID string) bool
- func (d *Service) HandleHold(w http.ResponseWriter, r *http.Request)
- func (d *Service) HandleNewContext(w http.ResponseWriter, r *http.Request)
- func (d *Service) HandleRestartWake(w http.ResponseWriter, r *http.Request)
- func (d *Service) HandleRestartWrap(w http.ResponseWriter, r *http.Request)
- func (d *Service) HandoffDir(taskID string) (string, error)
- func (d *Service) HandoffPath(t *store.Task) string
- func (d *Service) HandoffWritten(taskID, file string, since time.Time, token string) error
- func (d *Service) HeldBusy(h *store.RoomHold) map[string]string
- func (d *Service) HeldFor(taskID string) any
- func (d *Service) HoldChanged(h *store.RoomHold)
- func (d *Service) HoldLoop(ctx context.Context)
- func (d *Service) HoldTick(now time.Time)
- func (d *Service) HoldView() map[string]any
- func (d *Service) HoldableCards() []string
- func (d *Service) HoldingFrom(taskID, from string) bool
- func (d *Service) HoldingMessages(taskID string) bool
- func (d *Service) JoinWrapUp(ctx context.Context, run *WrapRun) WrapReport
- func (d *Service) KeepaliveAtLaunch(taskID string, h *store.Harness, env map[string]string)
- func (d *Service) KeepaliveSet(taskID string, on bool) (any, error)
- func (d *Service) LaunchHeld(req shared.LaunchRequest) error
- func (d *Service) LiftAtStartup()
- func (d *Service) LiftDeployHold(outcome string) (*store.RoomHold, error)
- func (d *Service) LoadHolds()
- func (d *Service) LoadWakes()
- func (d *Service) NcArm(taskID string, gen uint64) bool
- func (d *Service) NcAwaitArm(taskID string, gen uint64, limit time.Duration) error
- func (d *Service) NcBlocker(taskID string, busy func(string) bool) string
- func (d *Service) NcBusy(taskID string) bool
- func (d *Service) NcBusyAfterAck(taskID string) bool
- func (d *Service) NcCapture(taskID string, gen uint64, file string) (string, error)
- func (d *Service) NcClearLine(taskID string, n int) bool
- func (d *Service) NcType(taskID string, gen uint64, label, text string, limit time.Duration) error
- func (d *Service) NcTypeBusy(taskID string, gen uint64, label, text string, limit time.Duration, ...) error
- func (d *Service) NcWait(taskID string, gen uint64, limit time.Duration, what string, ...) error
- func (d *Service) NewContextFor(taskID string) any
- func (d *Service) NewContextWakeFor(taskID, path string) string
- func (d *Service) NoteWrapGaveUp(t *store.Task, path, what string)
- func (d *Service) PrepareHandoff(t *store.Task) (string, error)
- func (d *Service) QueueWake(taskID, text, by string) (*store.RestartWake, *store.RestartWake, error)
- func (d *Service) ReleaseHeld(taskID string)
- func (d *Service) RoomWord() string
- func (d *Service) RunNewContext(taskID string, gen uint64)
- func (d *Service) RunnerHasNoShell(taskID string) bool
- func (d *Service) SaveNewContextJournal(snap map[string]NcJournalRow)
- func (d *Service) StartDeployHold(in HoldStart) (*store.RoomHold, error)
- func (d *Service) StartNewContext(taskID string) error
- func (d *Service) TryWake(w *store.RestartWake, now time.Time)
- func (d *Service) WakeFor(taskID string) any
- func (d *Service) WakeLoop(ctx context.Context)
- func (d *Service) WakeRunnerReady(w *store.RestartWake, run shared.Runner, now time.Time) bool
- func (d *Service) WakeSawSession(taskID, conv string)
- func (d *Service) WakeTick(now time.Time)
- func (d *Service) WrapCandidate(t *store.Task) bool
- func (d *Service) WrapCard(ctx context.Context, t *store.Task, path string, ack <-chan struct{}) string
- func (d *Service) WrapUpForRestart(ctx context.Context, wait time.Duration, why string) (rep WrapReport)
- func (d *Service) WriteFallbackHandoff(t *store.Task, path string) error
- type UnsavedRefresh
- type Verdict
- type Wakes
- func (wk *Wakes) All() []*store.RestartWake
- func (wk *Wakes) Conversation(taskID string) string
- func (wk *Wakes) Forget(taskID string)
- func (wk *Wakes) Get(taskID string) *store.RestartWake
- func (wk *Wakes) Put(w *store.RestartWake)
- func (wk *Wakes) SawConversation(taskID, conv string)
- func (wk *Wakes) SawSession(taskID string, at time.Time)
- func (wk *Wakes) SessionStarted(taskID string) (time.Time, bool)
- type WrapReport
- type WrapRun
- type WrapTimings
Constants ¶
const ( // keepaliveMargin is how close to expiry a refresh fires. KeepaliveMargin = 5 * time.Minute // keepaliveMinContext is the smallest context worth keeping warm. Below it // a saved wake is worth under $0.40 on Opus 5.5. KeepaliveMinContext = rules.MinContextLimitK * 1000 // keepaliveBudgetFraction is the stop rule: refresh spend since the card // went idle may reach this fraction of one full 1h rehydration of its // context. 1/8 fits the resume data best across models. KeepaliveBudgetFraction = 0.125 // keepaliveWarmRead is the receipt threshold, as a fraction of the card's // context. There is no write threshold: a fork always writes its own tail, // the card's last reply and the prompt, and on a 55k card that tail alone // passed the old 5% while the fork read 99.99%. KeepaliveWarmRead = 0.90 // keepaliveForkTail is the tokens a fork writes at the 1h price on top of its read: the card's last // reply and the prompt, measured near 2,000 in the ledger. KeepaliveForkTail = 2_000 // keepaliveMaxWarms is the warm-ups an idle card gets after its last real turn. The next due time is the // cold handoff, while the cache is still warm. KeepaliveMaxWarms = 2 )
Policy defaults. See the design's "Policy" and "The stop rule".
const ( OutcomeActed = "acted" OutcomeRefused = "refused" OutcomeFailed = "failed" OutcomeWarmed = "warmed" OutcomeMiss = "miss" )
Receipt outcomes, in the order they are tested. See the design's "Reading the receipt".
const ( // NewContextLimit is the cycle's first step: the limit prompt typed, the ack awaited. NewContextLimit = "limit" // NewContextCapture is the idle parking's and the move's capture, which clears nothing. NewContextCapture = "capture" NewContextClear = "clear" NewContextWake = "wake" NewContextFailed = "failed" )
The steps a chip can be on.
const ( SentLines = 8 SentLen = 160 )
sentLines is how many already delivered says the wake lists, newest kept, and sentLen how much of each.
const ( // wakeTickEvery is how often waiting wakes are looked at. The same front // step as the peer backoff, so a wake lands about as soon as the gate opens. WakeTickEvery = 2 * time.Second // wakeSettle is how long after the runner's SessionStart hook a wake waits. // The hook fires as the session starts, which is a moment before its input // box is drawn, and bytes typed before then are lost. WakeSettle = 5 * time.Second // wakeNoHook is how long a runner that never posts SessionStart has to be up // before a wake is typed into it anyway. A runner with no hooks has no other // signal that it is ready. WakeNoHook = time.Minute )
const ( WrapReady = "ready" WrapIdle = "idle" WrapUnanswered = "unanswered" // wrapSkipped is a card that was not prompted: it settled before the prompt was typed, or its runner went. WrapSkipped = "skipped" )
The outcomes of one card.
const ( DeployHoldMaxDefault = 60 * time.Minute // holdTickEvery is how often an expired hold is looked for. HoldTickEvery = 30 * time.Second // maxHoldLine bounds the refusal, reasons cut to fit. MaxHoldLine = 600 )
const ( HoldOutcomeDeployed = "deployed" HoldOutcomeSameBuild = "same-build" HoldOutcomeCancelled = "cancelled" HoldOutcomeExpired = "expired" HoldOutcomeOperator = "operator" )
Outcomes a lift can have, recorded on each held card's timeline.
const BusyIdleAfter = 120 * time.Second
BusyIdleAfter is how long without activity means a session is not working.
const CaptureMarker = "atrium-capture: "
captureMarker leads the line. handoffWritten looks for the whole line, token and all.
const ColdHandoffBy = "cache-cold"
coldHandoffBy is the `by` on the event a cold handoff leaves on the card.
const ColdHandoffReason = "cache going cold"
coldHandoffReason is the reason written on that event.
const DecidedByDeployHold = "deploy-hold"
DecidedByDeployHold is what a refusal is recorded as decided by.
const HandoffDirName = "handoffs"
handoffDirName is the handoffs folder beside the database, for a card with no home. See handoffPath.
const HandoffFloor = 200
handoffFloor is the fewest bytes a handoff may be. A token alone is not one.
const HandoffHead = 4096
handoffHead is how much of the file is read looking for the token. Never all of it.
const KeepaliveForkTimeout = 120 * time.Second
keepaliveForkTimeout bounds one refresh. A fork is a process start and one API call.
const KeepaliveHookSettings = `` /* 221-byte string literal not displayed */
keepaliveHookSettings is the settings file layered onto every fork: one PreToolUse hook that refuses every tool. Hooks are not part of the request, so this keeps the prefix whole where a deny rule would not.
const KeepalivePricesVersion = "usageprices-2026-09-27"
keepalivePricesVersion names the price table below, and is written on every ledger row so a stale table shows.
const KeepalivePrompt = "Automated cache refresh from atrium. Reply with the single word OK. " +
"Do not use tools. Do not continue any task."
keepalivePrompt is what the fork is asked. The words do not matter to the cache, only to what the model does with its one turn.
const KeepaliveTTLVar = "CLAUDE_CODE_PROMPT_CACHE_TTL"
keepaliveTTLVar is Claude Code's choice of TTL for the main conversation.
const KeepaliveTick = time.Minute
keepaliveTick is how often cards are looked at. A refresh is due inside a five minute margin, so once a minute is plenty.
const LastReplyCap = 400
lastReplyCap bounds the read cache by count. The oldest entry goes first.
const MaxClearLine = 64 << 10
maxClearLine bounds the backspaces one clear-line frame can type.
const MaxLimitAsks = 3
maxLimitAsks is how many times the limit prompt is typed before the cycle stops re-asking and waits.
const NewContextBy = "new-context"
newContextBy is the `from` on the prompted events the sequence writes.
const NewContextClearCommand = "/clear"
newContextClear clears the session.
const NewContextHoldNote = "queued: this card is starting a new context, and everything for it is held " +
"until its wake prompt has been typed."
newContextHoldNote is what a sender is told while a card is held.
const SettingNewContextJournal = "new_context_journal"
settingNewContextJournal is the settings key. One value, the whole map.
const TranscriptTail = 2 << 20
transcriptTail bounds how much of a transcript is read. The last main reply is at the end, and a transcript reaches ninety megabytes in a day.
const WhyColdHandedOff = "handed off cold"
whyColdHandedOff is the skip reason of a card handed off cold: its cache is let go until a person's turn.
const WrapBy = "restart-wrap"
wrapBy is the `by` on the events and wakes the wrap-up writes.
Variables ¶
var ( ErrNoTerminal = errors.New("atrium does not own this session's terminal, so it cannot type into it") ErrNewContextBusy = errors.New("a new context is already under way on this card") )
var ( BuildOnce sync.Once BuildID string )
var AgentFork = func(exe string, args []string) (string, []string) { return exe, args }
agentFork is agentSpawn for a keep-alive fork, which is a one-shot model call. A test's TestMain makes it a command that fails at once.
var AtriumBinary = func() string { if p, err := os.Executable(); err == nil { if r, err := filepath.EvalSymlinks(p); err == nil { return r } return p } return "atrium" }
atriumBinary is the full path of this atrium, for the limit prompt. A variable for a test.
var ErrCycleUnder = errors.New("the card fell back under its limit")
errCycleUnder ends an automatic cycle whose card fell back under its limit before the ack: the runner compacted, and there is nothing left to cycle.
var ErrHoldExempt = small.ErrString("at most three exempt cards")
errHoldExempt is more exempt cards than a hold allows.
var ErrNewContextAcked = errors.New("atrium ready came and the handoff is written, so this new context finishes: " +
"it clears and wakes the card in a moment, and what you type is queued for after the wake")
var ErrNewContextGone = errors.New("superseded")
var ForkCarried = map[string]bool{ "--append-system-prompt": true, "--system-prompt": true, "--append-system-prompt-file": true, "--system-prompt-file": true, "--disallowedtools": true, "--disallowed-tools": true, "--tools": true, "--mcp-config": true, "--strict-mcp-config": true, "--agents": true, "--plugin-dir": true, }
forkCarried are the launch flags that shape the cached request, which is the system prompt and the tool list. Everything else in a card's launch is dropped from a fork on purpose: see docs/runtime/keepalive-fork-args-design.md.
var KeepalivePrices = map[string]KeepalivePrice{
"claude-opus-5-5": {In: 4, Cw5m: 5, Cw1h: 8, Cr: 0.20, Out: 20},
"claude-fable-5-1": {In: 10, Cw5m: 12.5, Cw1h: 20, Cr: 0.25, Out: 50},
"claude-sonnet-5-5": {In: 2, Cw5m: 2.5, Cw1h: 4, Cr: 0.10, Out: 10},
}
keepalivePrices mirrors `$UsagePrices` in dotfiles/claude/usage/UsageCommon.ps1 for the models a card may be refreshed on. Only models whose effort level is not part of the cache key are here, because atrium cannot know a card's current effort, and a fork at another effort would write the whole context.
var NewContextLabel = shared.AtriumLabel("new context:")
newContextLabel goes ahead of the limit, capture and wake prompts, so nobody reads them as the operator's own words. `/clear` goes with none, because a label in front of it is no longer a slash command. See atriumLabel.
var WakeLabel = shared.AtriumLabel("restart wake:")
wakeLabel goes ahead of a wake's text. See atriumLabel.
var WrapJoinMargin = 5 * time.Second
wrapJoinMargin is how long past the running wrap-up's own deadline a joiner waits before it gives up on it. A variable for a test.
var WrapLabel = shared.AtriumLabel("restart:")
wrapLabel goes ahead of the prompt, so nobody reads it as the operator's own words.
Functions ¶
func BudgetFor ¶
func BudgetFor(ctx int64, p KeepalivePrice) float64
budgetFor is the stop rule's cap: a fraction of one full 1h rehydration.
func BuildIdentity ¶
func BuildIdentity() string
buildIdentity names the binary this daemon is running, so a room that comes back can say whether the deploy took. A hash of the executable, because a build from a working tree carries the same version and commit as the one it replaced. Once per process: the binary does not change under it.
func BusyCard ¶
BusyCard is the room's one rule for "working right now", shared by `atrium room restart` and the deploy hold's wait. A supervised session in a column that means it is working, with fresh activity, that is not just thinking.
Stale activity is not activity: it is written when a tool starts and nothing writes when a turn ends. A session thinking has nothing half written.
func CapWrapWait ¶
capWrapWait holds a typed wait to the setting's own maximum, so a caller cannot ask for longer than the room allows.
func CaptureLine ¶
captureLine is the line a card puts in its handoff file to say it is this run's.
func CaptureToken ¶
captureToken is unique to one capture run: the run's generation and a random id.
func ClassifyReceipt ¶
func ClassifyReceipt(r *ForkReceipt, runErr error, ctx int64) string
classifyReceipt scores one fork. ctx is the card's context from its own transcript. A nil receipt, or one with no usage, is `failed`.
func ColdHandoffOff ¶
coldHandoffOff reports whether a card's own override switches the cold handoff off.
func ColdSpentKey ¶
coldSpentKey is the setting that holds a card's cold handoff as used. One handoff per human turn: only a turn the operator or a peer started puts it back, never atrium's own continuation after the clear, nor a keep-alive ping.
func ContainsID ¶
func FitReasons ¶
fitReasons joins head, the reasons and tail, cutting the reasons so the whole is at most maxHoldLine bytes.
func HandoffName ¶
HandoffName is the file a card's new-context cycle writes and reads: its alias when it has one, else the first 13 characters of its id. Eight is not enough, two cards here share `01a0ede4`. Exported for the idle parking, which wants the same file.
func HashExecutable ¶
func HashExecutable() string
func IsSharedErr ¶
func KeepFlags ¶
keepFlags keeps the allowlisted flags of args with their values. A flag's values are the tokens up to the next flag, and `--flag=value` is one token. An unknown flag is dropped along with its values, and a bare token before any flag (a prompt) is dropped.
func LocalHasHooks ¶
localHasHooks reports whether a card's `.claude/settings.local.json` names hooks. `--setting-sources local` still loads that file, so its hooks would run in the fork.
func NewContextCaptureText ¶
newContextCapture is what the session is asked to do before its context goes.
The token is matched as a SUBSTRING of the file's first 4 KB, not as a whole line: a model writing markdown puts it in backticks, a bullet or bold, and refusing a fresh capture for that is the failure this exists to fix. The token is random per run, so a substring is as unforgeable as an exact line.
ONE LINE. It is typed and submitted like any prompt, and the model gets the whole of it. It says what happens next, so a session that would otherwise carry on working after writing the file knows to stop.
func NewContextLimitPrompt ¶
newContextLimitPrompt is the limit prompt: why the card is cycling, where the handoff goes and how to say it is written. The binary is named in full, since the CLI is not on PATH in every room.
THE LIMIT IS ATRIUM'S, NOT THE MODEL'S, and an agent told only "you are at context limit" reads it as the window being full and rushes. So an automatic cycle names both numbers. A cycle somebody started by hand has none.
PAUSE, NOT FINISH. "Wrap what is in flight" let the agent decide its step was nearly done and keep going, further over the limit. The handoff says what is in flight instead, and the next context picks it up.
ONE WAY TO SAY IT IS WRITTEN. A card with a shell has `atrium ready`; atrium_ready is not on every card's tool list, so it is named only to a card with no shell, which is the card it exists for.
func NewContextView ¶
func NewContextView(c *NewContext) map[string]any
newContextView carries the wording, so the board says what the daemon means and there is one place to change it.
func NewContextWakeText ¶
newContextWake is what the new session is told, and reads the handoff back.
func ParseSeconds ¶
func ReceiptCost ¶
func ReceiptCost(r *ForkReceipt, p KeepalivePrice) float64
receiptCost prices a fork's tokens. Cache writes are priced at the 1h rate, because only cards on the 1h cache are refreshed.
func RefreshDueAt ¶
refreshDueAt is when a card whose cache expires at expiry becomes due for a refresh. decide() and the card view both read it, so they cannot drift.
func ReplyContent ¶
func ReplyContent(raw json.RawMessage) (string, bool)
replyContent is the words and whether there was a tool call in an assistant reply's content blocks. Best effort: content that is not a list of blocks says nothing.
func RestartWrapNudge ¶
func RestartWrapPrompt ¶
func RunForkProcess ¶
func RunForkProcess(ctx context.Context, spec ForkSpec, agentFork func(exe string, args []string) (string, []string)) ([]byte, error)
runForkProcess runs a fork and returns its stdout. The default fork runner.
func ScanMainReplies ¶
scanMainReplies calls fn for every main-thread assistant reply with usage in a transcript, in file order. Subagent replies (`isSidechain`) are not the card's prefix and are skipped.
It returns how many bytes of COMPLETE lines it read, so a caller reading a transcript that is still being written can start its next read there and never on half a line. A last line with no newline is still offered to fn when it parses, and not counted, so the next read offers it again.
The one transcript reader: the keep-alive's last reply and the usage record are both built on it.
func ScanReplies ¶
scanReplies is scanMainReplies with the inline subagent replies offered too, marked Sidechain. The usage record counts those as the subagent's.
func StampHandoff ¶
stampHandoff puts the time before the extension: <card-id>-20261022233412.md.
Types ¶
type Activity ¶
type Activity interface {
DialogOpen(id string) bool
TurnsBegun(id string) int
MidTurn(id string) bool
SinceBusy(id string) time.Duration
OnSubagents(id string) bool
QuietFor(id string) time.Duration
LooksIdle(id string) bool
What(id string) string
Describe(id string, now time.Time) (what, age string)
}
Activity is what the context cycle asks of the activity tracker.
type Calls ¶
type Calls struct {
Publish func(id string)
LabelFor func(w *store.RestartWake) string
DBPath func() string
Room func() string
HomeOf func(cardID string) (store.CardHome, bool)
HasGuest func(id string) bool
ResetPending func(taskID string)
ContextTokens func(t *store.Task) (int64, bool)
CycleLimit func(t *store.Task) int64
CycleSubject func(t *store.Task) bool
HarnessOf func(taskID string) (*store.Harness, *store.Task)
MidTurnInputFor func(taskID string) bool
TypeLabelledGuarded func(run shared.Runner, taskID, banner, text string, ok func() bool) (bool, error)
TypeLabelledThroughGate func(run shared.Runner, taskID, banner, text string) (bool, error)
TakeInContext func(taskID string) []shared.DeliveredSay
RequeueCarried func(taskID string, carried []shared.DeliveredSay)
ItemMissed func(taskID string, carried []shared.DeliveredSay) []shared.DeliveredSay
ShutdownAllowed func(w http.ResponseWriter, r *http.Request) bool
ClearStaleLine func(taskID string) bool
}
Calls is every call out of the context cycle into another feature.
type ForkReceipt ¶
type ForkReceipt struct {
Subtype string `json:"subtype"`
IsError bool `json:"is_error"`
Result string `json:"result"`
NumTurns int `json:"num_turns"`
SessionID string `json:"session_id"`
PermissionDenials []json.RawMessage `json:"permission_denials"`
// ModelUsage is keyed by the model that answered, so a caller that did not
// choose the model can still price the call.
ModelUsage map[string]json.RawMessage `json:"modelUsage"`
Usage *struct {
Input int64 `json:"input_tokens"`
CacheWrite int64 `json:"cache_creation_input_tokens"`
CacheRead int64 `json:"cache_read_input_tokens"`
Output int64 `json:"output_tokens"`
} `json:"usage"`
}
forkReceipt is the part of `claude -p --output-format json` a refresh reads.
type ForkSpec ¶
type ForkSpec struct {
Exe string
Args []string
Dir string
Env []string
// Stdin is the prompt for a caller whose prompt is too long for a command
// line. Nil for keep-alive.
Stdin []byte
// Timeout bounds the run. Zero is keepaliveForkTimeout.
Timeout time.Duration
}
forkSpec is one refresh's command line.
type HoldStart ¶
type HoldStart struct {
By string `json:"by"`
ByCard string `json:"by_card"`
Whys []string `json:"whys"`
Exempt []string `json:"exempt"`
}
holdStart is what `POST /v1/hold` takes to set a deploy hold.
type HoldState ¶
holdState is the copy of the room's holds the hot path reads.
func NewHoldState ¶
func NewHoldState() *HoldState
type Keepalive ¶
type Keepalive struct {
// replies is the transcript read cache. The daemon points it at its own.
Replies *LastReplies
// agentFork and cardArgs are the seams a fork reads. The daemon points them at its hooks.
AgentFork func(exe string, args []string) (string, []string)
CardArgs func(h *store.Harness, t *store.Task) ([]string, error)
// EffortArgs is the card's launch effort in the shape its harness declares.
EffortArgs func(h *store.Harness, t *store.Task) ([]string, error)
// ForkEnvOf is the fork's environment over base: the one a launch builds, minus the card's identity.
ForkEnvOf func(h *store.Harness, t *store.Task, base []string) ([]string, error)
St *store.Store
Now func() time.Time
// fork runs one refresh and returns the receipt's bytes.
Fork func(ctx context.Context, spec ForkSpec) ([]byte, error)
// transcript finds a card's transcript from its directory and session id.
Transcript func(cwd, sessionID string) string
// window is the card's context window from telemetry, or 0.
Window func(taskID string) int
// broadcast tells the board, and toast raises one on it.
Broadcast func(event string, payload any)
// hookFile is the path of the block-all settings file.
HookFile string
// baseEnv is the environment a fork starts from.
BaseEnv func() []string
// record saves one refresh's ledger row.
Record func(*store.KeepaliveRefresh) error
// spent saves one refresh's row in the card's usage record. See usage.go.
Spent func(*store.SessionUsage) error
// holding says a new-context cycle is under way on the card, and session is the
// session its runner last started, which moves on at a `/clear` while the resume
// id lags. Both nil in a test that has no daemon.
Holding func(taskID string) bool
Session func(t *store.Task) string
// deployHeld says the card is held for a room deploy, which ends its runner
// and resumes it cold, so a refresh buys nothing. Nil in a test with no daemon.
DeployHeld func(taskID string) bool
// cold starts the new-context cycle on a card whose cache is going cold. Nil in a test that has no daemon.
// See keepalive_cold.go.
Cold func(t *store.Task) error
Mu sync.Mutex
// cooled is the last reply a card was handed off on, per card.
Cooled map[string]time.Time
// lastMissCard is the card of the room's most recent attempt when that
// attempt was a miss, for "two misses on different cards in a row".
LastMissCard string
// why is the last skip reason per card, for the board.
Why map[string]string
// inFlight stops a slow fork from being started twice.
InFlight map[string]bool
// unsaved holds back a card whose last refresh row could not be saved. The
// warm window and the budget come from saved rows, so without it the next
// tick would see the old expiry and fork again.
Unsaved map[string]UnsavedRefresh
}
keepalive holds the loop's collaborators, so a test can run a tick with a fake fork, a fake clock and hand-written transcripts.
func NewKeepalive ¶
func (*Keepalive) ClearOnRealTurn ¶
func (k *Keepalive) ClearOnRealTurn(t *store.Task, card *store.KeepaliveCard) *store.KeepaliveCard
clearOnRealTurn puts a self-clearing stopped card back on once the card has taken a real turn since it stopped.
func (*Keepalive) ColdCheck ¶
coldCheck starts the new-context cycle on a card whose cache atrium is no longer warming and which is about to go cold. warming says keep-alive will refresh it, or has just held a refresh back for a reason that passes.
func (*Keepalive) ColdDone ¶
coldDone says a handoff was already made for the reply the card's last turn ended on. A new turn moves the reply on, which is what lets the next cold event hand off again. The card's events say it too, so a restart of the room does not forget.
func (*Keepalive) ColdRearm ¶
coldRearm lets the card be handed off again, on a turn a person or a peer started.
func (*Keepalive) ColdSpent ¶
coldSpent says the card was cold-handed-off and no turn of a person's has come since. A read failure answers spent, so a store that cannot be read cannot start a loop.
func (*Keepalive) ColdSpentAt ¶
coldSpentAt is when the card was cold-handed-off, while no turn of a person's has come since.
func (*Keepalive) Decide ¶
decide applies the design's seven rules to one card. It reads, and writes nothing.
func (*Keepalive) EnsureHookFile ¶
ensureHookFile writes the block-all settings file if it is missing or wrong.
func (*Keepalive) FollowSession ¶
followSession is the card with its resume id moved to the session its runner last started. After a new context the cache worth keeping warm is the new session's, and the stored id names the old one until the next Stop.
func (*Keepalive) ForkArgs ¶
forkArgs is the refresh command line. Kept in one place so the test pins it.
func (*Keepalive) ForkEnv ¶
ForkEnv is the fork's environment, built by the launch code the root points ForkEnvOf at.
func (*Keepalive) ModelArg ¶
modelArg is the model to fork on. A card whose telemetry says it has a window over 200k runs the 1M variant, which is a different request.
func (*Keepalive) StretchState ¶
func (k *Keepalive) StretchState(taskID string, card *store.KeepaliveCard, r *LastReply) ( anchor time.Time, rows []*store.KeepaliveRefresh, spent float64, count, missed int, expiry time.Time, last time.Time)
stretchState reads the current idle stretch of a card: the refreshes since its budget last restarted, their spend, and when the cache expires.
Two different starting points. The BUDGET restarts at the later of the last real reply and the switch last being set, so turning it on by hand gives a fresh budget. The WARM WINDOW counts every warmed refresh since the last real reply, because a refresh made before a hand re-enable still refreshed the cache.
func (*Keepalive) View ¶
view is a card's keep-alive as the board reads it, or nil for a card with no switch.
func (*Keepalive) ViewOf ¶
func (k *Keepalive) ViewOf(t *store.Task, card *store.KeepaliveCard, out *KeepaliveCardView) any
type KeepaliveCardView ¶
type KeepaliveCardView struct {
State string `json:"state"`
StateAt time.Time `json:"state_at"`
// Why is the reason a card cannot be warmed, for the greyed switch, or the
// last skip reason while it is on.
Why string `json:"why,omitempty"`
// Refreshes, Missed, Spent and Budget describe the current idle stretch.
// Refreshes counts the warmed ones and Missed the misses, which are in Spent
// too: one miss rewrites the whole context, about eight budgets.
Refreshes int `json:"refreshes"`
Missed int `json:"missed,omitempty"`
Spent float64 `json:"-"`
Budget float64 `json:"-"`
// WarmUntil is when the card's cache expires, when atrium knows.
WarmUntil *time.Time `json:"warm_until,omitempty"`
// LastRefreshAt is the last refresh of the current idle stretch, absent when
// there was none. NextRefreshAt is when the loop will next refresh the card,
// sent only while decide() says "not due".
LastRefreshAt *time.Time `json:"last_refresh_at,omitempty"`
NextRefreshAt *time.Time `json:"next_refresh_at,omitempty"`
// Suspended is why the whole room is suspended, so a card's badge does not
// blame the card.
Suspended string `json:"suspended,omitempty"`
}
keepaliveCardView is what the board draws for one card.
type KeepalivePrice ¶
type KeepalivePrice struct{ In, Cw5m, Cw1h, Cr, Out float64 }
keepalivePrice is per million tokens: the 5m and 1h writes and the cache read, plus plain input and output for the fork's own few tokens. Cw5m is 1.25 times input, Anthropic's list rule, and is written out so a row's price is read and not derived.
func KeepalivePriceFor ¶
func KeepalivePriceFor(model string) (KeepalivePrice, bool)
keepalivePriceFor looks a model up with any `[1m]` style suffix and date stamp tolerated.
type LastReplies ¶
type LastReplies struct {
Mu sync.Mutex
M map[string]*LastReplyEntry
Order []string
// scans counts transcript scans, for tests.
Scans atomic.Int64
}
lastReplies is readLastReply's memory, one per daemon. It has its own lock and never k.mu, so the list handler's view stays cheap. The zero value is ready.
func (*LastReplies) LastReplyDrop ¶
func (c *LastReplies) LastReplyDrop(path string)
func (*LastReplies) LastReplyLoad ¶
func (c *LastReplies) LastReplyLoad(path string) (LastReplyEntry, bool)
func (*LastReplies) LastReplyStore ¶
func (c *LastReplies) LastReplyStore(path string, e LastReplyEntry)
func (*LastReplies) ReadLastReply ¶
func (c *LastReplies) ReadLastReply(path string) (*LastReply, error)
readLastReply finds the last main-thread assistant reply with usage in a transcript. The answer is cached per path on the file's size and mtime. A grown file is scanned from the cached offset when the whole file is inside the tail window, where that gives the same answer as a whole read. A file that shrank or whose mtime went back is read whole.
type LastReply ¶
type LastReply struct {
Model string
At time.Time
Speed string
Context int64
// TTL is the cache lifetime the reply wrote at, from its cache_creation
// split. Zero when it wrote nothing and read everything, which says nothing
// about the TTL, so the last reply that did write is used for it.
TTL time.Duration
}
lastReply is what a card's transcript says about its last main reply. Every fact the policy needs about the card comes from here and never from a fork.
type LastReplyEntry ¶
type LastReplyEntry struct {
Size int64
Mtime time.Time
Offset int64 // bytes of complete lines scanned, from the start of the file
From int64 // where the scan began, nonzero when the file was over the tail
Reply LastReply
Ttl time.Duration
}
lastReplyEntry is what one transcript read found, and where in the file it stopped, so a grown file is read from there and an unchanged one not at all.
type MainReply ¶
type MainReply struct {
MessageID string
Model string
At time.Time
Speed string
// Input, CacheWrite and CacheRead are the request's input side. Their sum is
// the context the reply was answered on.
Input, CacheWrite, CacheRead int64
// Write5m and Write1h are CacheWrite split by TTL.
Write5m, Write1h int64
Output int64
// Sidechain is a subagent's reply written inline, as older Claude Code
// did. Only scanReplies offers these.
Sidechain bool
// Text is what the reply said, joined, and ToolUse is whether it called a tool. A reply written in several
// lines carries what all of them did once it has been through replySet.take. The turn cost report reads them.
Text string
ToolUse bool
}
mainReply is one line of a transcript that carries a main-thread assistant reply's usage. A reply written in several content blocks is several lines with the same MessageID and the same usage, so a caller that sums keeps one per id.
type NcJournalRow ¶
type NcJournalRow struct {
Step string `json:"step"`
File string `json:"file"`
Conv string `json:"conv"`
Since time.Time `json:"since"`
}
ncJournalRow is what a restart needs to know about one run.
type NcTimings ¶
type NcTimings struct {
// poll is how often a wait looks at the card.
Poll time.Duration
// typeWait is how long a step waits for the gate to open and the runner to be
// between turns before it gives up typing. `/clear`, the wake and the capture
// wait for captureEnd instead: the turn they follow may be long.
TypeWait time.Duration
// ackWait is how long the limit step waits for `atrium ready` in all. Past it
// the cycle fails and the card's held input is released, since an agent that
// never acks (died, wedged, ignored the prompt) must not hold its card for ever.
AckWait time.Duration
// captureBegin is how long the capture prompt has to start a turn.
CaptureBegin time.Duration
// captureEnd is how long the capture turn has to finish.
CaptureEnd time.Duration
// turnSettle is how long the runner has to stay out of a turn for it to count
// as over. A gap between two tool calls is shorter.
TurnSettle time.Duration
// clearWait is how long `/clear` has to produce a new session.
ClearWait time.Duration
// clearTypeWait is how long `/clear` has to find a turn end and an open gate once
// the ack is in. Past it the cycle fails naming what blocked it, rather than
// sitting on step 2 for captureEnd.
ClearTypeWait time.Duration
// ackQuiet is how long after `atrium ready` the card may post no activity at all before the turn counts as over
// for `/clear`, whatever the activity says. The agent was told to end its turn, so a card this quiet lost its
// Stop hook, and the screen cannot say so while a background shell keeps redrawing it.
AckQuiet time.Duration
// noteAfter is how long step 2 waits before it puts what it waits on on the card.
NoteAfter time.Duration
// logEvery is how often a step that waits says what it waits on.
LogEvery time.Duration
// sessionSettle is how long after the new session's SessionStart the wake
// waits. The hook fires a moment before the input box is drawn, and bytes
// typed before then are lost. See wakeSettle.
SessionSettle time.Duration
// promptGap is the least time between two limit prompts, for a runner whose
// turns are not counted.
PromptGap time.Duration
// promptLost is how long a limit prompt may go unanswered before it is typed
// again, at an idle prompt only.
PromptLost time.Duration
}
ncTimings is how long each step waits, and how often it looks. Fields of the daemon's hooks so a test can run the whole sequence in milliseconds rather than name the thing that must not happen by waiting for it.
func DefaultNCTiming ¶
func DefaultNCTiming() NcTimings
defaultNCTiming is what a daemon starts with. A test changes its own daemon's copy, never a shared one.
type NewContext ¶
type NewContext struct {
Step string
File string
Since time.Time
Reason string
// conv is the conversation the run started in. A failed chip clears when a
// SessionStart names a different one, which is the proof the clear happened.
Conv string
// gen tells a run whether it is still the card's. A dismiss or a fresh run
// bumps it, and the goroutine it replaced stops without saying anything.
Gen uint64
// auto marks a run the daemon started at the card's limit, and tokens and limit
// are what it started on. See autocontext.go.
Auto bool
Tokens, Limit int64
// acked is set when `atrium ready` came, and cleared when `/clear` was typed. A
// rerun of a failed chip resumes after what they say happened.
Acked, Cleared bool
// prompted is how many times the limit prompt was typed, the last at lastPrompt,
// in the turn promptTurn (see cyclePromptDue).
Prompted int
PromptTurn int
LastPrompt time.Time
// kick wakes the run's wait at once: an ack, a statusline update, a tick.
Kick chan struct{}
// capOnly marks the idle parking's capture, which clears nothing and is not
// journalled: a restart that cuts it off has nothing to report.
CapOnly bool
// abandoned marks a failed chip seeded at startup from the journal. A
// SessionStart cannot clear it: see sessionStarted.
Abandoned bool
// typing is set while atrium's own write to the terminal is under way, and says
// so on the card. Board typing is refused for the whole cycle. See typingHeld.
Typing bool
// armed is set once the operator's line gate has been open since the claim. Until then the cycle holds
// nothing, so keys already typed are never shut behind it. See ncArm.
Armed bool
}
newContext is one card's sequence as the board draws it.
type NewContextHooks ¶
type NewContextHooks struct {
NcTiming NcTimings
WrapTiming WrapTimings
WrapJoinMargin time.Duration
AtriumBinary func() string
}
newContextHooks are the seams of the new-context and restart-wrap sequences.
func DefaultNewContextHooks ¶
func DefaultNewContextHooks() NewContextHooks
type NewContextSharedError ¶
newContextSharedError refuses a cycle while another card in the same directory is itself mid-cycle.
func (*NewContextSharedError) Error ¶
func (e *NewContextSharedError) Error() string
type NewContexts ¶
type NewContexts struct {
Mu sync.Mutex
By map[string]*NewContext
Gens uint64
// dropped is a cleared auto run per card. See Clear.
Dropped map[string]ncDropped
// stop ends every run in flight, at shutdown.
Stop chan struct{}
StopOnce sync.Once
// persist writes the runs in flight somewhere a restart can find them. See
// newcontext_journal.go. Nil in a test that does not care.
Persist func(map[string]NcJournalRow)
// saveMu keeps two snapshots from reaching persist out of order.
SaveMu sync.Mutex
}
func NewNewContexts ¶
func NewNewContexts() *NewContexts
func (*NewContexts) Ack ¶
func (n *NewContexts) Ack(taskID string) bool
ack marks the card's run acked, when it is waiting on the limit step. It reports whether there was one.
func (*NewContexts) Advance ¶
func (n *NewContexts) Advance(taskID string, gen uint64, step string) bool
advance moves a run to its next step.
func (*NewContexts) Arm ¶
func (n *NewContexts) Arm(taskID string, gen uint64) (armed, changed bool)
arm marks gen's run as holding input. It reports whether the run is armed, and whether this call armed it.
func (*NewContexts) BeginCaptureOnly ¶
func (n *NewContexts) BeginCaptureOnly(taskID, file, conv string) (uint64, bool)
beginCaptureOnly is begin for the idle parking's run. It is marked before the claim saves, so it is never journalled, not even for a moment.
func (*NewContexts) BusyCard ¶
func (n *NewContexts) BusyCard() string
BusyCard is a card inside a new-context cycle that has not ended, or "".
func (*NewContexts) Claim ¶
func (n *NewContexts) Claim(taskID string, c *NewContext) (uint64, bool)
func (*NewContexts) Clear ¶
func (n *NewContexts) Clear(taskID string) bool
clear removes a card's chip whatever it says and stops its run. A run that had already asked leaves a marker, so the next tick does not ask the same card again over the same limit.
func (*NewContexts) DropMarker ¶
func (n *NewContexts) DropMarker(taskID string)
DropMarker forgets the card's cleared run.
func (*NewContexts) DroppedHolds ¶
func (n *NewContexts) DroppedHolds(taskID, conv string) bool
DroppedHolds is whether the card's cleared run still holds the trigger off: same conversation, under droppedHold.
func (*NewContexts) Fail ¶
func (n *NewContexts) Fail(taskID string, gen uint64, reason string) bool
fail leaves the chip on the step that stopped, saying why.
func (*NewContexts) Finish ¶
func (n *NewContexts) Finish(taskID string, gen uint64) bool
finish takes the chip off: the wake prompt landed.
func (*NewContexts) FinishRecorded ¶
func (n *NewContexts) FinishRecorded(taskID string, gen uint64, record func()) bool
finishRecorded is finish that runs record first, while the chip is still on and only if it is still gen's, so nobody who sees the chip gone reads a history that does not yet say why.
func (*NewContexts) Get ¶
func (n *NewContexts) Get(taskID string) *NewContext
func (*NewContexts) Holding ¶
func (n *NewContexts) Holding(taskID string) bool
holding reports whether a card is inside a new-context cycle that has not ended: from `begin` until the wake prompt has been typed. A failed chip is not holding, since nothing is running any more and a held message would be stranded.
func (*NewContexts) HoldsInput ¶
func (n *NewContexts) HoldsInput(taskID string) bool
holdsInput is holding once the limit prompt has gone in. Before it, nothing is under way that a message could land in the wrong side of, so a cycle whose prompt was never typed holds nothing.
func (*NewContexts) Kick ¶
func (n *NewContexts) Kick(taskID string)
kick wakes the card's run, if it is waiting, without blocking.
func (*NewContexts) Mine ¶
func (n *NewContexts) Mine(taskID string, gen uint64) bool
mine reports whether gen is still the card's run.
func (*NewContexts) NoteCleared ¶
func (n *NewContexts) NoteCleared(taskID string, gen uint64)
noteCleared records that `/clear` was typed.
func (*NewContexts) NotePrompt ¶
notePrompt records a limit prompt typed in turn.
func (*NewContexts) ResumeAcked ¶ added in v0.0.4
func (n *NewContexts) ResumeAcked(taskID, conv string) (uint64, bool)
ResumeAcked puts a cleared run that was past the ack back at the clear, in the conversation it began in, so the handoff already written is used and no second one is asked for.
func (*NewContexts) Revive ¶
func (n *NewContexts) Revive(taskID string) (uint64, bool)
Revive puts a cleared auto run back, for an `atrium ready` that arrives after the clear.
func (*NewContexts) SameDirBusy ¶
sameDirBusy names a card, other than task, that shares its directory and has a cycle under way. A failed chip is not under way.
func (*NewContexts) Save ¶
func (n *NewContexts) Save()
save hands persist the runs now in flight. A failed chip is not in flight.
func (*NewContexts) SeedFailed ¶
func (n *NewContexts) SeedFailed(taskID string, row NcJournalRow, reason string)
seedFailed puts a failed chip on a card for a run that no goroutine owns.
func (*NewContexts) SessionStarted ¶
func (n *NewContexts) SessionStarted(taskID, conv string) bool
SessionStarted keeps an acked chip, since a new conversation that never read the handoff must not look done.
func (*NewContexts) SetTyping ¶
func (n *NewContexts) SetTyping(taskID string, gen uint64, on bool) bool
setTyping marks atrium's own write to the terminal as under way or over, for gen's run only. It reports whether the run is still the card's.
func (*NewContexts) SetWaiting ¶
func (n *NewContexts) SetWaiting(taskID string, gen uint64, why string) bool
setWaiting puts what a step waits on on the card's chip, or takes it off with "". It reports whether the text changed, so the caller publishes only then. Never on a failed chip, whose reason is its own.
func (*NewContexts) StopAll ¶
func (n *NewContexts) StopAll()
func (*NewContexts) TypingHeld ¶
func (n *NewContexts) TypingHeld(taskID string) bool
typingHeld reports whether board typing is refused: for the whole cycle, from the moment it is armed, because a key typed while it waits lands between its steps and in the context about to be cleared. The way out never depends on a step finishing: "let me type" ends the run. A failed run and the idle parking's capture hold nothing.
func (*NewContexts) TypingNow ¶
func (n *NewContexts) TypingNow(taskID string) bool
typingNow reports whether atrium's own write to the terminal is under way.
func (*NewContexts) WaitingForAck ¶
func (n *NewContexts) WaitingForAck(taskID string) bool
waitingForAck is whether the card's run is on the limit step with no ack yet.
func (*NewContexts) Writing ¶ added in v0.0.5
func (n *NewContexts) Writing(taskID string) bool
Writing reports whether the card was told to write its handoff and has not run `atrium ready`, held or not.
type RestartWrap ¶
type RestartWrap struct {
Mu sync.Mutex
Running bool
Cancel context.CancelFunc
Cur *WrapRun
Acks map[string]chan struct{}
}
restartWrap is the wrap-up under way: one at a time, with the cards waiting for their ack.
func NewRestartWrap ¶
func NewRestartWrap() *RestartWrap
func (*RestartWrap) Ack ¶
func (w *RestartWrap) Ack(taskID string) bool
ack records `atrium ready` from a card and says whether one was waited for.
func (*RestartWrap) Begin ¶
func (w *RestartWrap) Begin(cancel context.CancelFunc, deadline time.Time) (*WrapRun, bool)
begin claims the wrap-up, due by deadline. When one is already running it returns that one to join and false.
func (*RestartWrap) CancelRunning ¶
func (w *RestartWrap) CancelRunning()
cancelRunning ends the wrap-up under way, if any: the restart is no longer waiting.
func (*RestartWrap) End ¶
func (w *RestartWrap) End(rep WrapReport)
end releases the wrap-up with what it did, and wakes whoever joined it.
func (*RestartWrap) Expect ¶
func (w *RestartWrap) Expect(taskID string) chan struct{}
func (*RestartWrap) Forget ¶
func (w *RestartWrap) Forget(taskID string)
func (*RestartWrap) Waiting ¶
func (w *RestartWrap) Waiting(taskID string) bool
waiting is whether a wrap-up waits on this card's ack.
type Service ¶
type Service struct {
St *store.Store
Ap *api.Server
Hk *NewContextHooks
Act Activity
Sup shared.Registry
Calls
// wake holds the after-restart wakes, mirrored from the store, and when each
// card's session last started. See restartwake.go.
Wake *Wakes
// holds is the room's deploy hold, copied from the store for the permission
// path, and build is the binary it was set against. See roomhold.go.
Holds *HoldState
Build string
// nctx holds the new-context sequences under way and the failed ones nobody
// has dismissed. In memory. See newcontext.go.
Nctx *NewContexts
// wrap is the restart wrap-up under way. See restartwrap.go.
Wrap *RestartWrap
// ka keeps idle Claude cards' prompt caches warm. See keepalive.go.
Ka *Keepalive
}
Service is the context cycle, the keepalive, the restart wrap and wake, and the room hold.
func (*Service) AbortWrapWakes ¶
func (d *Service) AbortWrapWakes()
AbortWrapWakes is for a restart that did not happen after its wrap-up: the wakes it queued wait for a new runner that is not coming, so they are dropped and each card is told in place that the restart is off.
func (*Service) AtIdlePrompt ¶
atIdlePrompt is whether a claude card is flagged looks-idle or shows a settled prompt on a pty silent for shared.LooksIdleAfter, with no dialog and no subagents.
func (*Service) CardRunning ¶
cardRunning is whether the card's own status says a turn is going (r-022). The activity alone is not enough: a turn that ended on background work reads idle while the card stays running, and the next turn starts when that work reports. A capture typed into that gap is merged into the turn that follows, whose Stop then reads as the capture's.
func (*Service) ColdHandoff ¶
coldHandoff is the daemon's side of the seam: the cycle, with the guards a lent or moving card needs.
func (*Service) ConversationOf ¶
conversationOf is the conversation a card's session is in now: the id its last SessionStart reported, else the resume id stored on the card.
func (*Service) CycleAwaitAck ¶
cycleAwaitAck types the limit prompt and waits for `atrium ready`, for as long as it takes. Woken by a poll, an ack, a statusline update or the tick.
func (*Service) CyclePrompt ¶
func (d *Service) CyclePrompt(taskID string, gen uint64, c *NewContext) error
cyclePrompt types the limit prompt through the gate, with no turn check for a runner that takes input mid-turn. A closed gate writes nothing, and the next poll tries again.
func (*Service) CyclePromptDue ¶
func (d *Service) CyclePromptDue(taskID string, c *NewContext) bool
cyclePromptDue is whether the limit prompt goes now. ONCE PER CYCLE: the first goes as soon as the line is free, mid-turn included, unless the runner loses input typed mid-turn, when it waits for the turn to end. Another goes only at an idle prompt promptLost after the last. Never mid-turn: a prompt queued mid-turn starts a turn of its own when it is read, and the agent may be inside `atrium ready` (f-new-context-nudge-repeats).
Never closer than promptGap. Never with a dialog on screen, whose Enter it would answer.
func (*Service) DeployHeld ¶
deployHeld reports whether a card is held for a deploy: its gated calls are refused and its agents' messages wait.
func (*Service) DeployHold ¶
deployHold is the room's deploy hold, or nil.
func (*Service) DeployHoldMax ¶
func (*Service) DeployHoldNote ¶
deployHoldNote is what a sender is told while its target is held.
func (*Service) DeployRefusal ¶
deployRefusal is what a held card's gated call is answered with.
func (*Service) EndAbandonedNewContexts ¶
func (d *Service) EndAbandonedNewContexts()
endAbandonedNewContexts runs once at startup, before any runner is reopened. Every journalled run belonged to a process that is gone, so each is ended: a failed chip naming the step, an event in the card's history, and the journal emptied. Nothing is typed. The card's terminal is not back yet, and a clear that may or may not have happened is not something to guess at.
func (*Service) FrozenForMove ¶
frozenForMove reports whether the card is frozen for a move between rooms. It takes no turn and types nothing until the move ends or is undone.
func (*Service) HandleHold ¶
func (d *Service) HandleHold(w http.ResponseWriter, r *http.Request)
handleHold is `/v1/hold`. GET answers the hold and who is busy. POST takes `{"action": "start"|"lift", ...}`. On the human listener, reached by the hub through its proxy.
func (*Service) HandleNewContext ¶
func (d *Service) HandleNewContext(w http.ResponseWriter, r *http.Request)
HandleNewContext refuses a DELETE past the ack: a run stopped there leaves its handoff unread for good.
func (*Service) HandleRestartWake ¶
func (d *Service) HandleRestartWake(w http.ResponseWriter, r *http.Request)
handleRestartWake is `/v1/tasks/{id}/restart-wake`: POST queues, GET reads, DELETE clears. `{id}` is a card id or a wire name, so a deploy script can name the session it knows.
func (*Service) HandleRestartWrap ¶
func (d *Service) HandleRestartWrap(w http.ResponseWriter, r *http.Request)
handleRestartWrap is POST /v1/restart-wrap: the wrap-up alone, answered when it is over. The hub-asked restart calls it before it schedules the restarter. `?wait=` is seconds, else the room's setting.
func (*Service) HandoffDir ¶
handoffDir is the card's directory, or "" when it cannot be read from here, which is a card whose files this daemon has no way to look at. The capture then trusts the turn ending as its only signal.
func (*Service) HandoffPath ¶
handoffPath is where a card's cycle writes its handoff: the room's context_handoff_dir, else the card's home (<home>/.atrium/handoff.md), else the handoffs folder beside the room's database, then <card-id>.md.
NOT THE SYSTEM TEMP FOLDER. A handoff is the only record of the work in flight, and temp is swept by the OS and sits on a drive the operator may keep clean of working files on purpose.
func (*Service) HandoffWritten ¶
handoffWritten checks the capture left this card's file. Two ways through: the file carries this run's `atrium-capture: <token>` line in its first 4 KB, which a card that wrote its notes a minute ago can add, or it was written during the capture turn. Under 200 bytes is refused either way. Each refusal says what the card should have done, in one sentence, because the chip shows it.
func (*Service) HoldChanged ¶
holdChanged tells the board. `h` is the hold now on, or nil.
func (*Service) HoldView ¶
holdView is the hold, the cards still busy under it, and the cards it could not hold because atrium does not gate them.
func (*Service) HoldableCards ¶
holdableCards is every card with a session that could make a gated call: the ones this room supervises, and any other that is open.
func (*Service) HoldingFrom ¶
holdingFrom is the question a delivery path asks about one message: a new-context cycle holds every message, and a deploy hold holds an agent's but never the operator's, since the operator reaching out is what must still work.
func (*Service) HoldingMessages ¶
holdingMessages is the question every delivery path asks for a card: is it in a new-context cycle. While it is, no message is typed and no hook carries one, because it would land in the context about to be cleared, or be lost with it. The cycle's own typing (`ncType`) does not ask.
func (*Service) JoinWrapUp ¶
func (d *Service) JoinWrapUp(ctx context.Context, run *WrapRun) WrapReport
joinWrapUp waits for the wrap-up already running instead of starting another, so a second stop does not skip the wait. It is bounded by that wrap-up's own deadline plus a margin, and by ctx. It answers with the same outcome.
func (*Service) KeepaliveAtLaunch ¶
keepaliveAtLaunch gives a NEW Claude card its switch from the room default, and pins its main conversation to the 1h cache unless the switch is off. Called from Launch, which owns the environment.
A card that already has a switch keeps it. Launch also runs when a card is reopened after a restart or resumed, and the board default applies to new cards only: a card somebody turned off stays off.
func (*Service) KeepaliveSet ¶
keepaliveSet is the per-card switch from the board. Turning it on by hand clears any stopped state and restarts the budget.
func (*Service) LaunchHeld ¶
func (d *Service) LaunchHeld(req shared.LaunchRequest) error
launchHeld refuses a launch onto a held room, which would start a runner the restart ends a minute later. The deployer and its exempt cards may still launch.
func (*Service) LiftAtStartup ¶
func (d *Service) LiftAtStartup()
liftAtStartup lifts a deploy hold this room was restarted under, silently.
func (*Service) LiftDeployHold ¶
liftDeployHold ends the hold with no restart. Nothing is sent to a held card. Answers nil when there was no hold to lift.
func (*Service) LoadHolds ¶
func (d *Service) LoadHolds()
loadHolds fills the copy at startup. A hold that cannot be read is logged and treated as none: the permission path must never halt on it.
func (*Service) LoadWakes ¶
func (d *Service) LoadWakes()
loadWakes fills the mirror from the store at startup.
func (*Service) NcArm ¶
ncArm arms gen's run if the operator's line gate is open now, and reports whether it is armed. Judged under the input lock, so an operator key already written has closed the gate first. Text nobody has typed into for five minutes is cleared first. See clearStaleLine.
func (*Service) NcAwaitArm ¶
ncAwaitArm waits for ncArm, up to limit.
func (*Service) NcBlocker ¶
ncBlocker says what keeps a step from typing now, for the log and the card's reason.
func (*Service) NcBusy ¶
ncBusy is whether the card is inside a turn as far as typing is concerned: the activity says so or the status says running, and the screen does not show a settled prompt. A card whose Stop never landed, or whose daemon restarted under a status of running, reads busy to both and will never end a turn it is not taking, so the step waited for a turn end that could not come. The screen is the tiebreak, the same signature `watchLooksIdle` flags on.
func (*Service) NcBusyAfterAck ¶
ncBusyAfterAck is ncBusy for `/clear`, typed once the agent has run `atrium ready` and been told to end its turn. Only the activity counts, with the settled screen as the tiebreak for a lost Stop: the Stop hook has landed when it reads idle. The card's status and the subagent tally do not, because a turn that ended with subagents or background work out leaves the status on running and the screen unsettled for as long as they last, or for ever when a SubagentStop hook was lost. That held `/clear` back with no end (r-new-context-stuck-at-clearing), and the context it clears is the one that work was reporting into anyway.
func (*Service) NcCapture ¶
ncCapture is the capture half of the sequence: the prompt typed between turns, the turn it starts waited out, and the card's own file checked. It returns the step that stopped it and why. The idle parking runs this alone, with no clear after it, so a card is asked to write its handoff without losing its context.
func (*Service) NcClearLine ¶
ncClearLine takes n characters, which the board moved into its compose box when the hold began, off the terminal's input line, so they are neither left behind nor sent twice. Only while the hold is on, and never while atrium is typing: judged under the input lock, so its own write cannot be under way.
func (*Service) NcType ¶
ncType types one step into the card's terminal, through the gate every automated write goes through, and waits for the gate rather than skipping.
Only between turns: a prompt typed mid-turn is held by the runner and merged with whatever else lands, which is the race this sequence exists to avoid. A dialog on screen stops it as well, since the Enter would answer it.
THE QUIET CHECK AND THE WRITE ARE ONE STEP. The check (no prompt event and no turn begun for `turnSettle`, no turn in progress, no dialog, and the run still the card's) runs under the input lock `injectPeer` takes, so nothing typed by the injector or the operator can land between "quiet" and the write. The cheap look before it only spares taking the lock every poll.
THE HOLD IS NOT ADDED HERE. r-007 stage 1b already holds the card's peer injector and every delivery path (`holdingMessages`) from the claim to the wake, so nothing else types into the card during a run. What that could not give was atomicity: a message already past its own check when the run began. The lock gives it.
func (*Service) NcTypeBusy ¶
func (d *Service) NcTypeBusy(taskID string, gen uint64, label, text string, limit time.Duration, busy func(string) bool) error
ncTypeBusy is ncType with the question of what counts as a turn in progress given. It logs what it waits on every ncTiming.logEvery, and names it in the reason it gives up with.
func (*Service) NcWait ¶
func (d *Service) NcWait(taskID string, gen uint64, limit time.Duration, what string, cond func() (bool, error)) error
ncWait polls cond until it is true, the run is replaced, the terminal goes, or the time is up.
func (*Service) NewContextFor ¶
newContextFor is the card's sequence as the board draws it, or nil.
func (*Service) NewContextWakeFor ¶
newContextWakeFor is the wake with the says the card sent since its launcher last prompted it, marked as already delivered. The fresh context knows only the handoff, and one that re-ran its last errand sent the same reply twice.
func (*Service) NoteWrapGaveUp ¶
NoteWrapGaveUp ends a wait that got no ready: the room writes the fallback handoff and says so on the card's history.
func (*Service) PrepareHandoff ¶
prepareHandoff is handoffPath stamped with the time, with its directory made, so the agent can write there. A new name each cycle, since an agent that overwrites must read the old file first.
func (*Service) QueueWake ¶
func (d *Service) QueueWake(taskID, text, by string) (*store.RestartWake, *store.RestartWake, error)
queueWake stores a wake for a card and mirrors it.
func (*Service) ReleaseHeld ¶
releaseHeld is called when a cycle ends any way at all: the wake typed, a failed step, a dismissal. What was held is then delivered by the ordinary paths, so the typist is kicked to try at once rather than at the end of a backoff. It never types ahead of the wake prompt, which has been typed by now.
func (*Service) RunNewContext ¶
runNewContext is the sequence. Each step ends only when the one before it has really finished, and a step that cannot leaves the chip failed with a reason and types nothing further.
func (*Service) RunnerHasNoShell ¶
runnerHasNoShell is whether the card's launch withholds both shells, so the prompt names the tool alone.
func (*Service) SaveNewContextJournal ¶
func (d *Service) SaveNewContextJournal(snap map[string]NcJournalRow)
saveNewContextJournal writes the snapshot. A store that cannot take it has halted, which says so on its own, so this only logs.
func (*Service) StartDeployHold ¶
startDeployHold sets the hold on every card here with a live session, but the deployer's and the exempt ones.
func (*Service) StartNewContext ¶
StartNewContext begins the sequence on a card and returns at once. The steps run in the background and the card's chip says where they are. A failed chip past the ack resumes where it stopped, so a session that already wrote its handoff, or was already cleared, is not asked to write another.
func (*Service) TryWake ¶
func (d *Service) TryWake(w *store.RestartWake, now time.Time)
tryWake types one wake in when the runner is back and the gate is open, and otherwise leaves it for the next tick.
func (*Service) WakeRunnerReady ¶
wakeRunnerReady reports whether the runner up now is the one the wake is for, and is ready to take input.
THE RUNNER MUST HAVE STARTED AFTER THE WAKE WAS QUEUED. The wake is queued while the old runner is still alive, and typing into it would be the forced turn this is not.
func (*Service) WakeSawSession ¶
wakeSawSession records a SessionStart for a card. Called from onSession.
`conv` is the conversation id the hook reported. A new one is the proof a failed new-context chip waits for: see `newContexts.sessionStarted`.
func (*Service) WakeTick ¶
wakeTick is one look at every wake, typing in each one whose card is ready.
func (*Service) WrapCandidate ¶
wrapCandidate is a card that is working and so is asked.
func (*Service) WrapCard ¶
func (d *Service) WrapCard(ctx context.Context, t *store.Task, path string, ack <-chan struct{}) string
wrapCard types the prompt into one card and waits for its ack or for it to go idle.
func (*Service) WrapUpForRestart ¶
func (d *Service) WrapUpForRestart(ctx context.Context, wait time.Duration, why string) (rep WrapReport)
wrapUpForRestart asks every working card to wrap up, waits for each to say ready or go idle (at most wait), queues a restart wake on each card asked and returns what happened. It narrates every step. The caller then restarts.
func (*Service) WriteFallbackHandoff ¶
WriteFallbackHandoff writes the state file the card did not, pointing at the newest earlier handoff of the card and the tail of its history, so the restart wake has something to name. It never replaces a file the card wrote.
type UnsavedRefresh ¶
unsavedRefresh holds a card's refreshes back until its cache would expire, or until the card takes a real turn after the fork.
type Verdict ¶
type Verdict struct {
Act string // "refresh", "skip", "break-even"
Why string
Reply *LastReply
H *store.Harness
Price KeepalivePrice
Budget float64
Spent float64
Count int
Expiry time.Time
Anchor time.Time
History []*store.KeepaliveRefresh
}
verdict is one card's decision on one tick.
type Wakes ¶
type Wakes struct {
Mu sync.Mutex
By map[string]*store.RestartWake
// sessionAt is the last SessionStart hook per card, in this process. In
// memory on purpose: the question is whether the runner that is up NOW has
// started, and no earlier process can answer that.
SessionAt map[string]time.Time
// convAt is the conversation id that SessionStart carried. In memory, like it.
ConvAt map[string]string
// deliver serializes a delivery attempt against a queue or a clear on the
// same wake, so a wake replaced mid-attempt is never typed as well as the
// wake that replaced it. Separate from mu so the board is never held behind
// a paste.
Deliver sync.Mutex
}
wakes mirrors the restart_wake table and remembers when each card's session last started in this daemon.
func (*Wakes) All ¶
func (wk *Wakes) All() []*store.RestartWake
func (*Wakes) Conversation ¶
conversation is the id the card's latest SessionStart reported, or "".
func (*Wakes) Put ¶
func (wk *Wakes) Put(w *store.RestartWake)
func (*Wakes) SawConversation ¶
sawConversation keeps the conversation id of the card's latest SessionStart. An empty id is not recorded: a hook that could not say leaves the last one.
type WrapReport ¶
type WrapReport struct {
Asked []string `json:"asked,omitempty"`
Ready []string `json:"ready,omitempty"`
Idle []string `json:"idle,omitempty"`
Unanswered []string `json:"unanswered,omitempty"`
Woken []string `json:"woken,omitempty"`
WaitedMS int64 `json:"waited_ms"`
Cancelled bool `json:"cancelled,omitempty"`
Already bool `json:"already,omitempty"`
}
WrapReport is what a wrap-up did, cards named by title.
type WrapRun ¶
type WrapRun struct {
Done chan struct{}
Deadline time.Time
Rep WrapReport
}
wrapRun is the wrap-up under way, for a second stop to join. rep is written before done is closed.
type WrapTimings ¶
wrapTimings is how often a card is looked at.