Package agent
Go module github.com/bide-ai/bide; all packages.
github.com/bide-ai/bide/agent · pkg.go.dev · Stability: core
Package agent is the core of bide, a Go framework for AI agents that move money: a durability-first, Go-idiomatic toolkit whose side effects fire at most once, whose approvals are signed and counted by k-of-n, and whose every action is provable afterwards.
Constants
const MaxDecisionCertChain = 8,const MaxDecisionCertDER = 16 << 10: MaxDecisionCertChain and MaxDecisionCertDER bound the certificate chain a decision carries: at most this many certificates, each at most this many bytes of DER.const ReasonNotEligible = "not an eligible approver",const ReasonSuperseded,const ReasonNoKey = "no key for this approver",const ReasonBadSig,const ReasonSharedKey,const ReasonNoKeyID,const ReasonAlg,const ReasonNoDecidedAt,const ReasonDecidedAt,const ReasonRequester,const ReasonNoRequester,const ReasonSibling,const ReasonNoSibling,const ReasonLate: Reasons a decision record does not count.const ReasonAfterExpiry: ReasonAfterExpiry: the decision's write landed after the gate recorded its expiry, even if it was stamped before the deadline.const ReasonNoCert,const ReasonCertChain,const ReasonCertIdentity,const ReasonCertUsage,const ReasonCertWindow: Reasons a certificate-bound approver's decision does not count (docs/design/approver-identity.md).const ReasonRevoked: ReasonRevoked: a certificate of the chain has an effective revocation time at or before A(d).const ReasonStatusUnknown: ReasonStatusUnknown: no usable status covers a certificate of the chain.const ReasonStatusStale: ReasonStatusStale: the status available is past nextUpdate or older than the policy allows.const ReasonNoCoveringHead: ReasonNoCoveringHead: no signed tree head of the run covers the decision yet, so the time it became provable is not known.const ReasonHeadTimes: ReasonHeadTimes: the head that first covers the decision is implicated in a contradiction among the run's head times (a larger head stamped earlier than a smaller one, beyond the tolerance).const ApprovalIdentityFormat = "bide.approval-identity.v2",const ApprovalStatusFormat = "bide.approval-status.v2",const ApprovalExecHoldFormat = "bide.approval-exec-hold.v2",const ApprovalIdentityRulesVer = "v1": Formats of the identity records.const EvaluatedLive = "live": EvaluatedLive is ApprovalIdentity.Evaluated of a record the live gate wrote.const MaxStatusInline = 256 << 10: MaxStatusInline is the largest status record (a CRL's DER) stored in the journal; above it the record holds the metadata and the hash, and the bytes go to the policy's status archive.const PauseAwaitingDecisions = "awaiting-decisions",const PauseAwaitingAnchor = "awaiting-anchor",const PauseAwaitingStatus = "awaiting-status",const PauseHeldUntilFinal = "held-until-final",const PauseExecHold = "exec-hold": Pause phases (ApprovalWait.Pause): why a gate with a certificate-bound approver is waiting.const TierIndependentFinal = "independent-final",const TierLogclockFinal = "logclock-final",const TierProvisional = "provisional": Identity tiers (IdentityDecision.Tier).const BasisAtOrAfterDecision = "at-or-after-decision",const BasisLiveBeforeDecision = "live-before-decision": Status bases (IdentityDecision.BasisKind).const TimeSourceLogSignerClock = "log-signer-clock",const TimeSourceRFC3161 = "rfc3161",const TimeSourceAnchorReceipt = "anchor-receipt": Time sources (IdentityDecision.TimeSource).const CompensationAllow = "allow",const CompensationBlock = "block": Compensation says whether a stop also holds the compensation (the rollback) of the calls it covers. (experimental)const DecisionFormat = "bide.approval.v3": DecisionFormat names the signed decision format this version writes and accepts: the domain tag of ApprovalDecisionBytes without its newline.const DecisionFormatCert = "bide.approval.v4": DecisionFormatCert names the signed decision format of a certificate-bound approver: the v3 layout plus the SHA-256 of the signer's leaf certificate (ApprovalDecisionBytesCert).const DefaultReceiver = "default": DefaultReceiver is the name of the receiver WithNotifier's Notifier is, in Notification.Receiver and in WithNotifyRoute, WithNotifyApproverRoute and EscalationStep.const ExpiredResult: ExpiredResult is the result an agent's model reads for a call whose approval gate expired: an error result, as for a denial.const JournalFormat = "bide.journal.v1-dev": JournalFormat is the journal format this version writes: the format every run's header names (see StepHeader).const MaxEscalationSteps = maxEscalationSteps: MaxEscalationSteps is the most steps an escalation chain may have.const MaxStopReason = 1024: MaxStopReason bounds the reason of a stop, a lift or a mode change, in bytes. (experimental)const NotifyDigestTrail = "notify:@digest": NotifyDigestTrail is the name of the trail the periodic digest uses; it belongs to no run.const NotifyOpenTrail = "notify:@open": NotifyOpenTrail is the prefix of the trail that lists the events whose all-clear may still be owed: a watch record before an outcome_unknown, approval_pending, recovery_failing or stop_set event is observed, an unwatch record when nothing more is owed for it.const OpenFirstYear = 2026: OpenFirstYear is the first year an open-trail index can exist: the year the open trail began.const PendingExecHoldReapproval: PendingExecHoldReapproval is ApprovalPending.Reason for a certificate-bound gate whose counted approvals were held before execution (ExecHold: a counted decision no longer holds): the call did not run, and it runs once approvers decide again and a new count passes (ApprovalIdentTallyStep of the next generation).const PendingIdentReapproval: PendingIdentReapproval is ApprovalPending.Reason for a certificate-bound gate whose recorded tally is a plain-name one (approval-tally:<id>), counted without the approvers' certificates: the gate does not run the call on it, and asks again; the new count is recorded under ApprovalIdentTallyStep.const PendingIdentityStatus: PendingIdentityStatus is ApprovalPending.Reason for a certificate-bound gate whose counted approvals cannot be shown to hold right now (the status of a certificate is missing or stale, or a decision no signed head covers): the call did not run and nothing authoritative was written.const PendingReapproval: PendingReapproval is ApprovalPending.Reason for a gate that passed under decisions signed before DecisionFormat (a run journaled by an earlier version): its call did not run, and it runs once approvers decide again under DecisionFormat with SubmitDecision.const PendingSoDReapproval: PendingSoDReapproval is ApprovalPending.Reason for a gate whose recorded tally passed without excluding the requester (ApprovalPolicy.ExcludePrincipal) while its policy now excludes it: the call did not run, and it runs once enough approvers who are not requesters have decided.const ReanchorMinInterval = 10 * time.Second: ReanchorMinInterval is the least time between two forced heads of one run: anchoring signs with the log key, which may be an HSM or KMS key with quotas and cost, so the gate rate-limits it.const SaltSize = 32: SaltSize is the length of Record.Salt: 32 bytes (256 bits) from crypto/rand.const StopControlRun = "@stop": StopControlRun is the run ID of the control run: the journal run in which a store holds the stop, lift and mode records. (experimental)const StopFormat = "bide.stop/1": StopFormat names the format of a stop record. (experimental)const StopTrailName = "stop": StopTrailName is the name of the audit trail of a deployment's stops: an append-only sequence of the control run's signed records, committed, signed and anchored by the audit package (audit.StopTrail over an audit.AuditedEventStore). (experimental)
Variables
var ErrConfig = errors.New("config"): ErrConfig is a programmer-facing misuse or misconfiguration, not a runtime fault.var ErrModel = errors.New("model"): ErrModel is a model-provider call that failed: HTTP status, decode, stream error.var ErrTool = errors.New("tool"): ErrTool is a tool that failed or was misused (unknown tool, bad arguments).var ErrStorage = errors.New("storage"): ErrStorage is a durable-store I/O failure: marshal, insert, query, history.var ErrProtocol = errors.New("protocol"): ErrProtocol is malformed wire or journal data (bad log entry, unknown content part).var ErrBudget = errors.New("budget"): ErrBudget is a middleware limit tripping (e.g. a token budget).var ErrUnknownTool = fmt.Errorf("unknown tool: %w", ErrTool),var ErrToolArgs: Condition sentinels, specific causes, each wrapping its category.var ErrToolOutcomeUnknown: ErrToolOutcomeUnknown is a tool call that may or may not have taken effect: the tool sent its request but lost the connection (or its deadline passed) before the answer came back.var ErrToolReinvoked: ErrToolReinvoked is a tool middleware calling a tool that is not retry-safe a second time for the same tool call.var ErrNoRecordedOutput: Condition sentinels, specific causes, each wrapping its category.var ErrIncompleteResponse: ErrIncompleteResponse is a model stream that ended without a Finish event: the response stopped partway through a turn, so what arrived is not the model's answer.var ErrTruncatedToolArgs: Condition sentinels, specific causes, each wrapping its category.var ErrOutputTruncated: ErrOutputTruncated is a model turn that ended at its output token limit (or the context window): Finish reason FinishLength.var ErrOutputFiltered: ErrOutputFiltered is a model turn that a provider's safety or content filter stopped, or that the model refused: Finish reason FinishFiltered.var ErrStreamProtocol: ErrStreamProtocol is a model stream that broke its provider's event protocol, such as content after the turn's end or an event after the Finish.var ErrToolUseIDReused: ErrToolUseIDReused is a model turn whose tool call has no ID, repeats an ID from an earlier turn of the conversation, repeats one within the turn, or has an ID that is not valid UTF-8 (the journal cannot hold it).var ErrToolUseIDInvalid: ErrToolUseIDInvalid is a model turn whose tool call has an ID that holds '#', which the engine reserves: it derives a second approval subject from a call's ID by appending "#" and a suffix, so no ID a model chooses may spell one.var ErrNegativeUsage: ErrNegativeUsage is token usage with a negative count, reported by a model or returned by a middleware.var ErrQuotaExhausted: ErrQuotaExhausted is a provider refusing a call because the account's quota or credit is used up (OpenAI insufficient_quota, Anthropic billing_error, HTTP 402, a Gemini daily quota), as opposed to a momentary rate limit.var ErrResponseTooLarge: ErrResponseTooLarge is a streamed response with a line longer than the adapter reads, or longer in all than its adapter's cap (see MaxSSELine and LimitResponse in model/provider).var ErrBudgetExceeded,var ErrMaxTurns: Condition sentinels, specific causes, each wrapping its category.var ErrInvalidApproval: ErrInvalidApproval is an approver decision rejected at submission by SubmitDecision's WithDecisionCheck: no such tool call, an unknown approver, or a signature that does not verify for this exact call.var ErrStatusUnavailable: ErrStatusUnavailable is a certificate-bound decision submitted (with WithDecisionCheck) while the revocation status of its chain is missing or stale: the decision is not refused, the gate cannot judge it yet, and nothing is written.var ErrAlreadyDecided: ErrAlreadyDecided is a decision submitted (with WithDecisionCheck) by an approver whose earlier valid decision on the same call already counts; the new one would be ignored.var ErrRedactNotTerminal: ErrRedactNotTerminal is a redaction in a run with no end marker. (experimental)var ErrRedactLeased: ErrRedactLeased is a redaction in a run whose lease is live: a driver may be running it. (experimental)var ErrRedactProtected: ErrRedactProtected is a redaction of a record a verifier or the engine needs (see RedactionProtected). (experimental)var ErrRedactMismatch: ErrRedactMismatch is a tombstone whose leaf hash is not the leaf hash of the bytes it replaces, or one that is not a well-formed tombstone. (experimental)var ErrRedactSession: ErrRedactSession is a redaction in a session's journal or turn run: the session reads its turns' runs and never ends, so a redaction there is refused. (experimental)var ErrRedactParentLive: ErrRedactParentLive is a redaction in a sub-agent's run while a run above it is not over: the parent reads the child's records when it replays the call. (experimental)var ErrRedactChanged: ErrRedactChanged is a redaction of an entry whose bytes are not the bytes the caller read: another writer changed it, or the caller's copy is not what is stored. (experimental)var ErrRedactNoEntry: ErrRedactNoEntry is a redaction of an entry the run does not hold. (experimental)var ErrAlreadyResolved: ErrAlreadyResolved is the condition of a resolution refused because the operation already has a different recorded outcome (see HaltAlreadyResolved).var ErrAlreadyStopped = errors.New("agent: already stopped"): ErrAlreadyStopped is matched (errors.Is) by the *AlreadyStoppedError SetStop returns, with the stop in force, when the scope with that compensation is already stopped. (experimental)var ErrApprovalExpired = errors.New("approval expired"): ErrApprovalExpired is returned (wrapped) when an approval gate's deadline has passed: by Approve and SubmitDecision for a decision on such a gate (also ErrConfig: nothing is recorded), and by a plan flow for a node whose gate expired (also plan.ErrApprovalDenied).var ErrGateNeedsNewRun = errors.New("the gate needs a new run"): ErrGateNeedsNewRun is wrapped (with ErrConfig) by the error of a certificate-bound gate that cannot go on in place: its recorded count passed without excluding the requester and the policy now excludes them, so no re-ask can be named.var ErrHoldExists: ErrHoldExists is a PlaceHold of an ID that is active. (experimental)var ErrInvalidStop = errors.New("agent: invalid stop record"): ErrInvalidStop marks a stop record that is malformed, or that no policy in force authorises. (experimental)var ErrJournalVersion: ErrJournalVersion is a run whose journal this version cannot read or write: its header names a journal format this version does not support, or the journal has no header first (written before the header existed, or by something other than a Journal).var ErrLeaseLost = errors.New("run lease lost"): ErrLeaseLost ends a drive whose run lease was lost while it ran: the store reported the lease no longer held (it lapsed and another process took it), or no renewal succeeded before the renewal cutoff (see Lease).var ErrNoLiveAttempt: ErrNoLiveAttempt is the condition of a resolution refused because the operation named has no live attempt marker: it never halted (it was never attempted, or its only attempts are recorded as not started and are re-attempted by the next drive).var ErrNotResumable: ErrNotResumable is a Resumer's answer for a run it does not drive (another kind, a typed run whose schema is not its type's).var ErrNotStarted: ErrNotStarted is a run with no run:start record: one never driven (a Signal sent to a mistyped run ID, say), or one whose first drive has not written it yet.var ErrNotifyPermanent: ErrNotifyPermanent marks a Notifier error as one a retry within the round cannot fix.var ErrRedactHeld: ErrRedactHeld is a redaction of a run an active hold covers. (experimental)var ErrRunCancelled = errors.New("run cancelled"): ErrRunCancelled is the end of a run that was cancelled (see Cancel): the first of the run's end markers in journal order is run:cancelled.var ErrRunEnded = errors.New("run already ended"): ErrRunEnded is Cancel's answer for a run that is already over: its first end marker is run:complete or run:aborted, so there is nothing left to cancel.var ErrStopRejected: ErrStopRejected is returned when a record was written but the control run's fold does not accept it (a policy transition raced it, or its signature does not verify under the policy in force at its position): it has no effect. (experimental)var ErrStopsUnknowable: ErrStopsUnknowable is returned by StopState.UnknowableErr when a control genuinely cannot judge which stops are in force: a basic process that holds an active stop set under a signed record (it lacks the deployment's policy), or an audited process whose pin the stored chain does not reach, or whose chain forks or competes. (experimental)var ErrToolNotCalled = errors.New("tool not called"): ErrToolNotCalled marks a tool call that is known never to have reached its tool, so its side effect cannot have happened.var ErrTrailConflict: ErrTrailConflict is returned by NotifyTrail.Append when the position is already taken by a different record: another process won the append.var ErrTurnContended: ErrTurnContended is returned by a Session's Send, SendOnce, Send and SendOnce when another driver holds the lease on the turn's run (see Session): another worker, or, while a cancelled saga turn's rollback is in progress, another caller on the same session handle (see Session.Send).
Functions
func AbortedKey(runID string) string: AbortedKey is the event key of runID reaching run:aborted.func Ack(ctx context.Context, d *Journal, runID, channel, key string) error: Ack marks a message consumed so Receive advances past it.func ApprovalDeadlineStep(toolUseID string) string: ApprovalDeadlineStep is the journal name of the record that fixes the deadline of the gate on toolUseID (a tool call's ID, or a plan flow node's key).func ApprovalDecisionBytes(s ApprovalSubject, approverID string, approved bool, decidedAt time.Time) []byte: ApprovalDecisionBytes returns the canonical bytes an approver signs and every verifier checks.func ApprovalDecisionBytesCert(s ApprovalSubject, approverID string, approved bool, decidedAt time.Time, leafHash [32]byte) []byte: ApprovalDecisionBytesCert returns the canonical bytes a certificate-bound approver signs (bide.approval.v4): the layout of ApprovalDecisionBytes with the domain tag "bide.approval.v4\n" and, between the verdict byte and the decision time,func ApprovalExecHoldStep(toolUseID string, gen int) string: ApprovalExecHoldStep is the journal name of the ExecHold record of generation gen of toolUseID's gate.func ApprovalIdentReaskKey(runID, call string, gen int) string: ApprovalIdentReaskKey is the event key of the approval gate for call on runID asking again for generation gen of a certificate-bound gate: 0 over a plain-name tally it does not act on (PendingIdentReapproval), n >= 1 after an exec hold of generation n-1 (PendingExecHoldReapproval).func ApprovalIdentReaskStep(toolUseID string, gen int) string: ApprovalIdentReaskStep is the journal name of the pause note a certificate-bound gate writes when it asks again for generation gen: 0 over a plain-name tally it does not act on (PendingIdentReapproval), n >= 1 over the generation n-1 tally that an exec hold superseded (PendingExecHoldReapproval).func ApprovalIdentTallyStep(toolUseID string, gen int) string: ApprovalIdentTallyStep is the journal name of the terminal tally of an identity-bound gate at generation gen: ApprovalTallyStep plus ":ident" for generation 0 and ":ident-reask:<gen>" for a gate re-asked after an exec hold.func ApprovalIdentityDigestStep(toolUseID string, gen int, digest string) string: ApprovalIdentityDigestStep is the name of the identity record of generation gen when the plain name already holds a record of a different tally (a crash between the record and the tally, then a different count): the record whose TallyDigest is the one the gate then writes is found under this name, digest being the first 16 hex digits of that digest.func ApprovalIdentityStep(toolUseID string, gen int) string: ApprovalIdentityStep is the journal name of the ApprovalIdentity record of toolUseID's gate at generation gen.func ApprovalKey(runID, call string, reminder int) string: ApprovalKey is the event key of the approval gate for call on runID.func ApprovalPauseStep(toolUseID string, n int) string: ApprovalPauseStep is the journal name of the n-th phase note of the gate on toolUseID (an ApprovalWait with Pause set), n counting from 1 in the order the gate wrote them.func ApprovalPendingStep(toolUseID string) string: ApprovalPendingStep is the journal name of the record that a run paused at the approval gate of the call toolUseID (see ApprovalWait).func ApprovalReaskKey(runID, call string, sod bool) string: ApprovalReaskKey is the event key of the approval gate for call on runID asking again over a recorded tally it does not act on (ApprovalPending.Reason): with sod, because its policy now excludes the requester (PendingSoDReapproval); without, because the tally predates DecisionFormat (PendingReapproval).func ApprovalReaskStep(toolUseID string, sod bool) string: ApprovalReaskStep is the journal name of the pause note a gate writes when it asks again over a recorded tally it does not act on: with sod, a tally that passed without excluding the requester under a policy that now excludes it (its outcome is recorded under ApprovalSoDRetallyStep); without, a tally that passed on decisions predating DecisionFormat (ApprovalRetallyStep).func ApprovalRequestStep(toolUseID string) string: ApprovalRequestStep is the journal name of the request a plan flow node's approval gate records when the run first reaches it (see ApprovalRequest).func ApprovalRetallyStep(toolUseID string) string: ApprovalRetallyStep is the journal name of the terminal tally a gate records when it re-asks for approval because the tally under ApprovalTallyStep passed on decisions that predate DecisionFormat (see ApprovalTally.Supersedes).func ApprovalSoDRetallyStep(toolUseID string) string: ApprovalSoDRetallyStep is the journal name of the terminal tally a gate records when it re-asks for approval because the tally it would otherwise go by passed without excluding the requester, and the gate's policy now excludes it (ApprovalPolicy.ExcludePrincipal: a redeploy added the exclusion, or a drive still running the old policy recorded first).func ApprovalStatusStep(hash string) string: ApprovalStatusStep is the journal name of the ApprovalStatusBytes record whose DER hashes (SHA-256, lowercase hex) to hash.func ApprovalTallyStep(toolUseID string) string: ApprovalTallyStep is the journal name of the gate's terminal tally for toolUseID.func Approve(ctx context.Context, d *Journal, runID, toolUseID string, approved bool, opts ...ApproveOption) error: Approve durably records a human approve/deny decision for a tool call (HITL).func Await[T any](ctx context.Context, name string) (T, error): Await blocks the current run until a single-shot signal namednameis delivered, then returns its payload.func AwaitFor[T any](ctx context.Context, name string, d time.Duration) (T, bool, error): AwaitFor blocks the current run until either a single-shot signal namednameis delivered or the duration d elapses, whichever happens first.func Cancel(ctx context.Context, j *Journal, runID, reason string, opts ...CancelOption) error: Cancel cancels runID's run (D1), recording reason.func Capability[T any](store Store) (T, bool): Capability returns store's implementation of the optional capability T (Lister, Leaser, or any other interface a store may implement beyond Store), looking through wrappers.func CertLeafHash(der []byte) [32]byte: CertLeafHash is the SHA-256 of a leaf certificate's DER: what a v4 decision signs in place of the certificate itself.func CertRecordVerifies(iv CertIntakeVerifier, s ApprovalSubject, r Record) bool: CertRecordVerifies reports whether r is a valid decision of a certificate-bound approver for s as the intake judges (CertIntakeVerifier): its chain, identity, scheme and signature hold now and nothing in its chain is revoked.func CheckHold(h Hold) error: CheckHold checks the parts of a hold no store needs to decide: an ID, a matter and runs that are not blank. (experimental)func CheckRedaction(runID, name string, current, tombstone []byte) error: CheckRedaction checks the part of a redaction that needs no store: that tombstone is a well-formed tombstone (TombstoneLeafHash), that the leaf hash it keeps is the leaf hash of current (LeafHash), and that the record current holds, named name in run runID, is not protected (RedactionProtected). (experimental)func DecisionStep(d Decision) string: DecisionStep returns the journal name SubmitDecision gives the record of d first: distinct for each distinct decision (call, approver, verdict, scheme and decision time), and the same for every resubmission of it, whatever its signature bytes, which is why that is a no-op.func DigestKey(bucket string) string: DigestKey is the event key of the digest for time bucket (an opaque, stable label).func EncodeRecord(r Record) ([]byte, error): EncodeRecord returns the journal encoding of r: the bytes a store persists for it and the bytes an audit leaf commits to.func EscalationKey(key string, level int) string: EscalationKey is the event key of step level (from 1) of the escalation chain of the event with key.func ExecHoldGen(toolUseID, name string) (int, bool): ExecHoldGen parses the generation out of name, which must be ApprovalExecHoldStep of toolUseID; ok is false for any other name.func ExpiredKey(runID, call string) string: ExpiredKey is the event key of the expiry of the approval gate for call on runID (NotificationApprovalExpired).func FormatTimestamp(t time.Time) string: FormatTimestamp returns t in the one form bide records times in (RunStart.StartedAt, a signed decision's decided_at, the recorded_at of a decision and of ApprovalWait): RFC 3339 in UTC, truncated to the millisecond, always 24 bytes and ending in "Z", e.g. "2026-10-13T12:14:03.123Z".func GateReask(t ApprovalTally, excludePrincipal bool) string: GateReask returns why a gate asks again instead of acting on its recorded tally t, or "": t passed on decisions that predate DecisionFormat (PendingReapproval), or passed without excluding the requester while the policy now excludes it (PendingSoDReapproval).func GateTallyValues(recs []Record, toolUseID string) map[string]Record: GateTallyValues returns the StepValue records of recs that decide the gate of toolUseID, by name, first writer winning: the plain-name tallies (ApprovalTallyStep, ApprovalRetallyStep, ApprovalSoDRetallyStep), the identity tally chain and the exec holds.func Generate(ctx context.Context, m Model, req Request) (Message, Usage, error): Generate is the convenience drain: stream and assemble in one call.func HaltedKey(runID string, kind OpKind, opID string, attemptedMS int64) string: HaltedKey is the event key of an unknown-outcome halt of the operation opID of kind on runID.func HeldDecisionStep(ctx context.Context, store *Journal, d Decision, verifierFor ApproverVerifierFor) (name string, held, verified bool, err error): HeldDecisionStep reports whether the journal holds a record of exactly the decision d (signature included) and the name of the record that does: under the identity name (DecisionStep), under the signature-derived name a bad record at the identity name pushes a decision to, or under the name a version that named by signature gave it.func IdentReaskGen(toolUseID, name string) (int, bool): IdentReaskGen parses the generation out of name, which must be ApprovalIdentReaskStep of toolUseID; ok is false for any other name.func IdentTallyGen(toolUseID, name string) (int, bool): IdentTallyGen parses the generation out of name, which must be ApprovalIdentTallyStep of toolUseID; ok is false for any other name.func IdentityTier(cc *CertCheck) string: IdentityTier maps a verifier's finding to the tier the identity record and the approvals intake report: only a final status is a final tier, and the time source says which (an independent source only when the finding names RFC 3161 or an anchor receipt; anything else is the log signer's clock); a live count or a short window is provisional.func Interrupt[T any](ctx context.Context, name string, prompt any) (T, error): Interrupt pauses the current run to request typed human input, identified by name.func IsApprovalDecision(r Record, toolUseID string) bool: IsApprovalDecision reports whether r is an m-of-n approver decision (written by SubmitDecision) on toolUseID.func IsCapRun(runID string) bool: IsCapRun reports whether runID is a cap ledger run: it starts with "@cap/", which checkRunID and Session refuse in a caller's ID, as do the exported calls that write to a run a caller names (checkCallerRun).func IsComplete(ctx context.Context, store *Journal, runID string) (bool, error): IsComplete reports whether runID completed: its first end marker in journal order is the completion marker the agent loop records at the end of a run (see runCompleteStep).func IsDecisionStepName(name, toolUseID, approverID string) bool: IsDecisionStepName reports whether name has the shape of the journal record name of a decision of approver on call: the call's approval prefix, the approver, and 64 lowercase hex digits.func IsPause(err error) bool: IsPause reports whether err, or any error it wraps, is a Pause: the run stopped durably and is waiting, rather than failed.func IsReservedRun(runID string) bool: IsReservedRun reports whether runID is a run the engine reserves for its own records, which is not a run of an agent: the stop control run (StopControlRun) or a cap ledger run (IsCapRun).func IsReservedStepName(name string) bool: IsReservedStepName reports whether name starts with a prefix the engine reserves for its own journal keys.func IsRunPrincipal(r Record) bool: IsRunPrincipal reports whether r is a run's run:principal record (see RunPrincipal).func IsSessionRun(runID string) bool: IsSessionRun reports whether runID is a session's journal or one of its turn runs, which the session drives (see Session).func IsSubRun(runID string) bool: IsSubRun reports whether runID is a sub-agent's run (SubRunID), which its root run drives: its last '>' is followed by an encoded call ID, not by a session's mark.func JournalEntry(name string, rec Record) ([]byte, error): JournalEntry returns the bytes a store persists when it records rec as the step named name: rec with Name set to name and a fresh random Salt (see Record.Salt; a salt the engine drew for the record is kept), in its journal encoding (EncodeRecord).func LastSegment(recs []NotifyRecord) string: LastSegment is the segment named by the last NotifySegment record of an open-trail index, "" if there is none.func LeafHash(recordBytes []byte) []byte: LeafHash returns the audit leaf hash of a journal record from the bytes the journal stores for it: SHA-256(0x00 || "bide.audit.journal-leaf.v1\x00" || recordBytes), the RFC 6962 leaf hash of the journal leaf.func Lease(ctx context.Context, store *Journal, runID string, drive func(context.Context) error, opts ...LeaseOption) (bool, error): Lease runs drive under an exclusive, auto-renewed lease on runID, so a primary driver and a recoverer (or two workers) do not drive the same run at once.func NewTombstone(name string, recordBytes []byte, at time.Time) ([]byte, error): NewTombstone returns the redaction tombstone that replaces the stored bytes recordBytes of the record named name: {"redacted":{"leaf_hash":"<hex of LeafHash(recordBytes)>","at_ms":<at in Unix millis>,"name":"<name>"}}.func NextOnceKey(ctx context.Context) string: NextOnceKey returns a key for the next exactly-once operation (an idempotent append, say) that the tool call running in ctx makes, or "" outside a tool call.func NotifyID(key string) string: NotifyID is the stable delivery ID of an event: the hex SHA-256 of its key.func NotifyPending(ctx context.Context, j *Journal, n Notifier, trail NotifyTrail, opts ...NotifyOption) error: NotifyPending runs one catch-up sweep for a notifier: it reads every unfinished run in j and delivers, through n and trail as WithNotifier would, each event that needs a person and has not been delivered: a run waiting at an approval gate, and a run halted on an effect whose outcome is unknown.func NotifyTrailName(runID string) string: NotifyTrailName is the name of runID's notification trail in a NotifyTrail.func OpenIndex(year int) string: OpenIndex is the name of the open trail's index for a UTC year: one NotifySegment record per segment created, so the newest segment is found by reading the last record of the newest index (one or two loads, whatever the gaps and the age of the deployment), and the index is the size of a year of days at most.func OpenSegment(t time.Time) string: OpenSegment is the name of the open-trail segment of the UTC day t is in.func OverdueKey(key string) string: OverdueKey is the event key of the overdue notice for the event with key.func ParseEscalationKey(key string) (level int, orig string, ok bool): ParseEscalationKey splits the key of an escalation step, "escalated:<level>:<key>" (see EscalationKey), into its level (from 1) and the key of the event it escalates.func ParseTimestamp(s string) (time.Time, error): ParseTimestamp reads s, which must be in exactly the form FormatTimestamp writes: it parses s and refuses it unless formatting the result again gives s byte for byte.func PromptDigest(msgs []Message) string: PromptDigest is the hex SHA-256 digest a model record journals of the system prompt a turn was sent: the text of every system message in msgs, in order, each length-prefixed under a domain tag, so no two different prompts share a digest.func Recover(ctx context.Context, store *Journal, resume Resumer, opts ...RecoverOption) (int, error): Recover re-drives the runs that were in flight when the process died, in one pass.func RecoverLoop(ctx context.Context, store *Journal, resume Resumer, opts ...RecoverLoopOption) error: RecoverLoop re-drives in-flight runs until ctx is done, so a run whose holder dies is taken over automatically: Recover is a single pass, and a run another holder leases at that moment is left for a later one.func RecoveryKey(runID string, episode int) string: RecoveryKey is the event key of runID's episode-th recovery failure (episode counts the recovered records before it, from zero).func RedactURLs(s string) string: RedactURLs returns s with every URL in it redacted: its userinfo, each query parameter's value, and its fragment become REDACTED, and its scheme, host, path, and query parameter names are kept.func RedactionAncestors(runID string) []string: RedactionAncestors returns the runs above runID, nearest first, whose records runID's are read with: for a sub-agent's run "a>b>c" they are "a>b" and "a". (experimental)func RedactionEndMarkers() []string: RedactionEndMarkers returns the names of the end markers: a run that holds one of them is over, and only such a run may be redacted. (experimental)func RedactionProtected(name string, kind StepKind) string: RedactionProtected reports why a record named name, of kind kind, may never be redacted, or "" if it may. (experimental)func RedactionSession(runID string) bool: RedactionSession reports whether runID is a session's journal or turn run (agent.IsSessionRun), or a sub-agent run inside one: they are never redacted. (experimental)func RenderMermaid(ctx context.Context, d *Journal, runID string) (string, error): RenderMermaid returns a Mermaid flowchart of a run's journaled steps, the "graph as derived OUTPUT" (Option B): you write plain Go, and the graph is rendered from what actually ran, not hand-authored.func ReportNotifyAck(ctx context.Context, ack NotifyAck): ReportNotifyAck is called by a Notifier, with the context it was given, to say how a delivery it is about to acknowledge was authenticated and answered.func ResolveHalt(ctx context.Context, store *Journal, ref HaltRef, out Outcome, opts ...ResolveOption) error: ResolveHalt is the sanctioned escape from an *OutcomeUnknown halt.func ResolvedKey(key string) string: ResolvedKey is the event key of the all-clear for the event with key: the notification that it stopped being current.func RootRunID(runID string) string: RootRunID returns the run that drives runID: the run itself, or for a sub-agent's run the root run to re-invoke to continue it (ApprovalPending.RootRunID for a gate inside a sub-agent).func SameApprover(a, b string) bool: SameApprover reports whether two ids name one approver: equal ignoring ASCII case, the rule Validate holds a policy's ids to, and the rule a gate that excludes the requester matches a requester to an approver id by.func SameNotifyRecord(a, b NotifyRecord) bool: SameNotifyRecord reports whether a and b are the same record: the same canonical JSON, so times compare by instant and not by location or monotonic clock reading.func SameStopRecord(a, b StopRecord) bool: SameStopRecord reports whether a and b are the same record: the same canonical bytes, signature included. (experimental)func Sleep(ctx context.Context, name string, d time.Duration) error: Sleep pauses the current run until d has elapsed from the FIRST time this timer was reached, durably.func SplitToKey(key string) (receiver, base string, ok bool): SplitToKey splits the key of a fan-out delivery, "to:<receiver>:<key>" (see ToKey), into the receiver and the key of the event it delivers.func StopClockAnomalies(recs []StopRecord, now time.Time, skew time.Duration) []string: StopClockAnomalies are the records of a control run, in store order, whose time is not believable: dated more than skew after now, or more than skew before an earlier record of the log. (experimental)func StopDigest(r StopRecord) string: StopDigest returns the hex SHA-256 of the canonical bytes of the whole record r, signature included: what a lift's SetDigest names. (experimental)func StopIDOf(r StopRecord) string: StopIDOf returns the ID of the stop a set record makes: the hex SHA-256 of its canonical bytes without StopID and Signature. (experimental)func StopLiftedKey(id string) string: StopLiftedKey is the event key of the stop with the given ID being lifted (NotificationStopLifted). (experimental)func StopPolicyDigest(d StopPolicyDoc) string: StopPolicyDigest returns the hex SHA-256 of the canonical bytes of a policy document. (experimental)func StopSetKey(id string) string: StopSetKey is the event key of the stop with the given ID being set (NotificationStopSet). (experimental)func StopSigningBytes(r StopRecord) []byte: StopSigningBytes returns the bytes a signature of r covers: the label, the record's kind and its canonical body (StopID included, Signature excluded). (experimental)func SubRunID(parent, toolUseID string) string: SubRunID returns the run ID of the sub-agent run that the call toolUseID of run parent starts: parent, '>', then toolUseID encoded (see encodeID).func SubmitDecision(ctx context.Context, store *Journal, d Decision, opts ...ApproveOption) error: SubmitDecision records d, one approver's signed decision on an m-of-n gated call.func SupersededTallies(byName map[string]Record, outcome string) []string: SupersededTallies returns the names of the tallies that outcome, the gate's outcome (as RecordedTally returns it, among byName) supersedes, oldest first: the tally its Supersedes names, and that one's, and so on.func TallyApprovals(recs []Record, s ApprovalSubject, p ApprovalPolicy, verifierFor ApproverVerifierFor) (ApprovalTally, []DecisionCheck): TallyApprovals is the m-of-n counting rule, shared by the gate and offline verification so the two cannot drift.func ToKey(receiver, key string) string: ToKey is the event key of key's delivery to receiver, for an event that goes to several receivers at once (an approval whose approvers are routed to different ones): each has a key, and so an ID, claim and acknowledgement, of its own.func TombstoneLeafHash(b []byte) ([]byte, bool): TombstoneLeafHash returns the leaf hash a tombstone keeps, and false if b is not a tombstone in the exact form NewTombstone writes (see isTombstone).func TombstoneMillis(b []byte) (int64, bool): TombstoneMillis returns the time a tombstone records, in Unix millis, and false if b is not a tombstone in the exact form NewTombstone writes.func TombstoneName(b []byte) (string, bool): TombstoneName returns the record name a tombstone carries, and false if b is not a tombstone or names none (the reserved form allows a tombstone without one).func ToolResultStep(toolUseID string) string: ToolResultStep is the key of the result of the call toolUseID: the record the loop, a saga rollback, or ResolveHalt writes when the call's outcome is known.func ToolsDigest(tools []ToolSpec) string: ToolsDigest is the hex SHA-256 digest a model record journals of the tool set a turn was sent: each tool's name, description and argument schema, length-prefixed under a domain tag, in the order of their names, so the digest does not depend on the order the tools were listed in.func ValidReaskNote(byName map[string]Record, toolUseID, name string, w ApprovalWait) bool: ValidReaskNote reports whether w, the content of the record named name (ApprovalReaskStep of toolUseID), is a re-ask note the journal proves: its Reask is the reason its name stands for, and its Supersedes names a recorded tally (among byName) that GateReask would ask again over for that reason, namely the call's tally for a format re-ask, and for a separation-of-duties re-ask the outcome so far (the format re-approval tally when the tally predates DecisionFormat and that one is recorded, else the tally) under a policy that excludes the requester.func ValidReceiver(name string) bool: ValidReceiver reports whether name is one a trail may record for a receiver other than the default: what WithNotifyReceiver accepts, and not DefaultReceiver, which a trail records as no name.func ValidateRunID(id string) error: ValidateRunID reports whether id may name a root run (Run, Resume, Stream, RunTyped): it is not empty, holds no '>', which the engine reserves for the run IDs of sub-agents and session turns, and does not start with "@cap/", which it reserves for cap ledger runs (IsCapRun).func WaitUntil(ctx context.Context, name string, until time.Time) error: WaitUntil pauses the current run until the absolute timeuntil, durably.
type APIError
type APIError struct {
StatusCode int
Body string
Message string
Type string
Code string
Err error
}APIError is returned by a provider adapter for a non-2xx HTTP response that is not a rate limit (which uses RateLimited), and for an exhausted quota whatever its status (wrapping ErrQuotaExhausted).
Methods
func (e *APIError) Error() string: Error describes the failure: the status, the provider's message and error code or type (or the Body when the provider sent no message), then Err.func (e *APIError) Unwrap() error: Unwrap returns Err, so errors.Is(err, ErrModel) holds when Err wraps ErrModel.
type Agent
type Agent struct {
// contains filtered or unexported fields
}Agent binds a model, a tool set, a durable store, and a middleware chain.
Constructors and functions
func New(model Model, j *Journal, opts ...Option) (*Agent, error): New constructs an Agent over model and the journal j, configured by opts.
Methods
func (a *Agent) Declarations() ([]byte, error): Declarations returns the agent's taint and cap declarations as a document (format bide.declarations.v1, indented JSON): the taint policy, and every registered tool with whether it can have a side effect, its own gate, its Untrusted source, its TaintExempt reason, its RaisesSafety reason and its cap rules.func (a *Agent) FlushNotifications(ctx context.Context) error: FlushNotifications waits for the deliveries of a's notifier that are in flight to finish their round, and stops its worker; a later event starts it again.func (a *Agent) Journal() *Journal: Journal returns the journal the agent writes through: the one New was given.func (a *Agent) Resume(ctx context.Context, runID string, opts ...RunOption) (*Result, error): Resume drives runID's run on from its journal: the input, saga flag and options its first drive journaled (see RunStart), and the last limit amendment.func (a *Agent) Run(ctx context.Context, runID string, input Message, opts ...RunOption) (*Result, error): Run drives the agent to the end of runID's run, answering input under opts, and returns the run's Result.func (a *Agent) RunTyped[T any](ctx context.Context, runID string, input Message, opts ...RunOption) (T, *Result, error): RunTyped runs the agent to the end of runID's run like Run, and returns its answer as a T instead of a free-form Message, with the run's Result (whose Output is the answer as journaled).func (a *Agent) Session(ctx context.Context, id string, opts ...LeaseOption) (*Session, error): Session opens (or reopens) a multi-turn conversation with the given id, rebuilding the transcript from the store so a restarted process continues where it left off.func (a *Agent) Stream(ctx context.Context, runID string, input Message, opts ...RunOption) *RunStream: Stream drives the agent like Run but returns a live RunStream: token deltas, turn boundaries and tool start and finish arrive as events while the durable loop runs, and RunStream.Result returns what Run would.func (a *Agent) With(opts ...Option) (*Agent, error): With returns a copy of a configured by opts, applied over a's configuration as New applies them: a setting given here replaces a's, and tools, middleware and retrievals given here are added after a's.
type AgentRunOption
type AgentRunOption interface {
Option
RunOption
}AgentRunOption is a setting that applies to an agent (Option) and to one run (RunOption): WithMaxTurns, WithTokenBudget, WithSystemPrompt, WithSampling, WithToolChoice, WithWaker and WithIdentity.
Constructors and functions
func WithIdentity(id Identity) AgentRunOption: WithIdentity sets the acting identity of a run (see Identity): tool calls read it with IdentityFrom, and the runs they start inherit it.func WithMaxTurns(n int) AgentRunOption: WithMaxTurns caps the model turns a run may take, so a model that keeps calling tools cannot loop forever.func WithSampling(opts ...SamplingOption) AgentRunOption: WithSampling sets generation controls applied to every model call (Temperature, TopP, MaxTokens, Stop, Seed).func WithSystemPrompt(s string) AgentRunOption: WithSystemPrompt sets a system message prepended to the conversation on every model turn.func WithTokenBudget(max int) AgentRunOption: WithTokenBudget caps the tokens a run, and the runs its tool calls start, may use (see Agent.WithTokenBudget for how the budget is counted and enforced).func WithToolChoice(tc ToolChoice) AgentRunOption: WithToolChoice sets the tool-choice control applied to every model call (see ToolChoice and Agent.WithToolChoice).func WithWaker(w Waker) AgentRunOption: WithWaker sets the Waker a run's durable Sleep registers its wake with (see Waker).
type Alg
type Alg stringAlg names a signature scheme: "ed25519", "ecdsa-p256", "ml-dsa-65", or "ed25519+ml-dsa-65".
Constants
const AlgCertificate Alg = "x509": AlgCertificate is the Alg a certificate-bound verifier reports.
type AlreadyStoppedError
type AlreadyStoppedError struct{ Entry StopEntry }AlreadyStoppedError is returned by SetStop when a stop with the same scope and compensation is already in force: Entry is that stop, set by someone else or by an earlier call. (experimental)
Methods
func (e *AlreadyStoppedError) Error() string: Error implements error. (experimental)func (e *AlreadyStoppedError) Unwrap() error: Unwrap lets errors.Is(err, ErrAlreadyStopped) match. (experimental)
type AnswerOption
type AnswerOption interface {
// contains filtered or unexported methods
}AnswerOption configures AnswerInterrupt and Signal: WithClock, the clock that stamps the record's RecordedAt.
type ApplyRequest
type ApplyRequest struct {
By, Host, Reason string
Signer StopSigner
}ApplyRequest names who applies pending records: an enrolled approver of the policy in force, with the key to sign the record that says so. (experimental)
type ApprovalDeadline
type ApprovalDeadline struct {
ToolUseID string `json:"tool_use_id"`
RequestedAt string `json:"requested_at"`
ExpiresAt string `json:"expires_at"`
TimeoutMS int64 `json:"timeout_ms"`
}ApprovalDeadline is what the record named ApprovalDeadlineStep holds.
Constructors and functions
func RecordedDeadline(recs []Record, toolUseID string) (d ApprovalDeadline, expiresAt time.Time, ok bool): RecordedDeadline returns the deadline the gate on toolUseID recorded in recs (a run's records), and its parsed ExpiresAt, or ok=false when the gate has none.
type ApprovalIdentity
type ApprovalIdentity struct {
Format string `json:"format"`
ToolUseID string `json:"tool_use_id"`
Generation int `json:"generation"`
Tally string `json:"tally"`
TallyDigest string `json:"tally_digest"`
Evaluated string `json:"evaluated"`
EvaluatedAt string `json:"evaluated_at"`
Policy IdentityPolicyRecord `json:"policy"`
PolicyDigest string `json:"policy_digest"`
RosterDigest string `json:"roster_digest"`
Decisions []IdentityDecision `json:"decisions"`
Rules string `json:"rules"`
Verifier string `json:"verifier"`
VerifierRev string `json:"verifier_rev,omitempty"`
GoDebug string `json:"godebug_declared,omitempty"`
BuildGoDebug string `json:"godebug_build,omitempty"`
RecordedAt string `json:"recorded_at,omitempty"`
}ApprovalIdentity is what the record named ApprovalIdentityStep holds: the identity environment of a terminal count.
Constructors and functions
func IdentityRecordFor(recs []Record, toolUseID string, gen int, tally Record) (ApprovalIdentity, bool): IdentityRecordFor returns the identity record of generation gen that belongs to tally, the recorded tally of toolUseID's gate at that generation: the record whose TallyDigest equals the SHA-256 of tally's stored bytes, looked up under ApprovalIdentityStep first and then under ApprovalIdentityDigestStep (two drives racing, or a count that differed from an earlier attempt, can produce either).
type ApprovalPending
type ApprovalPending struct {
RunRef
ToolUseID string
ToolName string
Args json.RawMessage
Quorum *ApprovalTally
Reason string
}ApprovalPending is returned by Agent.Run when a tool requiring human approval has no recorded decision yet.
Methods
func (e *ApprovalPending) Error() string: Error names the run and the call awaiting approval.func (e *ApprovalPending) Subject() ApprovalSubject: Subject returns the approval subject of the paused call, which is what approvers sign:
type ApprovalPolicy
type ApprovalPolicy struct {
Need int `json:"need"`
Approvers []string `json:"approvers,omitempty"`
ExcludePrincipal bool `json:"exclude_principal,omitempty"`
Timeout time.Duration `json:"-"`
// contains filtered or unexported fields
}ApprovalPolicy declares a human approval gate.
Constructors and functions
func SingleApproval() *ApprovalPolicy: SingleApproval returns the one-decision gate: a call pauses as *ApprovalPending until Approve records a decision for it.
Methods
func (p *ApprovalPolicy) Clone() *ApprovalPolicy: Clone returns a copy of p that shares nothing with it (a SingleApproval stays one), or nil for nil.func (p ApprovalPolicy) MarshalJSON() ([]byte, error): MarshalJSON encodes the policy as the journal records it: SingleApproval as {"single":true}, the bide protocol's wire form of the one-decision gate, so an offline reader sees the gate a call ran under without inferring it from a shape; any other policy as {"need":k,"approvers":...}, with "exclude_principal":true when ExcludePrincipal is set (omitted otherwise, so a policy without it encodes as it did before the field existed).func (p ApprovalPolicy) SeparatedFrom(own string) ApprovalPolicy: SeparatedFrom returns a copy of p that excludes the approvers the terminal tally of the gate on subject own counted: the rule the escalation Gate of a taint policy that separates approvers (TaintPolicy.SeparateApprovers) is counted under on a call's instance, for an offline recount (audit.VerifyApprovals, with the own gate's tally among the evidence).func (p *ApprovalPolicy) UnmarshalJSON(b []byte) error: UnmarshalJSON decodes what MarshalJSON encodes, strictly, as the bide protocol writes the gate: {"single":true}, with no other member, is SingleApproval; any other policy has need (and approvers, and optionally exclude_principal) and no single.func (p ApprovalPolicy) Validate() error: Validate reports whether the policy is well formed: at least one approver, every approver id non-empty printable ASCII, no two ids the same approver, and 1 <= Need <= len(Approvers).func (p ApprovalPolicy) ValidateKeys(verifierFor ApproverVerifierFor) error: ValidateKeys reports whether the policy is well formed (Validate) and holds one seat per signing key under verifierFor: it resolves every approver once and refuses, with ErrConfig, a nil verifierFor, an approver whose verifier reports no key identity (an empty KeyIDs, or an empty entry), and two approvers whose verifiers report a common key identity.
type ApprovalRequest
type ApprovalRequest struct {
ToolUseID string `json:"tool_use_id"`
ToolName string `json:"tool_name"`
Args json.RawMessage `json:"args"`
RecordedAt string `json:"recorded_at,omitempty"`
}ApprovalRequest is what the record named ApprovalRequestStep holds: the gated plan flow node approvers decide on.
type ApprovalRequired
type ApprovalRequired struct {
ToolUseID string `json:"tool_use_id"`
Name string `json:"name"`
Args json.RawMessage `json:"args"`
Quorum *ApprovalTally `json:"quorum,omitempty"`
}ApprovalRequired fires immediately before the run pauses for a human decision on a tool that requires approval.
type ApprovalStatusBytes
type ApprovalStatusBytes struct {
Format string `json:"format"`
Kind string `json:"kind"`
Issuer string `json:"issuer"`
Number string `json:"number,omitempty"`
ThisUpdate string `json:"this_update"`
NextUpdate string `json:"next_update,omitempty"`
Size int `json:"size"`
DER []byte `json:"der,omitempty"`
}ApprovalStatusBytes is what an ApprovalStatusStep record holds: one CRL (or OCSP response) a gate relied on.
type ApprovalSubject
type ApprovalSubject struct {
RunID string
ToolUseID string
ToolName string
Args json.RawMessage
}ApprovalSubject is exactly what an approver decides on: one tool call, with its name and arguments, in one run.
type ApprovalTally
type ApprovalTally struct {
Need int `json:"need"`
Approvers []string `json:"approvers"`
Approved int `json:"approved"`
Denied int `json:"denied"`
ApprovedBy []string `json:"approved_by,omitempty"`
DeniedBy []string `json:"denied_by,omitempty"`
Pending []string `json:"pending,omitempty"`
Excluded []string `json:"excluded,omitempty"`
ExcludePrincipal bool `json:"exclude_principal,omitempty"`
Requesters []string `json:"requesters,omitempty"`
ExcludedBySibling []string `json:"excluded_by_sibling,omitempty"`
Records []string `json:"records,omitempty"`
DecisionFormat string `json:"decision_format,omitempty"`
Supersedes string `json:"supersedes,omitempty"`
Expired bool `json:"expired,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
// contains filtered or unexported fields
}ApprovalTally is the m-of-n gate's count for one call.
Methods
func (t ApprovalTally) Passed() bool: Passed reports whether Need approvals are in.func (t ApprovalTally) Unreachable() bool: Unreachable reports whether Need can no longer be reached: fewer approvers remain who have not denied, and are not Excluded, than approvals are required.
type ApprovalWait
type ApprovalWait struct {
ToolUseID string `json:"tool_use_id"`
ToolName string `json:"tool_name"`
Single bool `json:"single,omitempty"`
Need int `json:"need,omitempty"`
Approvers []string `json:"approvers,omitempty"`
RecordedAt string `json:"recorded_at,omitempty"`
ExcludePrincipal bool `json:"exclude_principal,omitempty"`
Requesters []string `json:"requesters,omitempty"`
Reask string `json:"reask,omitempty"`
Supersedes string `json:"supersedes,omitempty"`
IdentityBound bool `json:"identity_bound,omitempty"`
IdentityApprovers []string `json:"identity_approvers,omitempty"`
IdentityKinds string `json:"identity_kinds,omitempty"`
IdentityPolicyDigest string `json:"identity_policy_digest,omitempty"`
Pause string `json:"pause,omitempty"`
PauseDetail string `json:"pause_detail,omitempty"`
}ApprovalWait is what the record named ApprovalPendingStep holds: that a run paused at a call's approval gate, the gate it waits on, and when (RecordedAt), which is when approvers are asked.
Constructors and functions
func LatestPausePhase(recs []Record, toolUseID string) (ApprovalWait, bool): LatestPausePhase returns the newest phase note of toolUseID's gate among recs (ApprovalPauseStep), decoded, and ok=false when the gate has written none (its phase is then PauseAwaitingDecisions).
type ApproveOption
type ApproveOption interface {
// contains filtered or unexported methods
}ApproveOption configures SubmitDecision: WithDecisionCheck, WithClock for the clock that stamps the decision's RecordedAt, or ReportWritten.
Constructors and functions
func ReportWritten(wrote *bool) ApproveOption: ReportWritten makes SubmitDecision set *wrote to whether this call stored the decision's record: true when its Insert won the store's first-writer race, false when the journal already held the decision (an identical resubmission, another writer's record under the same name, a concurrent call that wrote it first, in this process or another).func WithDecisionCheck(verifierFor ApproverVerifierFor) ApproveOption: WithDecisionCheck makes SubmitDecision check the decision before recording it, so an approver learns at submission time that it will not count: it reads the run, finds the call, and verifies the signature against that exact call with verifierFor.
type ApproverSignature
type ApproverSignature struct {
Approver string `json:"approver,omitempty"`
ApproverAlg Alg `json:"approver_alg,omitempty"`
Signature []byte `json:"signature,omitempty"`
DecidedAt string `json:"decided_at,omitempty"`
RecordedAt string `json:"recorded_at,omitempty"`
ApproverCert [][]byte `json:"approver_cert,omitempty"`
}ApproverSignature is the signed decision a StepApproval record written by SubmitDecision carries (see Record.ApproverSignature).
type ApproverVerifier
type ApproverVerifier interface {
Alg() Alg
Verify(message, sig []byte) bool
KeyIDs() []string
}ApproverVerifier checks an approver's signature over the decision bytes under one scheme and names the signing keys behind it.
type ApproverVerifierFor
type ApproverVerifierFor func(approverID string) (ApproverVerifier, bool)ApproverVerifierFor resolves the verifier for an approver id (the caller's PKI, mirroring audit's issuer lookup).
type AssistantTurn
type AssistantTurn struct {
Message Message `json:"message"`
Replayed bool `json:"replayed"`
}AssistantTurn is the fully-assembled assistant message for a turn.
type CancelOption
type CancelOption interface {
// contains filtered or unexported methods
}CancelOption configures Cancel: WithClock, the clock that stamps the record's RecordedAt.
type CertCheck
type CertCheck struct {
Reason string
Detail string
Identity string
KeyHash [32]byte
Anchored time.Time
Time string
Tier string
Basis string
StatusTime string
Window string
Warnings []string
Revocation *CertRevocation
Chain []string
Anchor string
HeadSize int
HeadRoot, HeadHash string
TimeEvidence string
BasisKind string
Evidence []ApprovalStatusBytes
}CertCheck is a certificate-bound verifier's finding about one decision.
type CertDecision
type CertDecision struct {
Subject ApprovalSubject
Record Record
Journal []Record
Index int
}CertDecision is one decision record presented to a certificate-bound approver's verifier.
type CertDecisionVerifier
type CertDecisionVerifier interface {
ApproverVerifier
VerifyCertDecision(cd CertDecision) CertCheck
}CertDecisionVerifier is implemented by the verifier of a certificate-bound approver.
type CertExecVerifier
type CertExecVerifier interface {
CertDecisionVerifier
VerifyCertExec(cd CertDecision) CertCheck
}CertExecVerifier is implemented by the verifier of a certificate-bound approver that can be asked, immediately before the call it authorizes executes, whether a counted decision still holds.
type CertIntakeVerifier
type CertIntakeVerifier interface {
CertDecisionVerifier
VerifyCertIntake(cd CertDecision) CertCheck
}CertIntakeVerifier is implemented by the verifier of a certificate-bound approver that can check a decision before it is written (audit.CertApprover).
type CertRevocation
type CertRevocation struct {
Serial string
E string
ReasonCode int
CRL string
}CertRevocation describes the revocation behind a CertCheck whose Reason is ReasonRevoked.
type ClockOption
type ClockOption interface {
Option
RunOption
ResolveOption
ApproveOption
CancelOption
AnswerOption
}ClockOption is a clock that applies to an agent (Option), to one run (RunOption), to a halt resolution (ResolveOption), to a recorded approver decision (ApproveOption), and to a cancellation (CancelOption), and to an interrupt answer or signal (AnswerOption): WithClock.
Constructors and functions
func WithClock(now func() time.Time) ClockOption: WithClock sets the clock that reads "now": for a run (an agent's runs, or one run), the clock its durable timers (Sleep, WaitUntil, AwaitFor) measure against and that stamps the times it records (RunStart.StartedAt, ApprovalWait.RecordedAt, the end markers' RecordedAt); for ResolveHalt, the one clock of the call: WithMinHaltAge measures against it, and it stamps the claim marker and the outcome's RecordedAt (the context's clock is not read); for SubmitDecision, Approve and Cancel, the clock that stamps the record's RecordedAt.
type CompactionReport
type CompactionReport struct {
Complete bool `json:"complete"`
Detail string `json:"detail"`
}CompactionReport says what Compact did. (experimental)
type Compactor
type Compactor interface {
Compact(ctx context.Context) (CompactionReport, error)
}Compactor is the optional store capability that makes an erasure complete at the storage layer: a store whose engine keeps the bytes a redaction replaced (SQLite's write-ahead log and freed pages) overwrites them. (experimental)
type Compensator
type Compensator interface {
Compensate(ctx context.Context, args, result json.RawMessage) error
}Compensator is an optional interface a Tool implements to declare how to UNDO its side effect.
type ConcurrencyOption
type ConcurrencyOption interface {
Option
RunOption
ParallelOption
}ConcurrencyOption is a concurrency cap that applies to an agent's tool calls (Option), to one run's (RunOption), and to Parallel's tasks (ParallelOption): WithMaxConcurrency.
Constructors and functions
func WithMaxConcurrency(n int) ConcurrencyOption: WithMaxConcurrency caps how many tool calls of one turn run at once (for an agent or a run), or how many of Parallel's tasks do.
type CountedDecision
type CountedDecision struct {
Approver string
Decision CertDecision
}CountedDecision is one counted certificate-bound decision the execution check must re-verify.
type Decision
type Decision struct {
RunID string
ToolUseID string
ApproverID string
Approved bool
DecidedAt time.Time
Alg Alg
Signature []byte
Cert [][]byte
}Decision is one named approver's signed decision on a tool call gated by an m-of-n Approval policy.
type DecisionCheck
type DecisionCheck struct {
Step string
Approver string
Approved bool
Counted bool
Reason string
Cert *CertCheck
}DecisionCheck is how the counting rule classified one decision record.
type Describer
type Describer interface {
Describe() ModelInfo
}Describer is implemented by a Model that can say what it is.
type Doc
type Doc struct {
ID string `json:"id,omitempty"`
Text string `json:"text"`
Score float64 `json:"score,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}Doc is a document returned by a Retriever: its text plus optional id, similarity score, and metadata.
type Emit
type Emit struct {
Event Event
Err error
}Emit is what an adapter pushes onto its event channel (event or terminal error).
type Entry
type Entry struct {
Seq int64
Name string
Data []byte
}Entry is one stored entry of a run: its position, name and bytes.
type EscalationStep
type EscalationStep struct {
Receiver string
Deadline time.Duration
}EscalationStep is one step of an escalation chain: the receiver to tell, and how long it has, from the moment the step is observed, before the next step is due.
type Event
type Event interface {
// contains filtered or unexported methods
}Event is a normalized streamed model event.
type ExecFailure
type ExecFailure struct {
Approver string
Reason string
Detail string
Revocation *CertRevocation
Anchored string
StatusTime string
}ExecFailure is a counted decision that does not hold.
type ExecHold
type ExecHold struct {
Format string `json:"format"`
ToolUseID string `json:"tool_use_id"`
Generation int `json:"generation"`
Reason string `json:"reason"`
Detail string `json:"detail"`
Approvers []string `json:"approvers,omitempty"`
CheckedAt string `json:"checked_at"`
StatusTime string `json:"status_time,omitempty"`
Serial string `json:"serial,omitempty"`
E string `json:"e,omitempty"`
ReasonCode int `json:"reason_code"`
CRLHash string `json:"crl_hash,omitempty"`
AnchoredAt string `json:"anchored_at,omitempty"`
PolicyDigest string `json:"policy_digest,omitempty"`
}ExecHold is what an ApprovalExecHoldStep record holds: the pre-execution status check found that the call may not run, with the evidence an operator decides on.
type ExecOutcome
type ExecOutcome intExecOutcome is what the pre-execution check decided.
Constants
const ExecProceed ExecOutcome: ExecProceed: every counted certificate-bound decision still holds; the call may run.const ExecWait ExecOutcome: ExecWait: status is missing or stale, or the decision cannot be proven now (no covering head at hand).const ExecReask ExecOutcome: ExecReask: a counted decision no longer holds and cannot hold again (its certificate is revoked with E <= A(d), or it no longer verifies for a reason that is not a wait).
type ExecVerdict
type ExecVerdict struct {
Outcome ExecOutcome
Failed []ExecFailure
Checked int
}ExecVerdict is the result of CheckExec.
Constructors and functions
func CheckExec(counted []CountedDecision, verifierFor ApproverVerifierFor) ExecVerdict: CheckExec re-verifies every counted decision through its approver's CertExecVerifier.
type Finish
type Finish struct {
Reason FinishReason `json:"reason"`
Raw string `json:"raw"`
Usage Usage `json:"usage"`
Discarded Usage `json:"discarded"`
// contains filtered or unexported fields
}Finish ends a model turn.
type FinishReason
type FinishReason stringFinishReason is why a model turn ended, in a neutral vocabulary every adapter maps its provider's reasons onto (see Finish).
Constants
const FinishStop FinishReason = "stop",const FinishToolUse FinishReason = "tool_use",const FinishLength FinishReason = "length",const FinishFiltered FinishReason = "filtered": The neutral finish reasons (see Finish).
type Finished
type Finished struct {
Final Message `json:"final"`
}Finished carries the terminal assistant answer, the same Message that Run returns and that Final reports.
type FlowRef
type FlowRef struct {
Name string `json:"name"`
}FlowRef names the plan flow that drives a run of kind RunKindFlow.
type GateReason
type GateReason struct {
Kind string `json:"kind"`
Source string `json:"source,omitempty"`
Ref string `json:"ref,omitempty"`
Pos int `json:"pos,omitempty"`
Rule string `json:"rule,omitempty"`
Action string `json:"action,omitempty"`
Why string `json:"why,omitempty"`
Currency string `json:"currency,omitempty"`
Amount *int64 `json:"amount,omitempty"`
Limit int64 `json:"limit,omitempty"`
At string `json:"at,omitempty"`
}GateReason is one reason a call needs a gate beyond its tool's own, as the gate-reason record the engine wrote holds it. (experimental)
Methods
func (r GateReason) Line() string: Line is the reason as one line of text, for a terminal or a log: "untrusted content from inbound-email (read by tool read_email, call c3, journal position 4)", or "cap refund_one: this call 6000.00 USD, limit 5000.00 USD (over, gate)". (experimental)
type GateStanding
type GateStanding struct {
Status GateStatus
Tally ApprovalTally
Recorded bool
Checks []DecisionCheck
Reason string
Err error
Ran, Denied bool
SingleDecided, SingleApproved bool
Expired bool
Deadline time.Time
}GateStanding is the result of EvaluateGate.
Constructors and functions
func EvaluateGate(recs []Record, s ApprovalSubject, pol *ApprovalPolicy, verifierFor ApproverVerifierFor) GateStanding: EvaluateGate says where the approval gate stands on the call s in runID's journal recs, under the policy pol it is built with now (nil: the tool has no gate) and the approver verifiers, exactly as the agent's own gate reads it: the same function counts for both, so a service that tells approvers whether a call waits cannot disagree with the run.func EvaluateGateAfter(recs []Record, s ApprovalSubject, pol *ApprovalPolicy, verifierFor ApproverVerifierFor, since string) GateStanding: EvaluateGateAfter is EvaluateGate for a plan flow node's gate (s.ToolUseID a node key), which counts only the decisions recorded after the gate's request, the step ApprovalRequestStep(key) names, and whose result is the key's own record.
type GateStatus
type GateStatus stringGateStatus is where an approval gate stands on one call, as the gate itself reads it.
Constants
const GateWaiting GateStatus = "waiting": GateWaiting: an m-of-n gate with no recorded outcome.const GateDecided GateStatus = "decided": GateDecided: the call has an outcome the gate acts on: its result is recorded, or a recorded denial (a human's Approve(false), or an m-of-n tally that did not pass), or the gate's recorded terminal tally that it accepts under the policy now.const GateSingle GateStatus = "single": GateSingle: the policy is a one-decision gate (SingleApproval).const GateUngated GateStatus = "ungated": GateUngated: no policy now (a redeploy removed the gate): the call runs without approval.const GateMisconfigured GateStatus = "misconfigured": GateMisconfigured: the gate would refuse to evaluate, so the run fails at the call rather than pauses: an invalid policy, approvers that share a key, no approver verifiers, a policy that excludes the requester for a run that records none, a tally journaled by something that is not this gate.
type HaltAlreadyResolved
type HaltAlreadyResolved struct {
RunID string
Op OpRef
Result json.RawMessage
IsError bool
}HaltAlreadyResolved is returned by ResolveHalt when the operation already has a recorded outcome that differs from the one given: an earlier resolution, or the result the live driver recorded.
Methods
func (e *HaltAlreadyResolved) Error() string: Error names the operation and the outcome that stands.func (e *HaltAlreadyResolved) Unwrap() error: Unwrap returns ErrAlreadyResolved.
type HaltCause
type HaltCause stringHaltCause says why a run halted on an operation whose outcome is unknown.
Constants
const HaltCrashed HaltCause = "crashed": HaltCrashed: the operation's attempt marker is recorded with no result, and the halting driver knows of no live claimant.const HaltContended HaltCause = "contended": HaltContended: another driver of the same run won the claim on the operation while this one was running: a tool call's claim lost after this drive read no marker for it, or a Step's claim lost to a call of the step in flight in this process.
type HaltInFlight
type HaltInFlight struct {
RunID string
RootRunID string
Op OpRef
Attempt string
}HaltInFlight is returned by ResolveHalt when a driver may be running the operation's effect right now, and its own result must win over a resolution: a driver holds the lease on the halted run's root (a session turn's run, for a turn and the sub-runs inside it), or (see ResolveHalt) a driver holds the claim on the attempt after the live one, having found the live one recorded as never started.
Methods
func (e *HaltInFlight) Error() string: Error names the operation and what a driver holds.
type HaltRef
type HaltRef struct {
RunID string
Op OpRef
Cause HaltCause
}HaltRef is what ResolveHalt needs to clear a halt: the run whose journal holds the operation, the operation, and why it halted.
type HaltTooYoung
type HaltTooYoung struct {
RunID string
ToolUseID string
Age time.Duration
Min time.Duration
}HaltTooYoung is returned by ResolveHalt when WithMinHaltAge is set and the halt has not aged past the grace period yet.
Methods
func (e *HaltTooYoung) Error() string: Error names the run and operation, the halt's age and the minimum it must reach.
type Hold
type Hold struct {
ID string `json:"id"`
Matter string `json:"matter"`
Runs []string `json:"runs"`
Tree bool `json:"tree,omitempty"`
PlacedAtMs int64 `json:"placed_at_ms"`
}A Hold is a legal hold: a promise that the records of some runs are not erased while a matter is open. (experimental)
Constructors and functions
func HoldsOf(ctx context.Context, store Store, runID string) ([]Hold, error): HoldsOf returns the active holds in store's Holder that cover runID, or none for a store with no Holder. (experimental)
Methods
func (h Hold) Covers(runID string) bool: Covers reports whether the hold covers runID: it is one of the hold's runs, or, for a hold with Tree, a sub-agent run below one of them. (experimental)
type Holder
type Holder interface {
PlaceHold(ctx context.Context, h Hold) error
LiftHold(ctx context.Context, id string) (bool, error)
Holds(ctx context.Context) ([]Hold, error)
}Holder is the optional store capability that keeps legal holds. (experimental)
type Identity
type Identity struct {
Actor string `json:"actor,omitempty"`
OnBehalfOf string `json:"on_behalf_of,omitempty"`
AuthorityRef string `json:"authority_ref,omitempty"`
}Identity is the accountability binding for a run: which agent instance acted, on whose behalf, and under what authority.
Constructors and functions
func IdentityFrom(ctx context.Context) (Identity, bool): IdentityFrom returns the acting identity bound to ctx, and whether one was set.
Methods
func (i Identity) Empty() bool: Empty reports whether the identity carries no attribution at all.
type IdentityDecision
type IdentityDecision struct {
Approver string `json:"approver"`
Step string `json:"step"`
Identifier string `json:"identifier"`
LeafHash string `json:"leaf_hash"`
Chain []string `json:"chain"`
Anchor string `json:"anchor"`
AnchoredAt string `json:"anchored_at"`
TimeSource string `json:"time_source"`
TimeEvidence string `json:"time_evidence,omitempty"`
HeadSize int `json:"head_size"`
HeadRoot string `json:"head_root"`
HeadHash string `json:"head_hash"`
Tier string `json:"tier"`
BasisKind string `json:"basis_kind"`
Basis string `json:"basis"`
StatusTime string `json:"status_time,omitempty"`
Window string `json:"window,omitempty"`
Status []string `json:"status,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}IdentityDecision is one counted certificate-bound decision in an ApprovalIdentity.
type IdentityDescriber
type IdentityDescriber interface {
DescribeIdentity() IdentityPolicyRecord
PolicyDigest() string
RosterDigest() string
VerifierInfo() (revision, goDebug, buildGoDebug string)
}IdentityDescriber is implemented by the verifier of a certificate-bound approver that can describe the certificate policy in force, for the identity record a gate journals with its terminal count: DescribeIdentity is the policy and status values, PolicyDigest the SHA-256 (lowercase hex) of the JSON of that description (the value the pause note and the record both carry), and RosterDigest the SHA-256 over the whole identity map in sorted approver order, each entry len32(approver) approver len32(identifier) identifier.
type IdentityPolicyRecord
type IdentityPolicyRecord struct {
EffectiveFrom string `json:"effective_from"`
Anchors []string `json:"anchors"`
Intermediates []string `json:"intermediates"`
Distrust map[string]string `json:"distrust,omitempty"`
EKU string `json:"eku"`
PolicyOID string `json:"policy_oid,omitempty"`
IDKind string `json:"id_kind"`
Canonical string `json:"canonical"`
AllowEmailProtectionEKU bool `json:"allow_email_protection_eku,omitempty"`
RequireNameConstraints bool `json:"require_name_constraints,omitempty"`
RequirePolicyOnCAs bool `json:"require_policy_on_cas,omitempty"`
RSA2048Until string `json:"rsa2048_until,omitempty"`
MaxChain int `json:"max_chain"`
MaxLeafLifetime string `json:"max_leaf_lifetime"`
NotBeforeBackdate string `json:"not_before_backdate"`
Skew string `json:"skew"`
AnchorGrace string `json:"anchor_grace"`
ClockTolerance string `json:"clock_tolerance"`
W string `json:"w"`
MinW string `json:"min_w"`
RoutineGrace string `json:"routine_grace,omitempty"`
MaxStatusAge string `json:"max_status_age"`
ExecStatusAge string `json:"exec_status_age"`
ExecStatusAgeFor map[string]string `json:"exec_status_age_for,omitempty"`
MaxStatusAgeFor map[string]string `json:"max_status_age_for,omitempty"`
CAPeriod string `json:"ca_period"`
CAPeriodFor map[string]string `json:"ca_period_for,omitempty"`
CAOverlapFor map[string]string `json:"ca_overlap_for,omitempty"`
CoverageTolerance string `json:"coverage_tolerance"`
ThisUpdateSkew string `json:"this_update_skew"`
ThisUpdateSkewFor map[string]string `json:"this_update_skew_for,omitempty"`
AllowHolds bool `json:"allow_holds,omitempty"`
ConsecutiveNumbers bool `json:"consecutive_numbers,omitempty"`
CountLive bool `json:"count_live,omitempty"`
Retained bool `json:"retained,omitempty"`
IndependentTime bool `json:"independent_time,omitempty"`
}IdentityPolicyRecord is the certificate policy and status values in force when a gate counted, every one that reaches a verdict.
type IdentityRoster
type IdentityRoster interface {
HasIdentity(approverID string) bool
Identifier(approverID string) (identifier string, ok bool)
RequesterIdentifier(principal string) (identifier string, ok bool)
IdentityMappingConfigured() bool
RosterDigest() string
}IdentityRoster is implemented by the verifier of a certificate-bound approver that knows the policy's identity map.
type Image
type Image struct {
Mime string `json:"mime,omitempty"`
Data []byte `json:"data,omitempty"`
URL string `json:"url,omitempty"`
}Image is a provider-neutral image input.
Constructors and functions
func ImageData(mime string, data []byte) Image: ImageData builds an Image part from raw bytes with the given MIME type; the adapter base64-encodes the bytes onto the wire.func ImageURL(url string) Image: ImageURL builds an Image part referencing a hosted image by URL.
type InterruptPending
type InterruptPending struct {
RunRef
Name string
Prompt any
}InterruptPending is returned by Run when a tool called Interrupt and no answer has been recorded for that name yet.
Methods
func (e *InterruptPending) Error() string: Error names the run and the interrupt point.
type Journal
type Journal struct {
// contains filtered or unexported fields
}Journal is the durable journal the engine writes through: it owns everything a run's records mean on top of a Store.
Constructors and functions
func NewJournal(s Store, opts ...JournalOption) (*Journal, error): NewJournal returns a Journal over s.
Methods
func (j *Journal) AnswerInterrupt[T any](ctx context.Context, runID, name string, value T, opts ...AnswerOption) error: AnswerInterrupt records the typed value a paused run is waiting for at the interrupt point name (see Interrupt); then re-invoke Run with the pause's RootRunID to continue.func (j *Journal) Enqueue[T any](ctx context.Context, runID, channel, key string, payload T) error: Enqueue appends a message to an ordered per-run channel, deduped by key: a redelivery with the same (runID, channel, key) is a no-op and the first payload wins (at-most-once intake over at-least-once transport).func (j *Journal) Format(ctx context.Context, runID string) (string, error): Format returns the journal format runID's header names, "" for a run with no entries, and a *JournalVersionError for a run whose first entry is not a header.func (j *Journal) Get(ctx context.Context, runID, name string) (Record, bool, error): Get returns the record named name in runID's journal, if there is one.func (j *Journal) History(ctx context.Context, runID string) ([]Record, error): History returns runID's records in journal order, the header first (see Records).func (j *Journal) Parallel[T any](ctx context.Context, runID string, tasks []Task[T], opts ...ParallelOption) ([]T, error): Parallel runs tasks concurrently, each as a durable named step (see Step), and returns their results in task order.func (j *Journal) Reanchor(ctx context.Context, runID string) (anchored bool, err error): Reanchor asks the journal's store, if it can (a Reanchorer such as audit.AuditedStore), to publish a signed head over runID's journal now, and reports whether it could.func (j *Journal) Records(ctx context.Context, runID string) iter.Seq2[Record, error]: Records yields runID's records in journal order, the header first.func (j *Journal) Signal[T any](ctx context.Context, runID, name string, payload T, opts ...AnswerOption) error: Signal delivers a single-shot signal to a run, journaled at-most-once by name: a redelivery (a retried webhook, an at-least-once queue) is a no-op and the first payload wins.func (j *Journal) Step[T any](ctx context.Context, runID, name string, fn func(context.Context) (T, error), opts ...StepOption) (T, error): Step runs fn as a named durable step and returns its typed result.func (j *Journal) Store() Store: Store returns the store the journal writes to.
type JournalNotifyEvent
type JournalNotifyEvent struct {
Key string
Kind NotificationKind
RunID string
At time.Time
Current bool
Approvers []string
ResolvedAt time.Time
}JournalNotifyEvent is an event the journal of a run records that needs a person: a gate the run paused at, an effect whose outcome is unknown, a run that aborted.
Constructors and functions
func JournalNotifyEvents(runID string, recs []Record) []JournalNotifyEvent: JournalNotifyEvents returns the events recs, the history of runID, records that need a person, in journal order (gates, then halts in key order, then the abort).func StopNotifyEvents(st StopState, now time.Time, within time.Duration, observed func(key string) bool) []JournalNotifyEvent: StopNotifyEvents are the events a state of the control run owes a notifier at now, with a window of within (0: the notifier's default, 7 days), as the journal-side facts audit.VerifyNotifications compares with the trail of the control run: a stop_set for each stop in force (and each lifted one that is owed, see stopsOwed; Current while the stop stands, with the time it was lifted as ResolvedAt otherwise), and a stop_lifted for each lift owed. (experimental)
type JournalOption
type JournalOption interface {
// contains filtered or unexported methods
}JournalOption configures NewJournal.
type JournalVersionError
type JournalVersionError struct {
RunID string
Found string
Supported []string
}JournalVersionError is returned by a Journal asked to read or write a run whose journal format it does not support (see JournalFormat).
Methods
func (e *JournalVersionError) Error() string: Error describes the run, the format found, and the formats supported.func (e *JournalVersionError) Unwrap() error: Unwrap returns ErrJournalVersion.
type KeptRecord
type KeptRecord struct {
Position int `json:"position"`
Name string `json:"name"`
Reason string `json:"reason"`
}KeptRecord is a record a selector chose and a redaction keeps, and why. (experimental)
type LeaseControl
type LeaseControl interface {
LeaseOption
RecoverOption
RecoverLoopOption
}LeaseControl is a lease setting that applies to Lease (LeaseOption), Recover (RecoverOption) and RecoverLoop (RecoverLoopOption): WithLeaseHolder and WithLeaseTTL.
Constructors and functions
func WithLeaseHolder(id string) LeaseControl: WithLeaseHolder names the worker that claims leases, as the leases table and logs show it.func WithLeaseTTL(d time.Duration) LeaseControl: WithLeaseTTL sets how long an acquired lease is valid.
type LeaseOption
type LeaseOption interface {
// contains filtered or unexported methods
}LeaseOption configures Lease, and the lease Agent.Session drives each turn's run under.
type Leaser
type Leaser interface {
AcquireLease(ctx context.Context, runID, holder string, ttl time.Duration) (bool, error)
RenewLease(ctx context.Context, runID, holder string, ttl time.Duration) (bool, error)
ReleaseLease(ctx context.Context, runID, holder string) error
ReapLeases(ctx context.Context, ended []string) (int, error)
}Leaser is the optional capability that coordinates driving a run across processes.
type LiftRequest
type LiftRequest struct {
Reason string
By, Host string
Signer StopSigner
}LiftRequest is what LiftStop takes: one lifter's approval. (experimental)
type Lister
type Lister interface {
Runs(ctx context.Context, f RunFilter) iter.Seq2[string, error]
}Lister is the optional store capability a crash-recovery supervisor needs: it enumerates the runs a store holds, so Recover can find the ones to re-drive after a restart.
type MemNotifyTrail
type MemNotifyTrail struct {
// contains filtered or unexported fields
}MemNotifyTrail is an in-memory NotifyTrail, safe for concurrent use.
Constructors and functions
func NewMemNotifyTrail() *MemNotifyTrail: NewMemNotifyTrail returns an empty in-memory trail store.
Methods
func (m *MemNotifyTrail) Append(_ context.Context, trail string, seq int, rec NotifyRecord) error: Append implements NotifyTrail.func (m *MemNotifyTrail) Load(_ context.Context, trail string) ([]NotifyRecord, error): Load implements NotifyTrail.
type MemStopTrail
type MemStopTrail struct {
// contains filtered or unexported fields
}MemStopTrail is an in-memory StopTrail, safe for concurrent use. (experimental)
Constructors and functions
func NewMemStopTrail() *MemStopTrail: NewMemStopTrail returns an empty in-memory stop trail. (experimental)
Methods
func (m *MemStopTrail) Append(_ context.Context, trail string, seq int, rec StopRecord) error: Append implements StopTrail. (experimental)func (m *MemStopTrail) Load(_ context.Context, trail string) ([]StopRecord, error): Load implements StopTrail. (experimental)
type MemStore
type MemStore struct {
// contains filtered or unexported fields
}MemStore is an in-memory Store for tests and local development.
Constructors and functions
func NewMemStore() *MemStore: NewMemStore returns an empty MemStore.
Methods
func (m *MemStore) AcquireLease(_ context.Context, runID, holder string, ttl time.Duration) (bool, error): AcquireLease implements Leaser.func (m *MemStore) Get(ctx context.Context, runID, name string) (Entry, bool, error): Get implements Store.func (m *MemStore) Holds(ctx context.Context) ([]Hold, error): Holds implements Holder.func (m *MemStore) Insert(ctx context.Context, runID, name string, data []byte) (Entry, bool, error): Insert implements Store.func (m *MemStore) LiftHold(ctx context.Context, id string) (bool, error): LiftHold implements Holder.func (m *MemStore) Load(ctx context.Context, runID string, after int64) iter.Seq2[Entry, error]: Load implements Store.func (m *MemStore) PlaceHold(ctx context.Context, h Hold) error: PlaceHold implements Holder.func (m *MemStore) ReapLeases(_ context.Context, ended []string) (int, error): ReapLeases implements Leaser.func (m *MemStore) Redact(ctx context.Context, runID, name string, current, tombstone []byte) (bool, error): Redact implements Redactor.func (m *MemStore) ReleaseLease(_ context.Context, runID, holder string) error: ReleaseLease implements Leaser.func (m *MemStore) RenewLease(_ context.Context, runID, holder string, ttl time.Duration) (bool, error): RenewLease implements Leaser.func (m *MemStore) Runs(ctx context.Context, f RunFilter) iter.Seq2[string, error]: Runs implements Lister: the runs f admits, in ascending order.
type MemWaker
type MemWaker struct {
// contains filtered or unexported fields
}MemWaker is an in-process Waker: it holds pending timers and, when Fire is called with the current time (or via a Start ticker), resumes every run whose timer is due by calling the resume function it was built with.
Constructors and functions
func NewMemWaker(resume func(ctx context.Context, runID string) error) *MemWaker: NewMemWaker builds an in-process waker that resumes due runs via resume.
Methods
func (w *MemWaker) Fire(ctx context.Context, now time.Time) (int, error): Fire resumes every run that has a timer due at or before now, each run once even if several of its timers are due, drops the fired timers, and returns how many runs it resumed.func (w *MemWaker) Schedule(_ context.Context, wk Wake) error: Schedule registers a wake, idempotent per (w.RunID, w.Name): re-scheduling the same timer overwrites its fire time rather than adding a duplicate.func (w *MemWaker) Start(ctx context.Context, every time.Duration, onError func(error)) <-chan struct{}: Start runs Fire on a ticker everyeveryuntil ctx is cancelled, so sleeping runs wake on their own.
type Message
type Message struct {
Role Role
Parts []Part
}Message is one turn.
Constructors and functions
func SystemText(s string) Message: SystemText returns a system message holding the text s.func UserParts(parts ...Part) Message: UserParts builds a user message from mixed parts, e.g. a prompt and one or more images: UserParts(Text{"what is this?"}, ImageData("image/png", raw)).func UserText(s string) Message: UserText returns a user message holding the text s.
Methods
func (m Message) MarshalJSON() ([]byte, error): MarshalJSON encodes the message with each part tagged by its type, so UnmarshalJSON can restore the concrete Part types.func (m Message) Text() string: Text returns the concatenation of the message's Text parts (ignoring reasoning, tool calls, and tool results).func (m *Message) UnmarshalJSON(b []byte) error: UnmarshalJSON decodes a message written by MarshalJSON, restoring each part's concrete type.
type Middleware
type Middleware func(next ModelHandler) ModelHandlerMiddleware wraps a ModelHandler: the net/http-style func(Handler) Handler chain, at the semantic layer (it sees messages, tool calls and token usage, not bytes).
type ModeRequest
type ModeRequest struct {
To StopMode
Reason string
By, Host string
Signer StopSigner
}ModeRequest is what ChangeMode takes: one signer's evidence record of a change of mode. (experimental)
type Model
type Model interface {
Stream(ctx context.Context, req Request) (*Stream, error)
}Model is the provider primitive.
Constructors and functions
func Replay(ctx context.Context, source *Journal, runID string) (Model, error): Replay returns a Model that re-emits the model outputs recorded insourcefor runID, in order, instead of calling a live LLM.
type ModelAttempt
type ModelAttempt struct {
Response ModelResponse
Discarded Usage
Err error
}ModelAttempt is how one request ended, as an After hook sees it.
type ModelCall
type ModelCall struct {
Request Request
Model Model
RunID string
Turn int
// contains filtered or unexported fields
}ModelCall is one model call as it passes through the middleware chain.
Methods
func (c ModelCall) AddHook(h ModelCallHook) ModelCall: AddHook returns a copy of c with h appended to its hooks, which the agent's model handler runs around every request it sends for the returned call and every call derived from it.func (c ModelCall) Attempt() int: Attempt is the number of the request a hook is observing.func (c ModelCall) OnAnswer(key any, fn func(ctx context.Context, resp ModelResponse)) bool: OnAnswer registers fn to run once with the call's answer: the response the whole chain returns to the agent, after the agent's checks, once the journal holds it as the turn's record (for CallModel, which has no journal, once the call returns it).
type ModelCallHook
type ModelCallHook struct {
Before func(ctx context.Context, call ModelCall) error
After func(ctx context.Context, call ModelCall, a ModelAttempt)
}ModelCallHook runs around each request the agent's model handler sends: every retried attempt and every hedged target, wherever the middleware that added it (ModelCall.AddHook) sits in the chain.
type ModelEvent
type ModelEvent struct {
Event Event `json:"event"`
}ModelEvent forwards one live model stream Event (TextDelta, ReasoningDelta, ToolCallDelta, Finish) from the current turn, the token-by-token feed.
type ModelHandler
type ModelHandler func(ctx context.Context, call ModelCall) (ModelResponse, error)ModelHandler answers one model call: it returns the response the turn records.
type ModelInfo
type ModelInfo struct {
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
ResponseFormat bool `json:"response_format,omitempty"`
}ModelInfo identifies a Model.
Constructors and functions
func ModelInfoOf(m Model) (ModelInfo, bool): ModelInfoOf describes m.
type ModelResponse
type ModelResponse struct {
Message Message
Usage Usage
Finish FinishReason
RawFinish string
// contains filtered or unexported fields
}ModelResponse is the answer to a model call: the assistant message, the usage of the request that produced it, and why the turn ended.
Constructors and functions
func CallModel(ctx context.Context, m Model, req Request, mw ...Middleware) (ModelResponse, error): CallModel sends one model call outside an agent, through mw (first = outermost) and the same model handler an agent uses: hooks run around every request, Messages and Tools arrive clipped, and the response is checked as an agent checks it (usage, finish reason, tool-use ids).
type ModelTurn
type ModelTurn struct {
Finish FinishReason `json:"finish,omitempty"`
RawFinish string `json:"raw_finish,omitempty"`
Model *ModelInfo `json:"model,omitempty"`
PromptDigest string `json:"prompt_digest,omitempty"`
ToolsDigest string `json:"tools_digest,omitempty"`
}ModelTurn is a StepModel record's model-turn metadata (see Record.ModelTurn).
type Notification
type Notification struct {
ID string
Key string
Kind NotificationKind
RunID string
EventAt, Observed time.Time
Deadline time.Time
Attempt int
Halt *NotifyHalt
Approval *NotifyApproval
Stop *NotifyStop
Principal *Principal
Clears *NotifyClears
Escalates *NotifyEscalates
Receiver string
Reason string
Err error
}Notification is one delivery attempt of an event to a Notifier.
type NotificationKind
type NotificationKind stringNotificationKind says what a Notification is about.
Constants
const NotificationOutcomeUnknown NotificationKind = "outcome_unknown": NotificationOutcomeUnknown: a drive ended with *OutcomeUnknown.const NotificationApprovalPending NotificationKind = "approval_pending": NotificationApprovalPending: a drive ended with *ApprovalPending.const NotificationRunAborted NotificationKind = "run_aborted": NotificationRunAborted: the run reached the run:aborted end marker.const NotificationRecoveryFailing NotificationKind = "recovery_failing": NotificationRecoveryFailing: recovery has kept failing for a run for longer than the configured time.const NotificationOverdue NotificationKind = "notification_overdue": NotificationOverdue: an event was not acknowledged by its deadline.const NotificationResolved NotificationKind = "resolved": NotificationResolved: an outcome_unknown, approval_pending, recovery_failing or stop_set event that a receiver has, or may have, stopped being current (the halt was resolved, the gate decided, the run ended, recovery recovered).const NotificationApprovalExpired NotificationKind = "approval_expired": NotificationApprovalExpired: an approval gate a receiver was, or may have been, told of (approval_pending) expired: its deadline (ApprovalPolicy.Timeout) passed with no approval, so the call will not run.const NotificationEscalated NotificationKind = "escalated": NotificationEscalated: an outcome_unknown, approval_pending, recovery_failing or stop_set event was not acknowledged (an approval: not decided) by its deadline, and the next receiver of its escalation chain is told.const NotificationStopSet NotificationKind = "stop_set": NotificationStopSet: a stop was set. (experimental)const NotificationStopLifted NotificationKind = "stop_lifted": NotificationStopLifted: a stop was lifted, by the lift rule in force (an audited stop needs its quorum, so one partial lift raises nothing). (experimental)
Constructors and functions
func ParseStopKey(key string) (id string, kind NotificationKind, ok bool): ParseStopKey is the stop and the kind an event key names: StopSetKey is a stop_set, StopLiftedKey a stop_lifted. (experimental)
type Notifier
type Notifier interface {
Notify(ctx context.Context, n Notification) error
}Notifier delivers one Notification.
type NotifierOption
type NotifierOption interface {
Option
RecoverOption
RecoverLoopOption
}NotifierOption is the result of WithNotifier: it configures an Agent (New, With), RecoverLoop and Recover.
Constructors and functions
func WithNotifier(n Notifier, trail NotifyTrail, opts ...NotifyOption) NotifierOption: WithNotifier tells n, at least once and with a stable ID, when a run needs a person: it halts on an unknown outcome, waits for approval, is aborted, or cannot be recovered.
type NotifyAck
type NotifyAck struct {
Status int
Auth *NotifyAuth
}NotifyAck is what a Notifier reports about an accepted delivery, recorded in the trail beside the acknowledgement as audit evidence of how it was authenticated.
type NotifyApproval
type NotifyApproval struct {
ToolUseID string
ToolName string
Need, Of int
Approvers []string
Approved int
Excluded []string
Reask string
Why []GateReason
// contains filtered or unexported fields
}NotifyApproval is the structured detail of a NotificationApprovalPending notification.
type NotifyAuth
type NotifyAuth struct {
Signature string `json:"signature,omitempty"`
SecretSlot string `json:"secret_slot,omitempty"`
MTLS bool `json:"mtls,omitempty"`
ClientSPKI string `json:"client_spki,omitempty"`
ServerPinned bool `json:"server_pinned,omitempty"`
CustomCA bool `json:"custom_ca,omitempty"`
TLSVersion string `json:"tls_version,omitempty"`
}NotifyAuth records how a delivery was authenticated, next to the delivery it authenticated.
type NotifyClears
type NotifyClears struct {
Key, ID string
Kind NotificationKind
}NotifyClears is the structured detail of a NotificationResolved notification: the event it ends.
type NotifyEscalates
type NotifyEscalates struct {
Key, ID string
Kind NotificationKind
Level int
}NotifyEscalates is the structured detail of a NotificationEscalated notification: the event it escalates, and the step of the chain it is.
type NotifyEvent
type NotifyEvent struct {
Key string
Kind string
RunID string
EventAt time.Time
ObservedAt time.Time
DeadlineAt time.Time
OpRun, OpKind, OpID string
Reason string
Receiver string
Level int
Claim *NotifyRecord
Rounds int
Acked *NotifyRecord
Cleared *NotifyRecord
Failing *NotifyRecord
Overdue *NotifyRecord
}NotifyEvent is the state of one event, folded from a notification trail.
Methods
func (e *NotifyEvent) ClaimLive(now time.Time) bool: ClaimLive reports whether some process holds a live claim at now.func (e *NotifyEvent) Open() bool: Open reports whether delivery of the event is still owed: it has been neither acknowledged nor cleared.func (e *NotifyEvent) OverdueDue(now time.Time) bool: OverdueDue reports whether the event is open, past its deadline at now, and not yet marked overdue.func (e *NotifyEvent) ReceiverName() string: ReceiverName is the name of the receiver the event is to: DefaultReceiver when none is recorded.
type NotifyHalt
type NotifyHalt struct {
Op OpRef
Cause HaltCause
AttemptedAt time.Time
}NotifyHalt is the structured detail of a NotificationOutcomeUnknown notification.
type NotifyOption
type NotifyOption interface {
// contains filtered or unexported methods
}NotifyOption configures the notifier WithNotifier and NotifyPending build.
Constructors and functions
func WithNotifyAbortedWithin(d time.Duration) NotifyOption: WithNotifyAbortedWithin sets how recent an aborted run must be for NotifyPending to raise its run_aborted event (default 24 hours), by the time the run started, which is the only time its journal records.func WithNotifyApproverRoute(approver, receiver string) NotifyOption: WithNotifyApproverRoute sends the approval_pending event of a gate whose approvers include approver to the named receiver.func WithNotifyClaimTTL(d time.Duration) NotifyOption: WithNotifyClaimTTL sets how long a process's claim on an event lasts (default 2 minutes).func WithNotifyClock(now func() time.Time) NotifyOption: WithNotifyClock sets the clock the notifier reads: for claim and deadline times, backoff, and the age of an aborted run or a halt in a sweep.func WithNotifyDeadline(d time.Duration) NotifyOption: WithNotifyDeadline sets how long after an event is observed it may go unacknowledged before it is overdue (default 5 minutes).func WithNotifyErrors(fn func(error)) NotifyOption: WithNotifyErrors sets the function that receives the notifier's own failures: a trail or store error, a delivery that has become failing, a trail position it kept losing.func WithNotifyEscalation(kind NotificationKind, steps ...EscalationStep) NotifyOption: WithNotifyEscalation sets the escalation chain of events of kind: NotificationOutcomeUnknown, NotificationApprovalPending or NotificationRecoveryFailing.func WithNotifyFailingAfter(n int) NotifyOption: WithNotifyFailingAfter sets how many failed delivery attempts make a delivery failing (default 8).func WithNotifyHaltAge(d time.Duration) NotifyOption: WithNotifyHaltAge sets how old an attempt marker with no result must be before NotifyPending reports it as a halt (default 5 minutes).func WithNotifyHolder(id string) NotifyOption: WithNotifyHolder names this process in the claims it writes (default host, pid and a random number).func WithNotifyReceiver(name string, n Notifier) NotifyOption: WithNotifyReceiver names a receiver besides the one WithNotifier is given (DefaultReceiver), for WithNotifyRoute, WithNotifyApproverRoute and WithNotifyEscalation.func WithNotifyRecoveryFailingAfter(d time.Duration) NotifyOption: WithNotifyRecoveryFailingAfter sets how long recovery must keep failing for a run before a NotificationRecoveryFailing event is raised (default 15 minutes).func WithNotifyRetry(base, max time.Duration) NotifyOption: WithNotifyRetry sets the backoff between rounds of a failing delivery: base, doubling per failure, up to max (defaults 1 second and 15 minutes).func WithNotifyRoute(kind NotificationKind, receiver string) NotifyOption: WithNotifyRoute sends events of kind to the named receiver instead of the default one.func WithNotifyStops(ctl *StopControl) NotifyOption: WithNotifyStops makes NotifyPending also read ctl's control run and notify of each stop that was set, and each that was lifted, within the last WithNotifyStopsWithin (default 7 days; the set and the lift are judged by their own times). (experimental)func WithNotifyStopsWithin(d time.Duration) NotifyOption: WithNotifyStopsWithin sets how far back stop events are raised (see WithNotifyStops); at least one minute. (experimental)func WithNotifyUpgradeWindow(d time.Duration) NotifyOption: WithNotifyUpgradeWindow sets how long after the first backfill pass the second runs (default 24 hours).func WithOverdueNotifier(n Notifier) NotifyOption: WithOverdueNotifier sends NotificationOverdue events to n instead of the main Notifier, for the usual case where the main sink being down is why the event is overdue.
type NotifyRecord
type NotifyRecord struct {
Kind NotifyRecordKind `json:"kind"`
Key string `json:"key,omitempty"`
RunID string `json:"run_id,omitempty"`
At time.Time `json:"at"`
ClockAt time.Time `json:"clock_at,omitzero"`
EventKind string `json:"event_kind,omitempty"`
Receiver string `json:"receiver,omitempty"`
Level int `json:"level,omitempty"`
EventAt time.Time `json:"event_at,omitzero"`
DeadlineAt time.Time `json:"deadline_at,omitzero"`
Holder string `json:"holder,omitempty"`
Until time.Time `json:"until,omitzero"`
FirstSentAt time.Time `json:"first_sent_at,omitzero"`
Attempts int `json:"attempts,omitempty"`
Status int `json:"status,omitempty"`
Auth *NotifyAuth `json:"auth,omitempty"`
Failures int `json:"failures,omitempty"`
Latency time.Duration `json:"latency,omitempty"`
OpRun string `json:"op_run,omitempty"`
OpKind string `json:"op_kind,omitempty"`
OpID string `json:"op_id,omitempty"`
Watching []Watched `json:"watching,omitempty"`
Backfilled bool `json:"backfilled,omitempty"`
Backfills int `json:"backfills,omitempty"`
BackfillAt time.Time `json:"backfill_at,omitzero"`
BackfillWindow time.Duration `json:"backfill_window,omitempty"`
Next string `json:"next,omitempty"`
Reason string `json:"reason,omitempty"`
}NotifyRecord is one record of a notification trail.
Methods
func (r NotifyRecord) Normalized() NotifyRecord: Normalized returns r with every time in UTC and stripped of its monotonic clock reading, the form a trail stores and compares, so two records of one instant are equal whatever location they were written in.
type NotifyRecordKind
type NotifyRecordKind stringNotifyRecordKind says what a NotifyRecord records.
Constants
const NotifyObserved NotifyRecordKind = "observed": NotifyObserved: a notifier process first saw the event.const NotifyClaimed NotifyRecordKind = "claimed": NotifyClaimed: a process claimed the event for one delivery round, until Until.const NotifyAcked NotifyRecordKind = "acked": NotifyAcked: the sink acknowledged the event.const NotifyFailing NotifyRecordKind = "failing": NotifyFailing: delivery has failed Failures times.const NotifyOverdue NotifyRecordKind = "overdue": NotifyOverdue: the event was not acknowledged by its deadline.const NotifyCleared NotifyRecordKind = "cleared": NotifyCleared: the event stopped being current (resolved, decided, or the run ended).const NotifyFailingSince NotifyRecordKind = "failing_since": NotifyFailingSince: a recovery pass failed and no failure episode was open for the run.const NotifyRecovered NotifyRecordKind = "recovered": NotifyRecovered: a recovery pass succeeded while a failure episode was open.const NotifyWatch NotifyRecordKind = "watch": NotifyWatch: an event that can stop being current is about to be observed; written to the NotifyOpenTrail, not to a run's trail.const NotifyUnwatch NotifyRecordKind = "unwatch": NotifyUnwatch: nothing more is owed for the watched event (its all-clear was acknowledged, or it was cleared before any delivery was attempted, or it was never observed); written to the NotifyOpenTrail.const NotifyCheckpoint NotifyRecordKind = "checkpoint": NotifyCheckpoint: the first record of every open-trail segment but the first: the events listed when the previous segment was sealed, carried forward (Watching, Backfilled), so a read starts at the newest segment.const NotifySeal NotifyRecordKind = "seal": NotifySeal: the last record of an open-trail segment; Next names the segment that continues it.const NotifySegment NotifyRecordKind = "segment": NotifySegment: one record of the open trail's index, naming (Next) a segment that was created.const NotifyBackfilled NotifyRecordKind = "backfilled": NotifyBackfilled: the events observed before the open trail existed were listed (once).
type NotifyRouting
type NotifyRouting struct {
Routes map[NotificationKind]string `json:"routes,omitempty"`
ApproverRoutes map[string]string `json:"approver_routes,omitempty"`
Escalation map[NotificationKind][]string `json:"escalation,omitempty"`
}NotifyRouting is the routing of a notifier: which receiver each kind of event goes to, which receivers an approval goes to by its approvers, and the receivers of each escalation chain.
Constructors and functions
func RoutingOf(opts ...NotifyOption) (NotifyRouting, error): RoutingOf returns the routing the options give a notifier: build it from the same NotifyOptions you pass to WithNotifier or NotifyPending, and write it (as JSON) for the auditor.
Methods
func (r NotifyRouting) ApproverRouted() bool: ApproverRouted reports whether routing depends on a gate's approvers, so that a gate's receivers cannot be known without them.func (r NotifyRouting) Receivers(kind NotificationKind, approvers []string) []string: Receivers returns the receivers an event of kind is delivered to, sorted: for an approval whose approvers are routed, the receiver of each (one delivery each), and, when any approver of the gate has no route, the kind's route as well (else DefaultReceiver), through which that approver is reached; for any other event, or an approval none of whose approvers is routed, the kind's route, else DefaultReceiver.
type NotifyState
type NotifyState struct {
Events map[string]*NotifyEvent
Keys []string
FailingSince *NotifyRecord
Episodes int
}NotifyState is a notification trail folded to what a notifier needs to decide its next step.
Constructors and functions
func FoldNotify(recs []NotifyRecord) NotifyState: FoldNotify folds a trail, in append order, to its state.
Methods
func (s NotifyState) ByReceiver() map[string][]string: ByReceiver groups the keys of the events in the trail by the receiver they are to (DefaultReceiver for the default one), each in the order observed: the per-receiver view of a run's deliveries, whose acknowledgement an auditor reads from Eventskey.func (s *NotifyState) RecoveryFailingDue(now time.Time, d time.Duration) bool: RecoveryFailingDue reports whether the open recovery failure episode has lasted longer than d at now, so a recovery_failing event is due.
type NotifyStop
type NotifyStop struct {
ID string
Scope StopScope
Reason string
Compensation string
By, Host string
Mode StopMode
Signed bool
LiftedBy []string
}NotifyStop is the structured detail of a NotificationStopSet or NotificationStopLifted notification. (experimental)
type NotifyTrail
type NotifyTrail interface {
Load(ctx context.Context, trail string) ([]NotifyRecord, error)
Append(ctx context.Context, trail string, seq int, rec NotifyRecord) error
}NotifyTrail is the port for the notification trail: a named, append-only sequence of NotifyRecords with insert-if-absent at a position.
type NotifyTrailAnchorer
type NotifyTrailAnchorer interface {
AnchorTrails(ctx context.Context, trails []string) error
}NotifyTrailAnchorer is an optional capability of a NotifyTrail: one whose records are signed and anchored as they are written (audit.NotifyTrail over an audit.AuditedEventStore) can also be asked to catch up.
type OpKind
type OpKind stringOpKind is the kind of operation a halt is on.
Constants
const OpTool OpKind = "tool": OpTool is a tool call; OpRef.ID is its tool-use ID.const OpStep OpKind = "step": OpStep is a Step; OpRef.ID is the step name.
type OpRef
type OpRef struct {
Kind OpKind
ID string
ToolName string
}OpRef names an operation in a run's journal: a tool call (ID is the tool-use ID and ToolName the tool's name) or a Step (ID is the step name, ToolName is empty).
type OpenState
type OpenState struct {
Watched []Watched
Backfilled bool
Backfills int
BackfillAt time.Time
BackfillWindow time.Duration
Sealed string
}OpenState is one open-trail segment folded.
Constructors and functions
func FoldOpen(recs []NotifyRecord) OpenState: FoldOpen folds an open-trail segment, in append order.
type Option
type Option interface {
// contains filtered or unexported methods
}Option configures an Agent: New applies options to a new agent, and With to a copy of one.
Constructors and functions
func WithApproverVerifiers(fn ApproverVerifierFor) Option: WithApproverVerifiers sets how the m-of-n approval gate resolves an approver id to the verifier of its decision signatures.func WithCapNamespace(name string) Option: WithCapNamespace names the deployment's cap ledgers: the cumulative caps of two agents on one store that give the same namespace and the same rule name count in the same windows, and two that give different namespaces do not. (experimental)func WithMiddleware(mw ...Middleware) Option: WithMiddleware appends model-call middleware, after any the agent has; the first one added is the outermost.func WithOptions(opts ...Option) Option: WithOptions groups options into one, applied in order where it appears.func WithRetrieval(r Retriever, k int, opts ...RetrievalOption) Option: WithRetrieval adds classic retrieval-augmented generation: for each run, the agent retrieves the top-k documents for the run's user message, as a journaled engine step, and adds them to every model request of the run as a user message placed just before that user message (after the system prompt and any earlier turns).func WithStopSwitch(sw *StopSwitch) Option: WithStopSwitch gives the agent a kill switch (see StopSwitch, and docs/design/kill-switch.md): its runs are held, as a pause (*Stopped), where a stop covers them, before any side effect that has not begun. (experimental)func WithSystemPromptFunc(fn func(ctx context.Context, run RunInfo) (string, error)) Option: WithSystemPromptFunc sets a system message computed for each drive of a run (each Run, Stream or resume), from the run's context and its RunInfo, so it can carry dynamic context (the date, the tenant, state read from elsewhere).func WithTaintPolicy(p TaintPolicy) Option: WithTaintPolicy makes the agent enforce p on the runs it starts (experimental). (experimental)func WithToolErrorRedactor(fn func(tool string, err error) string) Option: WithToolErrorRedactor sets the text recorded for a tool call that fails (see Agent.WithToolErrorRedactor for what it covers).func WithToolMiddleware(mw ...ToolMiddleware) Option: WithToolMiddleware appends tool-call middleware, after any the agent has; the first one added is the outermost (see ToolMiddleware).func WithTools(tools ...Tool) Option: WithTools registers tools with the agent.
type Outcome
type Outcome struct {
Result any
IsError bool
Evidence any
}Outcome is the verified outcome of a halted operation, recorded by ResolveHalt as the operation's result.
type OutcomeUnknown
type OutcomeUnknown struct {
RunRef
Op OpRef
AttemptedAt time.Time
Cause HaltCause
}OutcomeUnknown is returned when a run cannot safely proceed past an operation whose outcome is unknown: a non-retriable tool call or Step was attempted (its marker is recorded) but no result was.
Methods
func (e *OutcomeUnknown) Error() string: Error names the operation whose outcome is unknown, and says when another driver holds its claim.func (e *OutcomeUnknown) Ref() HaltRef: Ref returns the reference ResolveHalt takes to clear this halt.
type OutputMode
type OutputMode stringOutputMode is how a typed run (RunTyped) collects its answer: OutputTool (the default) through a final_answer tool call whose arguments are the answer, or OutputNative through the provider's native structured-output constraint (a JSON-schema response format).
Constants
const OutputTool OutputMode = "tool": OutputTool collects a typed run's answer as the arguments of a final_answer tool call (the default; see RunTyped).const OutputNative OutputMode = "native": OutputNative collects a typed run's answer through the provider's native structured output (WithOutputMode(OutputNative)).
type ParallelOption
type ParallelOption interface {
// contains filtered or unexported methods
}ParallelOption configures Parallel.
type Part
type Part interface {
// contains filtered or unexported methods
}Part is a single piece of message content.
type Pause
type Pause interface {
error
Paused() RunRef
// contains filtered or unexported methods
}Pause is the error a run returns when it has stopped durably and is waiting on something outside it: a human's approval (*ApprovalPending), an answer to an interrupt (*InterruptPending), a signal or a channel message (*SignalPending), a durable timer (*TimerPending), a kill switch that holds the run (*Stopped), or a verdict on a side effect whose outcome is unknown (*OutcomeUnknown).
Constructors and functions
func AsPause(err error) (Pause, bool): AsPause returns the first Pause in err's chain, if there is one.
type PendingStop
type PendingStop struct {
Record StopRecord
Age time.Duration
Superseded bool
}PendingStop is a record on the trail that the control run lacks and that ApplyPending would consider: signed, not a stop, well formed. (experimental)
type PlannedHold
type PlannedHold struct {
ID string `json:"id"`
Matter string `json:"matter"`
}PlannedHold names a legal hold that covers a planned run. (experimental)
type PlannedRedaction
type PlannedRedaction struct {
Position int `json:"position"`
Name string `json:"name"`
Kind StepKind `json:"kind,omitempty"`
Length int `json:"length,omitempty"`
LeafHash string `json:"leaf_hash"`
AlreadyRedacted bool `json:"already_redacted,omitempty"`
}PlannedRedaction is one record a redaction would replace (or already replaced). (experimental)
type Principal
type Principal struct {
OnBehalfOf string `json:"on_behalf_of,omitempty"`
AuthorityRef string `json:"authority_ref,omitempty"`
}Principal is the part of a run's Identity that is journaled: on whose behalf it acts and under what authority.
type RateLimited
type RateLimited struct {
RetryAfter time.Duration
Message string
Err error
}RateLimited is returned by a provider adapter when it is rate limited (HTTP 429 that is not an exhausted quota; see ClassifyHTTPError).
Methods
func (e *RateLimited) Error() string: Error describes the rate limit: the retry hint and the provider's message when present, then Err.func (e *RateLimited) Unwrap() error: Unwrap returns Err, so errors.Is(err, ErrModel) holds when Err wraps ErrModel.
type ReanchorOption
type ReanchorOption interface {
RecoverOption
RecoverLoopOption
}ReanchorOption is a setting for the re-signing of runs that wait on a person: it applies to Recover (RecoverOption) and RecoverLoop (RecoverLoopOption): WithReanchor and WithReanchorTimeout.
Constructors and functions
func WithReanchor(fn func(ctx context.Context, runID string) error) ReanchorOption: WithReanchor sets the function Recover and RecoverLoop call to sign the journal of a run they found waiting on a decision or a halt resolution: a run whose drive ended at an ApprovalPending or an OutcomeUnknown (several, when parallel sub-agents wait together).func WithReanchorTimeout(d time.Duration) ReanchorOption: WithReanchorTimeout bounds each re-sign (see WithReanchor): the context fn gets expires after d.
type Reanchorer
type Reanchorer interface {
Reanchor(ctx context.Context, runID string) error
}Reanchorer is the optional capability of a store that signs and publishes a run's tree head on its own writes and can do so again on demand: audit.AuditedStore.
type Reasoning
type Reasoning struct {
Text string `json:"text"`
Signature string `json:"signature,omitempty"`
Redacted string `json:"redacted,omitempty"`
}Reasoning is model thinking.
type ReasoningDelta
type ReasoningDelta struct {
Text string `json:"text"`
Signature string `json:"signature"`
Redacted string `json:"redacted"`
}ReasoningDelta is a fragment of model thinking.
type Received
type Received[T any] struct {
Key string
Payload T
}Received is one message pulled from a channel.
Constructors and functions
func Receive[T any](ctx context.Context, channel string) (Received[T], error): Receive returns the oldest not-yet-acked message on channel, in delivery order.
type Record
type Record struct {
Name string `json:"name"`
Kind StepKind `json:"kind"`
Message *Message `json:"message,omitempty"`
Usage *Usage `json:"usage,omitempty"`
DiscardedUsage *Usage `json:"discarded_usage,omitempty"`
*ModelTurn
ToolUseID string `json:"tool_use_id,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
IsError bool `json:"is_error,omitempty"`
Approved bool `json:"approved,omitempty"`
*ApproverSignature
AttemptedAt int64 `json:"attempted_at,omitempty"`
Reconciled bool `json:"reconciled,omitempty"`
OutcomeUnknown bool `json:"outcome_unknown,omitempty"`
Redacted bool `json:"-"`
Safety *Safety `json:"safety,omitempty"`
Approval *ApprovalPolicy `json:"approval,omitempty"`
Evidence json.RawMessage `json:"evidence,omitempty"`
Format string `json:"format,omitempty"`
// contains filtered or unexported fields
}Record is one durably-recorded, named event.
Constructors and functions
func ClaimAttempt(ctx context.Context, j *Journal, runID, name string, rec Record) (won bool, got Record, err error): ClaimAttempt writes the attempt marker named name as an exclusive claim and reports whether the caller won it.func DecodeRecord(b []byte) (Record, error): DecodeRecord decodes a record from its journal encoding (see EncodeRecord) into an independent copy that shares no memory with b.func DecodeStoredRecord(runID, name string, b []byte) (Record, error): DecodeStoredRecord decodes the record a store holds for the step name of run runID (see DecodeRecord) and checks that the record carries that name.func LatestPauseNote(byName map[string]Record, toolUseID string) (r Record, ok bool): LatestPauseNote returns the newest pause note on toolUseID among records keyed by name: the separation-of-duties re-ask note (ApprovalReaskStep with sod), else the format re-ask note, else the first pause note (ApprovalPendingStep).func RecordedTally(byName map[string]Record, toolUseID string) (r Record, ok bool): RecordedTally returns the record of the gate's outcome on toolUseID among records keyed by name.
Methods
func (r Record) Approver() string: Approver returns the approver of a signed decision (ApproverSignature.Approver), or "" when the record carries none.func (r Record) ApproverAlg() Alg: ApproverAlg returns the scheme a signed decision is under (ApproverSignature.ApproverAlg), or "" when the record carries none.func (r Record) ApproverCert() [][]byte: ApproverCert returns the certificate chain a certificate-bound decision carries (ApproverSignature.ApproverCert), leaf first, or nil when the record carries none.func (r Record) ClaimID() string: ClaimID returns the random id of the driver that wrote this attempt marker or not-started record (see ClaimAttempt), or "" for any other record.func (r Record) DecidedAt() string: DecidedAt returns the signed decision time of a signed decision (ApproverSignature.DecidedAt), or "" when the record carries none.func (r Record) Finish() FinishReason: Finish returns why the model turn ended (ModelTurn.Finish), or "" when the record carries no model-turn metadata.func (r Record) MarshalJSON() ([]byte, error): MarshalJSON returns the record's JSON encoding, claim and salt included, without HTML escaping (see EncodeRecord for the canonical form a store persists).func (r Record) Model() *ModelInfo: Model returns the model that answered the turn (ModelTurn.Model), or nil when the record carries no model-turn metadata.func (r Record) PromptDigest() string: PromptDigest returns the digest of the system prompt the turn was sent (ModelTurn.PromptDigest), or "" when the record carries no model-turn metadata.func (r Record) Raw() []byte: Raw returns the bytes the store holds for the record, verbatim, for a record read back from a journal (Journal.Get, Journal.History, or Journal.Records).func (r Record) RawFinish() string: RawFinish returns the provider's own finish reason (ModelTurn.RawFinish), or "" when the record carries no model-turn metadata.func (r Record) RecordedAt() string: RecordedAt returns when a signed decision was journaled (ApproverSignature.RecordedAt), or "" when the record carries none.func (r Record) Salt() []byte: Salt returns the record's salt: SaltSize random bytes the journal sets when it first records the record (see JournalEntry), replacing any salt the step returned (the engine draws the salt of its own model records itself, just as randomly, to tell its record from another writer's).func (r Record) Signature() []byte: Signature returns the signature of a signed decision (ApproverSignature.Signature), or nil when the record carries none.func (r Record) ToolsDigest() string: ToolsDigest returns the digest of the tool set the turn was sent (ModelTurn.ToolsDigest), or "" when the record carries no model-turn metadata.func (r *Record) UnmarshalJSON(b []byte) error: UnmarshalJSON decodes a record from its JSON encoding, claim and salt included.
type RecoverLoopOption
type RecoverLoopOption interface {
// contains filtered or unexported methods
}RecoverLoopOption configures RecoverLoop.
Constructors and functions
func WithRecoverConcurrency(n int) RecoverLoopOption: WithRecoverConcurrency caps how many runs RecoverLoop's full pass drives at once.func WithRecoverErrors(fn func(error)) RecoverLoopOption: WithRecoverErrors sets the function RecoverLoop hands each genuine failure to: a store error while enumerating runs or acquiring a lease, or a drive that failed.func WithRecoverInterval(d time.Duration) RecoverLoopOption: WithRecoverInterval sets how often RecoverLoop starts a recovery pass.func WithRecoverLapsedConcurrency(n int) RecoverLoopOption: WithRecoverLapsedConcurrency caps how many runs RecoverLoop's lapsed loop drives at once: the runs whose lease lapsed, taken over from a holder that died or stalled (see RecoverLoop).
type RecoverOption
type RecoverOption interface {
// contains filtered or unexported methods
}RecoverOption configures Recover.
type RecoverStopOption
type RecoverStopOption struct {
// contains filtered or unexported fields
}RecoverStopOption is the option WithRecoverStop returns; it applies to Recover and RecoverLoop.
Constructors and functions
func WithRecoverStop(sw *StopSwitch) RecoverStopOption: WithRecoverStop gives Recover and RecoverLoop the process's kill switch (see StopSwitch). (experimental)
type RedactState
type RedactState struct {
Row Entry
Found bool
Ended bool
Leased bool
ParentLive bool
Held bool
}RedactState is what a Redactor read after its conditional replacement changed nothing, to say why. (experimental)
Methods
func (s RedactState) Explain(runID, name string, current, tombstone []byte) error: Explain says what a replacement that changed nothing meant: it returns nil if the entry already holds the tombstone's redaction (nothing to do), and otherwise an error that wraps the ErrRedact sentinel that names the refusal. (experimental)
type RedactionPlan
type RedactionPlan struct {
RunID string `json:"run_id"`
Records []PlannedRedaction `json:"records"`
Kept []KeptRecord `json:"kept,omitempty"`
JournalSize int `json:"journal_size"`
Terminal bool `json:"terminal"`
Refusal string `json:"refusal,omitempty"`
Holds []PlannedHold `json:"holds,omitempty"`
Digest string `json:"digest"`
}RedactionPlan is what a redaction of one run would do: the records it replaces, the selected records it keeps, and a digest of the replacements. (experimental)
Constructors and functions
func PlanRedaction(ctx context.Context, j *Journal, runID string, sel RedactionSelector) (RedactionPlan, error): PlanRedaction reads runID's journal and returns what redacting the records sel selects would do, without writing anything. (experimental)
type RedactionResult
type RedactionResult struct {
Redacted []PlannedRedaction `json:"redacted,omitempty"`
Already []PlannedRedaction `json:"already,omitempty"`
}RedactionResult is what Redact did. (experimental)
Constructors and functions
func Redact(ctx context.Context, j *Journal, plan RedactionPlan, at time.Time) (RedactionResult, error): Redact replaces the records plan names with tombstones, in position order, each in its own transaction of the store's Redactor (so a crash leaves a prefix replaced and a second call with the same plan finishes the rest). (experimental)func RedactUsing(ctx context.Context, j *Journal, store Redactor, plan RedactionPlan, at time.Time) (RedactionResult, error): RedactUsing is Redact with the Redactor given: the journal reads the records (plan and bytes) and store replaces them. (experimental)
type RedactionSelector
type RedactionSelector struct {
Names []string
Kinds []StepKind
Prefixes []string
Payloads bool
IncludeApprovals bool
}RedactionSelector chooses the records of one run a redaction replaces. (experimental)
type Redactor
type Redactor interface {
Redact(ctx context.Context, runID, name string, current, tombstone []byte) (bool, error)
}Redactor is the optional store capability that replaces one entry's bytes with a redaction tombstone (see Record.Redacted). (experimental)
type Rejection
type Rejection struct {
Name string `json:"name"`
Reason string `json:"reason"`
}Rejection is a record in the control run that has no effect, and why. (experimental)
type Request
type Request struct {
Messages []Message
Tools []ToolSpec
Sampling Sampling
ResponseFormat *ResponseFormat
ToolChoice *ToolChoice
}Request is a single model call.
type ResolveOption
type ResolveOption interface {
// contains filtered or unexported methods
}ResolveOption configures ResolveHalt.
Constructors and functions
func WithEvidence(v any) ResolveOption: WithEvidence records the resolution as reconciled from verified evidence rather than an operator's bare assertion: it marks the injected result Reconciled and stores v (JSON-marshalled) as its Evidence, signed alongside the outcome.func WithMinHaltAge(d time.Duration) ResolveOption: WithMinHaltAge refuses to resolve a halt younger than d, measured from the live attempt marker's AttemptedAt to now (an attempt recorded as never started does not count).func WithoutLiveDriverCheck() ResolveOption: WithoutLiveDriverCheck skips ResolveHalt's check that no driver may still be running the halted operation: the lease probe on a store that leases runs, and the WithMinHaltAge requirement on one that does not.
type ResponseFormat
type ResponseFormat struct {
Name string
Schema json.RawMessage
}ResponseFormat asks the provider to constrain the model's output to a named JSON schema (OpenAI structured outputs / "json_schema" response format).
type Result
type Result struct {
Message Message
Output json.RawMessage
Usage Usage
Spend Usage
Turns int
Duration time.Duration
RunID string
}Result is what a run entry point returns (Run, Resume, RunStream.Result, RunTyped, Session.Send): the final answer and the run's telemetry.
type Resumer
type Resumer func(ctx context.Context, runID string, start RunStart) errorResumer drives one run a recovery pass found unfinished: runID, started as start (its run:start, read under the run's lease).
Constructors and functions
func ResumeAgent(a *Agent, opts ...RunOption) Resumer: ResumeAgent returns the Resumer that drives a's runs: those of kind agent that are not typed, sagas included (the run's journal says which).func ResumeAny(rs ...Resumer) Resumer: ResumeAny returns the Resumer that hands a run to each of rs in turn, in order, until one returns anything that does not wrap ErrNotResumable (nil included), and returns that.func ResumeTyped[T any](a *Agent, opts ...RunOption) Resumer: ResumeTyped returns the Resumer that drives a's typed runs whose answer type is T: the runs of kind agent whose run:start journals T's schema digest, in their journaled output mode.
type RetrievalOption
type RetrievalOption interface {
// contains filtered or unexported methods
}RetrievalOption configures one WithRetrieval: WithRetrievalRetry.
Constructors and functions
func RetrievalUntrusted(source string) RetrievalOption: RetrievalUntrusted declares that the documents the layer retrieves are untrusted content from the named source. (experimental)func WithRetrievalRetry(n int, base, max time.Duration) RetrievalOption: WithRetrievalRetry retries a failed Retrieve up to n more times within the drive's retrieval step, sleeping between attempts with exponential backoff and full jitter: a random duration up to base, then up to twice that, and so on, capped at max.
type Retriever
type Retriever interface {
Retrieve(ctx context.Context, query string, k int) ([]Doc, error)
}Retriever is the bring-your-own-RAG port: given a query, return the top-k relevant documents from YOUR store (pgvector, Pinecone, a file index, anything).
type RetrieverFunc
type RetrieverFunc func(ctx context.Context, query string, k int) ([]Doc, error)RetrieverFunc adapts a function to a Retriever.
Methods
func (f RetrieverFunc) Retrieve(ctx context.Context, query string, k int) ([]Doc, error): Retrieve calls f.
type Role
type Role stringRole identifies the author of a Message.
Constants
const RoleSystem Role = "system",const RoleUser Role = "user",const RoleAssistant Role = "assistant",const RoleTool Role = "tool": The roles of a Message: the system prompt, the user, the model, and a tool result.
type RunEvent
type RunEvent interface {
// contains filtered or unexported methods
}RunEvent is a lifecycle event emitted by Agent.Stream as the run loop advances: turn boundaries, live model token deltas, and tool start/finish.
Constructors and functions
func ProjectEvents(recs []Record) (events []RunEvent, sources []int): ProjectEvents returns the events ReplayEvents returns for a journal holding recs, and for each event the index in recs of the record it projects: each event comes from exactly one record.func ReplayEvents(ctx context.Context, store *Journal, runID string) ([]RunEvent, error): ReplayEvents returns the semantic lifecycle events implied by runID's DURABLE journal: the same AssistantTurn and ToolCompleted events Agent.Stream re-emits when it resumes from that journal, in persisted order.
type RunFilter
type RunFilter struct {
After string
Prefix string
ExcludeHolding []string
LeaseLapsed bool
}RunFilter selects the runs a Lister yields.
Methods
func (f RunFilter) Admits(runID string, holds func(name string) bool, lapsed func() bool) bool: Admits reports whether f admits runID, given holds, which reports whether the run holds an entry with a given name, and lapsed, which reports whether the run's lease has lapsed (see LeaseLapsed; it is called only when f.LeaseLapsed is set).
type RunInfo
type RunInfo struct {
RunID string
RootRunID string
ToolUseID string
Saga bool
}RunInfo describes the run some code runs in: a tool call's (RunInfoFrom), or the run a WithSystemPromptFunc function is computing the prompt for.
Constructors and functions
func RunInfoFrom(ctx context.Context) (RunInfo, bool): RunInfoFrom returns the RunInfo of the tool call whose context ctx is (or derives from), and false outside one.
Methods
func (r RunInfo) SubRunFor(name string) string: SubRunFor returns the run ID of the programmatic sub-run name, for code that starts a run of another agent itself (where SubAgent would start it for a tool call): "<scope>>step:<name>", the name encoded as SubRunID encodes a tool-use ID, where scope is the tool call's sub-run ID (SubRunID(RunID, ToolUseID)) inside a tool call, and RunID outside one.
type RunKind
type RunKind stringRunKind is what drives a run, as its run:start records it (see RunStart).
Constants
const RunKindAgent RunKind = "agent": RunKindAgent is a run an Agent drives (Run, Stream, a sub-agent, a session turn).const RunKindFlow RunKind = "flow": RunKindFlow is a run a plan flow drives (plan.Flow.Run).const RunKindSessionTurn RunKind = "session_turn": RunKindSessionTurn is a Session turn's run (Session.Send, Session.SendOnce).
type RunNotifier
type RunNotifier struct {
// contains filtered or unexported fields
}RunNotifier tells a notifier when a run driven outside an Agent ends needing a person.
Constructors and functions
func NewRunNotifier(j *Journal, o NotifierOption) (*RunNotifier, error): NewRunNotifier binds o, a WithNotifier option, to j, the journal the runs it will be told about are in.
Methods
func (r *RunNotifier) DriveEnd(runID string, err error): DriveEnd tells the notifier that a drive of runID ended with err: it queues the event err raises (a halt, a pending approval, an aborted saga), if any, and returns at once.func (r *RunNotifier) Flush(ctx context.Context) error: Flush waits for the deliveries in flight to finish their round and stops the worker, as Agent.FlushNotifications does.
type RunOption
type RunOption interface {
// contains filtered or unexported methods
}RunOption configures one run (Run, Resume, Stream, RunTyped, Session.Send).
Constructors and functions
func WithOutputMode(m OutputMode) RunOption: WithOutputMode sets how a typed run (RunTyped) collects its answer: OutputTool (the default) or OutputNative (see OutputMode).func WithSaga() RunOption: WithSaga runs the run as a saga: a step that fails after earlier writes succeeded rolls the run back, compensating the completed writes in reverse order (recursing into sub-agent trees), and the run returns *SagaAborted.func WithToolFilter(names ...string) RunOption: WithToolFilter restricts a run to the named tools of its agent: the model is offered only those, and a call naming any other tool (a model naming a tool it was not offered, or a turn replayed from the journal) is refused at dispatch, with an error result recorded that the model reads, and the tool never runs.func WithTrustedInput(reason string) RunOption: WithTrustedInput declares that the run's input is the host's own, and why. (experimental)func WithUntrustedInput(source string) RunOption: WithUntrustedInput declares that the run's input is untrusted content from the named source: an agent started by an inbound email or a customer's message. (experimental)
type RunPrincipal
type RunPrincipal struct {
Principal Principal `json:"principal"`
Ancestors []Principal `json:"ancestors,omitempty"`
}RunPrincipal is what the run:principal record holds: the principal a run acts for, and the principals of the runs above it, root first.
Constructors and functions
func RecordedPrincipal(recs []Record) (p RunPrincipal, ok bool): RecordedPrincipal returns the run:principal record among recs (see RunPrincipal), read strictly: no duplicate or case-variant name at any depth (names a later version adds are allowed), so the record names one principal to every reader, the gate, an auditor and a verifier in another language alike.
Methods
func (p RunPrincipal) Matches(start RunStart) bool: Matches reports whether p names the principal and the ancestors start does (RunStart.Principal, read as an empty principal when nil, and RunStart.Ancestors): the agreement a drive and the gate hold run:principal and run:start to.func (p RunPrincipal) Requesters() []string: Requesters is every requester p names: the OnBehalfOf of each ancestor, root first, then the run's own.
type RunRef
type RunRef struct {
RunID string
RootRunID string
}RunRef names a paused run.
Methods
func (r RunRef) Paused() RunRef: Paused returns r.
type RunSettings
type RunSettings struct {
MaxTurns *int `json:"max_turns,omitempty"`
TokenBudget *int `json:"token_budget,omitempty"`
SystemPrompt *string `json:"system_prompt,omitempty"`
Sampling *Sampling `json:"sampling,omitempty"`
ToolChoice *ToolChoice `json:"tool_choice,omitempty"`
UntrustedInput *string `json:"untrusted_input,omitempty"`
TrustedInput *string `json:"trusted_input,omitempty"`
}RunSettings are the per-run values a run's first caller chose (RunOptions), as run:start journals them.
type RunStart
type RunStart struct {
Input Message `json:"input"`
Saga bool `json:"saga,omitempty"`
Kind RunKind `json:"kind,omitempty"`
Session *SessionRef `json:"session,omitempty"`
Flow *FlowRef `json:"flow,omitempty"`
Typed *TypedStart `json:"typed,omitempty"`
Settings RunSettings `json:"settings,omitzero"`
Principal *Principal `json:"principal,omitempty"`
Ancestors []Principal `json:"ancestors,omitempty"`
Tools []string `json:"tools,omitempty"`
Ext map[string]json.RawMessage `json:"ext,omitempty"`
StartedAt string `json:"started_at,omitempty"`
}RunStart is how a run was started, as its first drive records it in run:start: the input it answers (for a Session turn, the turn's message), whether it runs as a saga, what drives it, and the per-run options its first caller chose.
Constructors and functions
func RecordedStart(ctx context.Context, d *Journal, runID string) (RunStart, bool, error): RecordedStart returns how runID was started (see RunStart), and ok=false for a run whose journal holds no such record: one never driven, or one not driven since before the record existed.
Methods
func (s RunStart) MarshalJSON() ([]byte, error): MarshalJSON writes s's journal form: the input as a JSON string when it is a user message of one text part, and as a message otherwise.func (s RunStart) Started() (time.Time, bool): Started is StartedAt as a time, and false when the record holds none or one that is not RFC 3339 (see RunStart).func (s *RunStart) UnmarshalJSON(b []byte) error: UnmarshalJSON reads s's journal form (see MarshalJSON).
type RunState
type RunState stringRunState is a run's state as Status reads it from the run's journal.
Constants
const RunNotStarted RunState = "not_started": RunNotStarted is a run with no run:start record.const RunStarted RunState = "started": RunStarted is a run with a run:start record and no end marker: running, paused, halted, or stopped at a limit.const RunCompleted RunState = "completed": RunCompleted is a run whose first end marker is run:complete.const RunAborted RunState = "aborted": RunAborted is a saga whose first end marker is run:aborted: a step failed and its rollback finished.const RunCancelled RunState = "cancelled": RunCancelled is a run whose first end marker is run:cancelled.const RunEnded RunState = "ended": RunEnded is a run whose first end marker was redacted (RunStatus.EndRedacted): it is over, but how it ended (completed, aborted or cancelled) is not attested, because a tombstone's name is outside the leaf hash, so Status never reads it from the name. (experimental)
type RunStatus
type RunStatus struct {
StartRedacted bool
EndRedacted bool
State RunState
Terminal string
Records int
EndedAt string
}RunStatus is a run's state, as Status reads it.
Constructors and functions
func Status(ctx context.Context, j *Journal, runID string) (RunStatus, error): Status reads runID's state from its journal (D8), with one Load: a prefix of the journal, so the state is the run's at one instant.
type RunStream
type RunStream struct {
// contains filtered or unexported fields
}RunStream is a live view of a running agent: range Events for progress, then call Result for the run's Result and error, as Run returns them.
Methods
func (as *RunStream) Events() iter.Seq[RunEvent]: Events returns a range-over-func iterator over lifecycle events until the run ends.func (as *RunStream) Result() (*Result, error): Result drains any un-consumed events and returns the run's Result and error, as Run returns them: the Result is non-nil whenever the run ID is valid, whatever the error (including a *ApprovalPending or an *OutcomeUnknown).
type Safety
type Safety struct {
ReadOnly bool `json:"read_only,omitempty"`
Idempotent bool `json:"idempotent,omitempty"`
Untrusted string `json:"untrusted,omitempty"`
}Safety declares how a tool call may be retried: when a run resumes after a crash and the call's outcome is unknown (it was invoked, but no result was journaled), and when a tool middleware retries or caches it.
Methods
func (s Safety) RetrySafe() bool: RetrySafe reports whether a call to the tool may run more than once for one tool call: it is ReadOnly or Idempotent.
type SafetyOption
type SafetyOption interface {
ToolOption
StepOption
}SafetyOption is a Safety that applies to a tool (ToolOption) and to a step (StepOption): WithSafety.
Constructors and functions
func WithSafety(s Safety) SafetyOption: WithSafety declares how safe a tool's calls, or a step, are to re-run.
type SagaAborted
type SagaAborted struct {
RunID string
Cause error
Compensated []string
Uncompensated []string
UnknownOutcome []string
CompensateErr error
}SagaAborted is returned by a saga run (WithSaga) when a step failed and the transaction was rolled back.
Methods
func (e *SagaAborted) Error() string: Error describes the abort: the cause, the compensated steps, and any uncompensated writes, unknown outcomes and rollback error.func (e *SagaAborted) Unwrap() error: Unwrap returns Cause, the failure that aborted the saga.
type Sampling
type Sampling struct {
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
Stop []string `json:"stop,omitempty"`
Seed *int64 `json:"seed,omitempty"`
}Sampling holds provider-neutral generation controls.
type SamplingOption
type SamplingOption func(*Sampling)SamplingOption sets one field of the Sampling config; see Temperature, TopP, MaxTokens, Stop, Seed.
Constructors and functions
func MaxTokens(v int) SamplingOption: MaxTokens caps generated tokens, overriding the model adapter's construction default.func Seed(v int64) SamplingOption: Seed sets a best-effort determinism seed (honored by providers that support it).func Stop(seqs ...string) SamplingOption: Stop sets stop sequences.func Temperature(v float64) SamplingOption: Temperature sets the sampling temperature (0 = most deterministic).func TopP(v float64) SamplingOption: TopP sets nucleus-sampling top-p.
type Session
type Session struct {
// contains filtered or unexported fields
}Session is a durable multi-turn conversation.
Methods
func (s *Session) History() []Message: History returns a copy of the conversation transcript so far (alternating user and final-assistant messages).func (s *Session) Send(ctx context.Context, input Message, opts ...RunOption) (*Result, error): Send runs one conversation turn: the agent answers input (which may carry images) with the full prior transcript in context, under opts, the turn run's options (journaled in its run:start, as Run journals them), and the turn is journaled.func (s *Session) SendOnce(ctx context.Context, key string, input Message, opts ...RunOption) (*Result, error): SendOnce runs one conversation turn for an inbound message identified by key (an event or message id), at most once per key.func (s *Session) Turns() int: Turns returns the number of completed turns.
type SessionRef
type SessionRef struct {
ID string `json:"id"`
Turn *int `json:"turn,omitempty"`
Key string `json:"key,omitempty"`
}SessionRef names the session a session turn's run belongs to (RunKindSessionTurn): the session's ID, and the turn's index for a Send turn or its key for a SendOnce turn.
type SignalPending
type SignalPending struct {
RunRef
Name string
}SignalPending is returned by Run when a tool called Await, AwaitFor or Receive and nothing has been delivered under Name yet (for Receive, Name is the channel).
Methods
func (e *SignalPending) Error() string: Error names the run and the signal or channel it awaits.
type StatusArchiver
type StatusArchiver interface {
ArchiveStatus(ctx context.Context, hash string, der []byte) error
}StatusArchiver is implemented by the verifier of a certificate-bound approver that has a status archive: ArchiveStatus stores the bytes of a CRL larger than MaxStatusInline under its hash, so what the gate relied on survives although the journal holds only its hash.
type StepKind
type StepKind stringStepKind records what a journal entry represents.
Constants
const StepModel StepKind = "model": StepModel records an assistant message from the model.const StepToolResult StepKind = "tool_result": StepToolResult records a completed tool call and its result.const StepValue StepKind = "value": StepValue records the result of a user-authored durable step (see Journal.Step).const StepSignal StepKind = "signal": StepSignal records an external event delivered into a run (see Journal.Signal and Await).const StepApproval StepKind = "approval": StepApproval records a durable human decision to approve or deny a tool call.const StepAttempt StepKind = "attempt": StepAttempt is the marker a driver claims exclusively before a non-retriable side effect.const StepSagaFail StepKind = "saga_fail": StepSagaFail records that a saga step failed, which durably triggers the saga's rollback.const StepNotStarted StepKind = "not_started": StepNotStarted records that the attempt whose marker it names never called its side effect, written by the driver that claimed it (see attempt.go).const StepHeader StepKind = "header": StepHeader is the journal header: the first record of every run's journal, named "@journal", whose Format names the journal format the run is written in (see JournalFormat).
type StepOption
type StepOption interface {
// contains filtered or unexported methods
}StepOption configures Step.
type StopApprover
type StopApprover struct {
Alg Alg `json:"alg"`
Key string `json:"key"`
}StopApprover is an enrolled approver in a StopPolicyDoc: the signature scheme and the public key. (experimental)
type StopCause
type StopCause stringStopCause says why a run was held by a stop (see Stopped). (experimental)
Constants
const StopCauseStop StopCause = "stop": StopCauseStop: an active stop covers the run, the tool or the agent. (experimental)const StopCauseUnreadable StopCause = "unreadable": StopCauseUnreadable: no stop is known, and the control run could not be read within the staleness bound, so a side-effect call is held (fail closed). (experimental)const StopCauseUnknowable StopCause = "unknowable": StopCauseUnknowable: the stops cannot be judged (StopState.UnknowableErr), so a side-effect call a stop could cover is held (fail closed). (experimental)
type StopControl
type StopControl struct {
// contains filtered or unexported fields
}StopControl reads and writes the control run: the stops, lifts, mode and policy records of a deployment. (experimental)
Constructors and functions
func NewStopControl(j *Journal, opts ...StopOption) (*StopControl, error): NewStopControl returns the control over j's store. (experimental)
Methods
func (c *StopControl) ApplyPending(ctx context.Context, req ApplyRequest) (applied, superseded int, err error): ApplyPending writes to the control run the records of the trail that it lacks and that are not stops: what a crash between "trail first" and the control-run write leaves (a lift, a policy transition, the root or a mode change that was signed and evidenced and never took effect). (experimental)func (c *StopControl) ChangeMode(ctx context.Context, req ModeRequest) (StopState, error): ChangeMode records that the deployment changed mode: evidence for history and the audit trail, which changes nothing a process does (the mode is each process's configuration, rolled out by the operator). (experimental)func (c *StopControl) LiftStop(ctx context.Context, id string, req LiftRequest) (StopEntry, error): LiftStop adds one lifter's approval of lifting stop id and returns the stop as State then reports it (Lifted when the rule is met, else LiftsHeld of LiftsNeeded). (experimental)func (c *StopControl) Mode() StopMode: Mode is the mode the control runs under: the declared one, else audited with a policy and basic without (an undeclared mode is refused as soon as the control run holds a record). (experimental)func (c *StopControl) PendingRecords(ctx context.Context) ([]PendingStop, error): PendingRecords lists the records ApplyPending would consider, with each one's signer (Record.By) and age, so an operator sees what a run would make effective before making it so. (experimental)func (c *StopControl) Reaudit(ctx context.Context) (int, error): Reaudit appends to the trail every record of the control run that it lacks and that the control accepts (a record the fold rejects is a forgery, and copying it would turn a finding into evidence), in store order, and returns how many it appended: how a stop whose trail write failed (a *StopTrailError) is completed, and a trail that fell behind is caught up. (experimental)func (c *StopControl) RotatePolicy(ctx context.Context, next StopPolicy, req LiftRequest) (StopState, error): RotatePolicy adds one lifter's approval of replacing the policy in force with next, and returns the state afterwards (PolicySeq has advanced once a quorum of the policy in force has approved the same document). (experimental)func (c *StopControl) SetStop(ctx context.Context, req StopRequest) (StopEntry, error): SetStop sets a stop and returns it as State reports it. (experimental)func (c *StopControl) State(ctx context.Context) (StopState, error): State folds the control run into the effective state. (experimental)func (c *StopControl) StopRecords(ctx context.Context) ([]StopRecord, error): StopRecords returns the control run's decodable records, in store order: what the trail is compared with. (experimental)
type StopEntry
type StopEntry struct {
ID string
Scope StopScope
Reason string
Compensation string
By, Host, At string
Signed bool
Lifted bool
AdoptedFrom string
LiftedBy []string
LiftedAt string
LiftsHeld, LiftsNeeded int
// contains filtered or unexported fields
}StopEntry is one stop as State reports it. (experimental)
Methods
func (s StopEntry) Covers(q StopQuery) bool: Covers reports whether s covers q: a global stop covers everything; a tool, flow or agent stop covers a query that names exactly its name. (experimental)
type StopMode
type StopMode stringStopMode is the mode a deployment's stops run under: StopBasic (the default) or StopAudited. (experimental)
Constants
const StopBasic StopMode = "basic": StopBasic needs no keys: anyone who can write the store sets and lifts a stop, and the records are plain and unsigned. (experimental)const StopAudited StopMode = "audited": StopAudited signs every record with an enrolled key, lifts by a quorum and records to an anchored trail (package audit). (experimental)
type StopNotifier
type StopNotifier struct {
// contains filtered or unexported fields
}StopNotifier tells a notifier when a stop is set or lifted, from a StopSwitch's observations of the control run. (experimental)
Constructors and functions
func NewStopNotifier(j *Journal, o NotifierOption, ctl *StopControl) (*StopNotifier, error): NewStopNotifier binds o, a WithNotifier option, to j and ctl. (experimental)
Methods
func (n *StopNotifier) Flush(ctx context.Context) error: Flush waits for the deliveries in flight to finish their round and stops the worker, as Agent.FlushNotifications does. (experimental)func (n *StopNotifier) Observe(st StopState): Observe queues the events st owes. (experimental)
type StopOption
type StopOption interface {
// contains filtered or unexported methods
}StopOption configures NewStopControl. (experimental)
Constructors and functions
func WithStopClock(now func() time.Time) StopOption: WithStopClock sets the clock that stamps a record's At (default time.Now). (experimental)func WithStopInForce(fn func(StopEntry)) StopOption: WithStopInForce gives the control a function that is told, with the stop, the moment a stop has been written to the control run and is therefore in force, before its audit trail write starts (which can take a while under contention, and fail): a command can say "in force" at once. (experimental)func WithStopMode(m StopMode) StopOption: WithStopMode declares the mode of this process: StopBasic, or StopAudited (which needs WithStopPolicy). (experimental)func WithStopPolicy(p StopPolicy) StopOption: WithStopPolicy gives the control the audited-mode policy: the trust root, the policy this process pins (normally the one the deployment started audited mode with). (experimental)func WithStopRoot(digest string) StopOption: WithStopRoot names the digest (StopPolicy.Digest) of the deployment's root policy, the only policy that may start the chain a process walks. (experimental)func WithStopTrail(t StopTrail) StopOption: WithStopTrail gives an audited control the trail its records are also written to. (experimental)func WithStopVerifier(nv StopVerifierFunc) StopOption: WithStopVerifier gives the control the means to build the verifiers of a policy a transition carries (audit.NewVerifier). (experimental)
type StopPolicy
type StopPolicy struct {
DeploymentID string
Setters []string
Lifters []string
Verifiers ApproverVerifierFor
LiftQuorum int
LiftNeedsOther bool
}StopPolicy is who may set and lift stops in audited mode: the enrolled setters and lifters (by approver id), how to verify an id's signatures, and the lift rule. (experimental)
Constructors and functions
func PolicyFromDoc(d StopPolicyDoc, nv StopVerifierFunc) (StopPolicy, error): PolicyFromDoc builds the policy a transition names, with verifiers made by nv, and validates it. (experimental)
Methods
func (p StopPolicy) Digest() string: Digest returns the digest of the policy's document; "" for a policy that does not validate. (experimental)func (p StopPolicy) Doc() (StopPolicyDoc, error): Doc returns the policy as a transition carries it; it fails as Validate does. (experimental)func (p StopPolicy) Validate() error: Validate reports whether the policy is well formed and can be satisfied: a verifier for every enrolled id that exposes its public key, one seat per signing key (two ids never share a key identity), at least LiftQuorum lifters, and, with LiftNeedsOther, a lifter other than the setter of any stop. (experimental)
type StopPolicyDoc
type StopPolicyDoc struct {
DeploymentID string `json:"deployment_id"`
Approvers map[string]StopApprover `json:"approvers"`
Setters []string `json:"setters"`
Lifters []string `json:"lifters"`
LiftQuorum int `json:"lift_quorum"`
LiftNeedsOther bool `json:"lift_needs_other"`
}StopPolicyDoc is a stop policy as the control run carries it in a policy transition: the enrolled approvers with their public keys, the roles, and the lift rule. (experimental)
type StopQuery
type StopQuery struct {
Tool, Flow, Agent string
Compensation bool
}StopQuery is what a check point asks: which stop, if any, covers this. (experimental)
type StopRecord
type StopRecord struct {
Format string `json:"format"`
Kind string `json:"kind"`
Mode StopMode `json:"mode"`
Deployment string `json:"deployment,omitempty"`
AdoptedFrom string `json:"adopted_from,omitempty"`
StopID string `json:"stop_id,omitempty"`
SetDigest string `json:"set_digest,omitempty"`
Scope *StopScope `json:"scope,omitempty"`
Compensation string `json:"compensation,omitempty"`
Gen int `json:"gen,omitempty"`
To StopMode `json:"to,omitempty"`
Seq int `json:"seq,omitempty"`
Policy *StopPolicyDoc `json:"policy,omitempty"`
PrevDigest string `json:"prev_digest,omitempty"`
Applied []string `json:"applied,omitempty"`
Reason string `json:"reason,omitempty"`
At string `json:"at"`
By string `json:"by"`
Host string `json:"host,omitempty"`
PolicyDigest string `json:"policy_digest,omitempty"`
Alg Alg `json:"alg,omitempty"`
Signature string `json:"signature,omitempty"`
}StopRecord is one record of the control run. (experimental)
Constructors and functions
func DiffStopRecords(store, trail []StopRecord) (storeOnly, trailOnly []StopRecord): DiffStopRecords returns the records of store that are not in trail, and those of trail that are not in store, by content. (experimental)
Methods
func (r StopRecord) Signed() bool: Signed reports whether r carries a signature. (experimental)func (r StopRecord) Validate() error: Validate reports whether r is a well-formed record of its kind (not whether it is authorised): its format, mode, time, operator, reason, signature presence, and the fields its kind needs. (experimental)
type StopRequest
type StopRequest struct {
Scope StopScope
Reason string
Compensation string
By, Host string
Signer StopSigner
AdoptedFrom string
}StopRequest is what SetStop takes. (experimental)
type StopScope
type StopScope struct {
Kind StopScopeKind `json:"kind"`
Name string `json:"name,omitempty"`
}StopScope is what a stop covers: a kind and, except for StopGlobal, an exact name. (experimental)
Methods
func (s StopScope) String() string: String is the scope as a person reads it: "global", "tool refund". (experimental)func (s StopScope) Validate() error: Validate reports whether s names a scope: a known kind, no name for StopGlobal, and for every other kind a name of valid UTF-8, with no control or bidirectional character, at most 256 bytes. (experimental)
type StopScopeKind
type StopScopeKind stringStopScopeKind says what a stop covers. (experimental)
Constants
const StopGlobal StopScopeKind = "global": StopGlobal covers every run. (experimental)const StopTool StopScopeKind = "tool": StopTool covers the calls of the tool with exactly the scope's name. (experimental)const StopFlow StopScopeKind = "flow": StopFlow covers the runs and nodes of the plan flow with exactly the scope's name. (experimental)const StopAgent StopScopeKind = "agent": StopAgent covers the runs of the agent whose Identity.Actor is exactly the scope's name. (experimental)
type StopSigner
type StopSigner interface {
Alg() Alg
Sign(message []byte) ([]byte, error)
}StopSigner signs a stop record in audited mode. (experimental)
type StopState
type StopState struct {
Mode StopMode
PolicyDigest string
PolicySeq int
ChainErr string
UnverifiedActive int
Stops []StopEntry
Rejected []Rejection
RejectedTotal int
Unverified int
// contains filtered or unexported fields
}StopState is the effective state of the control run for one control. (experimental)
Constructors and functions
func VerifyStopRecords(recs []StopRecord, opts ...StopOption) (StopState, error): VerifyStopRecords folds records (a control run's, or a stop trail's) under the policy the options give, with no store: what bide audit stops does to a trail. (experimental)
Methods
func (s StopState) Active() []StopEntry: Active returns the stops that are not lifted, in the order they were set. (experimental)func (s StopState) Covering(q StopQuery) (StopEntry, bool): Covering returns the first active stop that covers q. (experimental)func (s StopState) Rejects(r StopRecord) bool: Rejects reports whether the fold rejected r (a record it did not accept: not signed by an enrolled approver of the policy in force, for another deployment, malformed, and so on). (experimental)func (s StopState) UnknowableErr() error: UnknowableErr returns ErrStopsUnknowable when the control cannot judge which stops are in force (see the error). (experimental)
type StopSwitch
type StopSwitch struct {
// contains filtered or unexported fields
}StopSwitch is what an Agent consults (WithStopSwitch): a StopControl and the records it has read. (experimental)
Constructors and functions
func NewStopSwitch(ctl *StopControl, opts ...StopSwitchOption) (*StopSwitch, error): NewStopSwitch returns a switch over ctl. (experimental)
Methods
func (s *StopSwitch) GlobalStop(ctx context.Context) (StopEntry, bool): GlobalStop returns the active global stop, if there is one, from a cached read (a read when it is older than the poll interval): what a recovery pass asks, so that it lists nothing while everything is stopped. (experimental)func (s *StopSwitch) Hold(ctx context.Context, ref RunRef, q StopQuery, sideEffect, sync bool) *Stopped: Hold decides whether q is held, for run ref. (experimental)
type StopSwitchOption
type StopSwitchOption interface {
// contains filtered or unexported methods
}StopSwitchOption configures NewStopSwitch. (experimental)
Constructors and functions
func WithStopErrors(fn func(error)) StopSwitchOption: WithStopErrors sets the function a StopSwitch hands a failed read of the control run, and the alerts of a control that cannot judge the stops (StopState.ChainErr, Unverified in a basic control). (experimental)func WithStopObserver(fn func(StopState)) StopSwitchOption: WithStopObserver gives a StopSwitch a function that is told, with the control run's state, each time a stop has appeared or been lifted since it last was (the first successful read included). (experimental)func WithStopPoll(d time.Duration) StopSwitchOption: WithStopPoll sets how often a StopSwitch reads the control run for the checks that use its cache (a drive's start, a turn's start, a call before its claim): the latency bound of a stop for them. (experimental)func WithStopStaleness(d time.Duration) StopSwitchOption: WithStopStaleness sets how old the last successful read may be for a side-effect call to run when the control run cannot be read now: past it the call is held (StopCauseUnreadable). (experimental)
type StopTrail
type StopTrail interface {
Load(ctx context.Context, trail string) ([]StopRecord, error)
Append(ctx context.Context, trail string, seq int, rec StopRecord) error
}StopTrail is the port of the stop trail: a named, append-only sequence of StopRecords with insert-if-absent at a position, as NotifyTrail is for notifications. (experimental)
type StopTrailError
type StopTrailError struct {
Record string
StoreWritten bool
Err error
}StopTrailError is returned when a record could not be written to the stop trail. (experimental)
Methods
func (e *StopTrailError) Error() string: Error implements error. (experimental)func (e *StopTrailError) Unwrap() error: Unwrap returns the trail's error. (experimental)
type StopVerifierFunc
type StopVerifierFunc func(alg Alg, publicKey []byte) (ApproverVerifier, error)StopVerifierFunc builds a verifier from a scheme and a public key, for the approvers of a policy a transition names (audit.NewVerifier has this form). (experimental)
type Stopped
type Stopped struct {
RunRef
Cause StopCause
StopID string
Scope StopScope
Reason string
By string
Since string
Detail string
}Stopped is returned by a run that a kill switch held (see StopSwitch): a pause, not a failure. (experimental)
Methods
func (e *Stopped) Error() string: Error implements error. (experimental)
type Store
type Store interface {
Insert(ctx context.Context, runID, name string, data []byte) (Entry, bool, error)
Get(ctx context.Context, runID, name string) (Entry, bool, error)
Load(ctx context.Context, runID string, after int64) iter.Seq2[Entry, error]
}Store is the storage port: an append-only set of named entries per run.
type Stream
type Stream struct {
// contains filtered or unexported fields
}Stream is a live model response.
Constructors and functions
func NewStream(ch <-chan Emit) *Stream: NewStream wraps an event channel the caller fills and closes.func NewStreamFunc(ctx context.Context, produce func(send func(Emit) bool)) *Stream: NewStreamFunc runs produce in its own goroutine and returns the Stream it feeds.
Methods
func (s *Stream) Close(): Close tells the producer the consumer will read no further events, so it can stop and release its resources.func (s *Stream) Events() iter.Seq2[Event, error]: Events returns a range-over-func iterator (Go 1.23+) over streamed events.func (s *Stream) Message() (Message, Usage, error): Message drains the stream and returns the assembled assistant Message + usage.
type TaintPolicy
type TaintPolicy struct {
Gate *ApprovalPolicy
Refuse bool
RequireProvenance bool
SeparateApprovers bool
}TaintPolicy is what an agent that enforces taint carries (WithTaintPolicy). (experimental)
type Task
type Task[T any] struct {
Name string
Fn func(context.Context) (T, error)
Safety Safety
}Task is one unit of durable parallel work: a named step returning a T.
type Text
type Text struct {
Text string `json:"text"`
}Text is plain assistant/user text.
type TextDelta
type TextDelta struct {
Text string `json:"text"`
}TextDelta is a fragment of the model's text answer.
type TimerPending
type TimerPending struct {
RunRef
Name string
FireAt time.Time
}TimerPending is returned by Run when a tool called Sleep or WaitUntil and the wake time has not yet passed.
Methods
func (e *TimerPending) Error() string: Error names the run, the timer, and its wake time.
type Tool
type Tool interface {
Spec() ToolSpec
Call(ctx context.Context, args json.RawMessage) (json.RawMessage, error)
}Tool is an action the agent can take.
Constructors and functions
func CompensatedFunc[In, Out any]( name, description string, do func(context.Context, In) (Out, error), undo func(context.Context, In, Out) error, opts ...ToolOption, ) (Tool, error): CompensatedFunc is a typed tool that declares both its forward action and its compensator.func Func[In, Out any](name, description string, fn func(context.Context, In) (Out, error), opts ...ToolOption) (Tool, error): Func wraps a typed Go function into a Tool.func MustCompensatedFunc[In, Out any]( name, description string, do func(context.Context, In) (Out, error), undo func(context.Context, In, Out) error, opts ...ToolOption, ) Tool: MustCompensatedFunc is CompensatedFunc for a tool built at init: it panics with CompensatedFunc's error.func MustFunc[In, Out any](name, description string, fn func(context.Context, In) (Out, error), opts ...ToolOption) Tool: MustFunc is Func for a tool built at init: it panics with Func's error.func MustRetrievalTool(name, description string, r Retriever, k int, opts ...ToolOption) Tool: MustRetrievalTool is RetrievalTool for a tool built at init: it panics with RetrievalTool's error.func MustSubAgent(name, description string, sub *Agent, opts ...ToolOption) Tool: MustSubAgent is SubAgent for a tool built at init: it panics with SubAgent's error.func RetrievalTool(name, description string, r Retriever, k int, opts ...ToolOption) (Tool, error): RetrievalTool exposes a Retriever as a tool the model can call to search on demand (agentic RAG): the model decides when to retrieve and with what query.func SubAgent(name, description string, sub *Agent, opts ...ToolOption) (Tool, error): SubAgent wraps an agent as a Tool so a parent can delegate to it, the multi-agent primitive, as a durable tree rather than a fragile handoff.
type ToolCall
type ToolCall struct {
Use ToolUse
Spec ToolSpec
RunID string
// contains filtered or unexported fields
}ToolCall is one tool call as tool middleware sees it: the ToolUse the model sent (ID, Name, Args), the Spec of the tool it names, and the run it belongs to.
Methods
func (c ToolCall) ErrorText(err error) string: ErrorText returns the text the agent journals, and sends to the model, for this call failing with err: the text chosen by the agent's WithToolErrorRedactor, if it has one, and otherwise err's own text, in either case with every URL in it redacted.
type ToolCallDelta
type ToolCallDelta struct {
Index int `json:"index"`
ID string `json:"id"`
Name string `json:"name"`
ArgsFragment json.RawMessage `json:"args_fragment"`
Signature string `json:"signature"`
}ToolCallDelta is an incremental fragment of a tool call, keyed by Index.
type ToolChoice
type ToolChoice struct {
Mode string `json:"mode,omitempty"`
Name string `json:"name,omitempty"`
}ToolChoice controls whether and how the model may call tools on a request.
type ToolCompleted
type ToolCompleted struct {
ToolUseID string `json:"tool_use_id"`
Name string `json:"name"`
Result json.RawMessage `json:"result"`
IsError bool `json:"is_error"`
}ToolCompleted carries a tool call's result.
type ToolHandler
type ToolHandler func(ctx context.Context, call ToolCall) (json.RawMessage, error)ToolHandler executes one tool call and returns the raw JSON result or an error.
type ToolMiddleware
type ToolMiddleware func(ToolHandler) ToolHandlerToolMiddleware wraps a ToolHandler, the same func(Handler) Handler idiom as model Middleware, but around TOOL execution.
type ToolOption
type ToolOption interface {
// contains filtered or unexported methods
}ToolOption configures a tool built by Func, CompensatedFunc or SubAgent.
Constructors and functions
func RaisesSafety(reason string) ToolOption: RaisesSafety lets a wrapper declare a Safety that is safer than a tool it wraps (Unwrap) or embeds, and says why (the reason is required, follows the rules of Trusted, and is kept in the declarations and their digest). (experimental)func TaintExempt(reason string) ToolOption: TaintExempt declares that the tool's calls need no escalation gate even in a run that read untrusted content, and why (the reason is required, and is kept for the audit). (experimental)func Trusted(reason string) ToolOption: Trusted declares that the results of the tool are the host's own, and why (the reason is required and is kept in the declarations): the tool reads a table the host writes, calls a service it runs. (experimental)func Untrusted(source string) ToolOption: Untrusted declares that the results of the tool are untrusted content, from the named source (for example "crm-notes" or "inbound-email"): text the host did not write and an attacker may have. (experimental)func WithApproval(p *ApprovalPolicy) ToolOption: WithApproval gates every call to the tool on human approval before it runs: p is SingleApproval() for one decision (Approve), or an m-of-n policy (SubmitDecision, and the agent's WithApproverVerifiers).func WithCaps(lines ...string) ToolOption: WithCaps declares amount-cap rules on a tool: one line per rule, in the grammar of the design note (docs/guides/amount-caps.md): (experimental)func WithOutputSchema(schema json.RawMessage) ToolOption: WithOutputSchema declares the JSON Schema of the tool's result (ToolSpec.Output).func WithSubRuns(agentFor func(name string) *Agent) ToolOption: WithSubRuns declares the agents that run the tool's programmatic sub-runs: agentFor(name) is the agent the tool runs RunInfo.SubRunFor(name) with.func WithTimeout(d time.Duration) ToolOption: WithTimeout bounds each call to the tool by d: the call runs under a context with that deadline, on top of the run's.func WithTitle(title string) ToolOption: WithTitle sets the tool's human-readable display name (ToolSpec.Title).
type ToolResult
type ToolResult struct {
ToolUseID string `json:"tool_use_id"`
Result json.RawMessage `json:"result,omitempty"`
IsError bool `json:"is_error,omitempty"`
}ToolResult carries a tool's output back to the model (tool turn).
type ToolRules
type ToolRules interface {
ToolNameRule() *regexp.Regexp
RequiresToolsForRequired() bool
}ToolRules is an optional interface a Model implements to declare the tool setups its provider refuses, so New and With refuse them when the agent is built instead of every run failing.
type ToolSpec
type ToolSpec struct {
Name string
Title string
Description string
Input json.RawMessage
Output json.RawMessage
Safety Safety
Approval *ApprovalPolicy
Caps []string
Untrusted string
TaintExempt string
Trusted string
RaisesSafety string
Timeout time.Duration
}ToolSpec is everything the agent knows about a tool: what the model is shown (Name, Description, Input), how a call may be retried (Safety), whether it waits for a human first (Approval), and how long a call may take (Timeout).
type ToolStarted
type ToolStarted struct {
ToolUseID string `json:"tool_use_id"`
Name string `json:"name"`
Args json.RawMessage `json:"args"`
}ToolStarted fires when a tool call begins executing: after any approval gate and, for non-idempotent tools, after the durable attempt marker is written, immediately before the tool is called.
type ToolUse
type ToolUse struct {
ID string `json:"id"`
Name string `json:"name"`
Args json.RawMessage `json:"args,omitempty"`
Signature string `json:"signature,omitempty"`
}ToolUse is the model's request to call a tool (assistant turn).
Constructors and functions
func FindToolCall(recs []Record, toolUseID string) (idx int, call ToolUse, ok bool): FindToolCall returns the journal index of the record that requested toolUseID, and the call itself (its name and arguments), or ok=false if no record requested it.
type TurnRestarted
type TurnRestarted struct {
Seq int `json:"seq"`
}TurnRestarted fires when the model call for turn Seq starts over after an attempt that had already streamed ModelEvent deltas: a middleware such as Retry called the model again after that attempt failed, or delivered a different response in its place.
type TurnStarted
type TurnStarted struct {
Seq int `json:"seq"`
}TurnStarted marks the beginning of a fresh model turn (Seq is the model-call sequence number within the run).
type TypedStart
type TypedStart struct {
Mode OutputMode `json:"mode"`
SchemaDigest string `json:"schema_digest"`
Schema json.RawMessage `json:"schema"`
}TypedStart is how a typed run (RunTyped) was started: its output mode and the JSON schema of its answer type, in full and as a digest.
type Usage
type Usage struct {
InputTokens int `json:"input_tokens,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
CacheReadTokens int `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
}Usage is token accounting for a call; middleware turns it into cost.
Methods
func (u Usage) TotalInputTokens() int: TotalInputTokens is every input token the call processed, cached or not.func (u Usage) TotalTokens() int: TotalTokens is every token the call processed: all input plus output.func (u Usage) Validate() error: Validate reports an error wrapping ErrNegativeUsage when any count in u is negative.
type Wake
type Wake struct {
RunID string
RootRunID string
Name string
FireAt time.Time
}Wake is one scheduled wake: re-invoke RootRunID at or after FireAt.
type Waker
type Waker interface {
Schedule(ctx context.Context, w Wake) error
}Waker is the pluggable trigger that re-invokes a sleeping run when its durable timer is due.
type Watched
type Watched struct {
Key string `json:"key"`
RunID string `json:"run_id"`
At time.Time `json:"at"`
}Watched is an event on the open trail whose all-clear may still be owed.
Constructors and functions
func FoldWatch(recs []NotifyRecord) []Watched: FoldWatch is the events FoldOpen lists.