Documentation
¶
Index ¶
- Constants
- Variables
- func AdmitApprovedCall(ctx context.Context, call agentcore.ToolCall, tool agentcore.Tool)
- func BuiltinNudgeRulesYAML() []byte
- func CurrentTurn(ctx context.Context) (sessionID, turnID string)
- func EmptyScopeHint(dir string, otherDirs int) string
- func EmptyScopeHintWithTranslator(t i18n.Translator, dir string, otherDirs int) string
- func EstimateTokens(s string) int
- func LoadRules(cwd, sugaHome string, noProject bool, ruleFile string) (string, string, error)
- func MemoryProvenance(ctx context.Context) memory.Provenance
- func NewEstimatingProvider(inner agentcore.Provider, options EstimateOptions) agentcore.Provider
- func NewSessionID() string
- func NewTurnID() string
- func NormalizeDir(path string) string
- func OpenOutput(sessionsDir, ref string) (io.ReadCloser, error)
- func OutputFileName(turnID, callID string) string
- func OutputStem(name string) (string, bool)
- func RecordApprovalRulePersist(ctx context.Context, file, action, result string)
- func RecordContract(ctx context.Context, rec contractRecorder, sessionID string, round int, ...)
- func RecordNudge(ctx context.Context, rec nudgeRecorder, sessionID, action string, ...)
- func RecordTaskEndIn(repo *store.Store, info tasks.Info)
- func RenderMemorySection(index string) string
- func ResolveSessionID(ctx context.Context, repo *store.Store, query string) (string, error)
- func RuleFiles(cwd, sugaHome string, noProject bool, ruleFile string) ([]string, error)
- func SameDir(a, b string) bool
- func ScanSpill(sessionsDir string) (SpillUsage, []SpillFile, error)
- func ServeTraceView(ctx context.Context, addr string, ...) error
- func SessionIDFromContext(ctx context.Context) string
- func SessionNotFound(err error, id string) error
- func SessionOutputsDir(sessionsDir, sessionID string) string
- func SessionRecoveredNoticeWithTranslator(t i18n.Translator) string
- func SessionSnapshotsDir(sessionsDir, sessionID string) string
- func SessionTitle(prompt string) string
- func SnapshotDirectoryBytes(dir string) (int64, error)
- func SteerMessage(s Steer) agentcore.Message
- func SteerSender(source string) string
- func TaskNoticeMessage(infos []tasks.Info) agentcore.Message
- func TaskNoticeText(infos []tasks.Info) string
- func TurnHops(ctx context.Context) int
- func WithTurnHops(ctx context.Context, hops int) context.Context
- func WriteTrace(w io.Writer, events []store.Event, plans []store.Entry, asJSON bool) error
- func WriteTraceAnalysis(w io.Writer, a TraceAnalysis, asJSON bool) error
- func WriteTranscript(w io.Writer, entries []store.Entry, opts TranscriptOptions) error
- type AgentSummary
- type Budget
- type BudgetMetric
- type BudgetSettings
- type BudgetSnapshot
- type Checkpoint
- type CheckpointAction
- type CheckpointItem
- type ChildRequest
- type ChildResult
- type ClearedContext
- type CompactResult
- type Config
- type ContextOccupancy
- type ContextUsage
- type ContractHooks
- type ContractReport
- type Count
- type EmitFunc
- type EstimateOptions
- type Event
- type ForkResult
- type HandoffRequest
- type HostEvent
- type Ledger
- type LoadedFile
- type NudgeFinding
- type NudgeRule
- type NudgeToolCall
- type PlanRecorder
- type Price
- type ReportedRunUsage
- type ReportedUsage
- type RetryInfo
- type RewindFileAction
- type RewindFileItem
- type RewindPlan
- type RewindResult
- type RewindScope
- type RewindTurn
- type RuleFileStat
- type RuleStats
- type RunRequest
- type RunResult
- type RunState
- type RunUsage
- type Runner
- func (r *Runner) AdoptSessionCwd(ctx context.Context, sessionID, dir string) (string, error)
- func (r *Runner) ApplyRewind(ctx context.Context, snapshots *SessionSnapshots, sessionsRoot string, ...) (RewindResult, error)
- func (r *Runner) Checkpoints(ctx context.Context, snapshots *SessionSnapshots, ...) ([]Checkpoint, error)
- func (r *Runner) ClearContext(ctx context.Context, sessionID string) (ClearedContext, error)
- func (r *Runner) Compact(ctx context.Context, sessionID string) (CompactResult, error)
- func (r *Runner) ConsolidateIdle(ctx context.Context, sessionID string) (CompactResult, error)
- func (r *Runner) ContextThreshold() int
- func (r *Runner) ContextUsage(ctx context.Context, sessionID string) (ContextUsage, error)
- func (r *Runner) Fold() (every, keep int, at float64)
- func (r *Runner) Fork(ctx context.Context, snapshots *SessionSnapshots, ...) (ForkResult, error)
- func (r *Runner) Handoff(ctx context.Context, req HandoffRequest) (Session, error)
- func (r *Runner) HoldSessionLock(sessionID string) (func() error, error)
- func (r *Runner) LastReply(ctx context.Context, sessionID string) (string, bool, error)
- func (r *Runner) LoadSession(ctx context.Context, id string) (Session, error)
- func (r *Runner) LoadedFiles(ctx context.Context, sessionID string, limit int) []LoadedFile
- func (r *Runner) MarkSessionUsedInteractively(ctx context.Context, sessionID string) error
- func (r *Runner) MaxSteps() int
- func (r *Runner) Model() string
- func (r *Runner) ModelSettings() (provider, model string, contextWindow, maxOutputTokens int)
- func (r *Runner) NewSession(ctx context.Context, id, title string) (Session, error)
- func (r *Runner) NewSessionFor(ctx context.Context, id, title, origin string) (Session, error)
- func (r *Runner) NewSessionWithMeta(ctx context.Context, id, title string, extra map[string]any) (Session, error)
- func (r *Runner) NudgeFindings(ctx context.Context, sessionID string, result RunResult) []NudgeFinding
- func (r *Runner) ProcessRoot() string
- func (r *Runner) ProviderName() string
- func (r *Runner) RecordEvent(ctx context.Context, sessionID string, ev HostEvent)
- func (r *Runner) RecordMemoryEvent(ctx context.Context, ev memory.Event)
- func (r *Runner) RecordTaskEnd(info tasks.Info)
- func (r *Runner) RewindPlan(ctx context.Context, snapshots *SessionSnapshots, ...) (RewindPlan, error)
- func (r *Runner) RewindTurns(ctx context.Context, sessionID string) ([]RewindTurn, error)
- func (r *Runner) Run(ctx context.Context, req RunRequest) (RunResult, error)
- func (r *Runner) RunWithContract(ctx context.Context, req RunRequest, contract *outschema.Contract, ...) (RunResult, ContractReport, error)
- func (r *Runner) SaveSessionMeta(ctx context.Context, sessionID string, patch map[string]any) error
- func (r *Runner) SaveSessionShortName(ctx context.Context, sessionID, name string) error
- func (r *Runner) SegmentHistory(ctx context.Context, sessionID string) (SegmentHistory, error)
- func (r *Runner) SelectUndoCheckpoints(ctx context.Context, snapshots *SessionSnapshots, ...) ([]Checkpoint, error)
- func (r *Runner) SessionCard(ctx context.Context, sessionID string) (SessionCard, error)
- func (r *Runner) SessionCwd(ctx context.Context, sessionID string) (string, error)
- func (r *Runner) SessionOrigin(fallback string) string
- func (r *Runner) SessionShortName(ctx context.Context, sessionID string) (string, error)
- func (r *Runner) SessionTainted(ctx context.Context) bool
- func (r *Runner) SessionsDir() string
- func (r *Runner) SetSessionTitle(ctx context.Context, sessionID, title string) error
- func (r *Runner) Steer(sessionID string, msg Steer) (bool, error)
- func (r *Runner) SwitchModel(ctx context.Context, sessionID string, provider agentcore.Provider, ...) error
- func (r *Runner) ToolRegistry() agentcore.ToolRegistry
- func (r *Runner) Undo(ctx context.Context, snapshots *SessionSnapshots, ...) (UndoResult, error)
- func (r *Runner) UndoCore(snapshots *SessionSnapshots, sessionsRoot string) *UndoCore
- func (r *Runner) WithdrawSteers(sessionID string, accept func(Steer) bool) []Steer
- type SectionSize
- type SegmentHistory
- type SegmentItem
- type SegmentSections
- type Session
- type SessionCard
- type SessionCardUsage
- type SessionNotFoundError
- type SessionSnapshots
- func (s *SessionSnapshots) AfterCall(ctx context.Context, result native.SnapshotResult) error
- func (s *SessionSnapshots) AfterUndo(ctx context.Context, result native.SnapshotResult) error
- func (s *SessionSnapshots) BeforeCall(ctx context.Context, req native.SnapshotRequest) (native.SnapshotBefore, error)
- func (s *SessionSnapshots) BeforeUndo(ctx context.Context, req native.SnapshotRequest) (native.SnapshotBefore, error)
- func (s *SessionSnapshots) CleanupAll() (SnapshotCleanupReport, error)
- func (s *SessionSnapshots) CleanupSession(sessionID string) (SnapshotCleanupReport, error)
- func (s *SessionSnapshots) Limits() SnapshotLimits
- func (s *SessionSnapshots) LoadCheckpointState(sessionID, turnID string) (SnapshotCheckpointState, error)
- func (s *SessionSnapshots) LoadTurn(sessionID, turnID string) ([]SnapshotMeta, error)
- func (s *SessionSnapshots) SetCheckpointState(sessionID, turnID string, state SnapshotState) error
- type SessionSpiller
- type ShellCommand
- type SkillsStats
- type SlowCall
- type SnapshotCheckpointState
- type SnapshotCleanupReport
- type SnapshotLimits
- type SnapshotMeta
- type SnapshotRootStatus
- type SnapshotState
- type SpillCompressEntry
- type SpillCompressOptions
- type SpillCompressReport
- type SpillFile
- type SpillUsage
- type Steer
- type TaskNotices
- type TraceAnalysis
- type TraceQuery
- type TraceView
- type Transcript
- func (t *Transcript) AppendAssistant(text string) error
- func (t *Transcript) AppendTool(name, content string) error
- func (t *Transcript) AppendToolCall(name string, args map[string]any, _ string) error
- func (t *Transcript) AppendUser(text string, injected bool) error
- func (t *Transcript) Close() error
- func (t *Transcript) Path() string
- type TranscriptOptions
- type UndoCore
- func (u *UndoCore) Checkpoints(ctx context.Context, sessionQuery string, limit int) ([]Checkpoint, error)
- func (u *UndoCore) Select(ctx context.Context, sessionQuery string, n int) ([]Checkpoint, error)
- func (u *UndoCore) Undo(ctx context.Context, sessionQuery string, n int, force bool) (UndoResult, error)
- func (u *UndoCore) UndoWithOptions(ctx context.Context, sessionQuery string, options UndoOptions) (UndoResult, error)
- type UndoGate
- type UndoOptions
- type UndoResult
- type UsageUpdate
Constants ¶
const ( // ContractActionOK: this check passed. ContractActionOK = "ok" // ContractActionCorrected: this check failed and one correction round follows. ContractActionCorrected = "corrected" // ContractActionFailed: the final check failed; the call ends with exit code 6. ContractActionFailed = "failed" )
The output contract of one call (design docs/design/2026-10-22-output-schema-design.md 4.1/4.3): the first turn is already done - nudge and --verify had their pushes - and the answer it returned is what the caller gets. The contract judges that answer; a failing one gets exactly one injected correction round.
const ( ContractReasonFailed = "failed" ContractReasonCanceled = "canceled" ContractReasonYielded = "yielded" ContractReasonWrapUp = "wrap_up" ContractReasonTruncated = "truncated" ContractReasonEmpty = "empty_final" )
Reasons a finished turn is not judged (design 4.5): the turn itself did not reach a normal end, so its failure is not the contract's.
const ( EstimateAuto = "auto" EstimateOn = "on" EstimateOff = "off" )
const ( // The actions a host reports for a finding. NudgeActionPushed = "pushed" NudgeActionHinted = "hinted" NudgeActionRecorded = "recorded" )
The rule names a finding and the trace event carry; the kinds of those rules are nudge_rules.go's NudgeKind* constants.
const ( // NudgeKindPromise marks a promise rule: the answer ends with "and now I // will ..." but no tool call follows it (the old N2). NudgeKindPromise = "promise" // NudgeKindUnverifiedWrite marks a write rule: a successful write tool call // ran and no check (a call of a check tool whose command matches the rule's // check_command) followed it. NudgeKindUnverifiedWrite = "unverified_write" // NudgeKindPlanOpen marks the plan rule: the session plan still has open // steps (it reads no field of its own). NudgeKindPlanOpen = "plan_open" )
The fixed rule kinds of the "stopped too early" check (design docs/design/2026-10-22-nudge-design.md): configuration can tune the built-in rules, add phrasings and switch a rule off, but it cannot teach them new logic - the kinds and what each one reads are fixed here.
const ( NudgeRulePromiseZh = "promise-zh" NudgeRulePromiseEn = "promise-en" NudgeRuleUnverifiedWrite = "unverified-write" NudgeRulePlanOpen = "plan-open" )
The built-in rule names; a rule file replaces them by name or switches them off with enabled: false.
const ( // EventSessionRecovered is the caller-facing event kind of a recovered // session. Chat renders SessionRecoveredNotice for it and run prints the // same notice on stderr; it has no stream-json line, so a consumer that does // not know it ignores it. EventSessionRecovered = "session_recovered" // SessionRecoveredNotice is the one-line notice a caller shows when a // session left running by a dead process was taken back to open. SessionRecoveredNotice = "上一回合异常中断,已恢复会话(中断的回合记为 cancelled)" )
Session recovery. Runner.markRunning marks a session running when one of its turns starts and only Runner.finish takes it back to open, so a process killed mid-turn (kill -9, a crash, a power loss) leaves its session in running for good: every later turn of that session is refused with "not ready for a new turn: running", which is what a chat continued with --resume (or run --resume) hits. recoverStaleSession takes such a session back to open so the next turn can start.
Recovering is only safe when no live process is inside a turn of the session. The proof used here is the session's cross-process lock (process.SessionLock): every writer takes it before it touches the session - chat holds it for its whole lifetime (Runner.HoldSessionLock), run and ACP take it for the turn (Runner.Run) - and the OS releases it when its holder dies. Holding the lock therefore means the running status cannot come from a live process: it is the leftover of one that died. Two cases are no proof at all and are left alone, so the caller keeps refusing (both are reported there):
- Config.LockRoot is empty: no cross-process lock is taken anywhere, so another process may well be inside a turn of the session.
- a sub-agent session (store.KindAgent): its runner is built without LockRoot (wiring.subAgents), so a live sub-agent turn holds no lock and holding it here proves nothing about that session.
The limit of the proof: it trusts a lock that is actually taken, i.e. the lock directory (LockRoot) still existing and the session being written by a suga that uses it.
const ( SessionCardSummaryHandoff = "handoff" // a --from handoff entry SessionCardSummaryCompaction = "compaction" // a segment break's handoff package )
The kinds of summary SessionCard.LatestSummary can come from.
const ( OriginChat = store.OriginChat OriginRun = store.OriginRun OriginACP = store.OriginACP OriginAgent = store.OriginAgent OriginSDK = store.OriginSDK )
Session origins (design 0.3, 会话来源). An entry point names itself when it creates a session, so `suga data gc --retention` can keep interactive sessions longer than the ones a batch job or an editor integration started. The constants are re-exported here so the chat, run and ACP entry points do not have to reach into the store package for them.
const ( DefaultSnapshotKeepTurns = 20 DefaultSnapshotKeepDays = 7 )
const ( // DefaultSnapshotMaxFileBytes is the largest before-image kept for one call. DefaultSnapshotMaxFileBytes int64 = 16 << 20 // DefaultSnapshotMaxSessionBytes bounds before-images in one session. DefaultSnapshotMaxSessionBytes int64 = 256 << 20 // DefaultSnapshotMaxGlobalBytes bounds before-images below the sessions root. DefaultSnapshotMaxGlobalBytes int64 = 1 << 30 )
const ( StopFinal = "final" StopMaxSteps = "max_steps" StopMaxTokens = "max_tokens" StopTimeout = "timeout" )
Stop reasons of a sub-agent run (ChildResult.Stop).
const ( // DefaultTranscriptObservation is the default --max-observation: the byte // limit of one rendered tool result. DefaultTranscriptObservation = 10000 // MinTranscriptObservation is the smallest accepted --max-observation. A // shorter cut makes a model diagnose the cut as a defect of the run. MinTranscriptObservation = 10000 )
const ( ModeReadOnly = "read_only" ModeAllowWrite = "allow_write" )
Run modes recorded in turn_context (Config.Mode).
const DefaultRuleFile = "AGENTS.md"
DefaultRuleFile is the project rule file read at every directory level when the caller has none configured (rules.file). The user-level file is fixed: $SUGA_HOME/AGENTS.md.
const DenialLimit = 3
DenialLimit is how many refused tool calls one turn may accumulate before the runner ends it (stream-json input_required, ACP stopReason refusal).
const MetaRunMode = "run_mode"
MetaRunMode is the session meta key of the run mode the session last ran a turn in (ModeReadOnly / ModeAllowWrite). The mode decides which tools a turn declares, so it is part of the request head: a segment break between turns in another process (`suga session compact`) reads it to declare the same tool table as the turn whose request the handoff package continues (H4).
const RuleSourceBuiltin = "builtin"
RuleSourceBuiltin marks a rule that ships with the binary; a user or project rule file carries its path instead.
const SteerSourceKeyboard = "keyboard"
SteerSourceKeyboard is the source of a steer a person typed into the chat (a steer delivered by `suga send --steer` carries "send:<from>" instead).
Variables ¶
var ( // ErrRewindTargetNotFound: the ordinal is out of range, or the turn id is not // a turn of this session (a turn of another session is reported the same way, // so the id does not leak its existence). ErrRewindTargetNotFound = errors.New("rewind target not found in this session") // ErrRewindTargetMasked: the turn was rewound away earlier; it is no longer part // of the conversation. ErrRewindTargetMasked = errors.New("rewind target was already rewound away") // ErrRewindTargetNotUserTurn: the turn exists but a person did not start it (an // injected prompt, a nudge, a delivery) or it has no request entry. ErrRewindTargetNotUserTurn = errors.New("rewind target is not a user turn") // ErrRewindSessionArchived: rewind and fork refuse an archived session. ErrRewindSessionArchived = errors.New("session is archived") // ErrRewindTasksRunning: a background task of the session still runs; rewinding // the conversation under it would leave it reporting into a history it is not in. ErrRewindTasksRunning = errors.New("session has running background tasks") )
Errors of target resolution and of the preconditions. They are sentinels (the returned errors wrap them with the offending argument or count), so the chat command can pick the message with errors.Is (plan T7).
var ErrBusy = errors.New("session busy")
ErrBusy reports an idle consolidation given up at once because a Run or Compact of the session held the gate (nothing was written).
var ErrContextOverflow = errors.New("context window exceeded even after compaction and tool-result truncation")
ErrContextOverflow ends a turn whose model context still exceeds the window after compaction and tool-result truncation. It is returned instead of retrying forever.
var ErrNothingToCompact = errors.New("nothing to compact")
ErrNothingToCompact means no legal cut point exists that would drop anything: the segment break is skipped (:compact reports it, the idle consolidation simply does nothing).
var ErrPreempted = errors.New("idle consolidation preempted")
ErrPreempted reports an idle consolidation that gave way to a Run or Compact before its commit point (it also matches context.Canceled).
var ErrRewindBusy = errors.New("session is busy")
ErrRewindBusy is returned by withSessionUnlessBusy (and the gate behind it) when a rewind/fork cannot take the session right now: a turn holds the in-process gate, or another process holds the session file lock. It never waits for a turn; only the preemptible idle consolidation is waited for.
var ErrRewindStale = errors.New("rewind plan is stale")
ErrRewindStale: the session changed between the preview and the execution (a new entry, a changed file plan, a different cwd...), so the confirmed plan is not what would run. Nothing was changed; preview again.
var ErrSessionBusy = process.ErrSessionLocked
ErrSessionBusy is returned when an undo/checkpoint operation cannot obtain the existing cross-process session lock without waiting.
var ErrSessionNotFound = store.ErrSessionNotFound
ErrSessionNotFound is returned when a session id does not exist.
var ErrSessionPrefixAmbiguous = errors.New("session prefix is ambiguous")
ErrSessionPrefixAmbiguous means a session query matched more than one persisted session. The caller must use a longer prefix or the full ID.
var ErrSteerQueueFull = errors.New("steering queue is full")
ErrSteerQueueFull reports an inbox that already holds steerCapacity steers: the caller tells the person to wait for the step to end instead of queueing without bound.
Functions ¶
func AdmitApprovedCall ¶
AdmitApprovedCall writes the ledger row of one call the approval layer just allowed (tools.Approval.SetOnApproved, installed by wiring): it runs after the decision and right before the tool executes. A call that was refused, or whose approval prompt was cancelled or timed out, never gets here and is not recorded - it never ran, so the next turn must not be told its state is unknown. A read-only tool is not recorded either: an interrupted read has no effect to verify, so the replay may simply drop it, as before.
The write is best-effort: a ledger that cannot be written must not stop the tool. An interruption then replays the call like any other incomplete one - no worse than before this ledger existed.
func BuiltinNudgeRulesYAML ¶
func BuiltinNudgeRulesYAML() []byte
BuiltinNudgeRulesYAML returns the built-in rules in the nudge-rules.yaml file shape, so `suga inspect rules nudge --builtin` prints them and a rule file can be written from the shipped rules (parsed again by LoadNudgeRules).
func CurrentTurn ¶
CurrentTurn returns the session and turn of the tool call ctx belongs to ("" outside a turn).
func EmptyScopeHint ¶
EmptyScopeHint is the stderr/hint line of an empty default-scoped session list (design 2026-10-20 会话列表默认当前目录; the CLI prints it on stderr and ACP session/list carries it in _meta.suga/hint): the message names the current directory, how many sessions the other directories hold and both ways out. otherDirs == 0 means there is nothing anywhere yet.
func EmptyScopeHintWithTranslator ¶
func EmptyScopeHintWithTranslator(t i18n.Translator, dir string, otherDirs int) string
EmptyScopeHintWithTranslator renders the default session scope hint for the host UI. Callers without startup wiring use the Chinese fallback for legacy compatibility; assembled hosts should pass their resolved translator.
func EstimateTokens ¶
EstimateTokens is the token estimate of one text, for the resident context report (the same estimator the context budget uses).
func LoadRules ¶
LoadRules reads user and project instructions in authority order. Project rules come from one file per directory level (the Git root down to cwd), named by ruleFile; "" means DefaultRuleFile. Includes are deliberately one level deep so a rule file cannot recursively expand a tree.
func MemoryProvenance ¶
func MemoryProvenance(ctx context.Context) memory.Provenance
MemoryProvenance is the provenance of a memory write made by a tool in the turn running in ctx.
func NewEstimatingProvider ¶
func NewEstimatingProvider(inner agentcore.Provider, options EstimateOptions) agentcore.Provider
NewEstimatingProvider wraps one concrete provider without changing its optional streaming, model-name, or tool-choice capabilities.
func NewSessionID ¶
func NewSessionID() string
NewSessionID returns a fresh session id: "sg_" + 12 random base32 characters, e.g. sg_3k9m2q1p0v7r. The whole id is random (no local date, timestamp or sequence): every id is unique-looking from its first characters, so a shortened form such as the 8 characters gofer shows identifies one session instead of a day's worth of them. Ids created by older versions ("s_" + 12 random characters and "sess_" + date + timestamp + sequence) stay valid everywhere an id is read.
func NewTurnID ¶
func NewTurnID() string
NewTurnID returns a fresh turn id ("t_" + 12 random characters); it doubles as the run id.
func NormalizeDir ¶
NormalizeDir renders a working directory in the form two directories are compared in: absolute, cleaned, with symbolic links resolved. A path that cannot be resolved - the directory is gone, or a link does not lead anywhere - falls back to its cleaned absolute form, so a session whose directory was deleted still compares by name instead of never matching. "" stays "".
func OpenOutput ¶
func OpenOutput(sessionsDir, ref string) (io.ReadCloser, error)
OpenOutput opens the spill file named by ref (out:<session_id>:<16 hex>) under sessionsDir for reading. It is the one reader of externalised outputs (recall, session_search with a ref, export): it validates the ref, refuses anything that would lead outside the session's outputs directory - a planted symlink included - and transparently reads <stem>.txt or <stem>.txt.gz, with the .txt winning when both exist. A .gz is decoded while it is read, so a large output is never loaded into memory as a whole; a damaged .gz is reported as such instead of yielding garbage.
func OutputFileName ¶
OutputFileName is the file stem of one externalised output: the first 16 hex digits of sha256(turn_id + "\x00" + call_id). The call id comes from the model and may hold ':', '/', '..' or an absolute path, so it never appears in the path itself.
func OutputStem ¶
OutputStem reports the ref stem of one outputs directory entry: the name of a plain .txt or of a compressed .txt.gz. Anything else (the .tmp of an interrupted write, a foreign file) is no output and yields false, so it is never reported or exported as a ref recall could not read back.
func RecordApprovalRulePersist ¶
RecordApprovalRulePersist adapts a chat writeback result to the personal trace store. The chat approver is assembled before the Runner, so it uses the public session id in the turn context and opens the shared store for this best-effort host event instead of depending on wiring internals.
func RecordContract ¶
func RecordContract(ctx context.Context, rec contractRecorder, sessionID string, round int, action string, res outschema.Result, schema []byte)
RecordContract writes one "output_schema" trace event: round, action, passed, source, at most 5 errors, and the schema's hash and size - never its text (design 5, the event table must stay small).
func RecordNudge ¶
func RecordNudge(ctx context.Context, rec nudgeRecorder, sessionID, action string, finding NudgeFinding)
RecordNudge writes the "nudge" trace event of one finding: attrs rule (the rule name), kind (its kind), action (pushed/hinted/recorded) and the evidence summary.
func RecordTaskEndIn ¶
RecordTaskEndIn records a task end straight into repo, for hosts whose tasks outlive the runner (ACP opens a runner per prompt, so a task may end between turns).
func RenderMemorySection ¶
RenderMemorySection is the exported form of renderMemorySection: the resident context report measures the same section the segment context sends.
func ResolveSessionID ¶
ResolveSessionID accepts a complete ID or a unique prefix. Exact matches win so a full ID remains usable even if another session starts with the same text.
func RuleFiles ¶
RuleFiles lists the rule files LoadRules reads, in order: the user-level file, then the project file of each level (the user-level one may not exist; LoadRules skips it then).
func SameDir ¶
SameDir reports whether two working directories are the same directory: both are normalized (NormalizeDir) and, on Windows (a case-insensitive file system), compared ignoring case.
func ScanSpill ¶
func ScanSpill(sessionsDir string) (SpillUsage, []SpillFile, error)
ScanSpill counts the spill files below sessionsDir and lists them, oldest first. A missing sessions root is not an error: a fresh home has no spill files yet.
func ServeTraceView ¶
func ServeTraceView(ctx context.Context, addr string, load func(context.Context, TraceQuery) (*TraceView, error), env func(context.Context) (any, error), ready func(url string)) error
ServeTraceView serves the trace page for view on addr (a loopback address; ":0" picks a port) until ctx ends. load is called per request, so a reload (or the page's own polling) shows a session still running; the request's since_seq / since_event reach it as a TraceQuery, so a page asks for the new part only. env, when set, serves /api/env: this machine's current environment for the session (the 本机环境 tab). ready receives the URL once the listener is up.
func SessionIDFromContext ¶
SessionIDFromContext returns the session of the turn running in ctx ("" outside a turn).
func SessionNotFound ¶
SessionNotFound maps a not-found error for id to SessionNotFoundError.
func SessionOutputsDir ¶
SessionOutputsDir is the outputs directory of one session under sessionsDir.
func SessionRecoveredNoticeWithTranslator ¶
func SessionRecoveredNoticeWithTranslator(t i18n.Translator) string
SessionRecoveredNoticeWithTranslator renders the caller-facing recovery notice.
func SessionSnapshotsDir ¶
SessionSnapshotsDir returns the snapshot directory of a session. It performs no I/O and is useful to callers that need to inspect the on-disk layout.
func SessionTitle ¶
SessionTitle derives a session title from a prompt: the first line of the task itself, with the sections gofer injects in front of a job's prompt skipped and markdown heading marks removed, at most titleLimit runes. A prompt that is nothing but such sections keeps its first line.
func SnapshotDirectoryBytes ¶
SnapshotDirectoryBytes returns the on-disk size of one snapshots directory. WalkDir does not follow links, so GC reporting cannot be redirected outside the session root by a malformed snapshot entry.
func SteerMessage ¶
SteerMessage is the user message of a steer: the text as typed, its source and id in the metadata (isSteerItem tells it apart from the turn's own messages, see injectedItemKeys).
func SteerSender ¶
SteerSender returns the sender of a steer source: the <from> of "send:<from>", or "" for a steer a person typed at this keyboard (SteerSourceKeyboard, an unknown source). The chat labels a message from elsewhere with it ("[来自 x]").
func TaskNoticeMessage ¶
TaskNoticeMessage is the user message of a notice.
func TaskNoticeText ¶
TaskNoticeText is the text of a notice for ended tasks and for what running tasks reported (a watch whose result changed).
func TurnHops ¶
TurnHops is the depth of the turn ctx belongs to (0 outside a turn, and for every turn the person started).
func WithTurnHops ¶
WithTurnHops records the depth of the turn ctx belongs to.
func WriteTrace ¶
WriteTrace prints events and plan entries (oldest first) as a timeline: text mode is one line per event (and one per plan step), asJSON writes one JSON object per line (kind "plan" for a plan entry).
func WriteTraceAnalysis ¶
func WriteTraceAnalysis(w io.Writer, a TraceAnalysis, asJSON bool) error
WriteTraceAnalysis prints the analysis as text, or as one JSON object.
func WriteTranscript ¶
WriteTranscript renders entries, in the order given (by seq), as the plain text transcript of a session.
Types ¶
type AgentSummary ¶
type AgentSummary struct {
Description string
ToolCalls int
Duration time.Duration
Background bool
// TaskID is the background task a background agent runs as (empty for a
// foreground run): chat ties the status line's entry to that task, so the
// manager - not a delivered notice - decides when the entry is gone.
TaskID string
}
AgentSummary is attached to an agent tool result so chat can report the completed child without changing stream-json or ACP event payloads.
type Budget ¶
type Budget = BudgetSettings
Budget is kept as an alias for callers that describe the setting as a budget rather than a set of configuration values.
type BudgetMetric ¶
type BudgetMetric struct {
Limit float64 `json:"limit"`
Used float64 `json:"used"`
Remaining float64 `json:"remaining"`
}
BudgetMetric is one budget dimension's limit and current usage.
type BudgetSettings ¶
type BudgetSettings struct {
Tokens int
CostUSD float64
Scope string
Estimate string
EstimateFactor float64
NoticeRatio float64
}
BudgetSettings is the personal-layer form of the resolved budget settings. A zero value disables budget accounting and preserves the pre-budget path.
type BudgetSnapshot ¶
type BudgetSnapshot struct {
Scope string `json:"scope"`
Tokens BudgetMetric `json:"tokens,omitempty"`
CostUSD BudgetMetric `json:"cost_usd,omitempty"`
Exceeded bool `json:"exceeded"`
Reason string `json:"reason,omitempty"`
// Parent identifies a child event caused by the foreground parent's budget,
// rather than by the child's own agents.max_tokens limit.
Parent bool `json:"parent,omitempty"`
// NoticeRatio is the configured fraction at which chat should remind the user.
NoticeRatio float64 `json:"-"`
Estimated bool `json:"estimated,omitempty"`
EstimatedInputTokens int `json:"est_input_tokens,omitempty"`
EstimatedOutputTokens int `json:"est_output_tokens,omitempty"`
}
BudgetSnapshot is attached to usage updates and budget events. It is an optional observation object: old callers receive nil when no budget exists.
type Checkpoint ¶
type Checkpoint struct {
SessionID string `json:"session_id"`
TurnID string `json:"turn_id"`
StartedAt time.Time `json:"started_at"`
State SnapshotState `json:"state,omitempty"`
Items []CheckpointItem `json:"items,omitempty"`
Shell []ShellCommand `json:"shell,omitempty"`
// Summary counts are deliberately derived from the directory and event
// sources on every read; no checkpoint index is added to the database.
Calls int `json:"calls"`
Files int `json:"files"`
Bytes int64 `json:"bytes"`
Restorable int `json:"restorable"`
Deletable int `json:"deletable"`
Skipped int `json:"skipped"`
Unrecoverable int `json:"unrecoverable"`
ShellOnly bool `json:"shell_only"`
}
Checkpoint describes one turn with file snapshots or shell activity. A shell-only turn is retained in the list so selecting the latest snapshot cannot silently hide an intervening command that may have changed files.
func ListCheckpoints ¶
func ListCheckpoints(ctx context.Context, repo *store.Store, snapshots *SessionSnapshots, sessionQuery string, limit int) ([]Checkpoint, error)
ListCheckpoints returns all turns that have either a file snapshot or a shell_exec event, newest first. limit applies to displayed rows; zero means no limit. The turn order is the database's started_at,id order, reversed here rather than inferred from snapshot directory names.
func SelectUndoCheckpoints ¶
func SelectUndoCheckpoints(ctx context.Context, repo *store.Store, snapshots *SessionSnapshots, sessionQuery string, n int) ([]Checkpoint, error)
SelectUndoCheckpoints selects the latest n turns that have snapshots and are not already undone. Shell-only rows encountered while scanning are included before the selected rows, making the omission visible to chat and CLI.
func (Checkpoint) HasSnapshots ¶
func (c Checkpoint) HasSnapshots() bool
HasSnapshots reports whether this turn can be selected as an undo target.
func (Checkpoint) IsShellOnly ¶
func (c Checkpoint) IsShellOnly() bool
ShellOnly reports whether this row has shell activity but no file snapshots.
type CheckpointAction ¶
type CheckpointAction string
CheckpointAction is the work an undo implementation may perform for one snapshot. T4a only classifies records; T5 supplies the conflict checks and the actual file operations.
const ( CheckpointActionRestore CheckpointAction = "restore" CheckpointActionDelete CheckpointAction = "delete" CheckpointActionSkip CheckpointAction = "skip" CheckpointActionUnrecoverable CheckpointAction = "unrecoverable" )
type CheckpointItem ¶
type CheckpointItem struct {
Meta SnapshotMeta `json:"meta"`
Action CheckpointAction `json:"action"`
RootStatus SnapshotRootStatus `json:"root_status,omitempty"`
Reason string `json:"reason,omitempty"`
// Conflict is set by Select when the target changed after the snapshot
// (contentConflict): undo skips it unless forced, so the plan shown before
// the confirmation lists it as skipped (design 3.4).
Conflict bool `json:"conflict,omitempty"`
}
CheckpointItem is the user-visible classification of one write-tool call.
type ChildRequest ¶
type ChildRequest struct {
ParentSession, ParentTurn, ParentCall string
Type, Description, Prompt string
// Timeout is the soft limit: when it passes the sub-agent is asked to wrap
// up (Config.RunTimeout of the child runner does that); a minute later the
// run is cancelled and the last answer text is the report.
Timeout time.Duration
// Background children keep running under their own limits and do not use the
// parent's budget to request a wrap-up.
Background bool
// Emit receives the sub-agent's progress ("agent_progress" events: its
// tool calls); nil drops them.
Emit EmitFunc
}
ChildRequest is one sub-agent run started by a turn's tool call.
type ChildResult ¶
type ChildResult struct {
SessionID string
Report string
// Stop is why it ended: StopFinal, StopMaxSteps, StopMaxTokens,
// StopTimeout, "cancelled" or "failed".
Stop string
Steps int // model calls
ToolCalls int
Usage agentcore.Usage // priced, every model call of the run
Duration time.Duration
// Tainted: the sub-agent read external content (its session is marked).
Tainted bool
}
ChildResult is the outcome of a sub-agent run.
func RunChild ¶
func RunChild(ctx context.Context, child *Runner, req ChildRequest) (ChildResult, error)
RunChild runs req on child, a Runner built for sub-agents, in a new session of its own. A model failure is returned as an error with the result so far (its SessionID set); a sub-agent that ran past its limits without answering gives its last answer text as the report.
type ClearedContext ¶ added in v0.52.0
type ClearedContext struct {
// Messages is the number of history messages that left the context.
Messages int `json:"messages"`
// Tokens is their estimated size (tokensOfMessages plus the handoff package
// of the closed segment): what the next turn no longer sends.
Tokens int `json:"tokens"`
// Segment is the ordinal of the new segment record (1-based; 0 unknown).
Segment int `json:"segment"`
}
ClearedContext reports what a --clear-ctx break took out of the turn's context: how many message entries left it and their estimated tokens.
type CompactResult ¶
type CompactResult struct {
TokensBefore, TokensAfter int
FirstKeptSeq int64
// Segment is the ordinal of the new segment record (1-based; 0 unknown).
Segment int
}
CompactResult reports a segment break between turns (token figures are estimates of the message context only, excluding system prompt and tool schemas).
type Config ¶
type Config struct {
// Repository is the single core store: sessions, turns, entries and
// agentcore run state (run_id == turn_id) all live in it.
Repository *store.Store
Provider agentcore.Provider
Model string
ProviderName string
Tools agentcore.ToolRegistry
// SessionOrigin is the meta.origin an embedded host records on the
// sessions it creates (wiring.Options.Origin). Empty keeps the entry
// point's own default (chat, run, ACP).
SessionOrigin string
// ApprovalMode is the start-up approval tier, recorded in each turn_context
// event (attr approval_mode); "" (the entry point's default) records nothing.
ApprovalMode tools.ApprovalMode
// Vision is the live capability of the current model: view_image leaves the
// tool table of a model that cannot see images, and a :model switch updates
// this gate instead of rebuilding the tools. nil = the model can see.
Vision *tools.VisionGate
// PromptBuilder is the stable system prompt (identity and working
// conventions only, design D1); the runner sends it unchanged.
PromptBuilder agentcore.PromptBuilder
// RuleSource reads the user/project rules (content, hash). Rules go into
// the segment context; a change inside a segment appends a context update.
RuleSource func() (string, string, error)
// EnvironmentSource and SkillsSource render the environment section (OS,
// workspace, shell, read/write mode and how to enable writing) and the
// skills listing. Both go into the segment context: read for every new
// segment, and the environment is also compared at each turn start (a
// resumed session in another mode or workspace gets a context update).
// SegmentEnvironmentSource is read only when a new segment snapshot is built.
// It may refresh cheap external facts without changing the current segment.
EnvironmentSource func() string
SegmentEnvironmentSource func() string
// PreferredToolsSource returns the names of the preferred tools the
// environment section lists (the available declarations, in configuration
// order); the turn_context event records them, so a trace shows which
// preferred tools the turn saw. nil = this session lists none.
PreferredToolsSource func() []string
SkillsSource func() string
// AddDirs returns the session's additional directories (--add-dir) as
// "path:ro"/"path:rw" entries; the turn_context event records them so a
// trace shows what the session could reach. nil = none.
AddDirs func() []string
// SkillsStats counts the skills by how the listing presents them; the
// context event records it.
SkillsStats func() SkillsStats
// Tasks hands over the notices of background tasks that ended unseen;
// they are added before the next model request (nil: no tasks).
Tasks TaskNotices
AppendSystemPrompt string
// AppendSystemPromptSet marks AppendSystemPrompt as explicitly supplied by
// the caller, so an empty value clears the saved prompt instead of keeping it.
AppendSystemPromptSet bool
// HostContextSource returns the embedding host's context text (persona, topic
// index, verbatim constraints) and a hash of it; nil = the host has none. The
// text is frozen in the segment snapshot at every segment start and compared
// by hash at each turn start: a change inside a segment appends a context
// update. Empty content is the same as no host context (no empty section).
HostContextSource func() (content, hash string)
Hooks []agentcore.Hook
TranscriptDir string
// SessionsDir is the per-session file root ($SUGA_HOME/sessions). Message
// images are stored below <SessionsDir>/<session_id>/images and read back
// from there when a request is assembled; empty disables both.
SessionsDir string
LockRoot string
ProcessRoot string
// OnFilesRestored is told the paths :undo restored or deleted, so the write
// guard of the file tools does not take suga's own restore for an outside
// change; nil = nobody to tell.
OnFilesRestored func(paths []string)
MaxSteps int
// MaxOutputTokens is the output token limit of the model's requests
// (appconfig.ResolveMaxOutputTokens); 0 leaves it to the provider, which
// applies its own default then.
MaxOutputTokens int
// MaxRunTokens and RunTimeout ask a run to wrap up (answer from what it
// has) past that many tokens (uncached input plus output) or that long;
// 0 = no limit. Sub-agent runners set them.
MaxRunTokens int
// Budget is the optional turn/session token and cost budget. A zero value
// keeps the historical unbounded behavior.
Budget BudgetSettings
// DeadlineEnv names the environment variable carrying this run's job
// deadline as RFC3339 (run.deadline_env; gofer sets GOFER_JOB_DEADLINE).
// Non-empty attaches the transient deadline hint to every model request
// (deadline.go); empty = off, the historical no-time-awareness path.
DeadlineEnv string
RunTimeout time.Duration
// Now is the clock of the run time limit (RunTimeout): a turn's deadline is
// Now()+RunTimeout and the limit hook checks Now() against it after every
// model call. nil means time.Now. A test injects a clock because the check
// needs the clock to have moved on, which the real one does not guarantee
// within so short a limit (its resolution can exceed the limit).
Now func() time.Time
// ContextWindow is the effective model's context window in tokens (0 = 128000).
ContextWindow int
// CompactReserveTokens overrides the compaction reserve (default 16000).
// A new segment keeps only the last complete tool exchange verbatim.
CompactReserveTokens int
// FoldEvery/FoldKeep configure history folding of the request view
// (context.fold_every / context.fold_keep, see foldHistory); FoldEvery 0 = off.
FoldEvery, FoldKeep int
// FoldAt is the size trigger of folding (context.fold_at): the segment
// starts folding once the pre-fold request estimate passes FoldAt × the
// compaction threshold. 0 turns the trigger off (FoldEvery then applies from
// the first step, as before).
FoldAt float64
// ImageHistoryTurns, ImageRequestCount and ImageRequestBytes are the image
// input limits of the request view (images.history_turns / max_request_count /
// max_request_bytes); 0 uses the built-in default (appconfig.DefaultImage*).
ImageHistoryTurns, ImageRequestCount, ImageRequestBytes int
// CompactProvider/CompactModel summarize history when llm.compact_model is
// set; nil means the turn's own provider is used.
CompactProvider agentcore.Provider
CompactModel string
// HandoffReusePrefix lets the handoff package of a segment break continue the
// segment's last main-loop request (context.handoff_reuse_prefix, default off
// at the wiring since the 2026-10-27 evaluation): the request is then the same System, tools and messages
// plus one instruction, so the provider cache serves it. Off keeps the old
// request byte for byte (the rollback switch, design 2026-10-27).
HandoffReusePrefix bool
// PinFirstUser, KeepUserWordsBudget and SummaryMaxTokens are the compaction
// knobs (context.pin_first_user / keep_user_words_budget / summary_max_tokens,
// see appconfig.CompactSettings); the zero values are the original behavior.
PinFirstUser bool
KeepUserWordsBudget int
SummaryMaxTokens int
// IdleProvider/IdleModel serve the idle consolidation (models.idle); nil
// means the compact provider is used. HandoffProvider/HandoffModel serve
// the --from handoff package (models.handoff) the same way.
IdleProvider agentcore.Provider
IdleModel string
HandoffProvider agentcore.Provider
HandoffModel string
// Plans is the update_plan sink handed to the tool at build time; New binds
// it to this runner's store.
Plans *PlanRecorder
// Visibility is the deferred-tool layer already wrapped around Tools; New
// binds it to this runner's store (loaded_tools meta) and event recorder,
// and its tool list is added to the segment context.
Visibility *tools.Visibility
// Price looks up the configured price of a (provider id, model); nil or a
// miss means cost stays 0 unless the provider reports it.
Price func(provider, model string) (Price, bool)
// InlineOutputBytes is the output layer's inline threshold
// (tools.max_output_bytes; 0 = tools.DefaultInlineOutputBytes).
InlineOutputBytes int
// Spiller stores tool outputs above the threshold (e.g. a SessionSpiller);
// nil means they are only truncated.
Spiller tools.Spiller
// MinimizeOutput tidies tool results before they enter the context
// (tools.minimize_output, see tools.OutputConfig.Minimize); nil = off.
MinimizeOutput func(call agentcore.ToolCall, content string) (string, bool)
// OutputTexts is the model-facing wording of the tool stack (the approved
// note and the ref/condensed headers) in the run's language (i18n phase
// 1b). The zero value is the historical Chinese text.
OutputTexts tools.ModelTexts
// Translator is the host catalog the model-facing wording of this package
// is read from (deadline hint, budget wrap-up instruction). nil keeps the
// Chinese compatibility fallback, byte-identical to the historical text.
Translator i18n.Translator
// PrefetchTools runs a reply's local read calls ahead concurrently
// (tools.parallel_reads, see agentcore.Config.PrefetchTools); nil = off.
PrefetchTools func(ctx context.Context, calls []agentcore.ToolCall)
// Ledger backs session_search / recall; New binds it to this runner's
// store (late binding, like Plans).
Ledger *Ledger
// TaintTools always taint the session when they return a result
// (memory.taint_tools); TaintOnSpill taint it only when their output was
// externalised (memory.taint_on_spill). Tools declaring External always
// taint.
TaintTools []string
TaintOnSpill []string
// Mode is the run mode recorded in turn_context events: "read_only" or
// "allow_write" (empty = unknown).
Mode string
// MemoryIndex returns the rendered memory indexes of every registered
// scope (memory.Index.Render, concatenated). The runner freezes them in
// the segment snapshot (re-read at every segment break) and renders them
// after the rules; nil means no memory section. A failure is logged and
// never affects the turn.
MemoryIndex func(ctx context.Context) (string, error)
// Version is the suga build version, recorded on each turn (turn_context)
// and as the session's suga_version meta (the last version that ran it).
Version string
// Workspace is recorded as the cwd of the sessions this runner creates
// (and of older sessions without one on their next turn); session_search
// scope workspace matches sessions by it.
Workspace string
// NudgeRules returns the enabled nudge rules CheckNudge evaluates
// (personal/nudge_rules.go); wiring loads the layered rule files. nil =
// the built-in rules.
NudgeRules func() []NudgeRule
// DiffPreview attaches what a file tool call changes on disk
// (internal/diffview, the same construction ACP sends its client) to its
// "tool_call" event, read before the tool runs. Chat asks for it (chat.diff),
// so it can show the diff before an approval question and under the tool
// result; run, stream-json and ACP leave it off and carry no file text in
// their events.
DiffPreview bool
// LoopGuard turns the loop guard on (tools.loop_guard, default on at the
// wiring): a turn that repeats the same tool call with the same arguments
// gets a reminder appended to one of its repeated results (loop_guard.go).
LoopGuard bool
}
Config holds the core store and the model/tool wiring used by a personal agent.
type ContextOccupancy ¶ added in v0.52.0
ContextOccupancy is the turn's context size as stream-json reports it on its turn_end and result lines: the estimated input tokens of the turn's last request and the window they are measured against. Both come from where the context trace event reads them (the builder's estimate, compactLimits), so a caller such as gofer sees the same figure as `suga trace`.
type ContextUsage ¶
type ContextUsage struct {
// Handoff is the handoff package of the current segment (0 without one).
Handoff int `json:"handoff"`
HandoffTokens int `json:"handoff_tokens"`
// History is the kept history of the segment: its chars, its estimated
// tokens and how many messages it holds.
History int `json:"history"`
HistoryTokens int `json:"history_tokens"`
HistoryMessages int `json:"history_messages"`
// Input is the size of the last turn's own messages, EstTokens the trace's
// estimate of that turn's request and Window its context window: all three
// are read from the session's last context event and stay zero before the
// first turn.
Input int `json:"input"`
EstTokens int `json:"est_tokens"`
Window int `json:"window"`
}
ContextUsage is the persisted half of a session's context composition, for chat's :context command. The handoff and history figures come from the same view a turn assembles (loadHistory) and are measured by the same helpers the context trace event uses (charsOfMessages, tokensOfMessages), so the command and `suga trace` never disagree about what the context holds.
type ContractHooks ¶
type ContractHooks struct {
// BeforeCorrection runs once, right before the injected correction turn.
BeforeCorrection func()
// Emit is the correction turn's event sink (the same one the first turn had).
Emit EmitFunc
}
ContractHooks lets the caller act around the correction round: end its streamed line before the round starts, and receive the round's events.
type ContractReport ¶
type ContractReport struct {
// Checked is false when the turn's end left nothing to judge.
Checked bool
// Passed is the final check's outcome (meaningful only when Checked).
Passed bool
// Rounds counts the checks: 1 when the first answer was fine, 2 when the
// correction round was needed.
Rounds int
// Source says where the checked JSON came from (whole/fenced/substring/no_json).
Source string
// Reason says why the answer was not checked (Checked=false only).
Reason string
// Errors are the last check's validation problems.
Errors []outschema.Error
// Value is the passing value, compacted raw JSON.
Value json.RawMessage
}
ContractReport is the outcome of judging one call's answer.
type EmitFunc ¶
func AgentProgress ¶
AgentProgress is where a sub-agent started by the turn of ctx sends its progress ("agent_progress" events reach the turn's Emit); nil outside a turn or for a turn without Emit.
type EstimateOptions ¶
EstimateOptions controls the provider-side usage estimator. Factor is applied after the shared rune/token approximation and is rounded up to whole tokens.
type Event ¶
type Event struct {
Kind string
SessionID string
TurnID string
RunID string
Text string
ToolName string
// CallID names the tool call a "tool_call", its "tool_result" and the
// "agent_progress" events of the sub-agent it started (the call's id from the
// model, e.g. call_abc): chat tracks a running sub-agent by it, so two agents
// with the same description cannot share an entry. Empty when the producer
// does not know it.
CallID string `json:"-"`
// ToolArgs is set on "tool_call" and "agent_progress" events: the call's
// whole arguments, for chat's one-line summary of the call (Text carries
// them as JSON cut at toolArgSummaryLimit, too short to decode a long shell
// command or a file_write). It is never serialized: run, stream-json, ACP
// and the trace keep using Text.
ToolArgs map[string]any `json:"-"`
// IsError is set on "tool_result" events whose tool call failed or was refused.
IsError bool
// Plan is set on "plan" events (the full replaced task list).
Plan *native.Plan
// Change is set on the "tool_call" event of a file tool call (file_edit,
// file_write, file_remove) when this runner previews it (Config.DiffPreview):
// what the call changes on disk, read before the tool ran. Every other event
// leaves it nil, and a caller that did not ask for it (run, ACP) never sees
// one.
Change *diffview.Change
// Usage is set on "usage" events (after each counted model call) and on
// "run_finished" (the final run total).
Usage *UsageUpdate
// Budget is set on budget events and on usage updates when a budget is
// configured. It is nil for the historical no-budget path.
Budget *BudgetSnapshot
// Retry is set on "retry" events: a model request failed for a transient
// reason and is retried after Wait; Text is the reason.
Retry *RetryInfo
// Agent is set on "agent_progress" events (a sub-agent's tool call,
// ToolName and Text as on "tool_call"): the sub-agent's description.
Agent string
// AgentSummary is set on the completed "agent" tool result.
AgentSummary *AgentSummary
// SteerID and SteerSource are set on "steer_delivered" and "steer_returned"
// events - Text is the steer's text: the id and the source ("keyboard",
// "send:<from>") of the message the event is about.
SteerID string
SteerSource string
Status agentcore.RunStatus
State RunState
}
Event is one transport-neutral lifecycle or model-stream update.
type ForkResult ¶ added in v0.54.0
ForkResult is what Fork created: the new session and what it holds.
type HandoffRequest ¶
type HandoffRequest struct {
SourceID string
// NewID is the id of the new session ("" = generate). It must not exist.
NewID string
Title string
// Origin names the entry point creating the new session (personal.OriginChat
// from chat, personal.OriginRun from run); it is stored as the new session's
// meta.origin.
Origin string
}
HandoffRequest creates a new session that continues from SourceID.
type HostEvent ¶
type HostEvent struct {
Kind, Name, Status string
Duration time.Duration
Error string
Attrs map[string]any
}
HostEvent is an observability event produced by the host around the runner (chat's scheduler, for one) rather than by a turn.
type Ledger ¶
type Ledger struct {
// contains filtered or unexported fields
}
Ledger implements native.LedgerSearcher over the session store and the sessions directory (externalised outputs). Like PlanRecorder it is created before the Runner and bound to the Runner's store in New (Config.Ledger).
func (*Ledger) Fetch ¶
Fetch returns a cleaned window of a message ref (<session_id>/<seq>) or of an output ref (out:<session_id>:<hex>).
func (*Ledger) Search ¶
func (l *Ledger) Search(ctx context.Context, q native.LedgerQuery) (native.LedgerSearchResult, error)
Search runs a ledger full-text search, or a line scan of one externalised output when q.Ref is set. Snippets are cleaned (redact.Clean).
type LoadedFile ¶
type LoadedFile struct {
Path string `json:"path"`
Tool string `json:"tool"`
// Turn is the 1-based turn this use belongs to (the order the turns appear
// in the session's events, not a stored id).
Turn int `json:"turn"`
Bytes int `json:"bytes"`
}
LoadedFile is one file a session's tool put into its context: the path, the tool that touched it, the turn it happened in and what the result cost.
type NudgeFinding ¶
type NudgeFinding struct {
Rule string
// Kind is the rule's kind (NudgeKind*), so hosts treat every rule kind the
// same without knowing rule names.
Kind string
Evidence string
}
NudgeFinding is one hit rule with the evidence the model (or the trace) is told about.
func CheckNudge ¶
func CheckNudge(rules []NudgeRule, calls []NudgeToolCall, plan *native.Plan, finalText string, completed bool) []NudgeFinding
CheckNudge evaluates the rules over one finished turn and returns the findings in rule order. rules are the enabled ones (LoadNudgeRules); completed says the turn ended with a plain-text answer (the final assistant message carried no tool call); plan is the session's latest plan, nil when the session never made one.
type NudgeRule ¶
type NudgeRule struct {
Name string `yaml:"name"`
// Kind is one of the three fixed kinds above; a new rule (one no built-in
// rule carries) must name it, so the evaluation knows what to read.
Kind string `yaml:"kind"`
// Enabled switches the rule off (nil = on): a same-name entry with
// enabled: false removes the earlier rule.
Enabled *bool `yaml:"enabled"`
// Patterns lists the promise kinds' continuation phrasings (Go regexp,
// matched against the answer's last paragraph).
Patterns []string `yaml:"patterns"`
// WriteTools lists the tools whose successful call changed the workspace;
// empty = the default (file_edit/file_write/file_remove).
WriteTools []string `yaml:"write_tools"`
// CheckTools lists the tools that can validate a change; empty = the
// default (shell_exec).
CheckTools []string `yaml:"check_tools"`
// CheckCommand, when set, is the regexp a check call's command must match
// to count as a verification; empty = any call of a check tool counts.
CheckCommand string `yaml:"check_command"`
// Source is where the rule came from (builtin, or the loaded file's path);
// LoadNudgeRules fills it.
Source string `yaml:"-"`
// contains filtered or unexported fields
}
NudgeRule is one rule of the check. Configuration writes it as a `rules` list in nudge-rules.yaml; a rule file entry replaces a same-name rule whole (an empty field falls back to the kind's default), so an entry that only sets check_command on unverified-write rebuilds the rule from its defaults.
func LoadNudgeRules ¶
LoadNudgeRules returns the built-in rules merged with the rule files in order (later files win): a rule with the name of an earlier one replaces it whole, a new name is appended. Missing files are skipped; a file that does not parse or holds a broken rule (bad regexp, unknown or missing kind) is reported with its path and skipped as a whole. The result is the enabled rules in load order, each with its Source set.
type NudgeToolCall ¶
type NudgeToolCall struct {
Name string
// OK is false for a refused or failed call: only a call that went through
// counts as "the workspace changed" or "the change was checked".
OK bool
// Targets are the files or directories the call was about (trace attr target).
Targets []string
// Command is the command a check tool ran (trace attr command, recorded for
// shell calls), so a write rule's check_command can match it. Empty when
// the call was not a shell command.
Command string
}
NudgeToolCall is one tool call of the turn, in execution order.
type PlanRecorder ¶
type PlanRecorder struct {
// contains filtered or unexported fields
}
PlanRecorder implements native.PlanSink. The update_plan tool is built before the Runner exists, so the recorder is bound to the Runner's store by Config.Plans in New (late binding). It persists a plan entry for the current turn and publishes a "plan" event through the running turn's Emit callback.
func NewPlanRecorder ¶
func NewPlanRecorder() *PlanRecorder
NewPlanRecorder creates an unbound recorder; pass it as Config.Plans.
func (*PlanRecorder) RecordPlan ¶
RecordPlan writes the plan entry (TurnID = current turn) and emits the event.
type Price ¶
type Price struct {
Input, Output, CacheRead, CacheWrite float64
}
Price is a model price in US dollars per million tokens.
type ReportedRunUsage ¶
type ReportedRunUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheReadTokens int `json:"cache_read_tokens"`
CacheWriteTokens int `json:"cache_write_tokens"`
TotalTokens int `json:"total_tokens"`
CostUSD float64 `json:"cost_usd"`
ToolCalls int `json:"tool_calls"`
}
ReportedRunUsage is the reported shape of RunUsage on the stream-json usage/turn_end/result/input_required/error lines and the ACP usage_update _meta. Accounting matches ReportedUsage (input_tokens excludes cache), but every field is always present and tool_calls is added.
func ReportRunUsage ¶
func ReportRunUsage(u RunUsage) ReportedRunUsage
ReportRunUsage converts a run total to the reported shape.
type ReportedUsage ¶
type ReportedUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheReadTokens int `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
TotalTokens int `json:"total_tokens"`
CostUSD float64 `json:"cost_usd,omitempty"`
}
ReportedUsage is the usage shape emitted on the output layer (stream-json result/input_required/error lines and ACP usage_update), in Anthropic-style accounting: input_tokens excludes cache, cache tokens are reported separately and total = input + output + cache_read + cache_write.
func ReportUsage ¶
func ReportUsage(u agentcore.Usage) ReportedUsage
ReportUsage converts internal usage to the reported shape. The provider layer normalizes agentcore.Usage.InputTokens to INCLUDE cache read/write tokens (OpenAI prompt_tokens already contains cached_tokens; the Claude provider adds cache_read/cache_creation to input_tokens), so the cache part is subtracted here instead of changing the provider normalization.
type RetryInfo ¶
type RetryInfo struct {
// Attempt counts the failed attempts so far (1 for the first retry).
Attempt int
Wait time.Duration
// Restart: the failed attempt had already streamed text; the message is
// streamed again from its start.
Restart bool
}
RetryInfo describes a model request retry (see agentcore.StreamEventRetry).
type RewindFileAction ¶ added in v0.54.0
type RewindFileAction string
RewindFileAction is what a rewind does (or reports) for one file.
const ( RewindFileRestore RewindFileAction = "restore" RewindFileDelete RewindFileAction = "delete" RewindFileConflict RewindFileAction = "conflict" RewindFileUnrecoverable RewindFileAction = "unrecoverable" )
type RewindFileItem ¶ added in v0.54.0
type RewindFileItem struct {
TurnID string
// Path is the snapshot entry path; for an unrecoverable item without a
// snapshot it is the raw attrs["target"] value (maybe relative or a dir).
Path string
Action RewindFileAction
// Reason explains a conflict or unrecoverable item.
Reason string
}
RewindFileItem is one file line of a rewind plan or result.
func DedupeRewindFiles ¶ added in v0.54.1
func DedupeRewindFiles(items []RewindFileItem) []RewindFileItem
DedupeRewindFiles reduces per-entry rewind file results to one row per path (the last entry of a path wins), for display. The input is not modified.
type RewindPlan ¶ added in v0.54.0
type RewindPlan struct {
SessionID, TargetTurn string
Scope RewindScope
CutSeq int64
// Files is filled when the scope includes files.
Files []RewindFileItem
// LatestSeq is the session's newest entry seq at preview time.
LatestSeq int64
}
RewindPlan is the preview of a rewind.
type RewindResult ¶ added in v0.54.0
type RewindResult struct {
// Files are the files actually restored, deleted, skipped or unrecoverable.
Files []RewindFileItem
// Conversation reports that a rewind record was written.
Conversation bool
// DroppedTasks are the ended-task notices taken out and discarded.
DroppedTasks []tasks.Info
// Notice is the text queued for the model; empty when nothing was queued.
Notice string
// Warnings are non-fatal problems the caller should show (the rewind stands):
// the fold meta reset failed after the record was written.
Warnings []string
}
RewindResult is what a rewind actually did.
type RewindScope ¶ added in v0.54.0
type RewindScope string
RewindScope is which parts of a session a rewind takes back.
const ( RewindScopeFiles RewindScope = "files" RewindScopeConversation RewindScope = "conversation" RewindScopeBoth RewindScope = "both" )
type RewindTurn ¶ added in v0.54.0
type RewindTurn struct {
// Ordinal is the 1-based position among the user turns, oldest first.
Ordinal int
TurnID string
// Summary is the first non-empty line of the request.
Summary string
StartedAt time.Time
}
RewindTurn is one user turn as `:rewind` lists it.
type RuleFileStat ¶
type RuleFileStat struct {
Path string
Original int // bytes on disk
Kept int // bytes emitted into the rules text
Truncated bool
Included bool // read through an @include directive
// Text is the kept content of the file, used to estimate its tokens.
Text string
}
RuleFileStat is one rule file that LoadRules read, and how much of it reached the segment context.
type RuleStats ¶
type RuleStats struct {
Files []RuleFileStat
OriginalBytes int // sum of Original
KeptBytes int // bytes of rule content emitted (headings and markers excluded)
Truncated bool
}
RuleStats reports the size and truncation of the loaded rules. It is diagnostic only: the rules text and hash do not depend on it.
func LoadRulesDetailed ¶
func LoadRulesDetailed(cwd, sugaHome string, noProject bool, ruleFile string) (string, string, RuleStats, error)
LoadRulesDetailed is LoadRules plus the per-file size and truncation report the manifest shows. The text and hash are exactly LoadRules' (this is its only implementation).
type RunRequest ¶
type RunRequest struct {
SessionID string
CreateIfMissing bool
AgentID string
Prompt string
// Images are pictures that go with Prompt (chat :image, Alt+V paste, or a
// caller that hands bytes in). They travel in memory only; the turn's user
// message carries them and the store writes their files (no bytes in the DB).
Images []agentcore.ImagePart
SystemContext string
// EphemeralContext goes into this model request only: it is appended at the
// very end of the projection and never stored in the session, so it does not
// survive a resume and does not touch the system prompt or the tools (the
// output contract travels this way, design 2026-10-22 4.2). Empty leaves the
// projection byte for byte as it was.
EphemeralContext string
Injected bool
// Hops is the automatic-reply depth of this turn (personal.TurnHops): how many
// session messages it is away from the person. 0 for a turn a person started
// (a typed line, `suga send`), h for a turn a hops-h session message started
// (design session_message D3).
Hops int
Emit EmitFunc
}
type RunResult ¶
type RunResult struct {
SessionID string
TurnID string
RunID string
Status agentcore.RunStatus
State RunState
Output string
// Usage is this invocation's usage (provider-normalized: input includes cache).
Usage agentcore.Usage
// SessionUsage is the session-cumulative usage persisted after this turn.
SessionUsage agentcore.Usage
// ModelCalls counts the successful model calls of this invocation,
// including those of a failed or cancelled turn.
ModelCalls int
// RunUsage is the observe-layer run total: every model call of this run
// (compaction and failed attempts that reported usage included) and the
// tool calls (refused included). stream-json and ACP report it as "usage".
RunUsage RunUsage
// LastInputTokens is the input tokens (cache included) of the most recent
// model call, i.e. the context size of the last request; 0 without a call.
LastInputTokens int
// DeniedTools lists the distinct tools refused by the approval layer in
// this turn (first-refusal order); empty when nothing was refused.
DeniedTools []string
// DenialLimitReached is true when the turn was ended because DenialLimit
// refusals accumulated (ACP maps it to stopReason refusal).
DenialLimitReached bool
// WrapUp is why the answer was a wrap-up ("max_steps", or the reason a
// hook asked for one, e.g. a sub-agent's "max_tokens"); empty for a
// normal answer.
WrapUp string
// EmptyFinal marks a normal completion whose final model answer was empty
// after repeated empty replies following a successful tool call.
EmptyFinal bool
// Truncated is true when this turn's answer was cut off at the output token
// limit and may be incomplete; OutputLimit names that limit (0 = the
// provider's or server's own default).
Truncated bool
OutputLimit int
// ErrorKind says why a failed turn failed (llm.ErrorKind):
// "provider_transient" for a cut or broken stream whose retries ran out,
// "provider_bad_response" for a provider answer that could not be used;
// empty for a completed turn, a cancelled one, or a failure that is not a
// provider error. The turn event carries it as attr error_kind and the
// stream-json error line as error_kind, so a caller such as gofer can decide
// whether continuing the session makes sense.
ErrorKind string
// ReturnedSteers are the steering messages the caller has to take care of
// after the turn (design D4), in arrival order: the ones the turn did not
// deliver (a completed turn) or all of them (a cancelled or failed turn, the
// delivered ones first). The caller runs them as the next turn or puts them
// back into its input line.
ReturnedSteers []Steer
}
type RunState ¶
type RunState string
RunState is the caller-facing run status reported in events and results (stream-json "status"). The values are a wire contract; do not change them.
type RunUsage ¶
type RunUsage struct {
// Usage is provider-normalized (input includes cache, see ReportUsage);
// the cost of each attempt is the one written on its model event.
Usage agentcore.Usage
// ToolCalls counts the run's tool calls, refused ones included.
ToolCalls int
}
RunUsage is the run-scoped usage counted at the observe layer (design D8). Unlike usageCollector (runtime AfterModel hook) it sees every model attempt of the run: main turn calls, compaction calls and failed attempts that reported usage. A failed attempt without usage (e.g. a cancelled request) is not counted.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner owns one synchronous turn at a time for a persisted personal session.
func (*Runner) AdoptSessionCwd ¶
AdoptSessionCwd records that sessionID is now worked on in dir: sessions.cwd is updated and the move is written to the trace as a session_cwd_changed event (attrs from/to), so `suga inspect trace` shows where the session moved and `suga session list` follows it. It returns the directory the session had before.
The callers only reach it after comparing the directories themselves (SameDir), so a session already on dir is left untouched, as is an empty dir.
func (*Runner) ApplyRewind ¶ added in v0.54.0
func (r *Runner) ApplyRewind(ctx context.Context, snapshots *SessionSnapshots, sessionsRoot string, plan RewindPlan) (RewindResult, error)
ApplyRewind executes a previewed plan under the session gate and lock; it returns ErrRewindStale when the session no longer matches the preview.
func (*Runner) Checkpoints ¶
func (r *Runner) Checkpoints(ctx context.Context, snapshots *SessionSnapshots, sessionsRoot, sessionQuery string, limit int) ([]Checkpoint, error)
Checkpoints is a thin Runner adapter; all selection and locking stays in UndoCore so CLI and chat can use the same implementation without a Provider.
func (*Runner) ClearContext ¶ added in v0.52.0
ClearContext starts a fresh segment of the session before the next turn: the turn then begins with the resident parts only (system prompt, project rules, segment context snapshot, append prompt) and none of the previous messages.
It is a segment break of the same machinery a compaction uses (the record, loadHistory and the snapshot are shared), with two differences: no handoff package is built - nothing is summarised, so no model call happens - and the session's plan and loaded deferred tools are cleared with it. The closed segment's entries are not deleted.
The session must exist (the caller decides what a missing one means) and it holds the session gate like Compact, so a running turn finishes first.
func (*Runner) Compact ¶
Compact starts a new segment of the session right now (chat :compact, reason manual). The record belongs to no turn, so it is adopted immediately. It holds the session gate: a running Run finishes first, an idle consolidation is preempted (cancelled before its commit point).
func (*Runner) ConsolidateIdle ¶
ConsolidateIdle starts a new segment between turns with reason idle, as the preemptible holder of the session gate (design D5/D6, chat idle consolidation). It never waits for the gate: when the gate is taken it returns ErrBusy right away. A Run or Compact arriving meanwhile cancels it and waits for it to let go. Whether the context is large enough to bother is the caller's decision.
Results: success (the record was written; a cancellation from the write on does not undo it); ErrBusy; ErrNothingToCompact; an error matching context.Canceled (and ErrPreempted when a Run/Compact took over) when it stopped before its commit point - then nothing was written except a cancelled event.
func (*Runner) ContextThreshold ¶
ContextThreshold is the context size (tokens) at which a turn starts a new segment. It depends only on the runner config, not on the session; chat compares the last request's input tokens with it before an idle consolidation (context.idle_min_ratio).
func (*Runner) ContextUsage ¶
ContextUsage returns what the current context holds besides the resident parts. Reading the persisted history fails only when the store cannot be read; a missing context event is not an error (the session has run no turn).
func (*Runner) Fold ¶
Fold returns the history folding settings (every, keep) and the size trigger (at); every 0 = no step cadence, at 0 = no size trigger.
func (*Runner) Fork ¶ added in v0.54.0
func (r *Runner) Fork(ctx context.Context, snapshots *SessionSnapshots, sessionsRoot, sid, target string) (ForkResult, error)
Fork copies the visible history of sid up to the cut of the target user turn into a new session. It runs inside withSessionUnlessBusy (a running turn is refused with ErrRewindBusy) and writes nothing to the source session. sessionsRoot is where the attachments live ($SUGA_HOME/sessions); empty means the runner's own SessionsDir.
func (*Runner) Handoff ¶
Handoff creates a new session whose first entry is a handoff record built from the source session. The source is only read: nothing is written to it and its session lock is not taken. The latest adopted summary is reused when it already covers the whole source view; otherwise a summary is generated in memory (model event recorded under the new session id).
The record is built before the session exists, so a failed handoff leaves no session behind and the same NewID can be retried. The summary call's events carry the new id anyway (events have no foreign key), so a later successful retry also accounts for the failed attempt's tokens.
func (*Runner) HoldSessionLock ¶
HoldSessionLock reserves a session for the lifetime of an interactive chat (the cross-process file lock; see the single flight notes above).
func (*Runner) LastReply ¶
LastReply returns the text of the last assistant message of the session that has any ("" when the session holds no model reply yet) and whether the session's last turn ended normally. An interactive chat that continues an existing session shows that text above its first prompt so the person can go on from it (internal/chat).
It only reads: no model call, no entry written, no hook. A session without a reply is not an error (a new session, or a session handed off with --from, has nothing to show yet).
func (*Runner) LoadSession ¶
func (*Runner) LoadedFiles ¶
LoadedFiles lists the files this session's file tools touched, most recent use first, at most limit of them (0 = all). It reads the recorded tool events only — the paths from addCallAttrs' "target" and the size from addOutputAttrs' "inline_bytes" — so no file is read or measured again, and a path is listed once, under its latest use.
func (*Runner) MarkSessionUsedInteractively ¶
MarkSessionUsedInteractively records that an interactive chat continued a session a non-interactive entry point created (run, ACP): the session counts as interactive for `suga data gc --retention` from then on. A chat session, a sub-agent session and a session from before meta.origin existed (no origin, treated as interactive anyway) have nothing to record.
func (*Runner) MaxSteps ¶
MaxSteps is this runner's per-turn step limit (0 = no limit); the CLI names it in the text-mode wrap-up notice.
func (*Runner) ModelSettings ¶
ModelSettings returns the effective main model settings used by the runner.
func (*Runner) NewSession ¶
func (*Runner) NewSessionFor ¶
NewSessionFor is NewSession for a caller that knows the entry point it runs as: origin is stored as meta.origin (an empty origin stores nothing, for a caller with no origin to declare).
func (*Runner) NewSessionWithMeta ¶
func (r *Runner) NewSessionWithMeta(ctx context.Context, id, title string, extra map[string]any) (Session, error)
NewSessionWithMeta is NewSession with extra meta stored as the session is created (a sub-agent session names its parent from the start, so it is never listed as a session of its own, not even after a crash). Without an id one is generated per attempt: a generated id already taken (a primary-key conflict) is replaced by a fresh one, at most maxIDAttempts times; an id the caller supplied is never retried.
func (*Runner) NudgeFindings ¶
func (r *Runner) NudgeFindings(ctx context.Context, sessionID string, result RunResult) []NudgeFinding
NudgeFindings gathers this turn's evidence from the store and evaluates the rules. It returns nil when agents.nudge is off or the turn must not be checked (a failed, cancelled, yielded or wrapped-up turn).
func (*Runner) ProcessRoot ¶
func (*Runner) ProviderName ¶
ProviderName and Model identify the provider config id and model this runner calls; chat shows them in its per-turn status line.
func (*Runner) RecordEvent ¶
RecordEvent writes a host event for sessionID outside any turn; best-effort like every event (a failed write is only logged).
func (*Runner) RecordMemoryEvent ¶
RecordMemoryEvent writes a memory_write / memory_denied event for the turn in ctx (memory.Policy.Observe); best-effort like every event.
func (*Runner) RecordTaskEnd ¶
RecordTaskEnd records a background task's end in the trace (a task event spanning its whole run). It is called from the task's own goroutine.
func (*Runner) RewindPlan ¶ added in v0.54.0
func (r *Runner) RewindPlan(ctx context.Context, snapshots *SessionSnapshots, sessionsRoot, sid, target string, scope RewindScope) (RewindPlan, error)
RewindPlan is the Runner adapter of the rewind preview (see rewind.go): a read-only plan that takes no gate and no lock.
func (*Runner) RewindTurns ¶ added in v0.54.0
RewindTurns lists the session's user turns a rewind or fork can target, oldest first: a read-only adapter over userTurns for the chat listing.
func (*Runner) Run ¶
Run executes one new turn (run_id == turn_id) of the session. A turn that yielded for input is finished as INPUT_REQUIRED and is not resumed in place: the caller's next prompt is simply a new turn that sees it as history.
func (*Runner) RunWithContract ¶
func (r *Runner) RunWithContract(ctx context.Context, req RunRequest, contract *outschema.Contract, schema []byte, first RunResult, hooks ContractHooks) (RunResult, ContractReport, error)
RunWithContract judges the answer of a finished turn against contract and, when it fails, gives the model one correction round whose answer is judged once more (design 4.3: at most 2 model turns for the whole call). schema is the caller's schema text, which the correction round re-sends in its per-request context. The returned result is the last turn's.
func (*Runner) SaveSessionMeta ¶
SaveSessionMeta merges patch into the stored session metadata (a nil value deletes a key). The front end records the session's added directories here.
func (*Runner) SaveSessionShortName ¶
SaveSessionShortName stores the short name of a session that has none yet: a resumed session keeps the name it was first given, even when two chats open it at the same time. An empty name is ignored.
func (*Runner) SegmentHistory ¶
SegmentHistory returns the persisted view of the session's current segment. It fails when the store cannot be read; the caller decides what a replay failure means (ACP session/load refuses).
func (*Runner) SelectUndoCheckpoints ¶
func (r *Runner) SelectUndoCheckpoints(ctx context.Context, snapshots *SessionSnapshots, sessionsRoot, sessionQuery string, n int) ([]Checkpoint, error)
SelectUndoCheckpoints is the corresponding locked Runner adapter for undo selection. It does not perform file restoration; later undo stages consume this stable, root-validated plan.
func (*Runner) SessionCard ¶
SessionCard reads where one session stands. It is strictly read-only: no entry and no meta is written and no migration is triggered (the repository is already open when the runner runs). Every query is scoped to the session - store.RecentEntries and store.LastEntryAt walk the (session_id, seq) primary key backwards and stop at the first rows, store.CountTurns reads idx_turns_session, store.SumUsageTree aggregates the session's model events - so the cost of a card does not grow with the store, only with the session itself (BenchmarkSessionCard in session_card_test.go measures it).
A session that does not exist returns SessionNotFoundError, which unwraps to ErrSessionNotFound.
func (*Runner) SessionCwd ¶
SessionCwd returns the working directory recorded on a session ("" for a session created before cwd was recorded; the next turn fills it in then).
func (*Runner) SessionOrigin ¶
SessionOrigin returns the origin to record on a session this runner creates: an embedded host declares its own through wiring.Options.Origin; a front end without one keeps its entry-point default (fallback).
func (*Runner) SessionShortName ¶
SessionShortName returns the short name stored in the session meta, or "" when the session has none.
func (*Runner) SessionTainted ¶
SessionTainted reports whether the session of the turn in ctx has seen external content (tainted_at in its meta, design D7). Outside a turn or when the session cannot be read it reports true (fail closed: the write then needs a confirmation).
func (*Runner) SessionsDir ¶
SessionsDir returns the per-session file root ($SUGA_HOME/sessions): images of a session live below <SessionsDir>/<session_id>/images (design 0.3).
func (*Runner) SetSessionTitle ¶
SetSessionTitle updates the persisted display title after an interactive chat's first prompt.
func (*Runner) Steer ¶
Steer hands msg to the running turn of sessionID (design D6, D11). It returns accepted=false when no turn of the session runs in this process, when that turn is already closing (its outcome is being decided) or when msg is empty; ErrSteerQueueFull when the inbox holds steerCapacity steers already. An accepted steer is either taken by the turn's next model request (a "steer_delivered" event and a user message in that request) or handed back through RunResult.ReturnedSteers when the turn ends.
func (*Runner) SwitchModel ¶
func (r *Runner) SwitchModel(ctx context.Context, sessionID string, provider agentcore.Provider, providerName, model string, contextWindow, maxOutputTokens int) error
SwitchModel changes the main model used by the next turn and records the change outside a turn, so it remains visible in the session metadata and trace. provider must already include any fallback pool the caller wants to retain.
func (*Runner) ToolRegistry ¶
func (r *Runner) ToolRegistry() agentcore.ToolRegistry
ToolRegistry is the tool table the runtime lists at every step (observe -> output -> visibility -> approval -> base), so it reflects the model-scoped filtering a turn sees (e.g. view_image and the current model's vision). nil when the runner was built without tools.
func (*Runner) Undo ¶
func (r *Runner) Undo(ctx context.Context, snapshots *SessionSnapshots, sessionsRoot, sessionQuery string, n int, force bool) (UndoResult, error)
Undo executes the same provider-independent file restoration used by chat and CLI. It is a thin adapter; lock ordering and conflict handling stay in core.
func (*Runner) UndoCore ¶
func (r *Runner) UndoCore(snapshots *SessionSnapshots, sessionsRoot string) *UndoCore
UndoCore builds the provider-independent checkpoint service for this runner. The snapshot store is supplied by wiring so the runner remains usable with snapshots disabled and no Provider is needed by the core itself.
func (*Runner) WithdrawSteers ¶
WithdrawSteers takes the session's pending steers accept matches back out of the running turn's inbox and returns them in the order they were typed; the ones a model request of that turn already took stay in the turn's history and are not withdrawn. accept=nil takes back the ones the person typed at this keyboard (SteerSourceKeyboard): a message a `suga send --steer` caller sent is not withdrawn, its sender is waiting for its own fate. Nothing is withdrawn when no turn of the session runs in this process, when nothing matches, or when the turn is already closing (its outcome is being decided and it hands the pending steers back itself).
Each withdrawn steer is recorded in the trace as a "withdrawn" steer event of the turn, so `suga inspect trace` shows what a turn did not receive after all. Chat puts the returned text back on the input line for editing (design "chat:退回插话的 处理").
type SectionSize ¶ added in v0.51.0
SectionSize is one section of a segment context message.
type SegmentHistory ¶
type SegmentHistory struct {
// Summary is the handoff package of the current segment: the latest adopted
// compaction summary ("" when there is none). The client replay shows it as
// one thought note outside the conversation (replay.go in acpserver).
Summary string
// Items are the kept message entries of the segment in their stored order,
// hydrated (full bodies, no stubs).
Items []SegmentItem
}
SegmentHistory is the read-only projection of one session's current segment for a front end that replays persisted history to its client (ACP session/load, design 2026-10-20): the segment's handoff package and the kept messages in order. It is exactly the view loadHistory assembles — the same boundaries and adoption rules, no second implementation of them — so what a client sees is what the next turn's model sees.
type SegmentItem ¶
SegmentItem is one kept message with the entries seq it was persisted under.
type SegmentSections ¶ added in v0.51.0
type SegmentSections struct {
// Segment is the 1-based ordinal of the segment (0 when the event did not
// carry one); Reason is why it started (threshold, manual, idle).
Segment int `json:"segment"`
Reason string `json:"reason,omitempty"`
Bytes int `json:"bytes"`
Sections []SectionSize `json:"sections,omitempty"`
// Changed names the sections whose hash differs from the previous segment (a
// section the new segment lacks counts as changed too). The first segment has
// no previous one, so it lists nothing.
Changed []string `json:"changed,omitempty"`
}
SegmentSections is what one segment started with (the sections attr of its compact event) and which sections changed since the previous segment.
type SessionCard ¶
type SessionCard struct {
SessionID string `json:"session_id"`
Title string `json:"title,omitempty"`
// ShortName is the name a person sees in `suga ps` and the address
// `suga send --session` uses; sessions that never registered a local socket
// (run, ACP) have none.
ShortName string `json:"short_name,omitempty"`
// State is the session's stored status: open, running (a turn is in
// progress, possibly left behind by a dead process) or archived.
State string `json:"state"`
// Origin is the entry point that created the session (chat/run/acp/agent);
// empty for a session from before the key existed.
Origin string `json:"origin,omitempty"`
// LatestSummary is the body of the newest handoff or compaction summary, ""
// when the session has none yet. SummaryKind names which of the two it is,
// SummaryReason the segment break's reason (threshold/manual/idle; empty for
// a handoff entry and for a record written by an older binary).
LatestSummary string `json:"latest_summary,omitempty"`
SummaryKind string `json:"summary_kind,omitempty"`
SummaryReason string `json:"summary_reason,omitempty"`
// SummaryAt is when that summary was written (zero: no summary).
SummaryAt time.Time `json:"summary_at"`
// OpenSteps are the pending and in_progress steps of the latest plan, in
// plan order; PlanUpdatedAt is when that plan was recorded (zero: no plan).
// A plan whose steps are all done has no open steps but keeps its time.
OpenSteps []string `json:"open_steps,omitempty"`
PlanUpdatedAt time.Time `json:"plan_updated_at"`
Usage SessionCardUsage `json:"usage"`
CreatedAt time.Time `json:"created_at"`
// LastActiveAt is the time of the newest entry of the session, or the
// session's update time when it holds no entry at all.
LastActiveAt time.Time `json:"last_active_at"`
// SegmentCount is how many segment records the session has: the start
// record plus one per segment break, so 1 is a session that never compacted.
SegmentCount int `json:"segment_count"`
// Turns is how many turns were started in the session.
Turns int `json:"turns"`
}
SessionCard is where a session stands right now. Building it writes nothing: no entry, no meta, no migration (Runner.SessionCard).
type SessionCardUsage ¶
type SessionCardUsage struct {
Calls int64 `json:"calls"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CacheReadTokens int64 `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int64 `json:"cache_write_tokens,omitempty"`
CostUSD float64 `json:"cost_usd"`
}
SessionCardUsage is the session's cumulative usage, the sub-agent sessions it started included (store.SumUsageTree: the same numbers the session total of chat and ACP shows). CostUSD is the sum of the provider-reported per-call cost of the model events.
type SessionNotFoundError ¶
type SessionNotFoundError struct{ ID string }
SessionNotFoundError reports that --resume or the --from source names no session. It is a stable contract for callers: exit code 4 and a stderr line starting with "session not found: ", so a caller can tell a missing (e.g. pre-store) session from any other failure and fall back to --from.
func (SessionNotFoundError) Error ¶
func (e SessionNotFoundError) Error() string
func (SessionNotFoundError) ExitCode ¶
func (e SessionNotFoundError) ExitCode() int
ExitCode is the process exit code main uses for this error.
func (SessionNotFoundError) Unwrap ¶
func (e SessionNotFoundError) Unwrap() error
type SessionSnapshots ¶
type SessionSnapshots struct {
// contains filtered or unexported fields
}
SessionSnapshots stores file-tool before-images below one sessions root. It implements native.Snapshotter without exposing session storage to native.
func NewSessionSnapshots ¶
func NewSessionSnapshots(sessionsDir string) *SessionSnapshots
NewSessionSnapshots creates a snapshot store with the design defaults.
func NewSessionSnapshotsWithLimits ¶
func NewSessionSnapshotsWithLimits(sessionsDir string, limits SnapshotLimits) *SessionSnapshots
NewSessionSnapshotsWithLimits creates a snapshot store with explicit limits.
func (*SessionSnapshots) AfterCall ¶
func (s *SessionSnapshots) AfterCall(ctx context.Context, result native.SnapshotResult) error
AfterCall fills the pending record belonging to the current session/turn and call. It is intentionally serialized with BeforeCall so repeated calls in a turn retain their inverse order on disk.
func (*SessionSnapshots) AfterUndo ¶
func (s *SessionSnapshots) AfterUndo(ctx context.Context, result native.SnapshotResult) error
AfterUndo completes the pending pre-undo record.
func (*SessionSnapshots) BeforeCall ¶
func (s *SessionSnapshots) BeforeCall(ctx context.Context, req native.SnapshotRequest) (native.SnapshotBefore, error)
BeforeCall persists the before-image before the native tool changes its target. Oversize images get metadata but no before file, allowing the write to continue with an explicit non-reversible result.
func (*SessionSnapshots) BeforeUndo ¶
func (s *SessionSnapshots) BeforeUndo(ctx context.Context, req native.SnapshotRequest) (native.SnapshotBefore, error)
BeforeUndo stores the state immediately before a future undo changes it. Pre-undo records are deliberately outside LoadTurn's normal call list.
func (*SessionSnapshots) CleanupAll ¶
func (s *SessionSnapshots) CleanupAll() (SnapshotCleanupReport, error)
CleanupAll applies per-session retention and then the global byte limit. It is intended for startup and explicit GC, where no active turn is known.
func (*SessionSnapshots) CleanupSession ¶
func (s *SessionSnapshots) CleanupSession(sessionID string) (SnapshotCleanupReport, error)
CleanupSession applies keep_turns, keep_days and the session byte limit. Pending or incomplete call records are never removed as cleanup cannot prove them safe.
func (*SessionSnapshots) Limits ¶
func (s *SessionSnapshots) Limits() SnapshotLimits
Limits returns the effective limits used by the store.
func (*SessionSnapshots) LoadCheckpointState ¶
func (s *SessionSnapshots) LoadCheckpointState(sessionID, turnID string) (SnapshotCheckpointState, error)
LoadCheckpointState reads a turn's state. Old snapshot directories without a state file are treated as open, which keeps pre-T3b sessions readable.
func (*SessionSnapshots) LoadTurn ¶
func (s *SessionSnapshots) LoadTurn(sessionID, turnID string) ([]SnapshotMeta, error)
LoadTurn reads all call records in sequence order. A missing turn is the normal representation of an old session or a session with no writes.
func (*SessionSnapshots) SetCheckpointState ¶
func (s *SessionSnapshots) SetCheckpointState(sessionID, turnID string, state SnapshotState) error
SetCheckpointState changes the lifecycle state without touching call records.
type SessionSpiller ¶
type SessionSpiller struct {
// contains filtered or unexported fields
}
SessionSpiller stores oversized tool outputs as <sessions>/<session_id>/outputs/<hex>.txt (tools.Spiller). The session and turn come from the observe scope in ctx.
func NewSessionSpiller ¶
func NewSessionSpiller(sessionsDir string) *SessionSpiller
NewSessionSpiller returns a spiller writing under sessionsDir.
func (*SessionSpiller) Spill ¶
func (s *SessionSpiller) Spill(ctx context.Context, call agentcore.ToolCall, content string) (string, error)
Spill writes content (secrets masked) and returns its ref. It fails without a session in ctx or with an invalid session id; the output layer then falls back to truncation.
func (*SessionSpiller) TaskOutput ¶
func (s *SessionSpiller) TaskOutput(sessionID, taskID string) (string, string, error)
TaskOutput names the output file of background task taskID of a session (tasks.Config.Output) and its ref: <sessions>/<sid>/outputs/<hex>.txt, so recall and session_search read it like any saved output while it grows. The task writes it itself (redacted line by line).
func (*SessionSpiller) WithQuota ¶
func (s *SessionSpiller) WithQuota(maxBytes int64) *SessionSpiller
WithQuota limits the logical size of all spill files below the sessions root (tools.spill.max_bytes; 0 leaves it unlimited). A new output that would push the total over the limit is refused and the output layer keeps head and tail only: the write path never drops older outputs to make room.
type ShellCommand ¶
type ShellCommand struct {
Command string `json:"command"`
TaskID string `json:"task_id,omitempty"`
Status string `json:"status,omitempty"`
StartedAt time.Time `json:"started_at"`
}
ShellCommand is a redacted shell_exec event associated with a checkpoint. shell_exec is intentionally reported, not included in the undo operation.
type SkillsStats ¶
type SkillsStats struct {
Listed int `json:"listed"`
Named int `json:"named"`
Preloaded int `json:"preloaded"`
Total int `json:"total"`
}
SkillsStats counts the installed skills by how the skills listing presents them: with their description, by name only, or preloaded whole.
type SlowCall ¶
type SlowCall struct {
Step int `json:"step"`
DurationMs int64 `json:"duration_ms"`
OutputTokens int64 `json:"output_tokens"`
ToolCalls int `json:"tool_calls"`
}
SlowCall is one long model call: its step number, duration and output.
type SnapshotCheckpointState ¶
type SnapshotCheckpointState struct {
State SnapshotState `json:"state"`
UpdatedAt time.Time `json:"updated_at"`
}
SnapshotCheckpointState is stored as state.json beside a turn's call records.
type SnapshotCleanupReport ¶
type SnapshotCleanupReport struct {
RemovedTurns int
RemovedBytes int64
// SkippedRecords counts call records left unreadable because their
// meta.json was missing or corrupt.
SkippedRecords int
// RepairedPartials counts stale half-written call directories removed by
// cleanup.
RepairedPartials int
}
SnapshotCleanupReport describes checkpoint directories removed by cleanup.
type SnapshotLimits ¶
type SnapshotLimits struct {
MaxFileBytes int64
MaxSessionBytes int64
MaxGlobalBytes int64
KeepTurns int
KeepDays int
}
SnapshotLimits controls the amount of before-image data retained by a SessionSnapshots. Non-positive values use the corresponding default.
type SnapshotMeta ¶
type SnapshotMeta struct {
SessionID string `json:"session_id"`
TurnID string `json:"turn_id"`
CallID string `json:"call_id"`
Seq int `json:"seq"`
Tool string `json:"tool"`
Root string `json:"root"`
Rel string `json:"rel"`
RealRel string `json:"real_rel"`
Kind string `json:"kind"`
Size int64 `json:"size"`
SHA256Before string `json:"sha256_before,omitempty"`
SHA256After string `json:"sha256_after,omitempty"`
Status string `json:"status"`
Mode string `json:"mode,omitempty"`
File string `json:"file,omitempty"`
TrashDir string `json:"trash_dir,omitempty"`
CreatedAt time.Time `json:"created_at"`
TrashEntries []string `json:"trash_entries,omitempty"`
PurgedDirs []string `json:"purged_dirs,omitempty"`
Source string `json:"source"`
Unrecoverable string `json:"unrecoverable,omitempty"`
}
SnapshotMeta is the self-describing record stored beside one before-image. The byte contents are deliberately kept in before, not in this JSON file.
type SnapshotRootStatus ¶
type SnapshotRootStatus string
SnapshotRootStatus describes whether a snapshot root is still an allowed, exact session root. Undo must not treat an ancestor as an allowed root.
const ( SnapshotRootTrusted SnapshotRootStatus = "trusted" SnapshotRootCwdChanged SnapshotRootStatus = "cwd_changed" SnapshotRootAddedDirRemoved SnapshotRootStatus = "added_dir_removed" SnapshotRootUntrusted SnapshotRootStatus = "untrusted" )
type SnapshotState ¶
type SnapshotState string
SnapshotState is the lifecycle state of one turn checkpoint.
const ( SnapshotStateOpen SnapshotState = "open" SnapshotStateUndone SnapshotState = "undone" SnapshotStatePartial SnapshotState = "partial" )
type SpillCompressEntry ¶
type SpillCompressEntry struct {
// File is the .txt that was (or would be) rewritten.
File SpillFile
// Size is its size on disk, CompressedSize the size of the .txt.gz.
Size int64
CompressedSize int64
}
SpillCompressEntry is one file a compression pass planned, with the size of its compressed form (measured in both modes, so a dry run reports the same numbers an apply would produce).
type SpillCompressOptions ¶
type SpillCompressOptions struct {
// OlderThan compresses only files whose mtime is older than this.
OlderThan time.Duration
// Active holds the session ids a live process is using; their files are
// never rewritten (a task output may still be growing).
Active map[string]bool
// Apply rewrites the files; false only measures what a pass would do.
Apply bool
// Now is the reference time of OlderThan (zero means time.Now).
Now time.Time
}
type SpillCompressReport ¶
type SpillCompressReport struct {
// Usage is the spill picture before the pass, AfterUsage the one after.
Usage SpillUsage
AfterUsage SpillUsage
// Planned are the files the age and activity rules allow to compress.
Planned []SpillCompressEntry
// BytesBefore is the on-disk size of Planned, BytesAfter the size its
// compressed form has (measured in both modes); SkippedActive and
// SkippedYoung count the files the rules left alone.
BytesBefore int64
BytesAfter int64
SkippedActive int
SkippedYoung int
}
SpillCompressReport is what one pass did (or, in a dry run, would do).
func CompressSpillOutputs ¶
func CompressSpillOutputs(ctx context.Context, sessionsDir string, opts SpillCompressOptions) (SpillCompressReport, error)
CompressSpillOutputs compresses the idle .txt outputs of sessionsDir. Each file is written as <stem>.txt.gz through a temporary file in the same directory, decompressed again to verify its content, renamed into place and only then is the plain file removed: a failure at any step leaves the original output readable under the same ref. In a dry run (Apply false) nothing on disk changes; the report measures the compressed size by compressing into a counter.
type SpillFile ¶
type SpillFile struct {
// SessionID owns the file; Stem plus SessionID is its ref.
SessionID string
Stem string
// Size is the bytes on disk, Logical the uncompressed bytes (a .gz records
// them in its trailer).
Size int64
Logical int64
// Compressed marks a .txt.gz.
Compressed bool
ModTime time.Time
}
SpillFile is one spill file found below the sessions root.
type SpillUsage ¶
type SpillUsage struct {
Sessions int
Files int
Compressed int
LogicalBytes int64
PhysicalBytes int64
MaxBytes int64
}
SpillUsage is the quota picture of a sessions root: spill files are counted logically (what recall has to read) and physically (what is on disk).
func (SpillUsage) OverQuota ¶
func (u SpillUsage) OverQuota() bool
OverQuota reports whether the logical size is over the configured quota.
type Steer ¶
type Steer struct {
// ID identifies the steer across the turn (the chat marks the one it sent
// as delivered, the trace records it); empty is allowed.
ID string
// Text is the message as typed. An empty text is never accepted.
Text string
// Source names where the steer came from: "keyboard", "send:<from>".
Source string
// Images are the pictures delivered with the message (`suga send --steer
// --image`): they enter the user message of this turn with their references
// only, and the request view reads the bytes back from the session directory.
Images []agentcore.ImagePart
}
Steer is one message a caller inserts into the running turn of a session (keyboard input, `suga send --steer`).
type TaskNotices ¶
type TaskNotices interface {
TakeNotices(sessionID string) []tasks.Info
// ReturnNotices puts notices a turn took but did not deliver back into the
// pending queue (a cancelled or failed turn: its entries do not replay the
// notice, see replayablePrefix).
ReturnNotices(sessionID string, infos []tasks.Info)
// List returns all of the session's tasks, running or ended (tasks.Manager.List).
// rewind and fork refuse while one runs (rewindPreconditions).
List(sessionID string) []tasks.Info
}
TaskNotices hands over the session's ended background tasks the model has not seen yet (tasks.Manager) and takes them back when the turn that took them did not deliver them.
type TraceAnalysis ¶
type TraceAnalysis struct {
ModelCalls int `json:"model_calls"`
ToolCalls int `json:"tool_calls"`
ParallelSteps int `json:"parallel_steps"` // model calls that issued more than one tool call
MaxCallsPerStep int `json:"max_calls_per_step"` // most tool calls one model call issued
InputTokens int64 `json:"input_tokens"`
CacheReadTokens int64 `json:"cache_read_tokens"`
OutputTokens int64 `json:"output_tokens"`
// ModelMs and ToolMs are the time spent in main model calls and in tool
// calls (side calls such as compaction are not counted).
ModelMs int64 `json:"model_ms"`
ToolMs int64 `json:"tool_ms"`
ReasoningChars int `json:"reasoning_chars"`
TextChars int `json:"text_chars"`
Tools map[string]int `json:"tools"`
ToolErrors map[string]int `json:"tool_errors,omitempty"`
// Rereads lists files read more than once; ReadsAfterWrite counts reads
// of a file this session had already written or edited.
Rereads []Count `json:"rereads,omitempty"`
ReadsAfterWrite int `json:"reads_after_write"`
EditsPerFile []Count `json:"edits_per_file,omitempty"`
// Shell: runs, failures (exit code != 0) and identical commands run again.
ShellRuns int `json:"shell_runs"`
ShellFailures int `json:"shell_failures"`
RepeatedCommands []Count `json:"repeated_commands,omitempty"`
// Tests: shell runs that look like test commands, and how many of them
// came after the first passing one (re-verification).
TestRuns int `json:"test_runs"`
TestRunsAfterPass int `json:"test_runs_after_pass"`
// Phases, in model calls: before the first write or edit, from that step
// to the first passing test run, and after it (-1 when the run never got
// there). A test run passes when its output reports no failure (attr
// test_failed) and it exited 0; a focused run (-run, -k) does not count.
ExploreSteps int `json:"explore_steps"`
WriteToGreenSteps int `json:"write_to_green_steps"`
AfterGreenSteps int `json:"after_green_steps"`
// EditSteps are model calls that wrote or edited files; SingleEditSteps
// those whose only call made a single change (one file_edit replacement
// or one file_write): fixes sent one per step instead of together.
EditSteps int `json:"edit_steps"`
SingleEditSteps int `json:"single_edit_steps"`
// ShellStderrOK counts shell runs that exited 0 but wrote to stderr (a
// failing command before ";" hides its exit code).
ShellStderrOK int `json:"shell_stderr_exit0"`
Spills int `json:"spills"`
Minimized int `json:"minimized"` // results tidied by the output minimizer
Folds int `json:"folds"`
// Cache attribution from the model attrs prefix*: the input tokens the
// provider did not serve from its cache, split into content new since
// the previous request, earlier content sent again after a prefix break
// (by reason: fold, segment, system, tools, rewrite) and content the
// prefix should have let the provider serve but it did not (expired or
// not yet written cache). Estimated from JSON sizes; calls without the
// attrs (older sessions) count in Uncached only.
Uncached int64 `json:"uncached_input_tokens"`
UncachedFresh int64 `json:"uncached_fresh"`
UncachedRebuilt map[string]int64 `json:"uncached_rebuilt,omitempty"`
UncachedProvider int64 `json:"uncached_provider"`
PrefixBreaks map[string]int `json:"prefix_breaks,omitempty"`
// CacheBuckets splits the model calls by cache bucket (store.BucketCold,
// BucketSteady, ...): the class says what happened to the request prefix since
// the previous call, which decides how much of it a prompt cache can serve.
// SteadyLowHit lists the first steady calls below the target hit rate with the
// events that preceded them: where a low hit rate is investigated.
CacheBuckets []store.CacheBucketStat `json:"cache_buckets,omitempty"`
SteadyLowHit []store.CacheLowHit `json:"steady_low_hit,omitempty"`
// FailedAttempts are provider attempts omitted from cache buckets because
// they failed or reported no token usage.
FailedAttempts int `json:"failed_attempts,omitempty"`
// PrefixTokens and PrefixReuse are the prefix reuse rate over every model
// call: cache read over the estimated cacheable prefix of the previous
// requests, capped at 1. It measures "of what the provider could have served,
// how much did it serve", so adding content to a call does not lower it; the
// steady 95% target is read with it beside the hit rate.
PrefixTokens int64 `json:"prefix_reused_tokens"`
PrefixReuse float64 `json:"prefix_reuse_rate"`
// PrefixReuseRead is the part of PrefixTokens the providers served from cache.
PrefixReuseRead int64 `json:"prefix_reuse_read_tokens"`
// Segments reports what each segment started with (the parts of its context
// message: environment, rules, memory index, skills, append prompt, host
// context, deferred tools, handoff package) and which parts changed since the
// previous segment: the data for judging whether the part order should follow
// how often a part changes.
Segments []SegmentSections `json:"segment_sections,omitempty"`
Compactions int `json:"compactions"`
// Retries are the model request retries after transient failures (every
// model call, side calls included) and RetryWaitMs the time waited.
Retries int `json:"retries"`
RetryWaitMs int64 `json:"retry_wait_ms"`
// BackgroundTasks / BackgroundMs: background tasks that ended (of every
// kind) and how long the tasks among them ran in all (time the loop did not
// have to wait for). A watch or a Stop hook stays for as long as it is
// wanted, so its time is not waiting saved: they count apart. A background
// sub-agent counts here like a shell task, its own numbers in AgentMs.
BackgroundTasks int `json:"background_tasks"`
BackgroundMs int64 `json:"background_ms"`
// By kind: WatchTasks counts the watch tasks of the session, WatchRuns the
// times their command ran and WatchChanges the times a run's result
// differed from the previous one; StopHooks counts the runs of the
// background Stop hook (hooks.stop_background). These are parts of
// BackgroundTasks.
WatchTasks int `json:"watch_tasks"`
WatchRuns int `json:"watch_runs"`
WatchChanges int `json:"watch_changes"`
StopHooks int `json:"stop_hooks"`
// BackgroundOverlapMs is the part of the commands' time the loop spent in
// model calls and foreground tool calls anyway: the time the backgrounding saved
// (spans count once where calls overlap, as in a parallel batch).
BackgroundOverlapMs int64 `json:"background_overlap_ms"`
// TaskWaits / TaskWaitMs: calls of the task tool that waited for a task to
// end (action=wait) and the time they blocked the loop.
TaskWaits int `json:"task_waits"`
TaskWaitMs int64 `json:"task_wait_ms"`
// ImmediateWaits counts those waits that came right after the task was
// started: between the shell_exec that returned the task id and the wait
// lay no other tool call, only model calls. It finds tasks run as if they
// were foreground work.
ImmediateWaits int `json:"immediate_waits"`
// Slowest are the longest model calls.
Slowest []SlowCall `json:"slowest,omitempty"`
// Sub-agents (the agent tool): the calls the session made (background
// calls included), the model steps and tool calls they ran, the tokens and
// cost of their own model calls and the time they ran in all (the same
// numbers its trace line shows). A background call returns a task id at
// once, so only its call counts here at first; what it spent (steps, tool
// calls, tokens, cost, stop) arrives with its task's end event. AgentStops
// is why the calls that reported an end stopped: final, max_steps,
// max_tokens, timeout, cancelled or failed.
AgentCalls int `json:"agent_calls"`
AgentSteps int `json:"agent_steps"`
AgentToolCalls int `json:"agent_tool_calls"`
AgentInputTokens int64 `json:"agent_input_tokens"`
AgentCacheReadTokens int64 `json:"agent_cache_read_tokens"`
AgentOutputTokens int64 `json:"agent_output_tokens"`
AgentCostUSD float64 `json:"agent_cost_usd"`
AgentMs int64 `json:"agent_ms"`
AgentStops map[string]int `json:"agent_stops,omitempty"`
}
TraceAnalysis summarizes a session's events for loop analysis (suga inspect trace --analyze): how many steps, which tools, repeated reads and commands, and how much verification happened after the tests first passed. It is derived from the events alone (tool attrs arg/target/exit_code, model attr tool_calls), so older sessions without these attrs give partial numbers.
func AnalyzeTrace ¶
func AnalyzeTrace(events []store.Event) TraceAnalysis
AnalyzeTrace derives a TraceAnalysis from a session's events (in order).
type TraceQuery ¶
type TraceQuery struct {
SinceSeq int64 // entries with seq > SinceSeq
SinceEvent int64 // events with id > SinceEvent
}
TraceQuery narrows a trace view load to what a page does not have yet: entries after SinceSeq and events after SinceEvent. The zero value loads everything (the first load).
type TraceView ¶
type TraceView struct {
Session traceSession `json:"session"`
Events []webEvent `json:"events"`
Entries []traceEntry `json:"entries"`
Analysis TraceAnalysis `json:"analysis"`
// Delta marks a view that carries only the part the page did not have yet
// (see TraceQuery): the page merges it into what it already shows. The
// analysis stays the whole session's, so the header numbers keep up.
Delta bool `json:"delta,omitempty"`
}
TraceView is what `suga inspect trace --web` serves at /api/session: the session, its events, its transcript entries joined to them (tool results to tool events by call id, assistant messages to the model call that produced them) and the loop analysis.
func BuildTraceView ¶
BuildTraceView loads one session for the trace page.
func BuildTraceViewSince ¶
func BuildTraceViewSince(ctx context.Context, repo *store.Store, sessionID string, q TraceQuery) (*TraceView, error)
BuildTraceViewSince loads one session for the trace page, narrowed to q: a page keeps what it loaded first and asks for the new part on every refresh, so a running session is not built and sent again in full each time.
type Transcript ¶
type Transcript struct {
// contains filtered or unexported fields
}
func OpenTranscript ¶
func OpenTranscript(root, sessionID string) (*Transcript, error)
OpenTranscript opens the per-session jsonl file in append mode with private permissions.
func (*Transcript) AppendAssistant ¶
func (t *Transcript) AppendAssistant(text string) error
func (*Transcript) AppendTool ¶
func (t *Transcript) AppendTool(name, content string) error
func (*Transcript) AppendToolCall ¶
AppendToolCall records a tool call as "<name> key=value ..." built from the call arguments (never the tool output), so a transcript reader can tell what was done. The summary is redacted and rune-bounded; values are cut on UTF-8 boundaries.
func (*Transcript) AppendUser ¶
func (t *Transcript) AppendUser(text string, injected bool) error
func (*Transcript) Close ¶
func (t *Transcript) Close() error
Close flushes the final session transcript to disk.
func (*Transcript) Path ¶
func (t *Transcript) Path() string
type TranscriptOptions ¶
type TranscriptOptions struct {
// SessionID names the session in the header and in every truncation marker.
SessionID string
// TurnID narrows the output to one turn ("" = the whole session).
TurnID string
// MaxObservation is the byte limit of one tool result; 0 (or a negative
// value) means DefaultTranscriptObservation. Below MinTranscriptObservation,
// WriteTranscript returns an error instead of cutting further.
MaxObservation int
// NoReasoning leaves the [reasoning] blocks out.
NoReasoning bool
}
TranscriptOptions selects what WriteTranscript renders.
type UndoCore ¶
type UndoCore struct {
Repository *store.Store
Snapshots *SessionSnapshots
SessionsRoot string
LockRoot string
Gate UndoGate
HeldLock func(sessionID string) bool
}
UndoCore owns the provider-independent checkpoint boundary. It only reads the store/snapshot directories and serializes access with the existing gate and run/locks session lock; file restoration is added by later undo tasks.
func NewUndoCore ¶
func NewUndoCore(repo *store.Store, snapshots *SessionSnapshots, sessionsRoot, lockRoot string) *UndoCore
NewUndoCore constructs the provider-independent checkpoint core.
func (*UndoCore) Checkpoints ¶
func (u *UndoCore) Checkpoints(ctx context.Context, sessionQuery string, limit int) ([]Checkpoint, error)
Checkpoints lists checkpoints while holding the session gate first and the existing cross-process lock second. A held chat lock is reused rather than acquired a second time, which is important on Windows as well as Unix.
func (*UndoCore) Select ¶
Select returns the latest n undo candidates with shell-only turns retained.
func (*UndoCore) Undo ¶
func (u *UndoCore) Undo(ctx context.Context, sessionQuery string, n int, force bool) (UndoResult, error)
Undo restores the latest n checkpoints in reverse turn and call order. The core owns the lock for the complete operation, so another writer cannot interleave a write between conflict detection and restoration.
func (*UndoCore) UndoWithOptions ¶
func (u *UndoCore) UndoWithOptions(ctx context.Context, sessionQuery string, options UndoOptions) (UndoResult, error)
UndoWithOptions restores selected checkpoints and queues the same deferred notification used by chat. It keeps the CLI provider-independent while preserving the existing lock and safety checks in UndoCore.
type UndoGate ¶
type UndoGate interface {
Acquire(context.Context) (func(), error)
// AcquireUnlessBusy is Acquire that fails with ErrRewindBusy while a
// non-preemptible holder (a turn) has the gate; see sessionGate.
AcquireUnlessBusy(context.Context) (func(), error)
}
UndoGate is the in-process session gate owned by a Runner. The selected session ID is carried in the context because the existing gate is per-session.
type UndoOptions ¶
UndoOptions selects the checkpoints an undo operation may restore. TurnID takes precedence over Count when it is set; Force only covers content conflicts and never bypasses the other safety checks.
type UndoResult ¶
type UndoResult struct {
SessionID string `json:"session_id"`
Turns int `json:"turns"`
Restored int `json:"restored"`
Deleted int `json:"deleted"`
Skipped int `json:"skipped"`
Unrecoverable int `json:"unrecoverable"`
Files []string `json:"files,omitempty"`
Failures []string `json:"failures,omitempty"`
Forced bool `json:"forced"`
}
UndoResult is the file-level outcome of one undo operation. Files contains the paths successfully restored or deleted; shell commands are intentionally outside this result because undo never attempts to reverse shell_exec.
type UsageUpdate ¶
type UsageUpdate struct {
Run RunUsage
// Session is the session-cumulative usage: earlier runs plus this run so far.
Session agentcore.Usage
// LastInputTokens is the input (cache included) of the model call behind a
// "usage" event, i.e. that request's context size; 0 on run_finished.
LastInputTokens int
// Estimated is true when one or more counted model calls used estimated
// provider usage.
Estimated bool
// Budget is the optional budget snapshot at this usage point.
Budget *BudgetSnapshot
// Context is the turn's context occupancy (nil: no request was assembled).
// It is set on run_finished only, so stream-json can report it on the
// turn_end and result lines.
Context *ContextOccupancy
}
UsageUpdate is carried by the "usage" event (after each counted model call) and by "run_finished" (the final value).
Source Files
¶
- admit.go
- analyze.go
- approval_rule_event.go
- budget.go
- compact.go
- context.go
- context_event.go
- context_usage.go
- contract.go
- cwd.go
- deadline.go
- denial.go
- estimate.go
- fold.go
- fold_supersede.go
- fork.go
- fork_files.go
- gate.go
- handoff.go
- handoff_budget.go
- hops.go
- idcreate.go
- ids.go
- images.go
- lastreply.go
- ledger.go
- logscope.go
- loop_guard.go
- memory.go
- model_texts.go
- nudge.go
- nudge_rules.go
- observe.go
- path_tally.go
- plan.go
- prefix.go
- price.go
- prompt_builder.go
- recovery.go
- replay.go
- rewind.go
- rewind_files.go
- rewind_files_cleared.go
- rewind_notice.go
- rewind_target.go
- rules.go
- runner.go
- runner_events.go
- runner_finish.go
- runner_sessions.go
- segment.go
- segment_clear.go
- segment_handoff.go
- segment_handoff_reuse.go
- segment_history.go
- session_card.go
- session_error.go
- session_origin.go
- shortname.go
- snapshot_bytes.go
- snapshot_retention.go
- snapshots.go
- spill.go
- spill_maintenance.go
- spill_reader.go
- steer.go
- subagent.go
- taint.go
- tasks.go
- title.go
- tokens.go
- trace.go
- trace_budget.go
- trace_transcript.go
- traceweb.go
- transcript.go
- turn_prompt.go
- turncontext.go
- undo.go
- undo_notice.go
- undo_options.go
- undo_restore.go
- undo_runner.go
- undo_trash.go
- usage.go
- visibility.go
- visible.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package backup owns the portable, verified suga data backup archive format.
|
Package backup owns the portable, verified suga data backup archive format. |
|
Package outschema implements the output contract of `suga run --output-schema` and sugasdk.Prompt.OutputSchema (design docs/design/2026-10-22-output-schema-design.md): compile a caller's JSON Schema in a sandbox, extract JSON from a model answer, check it, and render what a report, a trace event and a correction message need.
|
Package outschema implements the output contract of `suga run --output-schema` and sugasdk.Prompt.OutputSchema (design docs/design/2026-10-22-output-schema-design.md): compile a caller's JSON Schema in a sandbox, extract JSON from a model answer, check it, and render what a report, a trace event and a correction message need. |
|
Package store is the single-file SQLite core store for personal sessions: sessions, a linear entry log, turns (agentcore run state) and events.
|
Package store is the single-file SQLite core store for personal sessions: sessions, a linear entry log, turns (agentcore run state) and events. |