Documentation
¶
Overview ¶
Package store holds the domain types and persistence interface.
Index ¶
- Constants
- Variables
- func ApprovalResult(decision string, r ApprovalResponse) string
- func ApprovedToolsAfter(paused []string, a *Approval) []string
- func ArtifactPaths(metadata map[string]any) []string
- func CleanJSON(b []byte) []byte
- func CleanText(s string) string
- func CleanValue(v any) any
- func ErrorCodeFor(status, code string) string
- func IsDataError(err error) bool
- func IsTerminal(status string) bool
- func RegisterDataError(f func(error) bool)
- func RoleAtLeast(have, want string) bool
- func ToolKind(toolName string) string
- func ValidRole(r string) bool
- func Vouched(r *Run, alive []func(*Run) bool) bool
- type ActiveRun
- type Approval
- type ApprovalResponse
- type ApprovalStore
- type Artifact
- type ArtifactStore
- type ArtifactVersion
- type Attachment
- type AuditEntry
- type BlobStore
- type Compaction
- type Connector
- type EntryEmbedding
- type Event
- type Feedback
- type Full
- type Goal
- type GoalEvidence
- type GoalUpdate
- type GoalVerdict
- type HarnessStore
- type HistoryStore
- type Invite
- type LastRun
- type Member
- type MemoryEmbeddingStore
- type MemoryEntry
- type MemoryLimits
- type MemoryProposal
- type MemoryStore
- type Message
- type NewRun
- type NotificationStore
- type PendingQuestion
- type PlanItem
- type Project
- type ProjectPatch
- type ProjectRole
- type PutArtifact
- type QuestionOption
- type Resume
- type Run
- type SkillStore
- type Store
- type TeamStore
- type Thread
- type ThreadCursor
- type ThreadMeta
- type ThreadPatch
- type ThreadSummary
- type ToolCall
- type ToolCallFunction
- type User
- type WorkspaceGitArchive
- type WorkspaceGitIssue
- type WorkspaceGitStore
Constants ¶
const ( // ApprovalScopeOnce approves the paused call only (default). ApprovalScopeOnce = "once" // ApprovalScopeRun approves the tool kind for the rest of the run chain // (the run and its resume runs): "Allow for this task". ApprovalScopeRun = "run" // ApprovalExpired is the status of a pending approval older than APPROVAL_TTL_HOURS. ApprovalExpired = "expired" // ApprovalExpiredResult is the tool result of an expired approval. ApprovalExpiredResult = "The approval expired." )
Approval scopes and expiry.
const ( InteractionAutomatic = "automatic" InteractionInteractive = "interactive" )
Interaction modes of a run: interactive runs pause before risky tools until the user approves them (Work's "interactive" mode); automatic runs never pause.
const ( ApprovalKindRiskyTool = "risky_tool" ApprovalPending = "pending" ApprovalResolved = "resolved" ApprovalCancelled = "cancelled" DecisionApprove = "approve" DecisionDeny = "deny" DecisionRespond = "respond" // ReasonToolApproval is the AG-UI interrupt reason of a paused risky tool call. ReasonToolApproval = "tool_approval" )
Approval kinds, statuses and decisions (Work's approval record).
const ( ApprovalDeniedResult = "The user denied the pending action. Do not retry it. Choose a safe alternative and continue." // ApprovalCancelledResult is the result of an approval cancelled with the run (stop button). ApprovalCancelledResult = "The tool call was cancelled by the user." // ImplicitApprovalCancelResult is stored when the user sends a new message instead of deciding. ImplicitApprovalCancelResult = "The user did not approve the pending action and sent a new message instead. The action was not run." )
Tool results given to the model for a resolved approval (Work's build_resume_packet instructions) and for cancelled ones.
const ( ArtifactOutput = "output" ArtifactUpload = "upload" )
Artifact kinds.
const ( ChangeCreated = "created" ChangeUpdated = "updated" ChangeDeleted = "deleted" )
Artifact changes reported by PutArtifactVersion / MarkArtifactDeleted.
const ( KindChat = "chat" KindGoal = "goal" KindCompact = "compact" )
Run kinds.
const ( TitleAuto = "auto" TitleUser = "user" TitleGenerated = "generated" )
Thread title sources: auto (derived from the first message), user (set by the user, never overwritten), generated (LLM title after the first completed run).
const ( GoalActive = "active" GoalMet = "met" GoalExhausted = "exhausted" GoalCleared = "cleared" )
Goal statuses.
const ( PlanPending = "pending" PlanInProgress = "in_progress" PlanCompleted = "completed" )
Plan item statuses.
const ( MemoryActive = "active" MemoryPending = "pending" MemoryDeleted = "deleted" )
Memory entry statuses: pending entries were written by the model after it saw untrusted content and are not used until the user confirms them; deleted entries were soft-deleted (purged after the retention by the consolidation job).
const ( MemorySourceProxy = "proxy" MemorySourceUser = "user" )
Memory entry sources: written by the agent's memory tools, by the user in Settings > Memory.
const ( StatusQueued = "queued" StatusRunning = "running" StatusCompleted = "completed" StatusFailed = "failed" StatusCancelled = "cancelled" StatusInterrupted = "interrupted" )
Run statuses.
const ( RoleUser = "user" RoleAssistant = "assistant" RoleTool = "tool" RoleReasoning = "reasoning" )
Message roles.
const ( AuthorUser = "user" AuthorSupervisor = "supervisor" AuthorSystem = "system" )
Author kinds of a message (Message.AuthorKind).
const ( // ModeBuild: the run has all the tools its profile allows. ModeBuild = "build" // ModePlan: read-only; the engine offers no tool that changes anything. ModePlan = "plan" )
Modes of a run (Run.Mode).
const ( // SandboxAuto: sandbox tools are offered when a backend is configured; the // sandbox is created on the first command. SandboxAuto = "auto" // SandboxOff: the run has no sandbox tools and never creates a sandbox. SandboxOff = "off" // SandboxOn: like auto, but the run is refused without a backend. SandboxOn = "on" )
Sandbox modes of a run (Run.Sandbox).
const ( // RoleOwner manages members, settings and the repository link. RoleOwner = "owner" // RoleMember reads and works: creates threads, sends, steers, approves. RoleMember = "member" // RoleViewer only reads. RoleViewer = "viewer" )
Project roles (Member.Role), from the most to the least powerful.
const ( ThreadChat = "chat" ThreadSupervisor = "supervisor" )
Thread kinds (ThreadMeta.Kind).
const ( ConnectorGitHub = "github" ConnectorTelegram = "telegram" )
Connector kinds.
const ( // GitIssueTooLarge: the history exceeded the archive cap and was not archived. GitIssueTooLarge = "too_large" // GitIssueFailed: archiving failed (timeout, blob store error…). GitIssueFailed = "failed" )
Reasons of a WorkspaceGitIssue.
const ExtraAttachments = "work.attachments"
ExtraAttachments is the eino schema.Message Extra key holding the []Attachment of a user message in the model history (agent → image attacher).
const ImplicitCancelResult = "The user did not answer the question and sent a new message instead."
ImplicitCancelResult is the ask_user result stored when the user sends a new message instead of answering.
Variables ¶
var ( // ErrApprovalPending means the run kind cannot start while an approval waits for a decision. ErrApprovalPending = errors.New("an approval is pending") // ErrApprovalNotPending means the approval is resolved, cancelled, or its run is not awaiting it. ErrApprovalNotPending = errors.New("approval is not pending") )
var ( // ErrInvalidReplace means replaceFromMessageId is not a visible user message of the thread. ErrInvalidReplace = errors.New("invalid replace target") // ErrNoPendingQuestion means a resume does not match the thread's open question. ErrNoPendingQuestion = errors.New("no pending question") // ErrQuestionPending means the run kind cannot start while a question waits for an answer. ErrQuestionPending = errors.New("a question is pending") // ErrGoalInactive means a goal run was requested for a goal that is no longer active or out of turns. ErrGoalInactive = errors.New("goal is not active") )
var ( // ErrMemoryLimit means the user already has the maximum number of entries of that status. ErrMemoryLimit = errors.New("memory limit reached") // ErrMemoryPathExists means another non-deleted entry of the user has this path. ErrMemoryPathExists = errors.New("memory path exists") // ErrMemoryConflict means the entry changed since it was read (its version differs). ErrMemoryConflict = errors.New("memory entry changed") )
var ( // ErrNotFound means the row does not exist, is deleted or belongs to someone else. ErrNotFound = errors.New("not found") // ErrRunActive means the thread already has a queued/running run. ErrRunActive = errors.New("thread already has an active run") // ErrNotClaimable means the run is no longer queued. ErrNotClaimable = errors.New("run is not claimable") // ErrConflict means a unique constraint (e.g. message id) was violated. ErrConflict = errors.New("conflict") // ErrNotOwned means the run is no longer running on this runtime (the // sweeper interrupted it, or it was already finished). ErrNotOwned = errors.New("run is not running on this runtime") )
var ( // ErrForbidden means the user is known but may not do this. ErrForbidden = errors.New("forbidden") // ErrLastOwner means the change would leave a project without owner. ErrLastOwner = errors.New("a project needs at least one owner") )
var ErrInvalidData = errors.New("invalid data")
ErrInvalidData marks errors that will never succeed on retry (bad data, constraint).
var ErrLockTimeout = errors.New("lock wait timed out")
ErrLockTimeout means an advisory lock could not be taken in time.
Functions ¶
func ApprovalResult ¶
func ApprovalResult(decision string, r ApprovalResponse) string
ApprovalResult is the tool result of a deny or respond decision (Work's build_resume_packet instruction); "" for approve (the tool runs).
func ApprovedToolsAfter ¶
ApprovedToolsAfter is the approved tool kinds of a resume run: those of the paused run plus the decided approval's kind when approved for the run.
func ArtifactPaths ¶
ArtifactPaths lists the paths of a message's metadata.artifacts (tool results and end-of-run changes), deleted ones suffixed with " (deleted)".
func CleanValue ¶
CleanValue sanitizes every string in a JSON-like value (maps, slices, strings).
func ErrorCodeFor ¶
ErrorCodeFor is the error code stored for a terminal status (empty for successes).
func IsDataError ¶
IsDataError reports a permanent error: ErrInvalidData or one a registered backend classifies as such (Postgres: SQLSTATE class 22 data exception or 23 integrity constraint). Anything else (connection, timeout, server shutdown) is transient.
func IsTerminal ¶
IsTerminal reports whether a run status is final.
func RegisterDataError ¶
RegisterDataError adds a backend test for permanent errors (called from init).
func RoleAtLeast ¶
RoleAtLeast reports whether have is at least as powerful as want.
Types ¶
type Approval ¶
type Approval struct {
ID string
Kind string
ThreadID string
RunID string
ToolCallID string
ToolName string
ToolInputPreview string
Status string
// Decision is approve, deny or respond once resolved ("" otherwise).
Decision string
Response ApprovalResponse
// ResumeRunID is the run created by the decision (or the cancelling message).
ResumeRunID string
// Scope of the decision: once or run (harness v3 §7; "" before a decision is once).
Scope string
CreatedAt time.Time
ResolvedAt *time.Time
}
Approval is a risky tool call of an interactive run waiting for (or having received) the user's decision. One approval at most is pending per thread.
func (*Approval) Payload ¶
Payload is the approval in Work's record shape (camelCase), as sent in work.approval events, interrupts and thread.pendingApproval.
func (*Approval) SameDecision ¶
func (a *Approval) SameDecision(decision string, r ApprovalResponse) bool
SameDecision reports whether a repeated resolve asks for what was already decided.
type ApprovalResponse ¶
ApprovalResponse is the user's answer of a respond decision.
type ApprovalStore ¶
type ApprovalStore interface {
// CreateApproval records a pending approval (ID, CreatedAt are set when empty).
CreateApproval(ctx context.Context, a *Approval) error
// GetApproval returns an approval by id (no ownership check; ErrNotFound).
GetApproval(ctx context.Context, id string) (*Approval, error)
// ResumedApproval returns the approval a run was created to decide or that
// its message cancelled, or the latest one cancelled with its waiting run
// (stop) before this run, which the run announces (nil when none).
ResumedApproval(ctx context.Context, runID string) (*Approval, error)
// CancelRunApprovals cancels the pending approvals of a run that did not
// complete (no tool result is stored: the history marks the call interrupted).
CancelRunApprovals(ctx context.Context, runID string) error
// CancelPendingApproval cancels the pending approval of a completed run and
// stores result as its tool result (ErrApprovalNotPending when none).
CancelPendingApproval(ctx context.Context, runID, result string) (*Approval, error)
// ExpireApprovals expires the pending approvals created more than ttl ago
// (of threadID only when it is not empty): status expired, tool result
// ApprovalExpiredResult for those whose run waits for them. It returns how many.
ExpireApprovals(ctx context.Context, ttl time.Duration, threadID string) (int, error)
// LatestExpiredApproval returns the thread's latest approval when it is
// expired and belongs to the thread's latest run (nothing happened since);
// nil when there is none (review round 1: Thread.pendingApproval on reload).
LatestExpiredApproval(ctx context.Context, threadID string) (*Approval, error)
// ReopenApproval makes a resolved approval pending again when its resume
// run finished (completed, failed, cancelled or interrupted) without a tool
// result for the approved call, is still the thread's latest run and no run
// is active: the decision never took effect, so the user may decide again.
// ErrApprovalNotPending when that is not the case.
ReopenApproval(ctx context.Context, id string) (*Approval, error)
// SetThreadInteractionMode switches login's thread and its active (queued or
// running) run to mode in one transaction: the run's later tool calls and
// every next run of the thread follow it; a pending approval stays pending.
// ErrNotFound when the thread is not login's or is deleted.
SetThreadInteractionMode(ctx context.Context, login, threadID, mode string) error
// RunInteractionMode returns the run's current interaction mode ("" is
// automatic): the approval gate reads it before every tool call. ErrNotFound.
RunInteractionMode(ctx context.Context, runID string) (string, error)
}
ApprovalStore is the persistence of tool approvals (interactive mode). An approval counts as pending for its thread only while its run is completed (the run ended waiting for the decision).
type Artifact ¶
type Artifact struct {
ID string
ThreadID string
UserLogin string
Path string
Name string
MimeType string
Kind string
SizeBytes int64
SHA256 string
Version int
RunID string
// SourceMtime is the sandbox mtime (unix seconds) observed for the latest version.
SourceMtime float64
Deleted bool
// SandboxID is the sandbox in which the latest version is known to be
// present (seen in a listing or written); "" when none yet. Only artifacts
// materialized in the snapshotted sandbox can be found deleted there.
SandboxID string
// RestoreSkippedAt is set when a workspace restore could not write the
// artifact (limits, read/write failure); such files go first next time.
RestoreSkippedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
Artifact is a durable file of a thread's /workspace (latest version denormalized).
type ArtifactStore ¶
type ArtifactStore interface {
// PutArtifactVersion creates the artifact (ChangeCreated), adds a version when
// the content differs, Force is set or it was deleted (ChangeUpdated), or only
// refreshes the observed mtime ("").
PutArtifactVersion(ctx context.Context, in PutArtifact) (*Artifact, string, error)
// MarkArtifactDeleted flags the artifact as removed from /workspace of
// sandboxID: only when its latest version is materialized in that sandbox
// and was not changed since unchangedSince (ErrConflict otherwise).
MarkArtifactDeleted(ctx context.Context, artifactID, runID, sandboxID string, unchangedSince time.Time) (*Artifact, error)
// MarkArtifactsMaterialized records that the latest versions are present in the sandbox.
MarkArtifactsMaterialized(ctx context.Context, sandboxID string, artifactIDs []string) error
// MarkArtifactsRestoreSkipped records that a workspace restore could not write them.
MarkArtifactsRestoreSkipped(ctx context.Context, artifactIDs []string) error
// Clock is the database time (the reference of updated_at).
Clock(ctx context.Context) (time.Time, error)
// AdvisoryLock takes a cluster-wide lock (shared by every api and runtime
// process) waiting at most wait (ErrLockTimeout); call the func to release it.
AdvisoryLock(ctx context.Context, name string, wait time.Duration) (func(), error)
// PurgeDeletedThreads hard-deletes up to limit threads soft-deleted more
// than olderThan ago (runs, messages, events, artifacts, versions, goals,
// feedback) and queues their content blobs for garbage collection, last
// referenced now. A new artifact version referencing a queued blob
// refreshes its last reference in the same statement (PutArtifactVersion).
PurgeDeletedThreads(ctx context.Context, olderThan time.Duration, limit int) (int, error)
// TouchBlob refreshes the last reference of a queued blob; call it before
// checking that content to reuse is stored. It waits for an in-flight
// collection of the blob (CollectBlob), so the check that follows sees the
// content gone and stores it again.
TouchBlob(ctx context.Context, key string) error
// QueueBlob queues key for garbage collection, last referenced now (an
// existing queue row is refreshed). Call it before storing a blob that no
// artifact version may ever reference (an orphan after a failure, a cached
// preview): the GC deletes it once unreferenced for the grace period.
QueueBlob(ctx context.Context, key string) error
// BlobCandidates returns up to limit queued blob keys that no artifact
// version references and that were last referenced more than grace ago
// (queued keys that are referenced again leave the queue).
BlobCandidates(ctx context.Context, grace time.Duration, limit int) ([]string, error)
// CollectBlob removes key from the queue only when it is still unreferenced
// and was last referenced more than grace ago, then calls del (deleting the
// content from an external backend) before committing: the queue row stays
// locked until del returns and is kept when del fails. It reports whether
// the blob was collected.
CollectBlob(ctx context.Context, key string, grace time.Duration, del func(context.Context) error) (bool, error)
// ListArtifacts returns every artifact of a thread (deleted included).
ListArtifacts(ctx context.Context, threadID string) ([]*Artifact, error)
GetArtifact(ctx context.Context, id string) (*Artifact, error)
ListArtifactVersions(ctx context.Context, artifactID string) ([]ArtifactVersion, error)
GetArtifactVersion(ctx context.Context, artifactID string, version int) (*ArtifactVersion, error)
// AppendRunArtifacts appends items to metadata.artifacts of the run's last
// assistant message; a run without one gets an empty assistant message
// (content "") carrying them.
AppendRunArtifacts(ctx context.Context, runID string, items []any) error
}
ArtifactStore persists artifact metadata (content lives in a BlobStore).
type ArtifactVersion ¶
type ArtifactVersion struct {
Version int
SizeBytes int64
SHA256 string
RunID string
CreatedAt time.Time
}
ArtifactVersion is one stored version of an artifact.
type Attachment ¶
type Attachment struct {
ArtifactID string `json:"artifactId"`
Name string `json:"name"`
Path string `json:"path"`
SizeBytes int64 `json:"sizeBytes"`
MimeType string `json:"mimeType"`
// Version is the upload version attached (extra field, not in the contract's list).
Version int `json:"version,omitempty"`
}
Attachment is one entry of a user message's metadata.attachments.
func MessageAttachments ¶
func MessageAttachments(m *Message) []Attachment
MessageAttachments decodes metadata.attachments of a message.
type AuditEntry ¶
type AuditEntry struct {
ID int64 `json:"id"`
ProjectID string `json:"projectId,omitempty"`
ThreadID string `json:"threadId,omitempty"`
Actor string `json:"actor"`
OnBehalfOf string `json:"onBehalfOf,omitempty"`
Action string `json:"action"`
Detail map[string]any `json:"detail,omitempty"`
At time.Time `json:"at"`
}
AuditEntry records an action taken on a project or thread by a user.
type BlobStore ¶
type BlobStore interface {
// PutBlob stores data under key; an existing key is kept (content-addressed).
PutBlob(ctx context.Context, key string, data []byte) error
// GetBlob returns ErrNotFound for an unknown key.
GetBlob(ctx context.Context, key string) ([]byte, error)
HasBlob(ctx context.Context, key string) (bool, error)
DeleteBlob(ctx context.Context, key string) error
// CollectBlobs deletes in one statement, among keys, the queued blobs that
// are still unreferenced and were last referenced more than grace ago,
// with their queue row and cached preview ("preview/<key>.pdf"); it
// returns the collected keys.
CollectBlobs(ctx context.Context, keys []string, grace time.Duration) ([]string, error)
}
BlobStore is the Postgres blob backend (work_blobs).
type Compaction ¶
type Compaction struct {
ID string
ThreadID string
RunID string
AfterMessageID string
Trigger string
TokensBefore int
TokensAfter int
CreatedAt time.Time
}
Compaction is a completed context compaction, kept so the UI can show its divider after a reload (after the message AfterMessageID).
type Connector ¶
type Connector struct {
Login string `json:"login"`
Kind string `json:"kind"`
Account string `json:"account"` // the account's id at the provider (GitHub login, Telegram chat id)
Label string `json:"label"` // what to show (@name)
Data []byte `json:"data"`
CreatedAt time.Time `json:"createdAt"`
}
Connector links a user to an outside account (GitHub, Telegram). Data is opaque to the store (the host encrypts it: tokens live there).
type EntryEmbedding ¶
EntryEmbedding is the vector of a memory entry: computed from the entry's title and content by Model, valid while ContentHash is the entry's.
type Event ¶
type Event struct {
Seq int64
Type string
// Data is the full AG-UI event JSON (including type and timestamp).
Data json.RawMessage
}
Event is one persisted AG-UI event of a run.
type Feedback ¶
type Feedback struct {
Sentiment string `json:"sentiment"`
Comment string `json:"comment,omitempty"`
}
Feedback is a user's rating of an assistant message.
type Full ¶
type Full interface {
Store
ArtifactStore
BlobStore
SkillStore
HarnessStore
ApprovalStore
MemoryStore
NotificationStore
}
Full is the persistence of a complete deployment: the core store and the stores of every capability. The memory, file and Postgres backends implement it.
type Goal ¶
type Goal struct {
ID string
ThreadID string
Text string
Status string
TurnsUsed int
MaxTurns int
LastVerdict *GoalVerdict
EvalFailures int
CreatedAt time.Time
UpdatedAt time.Time
}
Goal is the thread's goal (§6).
type GoalEvidence ¶
GoalEvidence is what the judge sees of a deliverable of the run's turn: its last checker result (OK nil: not checked since its last change) and the start of its extracted text.
type GoalUpdate ¶
type GoalUpdate struct {
ID string
Verdict GoalVerdict
// EvalFailed counts a consecutive evaluation failure (reset otherwise).
EvalFailed bool
// Status is the new status ("" keeps it).
Status string
}
GoalUpdate records an evaluation of the goal with id ID (ignored when the goal changed meanwhile).
type GoalVerdict ¶
type GoalVerdict struct {
Met bool `json:"met"`
Reason string `json:"reason"`
// Blockers are what the judge found still missing or wrong (harness v3 §4).
Blockers []string `json:"blockers,omitempty"`
At time.Time `json:"at"`
}
GoalVerdict is the last evaluation of a goal.
type HarnessStore ¶
type HarnessStore interface {
// SearchThreads is ListThreads restricted to threads whose title or visible message content contains search.
SearchThreads(ctx context.Context, login, search string, limit int, before *ThreadCursor) ([]*Thread, error)
GetThreadSummary(ctx context.Context, threadID string) (ThreadSummary, error)
SetThreadSummary(ctx context.Context, threadID string, s ThreadSummary) error
SetThreadPlan(ctx context.Context, threadID string, items []PlanItem) error
// SetPendingQuestion opens (or, with nil, clears) the thread's ask_user question.
SetPendingQuestion(ctx context.Context, threadID string, q *PendingQuestion) error
// SetGeneratedTitle replaces an auto-derived title; false when the title is not auto any more.
SetGeneratedTitle(ctx context.Context, threadID, title string) (bool, error)
// PutGoal replaces the thread's goal with a new active one.
PutGoal(ctx context.Context, login, threadID, text string, maxTurns int) (*Goal, error)
// GetGoal returns the goal of an owned thread (ErrNotFound when none).
GetGoal(ctx context.Context, login, threadID string) (*Goal, error)
// ClearGoal sets the goal status to cleared (ErrNotFound when none).
ClearGoal(ctx context.Context, login, threadID string) error
// ThreadGoal returns a thread's goal without ownership check (runtime); nil when none.
ThreadGoal(ctx context.Context, threadID string) (*Goal, error)
// UpdateGoal records an evaluation; returns the goal as stored afterwards (nil when none).
UpdateGoal(ctx context.Context, threadID string, u GoalUpdate) (*Goal, error)
// SetFeedback rates a visible assistant message of one of the user's threads (ErrNotFound otherwise).
SetFeedback(ctx context.Context, login, messageID string, f Feedback) error
DeleteFeedback(ctx context.Context, login, messageID string) error
// ListFeedback returns the feedback of a thread's messages by message id.
ListFeedback(ctx context.Context, threadID string) (map[string]Feedback, error)
// AppendToolVerification appends checker results to metadata.verification
// of the visible tool message of a thread's call (round 3, N2: the checks
// of files past the per-call cap, run before the next model call); nothing
// when the call has no stored result.
AppendToolVerification(ctx context.Context, threadID, toolCallID string, items []any) error
// RecordCompaction records a completed compaction after the thread's last
// visible message (nothing when the thread has no message).
RecordCompaction(ctx context.Context, c Compaction) error
// ListCompactions returns the compactions whose message is still visible, oldest first.
ListCompactions(ctx context.Context, threadID string) ([]Compaction, error)
}
HarnessStore is the persistence of the harness v2 features.
type HistoryStore ¶
type HistoryStore interface {
// SupersedeFrom hides the user message messageID and every later message of the thread (like an edit
// and resend, without the new run), drops the context summary that covered them and the pending
// question. ErrNotFound when the thread is not login's, ErrInvalidReplace when messageID is not a
// visible user message, ErrRunActive when the thread has a queued or running run.
SupersedeFrom(ctx context.Context, login, threadID, messageID string) error
}
HistoryStore is the optional part of a Store that edits a thread's history without starting a run (undo). The three stores implement it; a host checks with a type assertion.
type Invite ¶
type Invite struct {
ProjectID string `json:"projectId"`
Email string `json:"email"`
Role string `json:"role"`
InvitedBy string `json:"invitedBy"`
CreatedAt time.Time `json:"createdAt"`
}
Invite is a membership waiting for its email to log in.
type Member ¶
type Member struct {
ProjectID string `json:"projectId"`
Login string `json:"login"`
Role string `json:"role"`
AddedAt time.Time `json:"addedAt"`
}
Member is a user's role in a project.
type MemoryEmbeddingStore ¶
type MemoryEmbeddingStore interface {
// PutMemoryEmbeddings stores or replaces the vectors of the user's entries.
PutMemoryEmbeddings(ctx context.Context, login string, items []EntryEmbedding) error
// GetMemoryEmbeddings returns the user's vectors by entry id.
GetMemoryEmbeddings(ctx context.Context, login string) (map[string]EntryEmbedding, error)
}
MemoryEmbeddingStore is implemented by stores that keep memory embeddings (the memory service type-asserts it; without it search stays lexical).
type MemoryEntry ¶
type MemoryEntry struct {
ID string
UserLogin string
Path string
Title string
Content string
Tags []string
Importance *float64
Metadata map[string]any
Scope string
Repository string
Source string
Status string
// SourceThreadID is the conversation that wrote the entry ("" for the user or migrated rows).
SourceThreadID string
ContentHash string
CreatedAt time.Time
UpdatedAt time.Time
ContentUpdatedAt time.Time
DeletedAt *time.Time
// Version is bumped by every update (optimistic concurrency, see UpdateMemoryEntry).
Version int64
// Proposal is a change the agent made to this active entry after untrusted
// content: the entry keeps (and is used with) its confirmed fields until the
// user keeps the proposal (applied) or discards it (dropped).
Proposal *MemoryProposal
}
MemoryEntry is one durable memory of a user (Work's memory catalog entry plus its content): a path such as memories/semantic/facts/….md, a title, markdown content, tags, an optional importance and free metadata (trigger…).
func (*MemoryEntry) Clone ¶
func (e *MemoryEntry) Clone() *MemoryEntry
Clone returns a deep copy of e.
type MemoryLimits ¶
MemoryLimits caps a user's entries per status (≤ 0: no limit): active ones, and pending ones (the agent's proposals after untrusted content, capped apart so they cannot crowd out the confirmed memory).
func (MemoryLimits) Of ¶
func (l MemoryLimits) Of(status string) int
Of returns the limit of status (0: none).
type MemoryProposal ¶
type MemoryProposal struct {
Path string `json:"path"`
Title string `json:"title"`
Content string `json:"content"`
Tags []string `json:"tags"`
Importance *float64 `json:"importance"`
Metadata map[string]any `json:"metadata"`
ContentHash string `json:"content_hash"`
// ThreadID is the conversation that proposed it.
ThreadID string `json:"thread_id,omitempty"`
ProposedAt time.Time `json:"proposed_at"`
}
MemoryProposal is a proposed state of an entry's editable fields.
func (*MemoryProposal) Clone ¶
func (p *MemoryProposal) Clone() *MemoryProposal
Clone returns a deep copy of p.
type MemoryStore ¶
type MemoryStore interface {
// MemoryEnabled is the user's memory setting (default on).
MemoryEnabled(ctx context.Context, login string) (bool, error)
SetMemoryEnabled(ctx context.Context, login string, enabled bool) error
// ListMemoryEntries returns the user's entries with one of statuses (all when
// empty), oldest first.
ListMemoryEntries(ctx context.Context, login string, statuses ...string) ([]*MemoryEntry, error)
// GetMemoryEntry returns one of the user's entries by id (ErrNotFound otherwise).
GetMemoryEntry(ctx context.Context, login, id string) (*MemoryEntry, error)
// GetMemoryEntryByPath returns the user's non-deleted entry at path, else the
// latest deleted one (ErrNotFound when none).
GetMemoryEntryByPath(ctx context.Context, login, path string) (*MemoryEntry, error)
// CreateMemoryEntry inserts e; ErrMemoryLimit when the user already has
// limits.Of(e.Status) entries of that status, ErrMemoryPathExists on a path clash.
CreateMemoryEntry(ctx context.Context, e *MemoryEntry, limits MemoryLimits) (*MemoryEntry, error)
// UpdateMemoryEntry stores the mutable fields of e (path, title, content,
// tags, importance, metadata, status, hashes, timestamps, proposal) for e.UserLogin/e.ID
// when the stored version is still e.Version (ErrMemoryConflict otherwise:
// re-read and retry, or give up), and bumps the version. When e moves to
// another status, the limit of the new one is checked under the same per-user
// lock as CreateMemoryEntry (ErrMemoryLimit): confirm, restore.
UpdateMemoryEntry(ctx context.Context, e *MemoryEntry, limits MemoryLimits) (*MemoryEntry, error)
// DeleteMemoryEntry hard-deletes one of the user's entries (ErrNotFound
// otherwise); with expectStatus set, only when the entry still has this
// status (ErrMemoryConflict otherwise).
DeleteMemoryEntry(ctx context.Context, login, id, expectStatus string) error
// ListMemoryUsers returns the users with active entries (consolidation).
ListMemoryUsers(ctx context.Context) ([]string, error)
// PurgeDeletedMemoryEntries hard-deletes entries soft-deleted before before.
PurgeDeletedMemoryEntries(ctx context.Context, before time.Time) (int, error)
}
MemoryStore is the persistence of the memory entries (per user).
type Message ¶
type Message struct {
ID string
ThreadID string
RunID string
Position int64
Role string
Content string
ToolCalls []ToolCall
ToolCallID string
Error string
Metadata map[string]any
// ReasoningItems are the opaque reasoning items (Responses API, encrypted by
// the provider) of an assistant message, sent back to its model with the
// message (column reasoning_items; never exposed by the API).
ReasoningItems json.RawMessage
CreatedAt time.Time
// Authorship. AuthorLogin is the user who typed a user message (empty for
// assistant and tool messages, and for messages of single-user threads
// written before authorship existed); AuthorKind says what wrote it
// (AuthorUser, AuthorSupervisor, AuthorSystem; empty is the thread owner's
// or the model's own message); OnBehalfOf is the user a supervisor acted for.
AuthorLogin string
AuthorKind string
OnBehalfOf string
}
Message is a persisted chat message.
type NewRun ¶
type NewRun struct {
RunID string
ThreadID string
UserLogin string
Model string
Message Message
// AutoTitle is used as the thread title when the thread has none.
AutoTitle string
// Skills are skill names explicitly requested for this run (work_runs.skills).
Skills []string
// Harness v2. Kind defaults to chat. A Message without Role is not stored
// (compact runs, resume-only runs).
Kind string
ReasoningEffort string
// ReplaceFromMessageID supersedes that user message and every later one.
ReplaceFromMessageID string
// GoalID claims a turn of that goal (ErrGoalInactive when not active or out of turns).
GoalID string
// Resume answers the pending question; without it a pending question is
// implicitly cancelled by a message (ErrQuestionPending without a message).
Resume *Resume
// InteractionMode is interactive or automatic; a non-empty mode is also
// remembered as the thread's last choice, an empty one uses that choice
// (automatic when the thread has none).
InteractionMode string
// Sandbox is the run's sandbox mode (SandboxAuto, SandboxOff, SandboxOn).
// Empty inherits the mode of the thread's latest run (resume, goal and
// compaction runs), else auto.
Sandbox string
// Mode is the run's mode (ModeBuild, ModePlan). Empty inherits the mode of
// the thread's latest run (resume runs), else build.
Mode string
}
NewRun is the input of CreateRun.
type NotificationStore ¶
type NotificationStore interface {
// MarkThreadSeen sets the thread's last_seen_at to now (ErrNotFound).
MarkThreadSeen(ctx context.Context, login, id string) error
// CountUnreadThreads counts the caller's unread threads.
CountUnreadThreads(ctx context.Context, login string) (int, error)
// SearchUnreadThreads is SearchThreads restricted to unread threads.
SearchUnreadThreads(ctx context.Context, login, search string, limit int, before *ThreadCursor) ([]*Thread, error)
}
NotificationStore tracks which threads finished work while their owner was away.
type PendingQuestion ¶
type PendingQuestion struct {
InterruptID string `json:"interruptId"`
RunID string `json:"runId"`
ToolCallID string `json:"toolCallId"`
Question string `json:"question"`
Options []QuestionOption `json:"options"`
AllowFreeText bool `json:"allowFreeText"`
}
PendingQuestion is an ask_user question waiting for the user's answer.
type PlanItem ¶
type PlanItem struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
}
PlanItem is one entry of the agent's update_plan todo list.
func LatestPlan ¶
LatestPlan is the plan of the last successful update_plan call among msgs (in position order): the thread's plan once an edit hid later messages (nil when no visible call wrote one).
type Project ¶
type Project struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
RepoURL string `json:"repoUrl,omitempty"`
DefaultBranch string `json:"defaultBranch,omitempty"`
// GitHubInstallation is the id of the GitHub App installation that grants
// access to the repository (0 when not connected).
GitHubInstallation int64 `json:"githubInstallation,omitempty"`
CreatedBy string `json:"createdBy"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Project is a repository the team works on.
type ProjectPatch ¶
type ProjectPatch struct {
Name *string
Description *string
RepoURL *string
DefaultBranch *string
GitHubInstallation *int64
}
ProjectPatch is a partial project update.
type ProjectRole ¶
ProjectRole is a project with the caller's role in it.
type PutArtifact ¶
type PutArtifact struct {
ThreadID string
UserLogin string
Path string
Name string
MimeType string
// Kind is used when the artifact is created; an existing artifact keeps its kind.
Kind string
SizeBytes int64
SHA256 string
RunID string
Mtime float64
// Force records a new version even when the content equals the latest one (restore).
Force bool
// SandboxID, when set, records that the content is present in that sandbox.
SandboxID string
}
PutArtifact is the input of PutArtifactVersion.
type QuestionOption ¶
type QuestionOption struct {
Label string `json:"label"`
Description string `json:"description,omitempty"`
}
QuestionOption is an ask_user answer choice.
type Resume ¶
type Resume struct {
InterruptID string
// Content is the ask_user tool result given to the model.
Content string
// Decision (approve, deny, respond) and Response decide a pending approval
// whose id is InterruptID; a cancelled resume of an approval is a deny.
Decision string
Response ApprovalResponse
// Scope of an approve decision: once (default) or run (ApprovalScopeRun).
Scope string
}
Resume answers a thread's pending ask_user question (or decides its pending approval) when a run is created.
type Run ¶
type Run struct {
ID string
ThreadID string
UserLogin string
Kind string
Status string
Model string
ReasoningEffort string
// InteractionMode is interactive or automatic ("" is automatic).
InteractionMode string
// Sandbox is the run's sandbox mode: SandboxAuto ("" too), SandboxOff or
// SandboxOn. A resumed run keeps the mode of the thread's previous run.
Sandbox string
// Mode is the run's mode: ModeBuild ("" too) or ModePlan (read-only). A resumed
// run keeps the mode of the thread's previous run.
Mode string
// ApprovedTools are the tool kinds approved with scope "run" in this run
// chain (the run and its resume runs): they run without asking again.
ApprovedTools []string
Error string
ErrorCode string
CancelRequested bool
RuntimeID string
HeartbeatAt *time.Time
LastSeq int64
CreatedAt time.Time
StartedAt *time.Time
FinishedAt *time.Time
}
Run is one agent execution on a thread.
type SkillStore ¶
type SkillStore interface {
// RunSkills returns the skill names requested at run creation.
RunSkills(ctx context.Context, runID string) ([]string, error)
}
SkillStore returns the skills requested for a run (RunOptions.Skills).
type Store ¶
type Store interface {
Ping(ctx context.Context) error
CreateThread(ctx context.Context, login, title string) (*Thread, error)
GetThread(ctx context.Context, login, id string) (*Thread, error)
ListThreads(ctx context.Context, login string, limit int, before *ThreadCursor) ([]*Thread, error)
UpdateThread(ctx context.Context, login, id string, patch ThreadPatch) (*Thread, error)
DeleteThread(ctx context.Context, login, id string) (*Thread, error)
CreateRun(ctx context.Context, in NewRun) (*Run, *Message, error)
GetRun(ctx context.Context, id string) (*Run, error)
// GetUserRun is GetRun for the API: ErrNotFound unless the run belongs to
// login and its thread is not deleted.
GetUserRun(ctx context.Context, login, id string) (*Run, error)
ClaimRun(ctx context.Context, id, runtimeID string) (*Run, error)
// Heartbeat refreshes heartbeat_at; owned=false when the run is no longer
// running on this runtime.
Heartbeat(ctx context.Context, id, runtimeID string) (owned, cancelRequested bool, err error)
RequestCancel(ctx context.Context, id string) (*Run, error)
// CancelQueuedRun moves a queued run to cancelled; false when it was not queued.
CancelQueuedRun(ctx context.Context, id string) (bool, error)
// FinishRun sets a terminal status; failed/interrupted runs store errCode (default "internal").
// ErrNotOwned when the run is not running on runtimeID any more.
FinishRun(ctx context.Context, id, runtimeID, status, errCode, errMsg string) error
ListQueuedRunsOlderThan(ctx context.Context, age time.Duration) ([]string, error)
// InterruptStaleRuns marks running runs whose heartbeat is older than age as
// interrupted and returns them; a run any alive check vouches for (its
// runtime still heartbeats elsewhere, e.g. in Redis during a Postgres
// outage) is left running.
InterruptStaleRuns(ctx context.Context, age time.Duration, alive ...func(*Run) bool) ([]*Run, error)
ListMessages(ctx context.Context, threadID string) ([]*Message, error)
AppendMessages(ctx context.Context, msgs ...*Message) error
AppendEvents(ctx context.Context, runID string, events []Event) error
ListEvents(ctx context.Context, runID string, afterSeq int64, limit int) ([]Event, error)
// LastEvent returns the highest-seq persisted event of a run.
LastEvent(ctx context.Context, runID string) (Event, bool, error)
// SetRunOutcome overwrites a run's terminal status (used when its log proves the outcome).
SetRunOutcome(ctx context.Context, id, status, errCode, errMsg string) error
}
Store is the core persistence: threads, runs, messages, the event journal and the thread-to-sandbox mapping. Everything the engine needs to run a conversation; the stores of the optional capabilities (artifacts, skills, goals and plans, approvals, memory, notifications) are separate interfaces, and Full is all of them. A package asks for the smallest one it uses.
type TeamStore ¶
type TeamStore interface {
// UpsertUser records the user at login and claims the invites sent to the
// email (the memberships are created).
UpsertUser(ctx context.Context, u User) (*User, error)
GetUser(ctx context.Context, login string) (*User, error)
// GetUsers returns the known users among logins, by login.
GetUsers(ctx context.Context, logins []string) (map[string]*User, error)
GetUserByEmail(ctx context.Context, email string) (*User, error)
// SetDisplayName sets the name the user chose ("" goes back to the provider's).
SetDisplayName(ctx context.Context, login, name string) error
// SetAvatar stores the user's avatar image and returns its version; empty data removes it.
SetAvatar(ctx context.Context, login, mime string, data []byte) (string, error)
// GetAvatar returns the uploaded avatar, ErrNotFound when none.
GetAvatar(ctx context.Context, login string) (mime string, data []byte, err error)
// Connectors: SetConnector replaces the user's connector of that kind.
SetConnector(ctx context.Context, c Connector) error
GetConnector(ctx context.Context, login, kind string) (*Connector, error)
ListConnectors(ctx context.Context, login string) ([]Connector, error)
DeleteConnector(ctx context.Context, login, kind string) error
// FindConnector finds the connector of a provider account (who owns Telegram chat 123).
FindConnector(ctx context.Context, kind, account string) (*Connector, error)
// ListUsers returns every known user (small teams: the supervisor watcher walks them).
ListUsers(ctx context.Context) ([]User, error)
// UserPrefs returns the user's preferences (an empty map when none were set).
UserPrefs(ctx context.Context, login string) (map[string]any, error)
// SetUserPrefs replaces the user's preferences.
SetUserPrefs(ctx context.Context, login string, prefs map[string]any) error
// SeenThreads returns when login last saw each thread (by thread id); threads never seen are absent.
SeenThreads(ctx context.Context, login string) (map[string]time.Time, error)
// SetThreadSeen records that login has seen the thread up to at. The time never moves backwards, so
// replays and several devices converge on the latest.
SetThreadSeen(ctx context.Context, login, threadID string, at time.Time) error
// CreateProject stores p (a fresh id when empty) and makes owner its owner.
CreateProject(ctx context.Context, p Project, owner string) (*Project, error)
GetProject(ctx context.Context, id string) (*Project, error)
UpdateProject(ctx context.Context, id string, patch ProjectPatch) (*Project, error)
// DeleteProject removes the project, its memberships, invites and thread links.
DeleteProject(ctx context.Context, id string) error
// ListProjects returns the projects login belongs to, with its role.
ListProjects(ctx context.Context, login string) ([]ProjectRole, error)
// MemberRole is login's role in the project, ErrNotFound when not a member.
MemberRole(ctx context.Context, projectID, login string) (string, error)
ListMembers(ctx context.Context, projectID string) ([]Member, error)
// SetMember adds login or changes its role (ErrLastOwner when it would demote the last owner).
SetMember(ctx context.Context, projectID, login, role string) error
// RemoveMember removes login (ErrLastOwner for the last owner).
RemoveMember(ctx context.Context, projectID, login string) error
// CreateInvite invites an email; when a user with that email exists it is added at once and nil is returned.
CreateInvite(ctx context.Context, in Invite) (*Invite, error)
ListInvites(ctx context.Context, projectID string) ([]Invite, error)
DeleteInvite(ctx context.Context, projectID, email string) error
// SetThreadMeta links a thread (idempotent).
SetThreadMeta(ctx context.Context, m ThreadMeta) error
// GetThreadMeta returns the link of a thread, ErrNotFound for a thread
// created before the team layer (then only its owner has access).
GetThreadMeta(ctx context.Context, threadID string) (*ThreadMeta, error)
ListProjectThreads(ctx context.Context, projectID string) ([]ThreadMeta, error)
// SupervisorThread returns the user's supervisor thread link, ErrNotFound when none.
SupervisorThread(ctx context.Context, login string) (*ThreadMeta, error)
DeleteThreadMeta(ctx context.Context, threadID string) error
Audit(ctx context.Context, e AuditEntry) error
ListAudit(ctx context.Context, projectID string, limit int) ([]AuditEntry, error)
}
TeamStore persists users, projects, memberships and the thread-to-project mapping. It is separate from Store: threads stay stored under their owner's login and the host decides, from here, who may act on them.
type Thread ¶
type Thread struct {
ID string
UserLogin string
Title string
PinnedAt *time.Time
SandboxID string
CreatedAt time.Time
UpdatedAt time.Time
ActiveRun *ActiveRun
// Harness v2.
TitleSource string
Plan []PlanItem
PendingQuestion *PendingQuestion
Goal *Goal
// Approvals: the last interaction mode chosen on the thread ("" when never
// set) and the risky tool call waiting for the user's decision.
InteractionMode string
PendingApproval *Approval
// Notifications (harness v3 §8): Unread when a run reached a terminal state
// after LastSeenAt; LastRun is the latest run (nil without runs).
LastSeenAt *time.Time
LastRun *LastRun
Unread bool
}
Thread is a conversation.
type ThreadCursor ¶
ThreadCursor positions thread pagination (pinned first, then createdAt desc): keyed on the immutable creation time, so a thread updated between two page fetches is neither skipped nor repeated.
type ThreadMeta ¶
type ThreadMeta struct {
ThreadID string `json:"threadId"`
ProjectID string `json:"projectId,omitempty"`
Owner string `json:"owner"`
CreatedBy string `json:"createdBy"`
Kind string `json:"kind"`
CreatedAt time.Time `json:"createdAt"`
}
ThreadMeta ties a thread to a project and records who created it. Owner is the login the thread is stored under (store calls for the thread use it); CreatedBy is the user who started it.
type ThreadPatch ¶
ThreadPatch is a partial thread update.
type ThreadSummary ¶
ThreadSummary is the compaction summary of the messages up to ThroughPosition.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function ToolCallFunction `json:"function"`
}
ToolCall is an assistant tool call (OpenAI/AG-UI shape).
type ToolCallFunction ¶
ToolCallFunction is the function part of a tool call.
type User ¶
type User struct {
Login string `json:"login"`
Email string `json:"email,omitempty"`
Name string `json:"name,omitempty"`
AvatarURL string `json:"avatarUrl,omitempty"`
CreatedAt time.Time `json:"createdAt"`
LastSeen time.Time `json:"lastSeen"`
// DisplayName is the name the user chose; empty means Name (from the identity provider: first and last name).
DisplayName string `json:"displayName,omitempty"`
// AvatarVersion identifies the uploaded avatar ("" when none); AvatarURL is then superseded.
AvatarVersion string `json:"avatarVersion,omitempty"`
}
User is a person known from the identity provider. Login is the stable key used everywhere (threads, memory, membership): the OIDC subject.
type WorkspaceGitArchive ¶
type WorkspaceGitArchive struct {
ThreadID string
// BlobKey is the blob holding the archive ("workspace-git/<thread>/<uuid>.tar.gz").
BlobKey string
// Head is the HEAD commit archived.
Head string
SizeBytes int64
UpdatedAt time.Time
}
WorkspaceGitArchive is the archived local Git history (/workspace/.git as a tar.gz blob) of a thread, restored into every new sandbox of the thread.
type WorkspaceGitIssue ¶
type WorkspaceGitIssue struct {
ThreadID string
Reason string
// Head is the HEAD that could not be archived; SizeBytes the refused archive size (too_large).
Head string
SizeBytes int64
UpdatedAt time.Time
}
WorkspaceGitIssue records that the thread's latest history was not archived (the stored archive, if any, is older than the sandbox's history).
type WorkspaceGitStore ¶
type WorkspaceGitStore interface {
// WorkspaceGit returns the thread's archive (ErrNotFound when none).
WorkspaceGit(ctx context.Context, threadID string) (*WorkspaceGitArchive, error)
// PutWorkspaceGit records the thread's new archive; the previous one's blob
// (when its key differs) is queued for garbage collection, last referenced now.
PutWorkspaceGit(ctx context.Context, a WorkspaceGitArchive) error
// WorkspaceGitIssue returns why the latest history is not archived (ErrNotFound: it is).
WorkspaceGitIssue(ctx context.Context, threadID string) (*WorkspaceGitIssue, error)
// SetWorkspaceGitIssue records a failed archive (a thread that no longer exists is ignored).
SetWorkspaceGitIssue(ctx context.Context, i WorkspaceGitIssue) error
// ClearWorkspaceGitIssue forgets it (the history was archived).
ClearWorkspaceGitIssue(ctx context.Context, threadID string) error
}
WorkspaceGitStore persists the thread's archived Git history. The archive blobs are never referenced by an artifact version: a replaced archive and the archive of a purged thread are queued for the blob garbage collection (work_blob_gc, collected after HARNESS_BLOB_GC_GRACE_HOURS).