Help us shape the future of Go! Take the 2026 Go Developer Survey

domain

package
v0.1.0-alpha.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultModelEffort = "high"
	DefaultModelSpeed  = "standard"
)
View Source
const (
	// List costs are accumulated as integer nano-dollars. All current Anthropic
	// token rates and geographic multipliers are exact in this unit.
	NanoUSDPerUSD  int64 = 1_000_000_000
	NanoUSDPerCent int64 = NanoUSDPerUSD / 100
)
View Source
const (
	DeploymentStatusActive = "active"
	DeploymentStatusPaused = "paused"

	DeploymentTriggerManual   = "manual"
	DeploymentTriggerSchedule = "schedule"
)
View Source
const (
	// Client-submittable input events.
	EvUserMessage          = "user.message"
	EvUserInterrupt        = "user.interrupt"
	EvUserToolConfirmation = "user.tool_confirmation"
	EvUserCustomToolResult = "user.custom_tool_result"
	EvUserToolResult       = "user.tool_result"
	EvUserDefineOutcome    = "user.define_outcome"
	EvSystemMessage        = "system.message"

	// Agent/server-emitted events (never accepted from clients).
	EvAgentMessage       = "agent.message"
	EvAgentThinking      = "agent.thinking"
	EvAgentCustomToolUse = "agent.custom_tool_use"
	EvAgentToolUse       = "agent.tool_use"
	EvAgentToolResult    = "agent.tool_result"

	// MCP tool calls are a distinct documented variant of the tool-use pair. The
	// use event additionally carries a required mcp_server_name and reports the
	// bare tool name as the server published it (not the namespaced model-facing
	// alias). The result event correlates through mcp_tool_use_id and carries no
	// server name: a client attributes a result to a server by joining back to
	// its use event.
	EvAgentMcpToolUse    = "agent.mcp_tool_use"
	EvAgentMcpToolResult = "agent.mcp_tool_result"

	EvSessionStatusIdle         = "session.status_idle"
	EvSessionStatusRunning      = "session.status_running"
	EvSessionStatusTerminated   = "session.status_terminated"
	EvSessionStatusRescheduling = "session.status_rescheduled"
	EvSessionError              = "session.error"
	EvSessionUpdated            = "session.updated"
	EvSessionUsage              = "session.usage"
	EvSessionDeleted            = "session.deleted"

	EvSessionThreadCreated           = "session.thread_created"
	EvSessionThreadStatusIdle        = "session.thread_status_idle"
	EvSessionThreadStatusRunning     = "session.thread_status_running"
	EvSessionThreadStatusTerminated  = "session.thread_status_terminated"
	EvSessionThreadStatusRescheduled = "session.thread_status_rescheduled"
	EvAgentThreadMessageReceived     = "agent.thread_message_received"
	EvAgentThreadMessageSent         = "agent.thread_message_sent"
	EvAgentThreadContextCompacted    = "agent.thread_context_compacted"

	EvSpanOutcomeEvaluationStart   = "span.outcome_evaluation_start"
	EvSpanOutcomeEvaluationOngoing = "span.outcome_evaluation_ongoing"
	EvSpanOutcomeEvaluationEnd     = "span.outcome_evaluation_end"
	EvSpanModelRequestStart        = "span.model_request_start"
	EvSpanModelRequestEnd          = "span.model_request_end"
)

Public event type constants. Every event is a top-level tagged union keyed on the "type" field following the {domain}.{action} convention. Mango currently retains wire values informed by the public Managed Agents events reference.

View Source
const (
	InternalCompanionSystemEventID = "__companion_system_event_id"
	InternalCompanionSystemContent = "__companion_system_content"
	InternalOriginTriggerEventID   = "__origin_trigger_event_id"
	InternalOriginPermissionIntent = "__origin_permission_intent"
	// InternalPermissionToolName correlates MCP wire names with the evaluated model alias.
	InternalPermissionToolName     = "__permission_tool_name"
	InternalToolExecutionOwner     = "__tool_execution_owner"
	InternalOutcomeEvaluationStart = "__outcome_evaluation_start_id"
	InternalOutcomeIteration       = "__outcome_evaluation_iteration"
	InternalOutcomeRubricContent   = "__outcome_rubric_content"
	InternalFileMessageContents    = "__file_message_contents"
)

Internal event payload keys support server-side causal linking without changing the public Mango event shape. HTTP projections must never expose keys with this prefix.

View Source
const (
	PrefixRunAttempt = "ratm_"
	PrefixToolStep   = "tstep_"
)
View Source
const (
	PrefixAgent           = "agent_"
	PrefixEnv             = "env_"
	PrefixSession         = "sesn_"
	PrefixSessionThread   = "sthr_"
	PrefixContextSnapshot = "csnp_"
	PrefixEvent           = "sevt_"
	PrefixRun             = "run_"
	PrefixOutcome         = "outc_"
	PrefixFile            = "file_"
	PrefixSessionResource = "sesrsc_"
	PrefixSkill           = "skill_"
	PrefixMemoryStore     = "memstore_"
	PrefixMemory          = "mem_"
	PrefixMemoryVersion   = "memver_"
	PrefixVault           = "vlt_"
	PrefixVaultCredential = "vcrd_"
	PrefixDeployment      = "depl_"
	PrefixDeploymentRun   = "drun_"
	PrefixDeploymentClaim = "dclaim_"
	PrefixEnvironmentWork = "work_"
	PrefixWebhook         = "wh_"
	PrefixWebhookEvent    = "whe_"
	PrefixWebhookClaim    = "whclaim_"
)
View Source
const (
	MaxMetadataKeys       = 16
	MaxMetadataKeyRunes   = 64
	MaxMetadataValueRunes = 512
)

Public metadata limits shared by every resource that exposes a metadata bag.

View Source
const (
	PreviewEventStart = "event_start"
	PreviewEventDelta = "event_delta"
)
View Source
const (
	SessionMemoryRoot                 = "/mnt/memory"
	SessionWorkspaceRoot              = "/workspace"
	MaxSessionMemoryStores            = 8
	MaxSessionMemoryInstructionsChars = 4096
)
View Source
const (
	SessionResourceTypeMemoryStore = "memory_store"
	MemoryAccessReadWrite          = "read_write"
	MemoryAccessReadOnly           = "read_only"
)
View Source
const (
	// SessionSkillsRoot is the provider-independent runtime directory containing
	// immutable-source custom Skills. Each Skill is re-rooted beneath its
	// validated frontmatter name, independent of the uploaded archive
	// directory's original casing.
	SessionSkillsRoot = "/workspace/skills"

	// SessionSkillsRelativeRoot is the model-visible root for self-hosted
	// workers. Their concrete Workdir is launcher-owned and intentionally absent
	// from the Environment API, so the control plane must describe Skill files
	// relative to that root rather than assume /workspace.
	SessionSkillsRelativeRoot = "skills"
)
View Source
const (
	CredentialAuthMCPOAuth     = "mcp_oauth"
	CredentialAuthStaticBearer = "static_bearer"
)
View Source
const (
	WebhookEventSessionStatusScheduled        = "session.status_scheduled"
	WebhookEventSessionStatusRunStarted       = "session.status_run_started"
	WebhookEventSessionStatusIdled            = "session.status_idled"
	WebhookEventSessionStatusRescheduled      = "session.status_rescheduled"
	WebhookEventSessionStatusTerminated       = "session.status_terminated"
	WebhookEventSessionBudgetReached          = "session.budget_reached"
	WebhookEventSessionThreadCreated          = "session.thread_created"
	WebhookEventSessionThreadIdled            = "session.thread_idled"
	WebhookEventSessionThreadTerminated       = "session.thread_terminated"
	WebhookEventSessionOutcomeEvaluationEnded = "session.outcome_evaluation_ended"
	WebhookEventSessionUpdated                = "session.updated"
	WebhookEventSessionArchived               = "session.archived"
	WebhookEventSessionDeleted                = "session.deleted"
	WebhookEventDeploymentRunSucceeded        = "deployment_run.succeeded"
	WebhookEventDeploymentRunFailed           = "deployment_run.failed"
)
View Source
const AdvisorAgentName = "anthropic.advisor"
View Source
const BuiltinToolsetType = "agent_toolset_20260401"
View Source
const ContextPolicyVersion = 1
View Source
const MaxFileMessageCharacters = 262144

MaxFileMessageCharacters bounds one uploaded UTF-8 File projected into a user.message. The limit keeps admission reads and durable event snapshots bounded independently of the 500 MB Files storage limit.

View Source
const MaxOutcomeRubricCharacters = 262144

MaxOutcomeRubricCharacters is the documented limit for inline and File rubrics.

View Source
const PrefixPendingAction = "pact_"

PrefixPendingAction is the id prefix for durable pending-action records.

Variables

View Source
var BuiltinToolNames = []string{"bash", "read", "write", "edit", "glob", "grep", "web_fetch", "web_search"}
View Source
var ErrInvalidTransition = &DomainError{Kind: KindValidation, Message: "invalid status transition"}

Functions

func AgentToolResultReference

func AgentToolResultReference(
	eventType string,
	payload map[string]any,
) (toolUseEventID string, ok bool)

AgentToolResultReference returns the tool-use event id a server-emitted tool result correlates to, reading the id field the documented variant uses: tool_use_id for agent.tool_result and mcp_tool_use_id for agent.mcp_tool_result. ok is false for any other event type.

func AgentToolResultTypeFor

func AgentToolResultTypeFor(toolUseEventType string) string

AgentToolResultTypeFor returns the result event type that answers a server-emitted tool-use event: agent.mcp_tool_result for agent.mcp_tool_use and agent.tool_result for every other server-executed call.

The pairing is a property of the committed use event, not of the code that happens to be running when the answer is produced. A tool call can park on a client confirmation for an unbounded time and be answered by a later, upgraded process, so the answering side must read the durable type rather than assume its own naming scheme.

func CompactMessages

func CompactMessages(messages []Message, maxEstimatedTokens int) ([]Message, ContextProjection)

CompactMessages builds a bounded model-context projection while leaving the source transcript untouched. It keeps the newest legal suffix, never starts that suffix with an orphan tool_result, and replaces older rich content with a small extractive summary rather than replaying base64 or huge results.

func EstimateMessagesTokens

func EstimateMessagesTokens(messages []Message) int

EstimateMessagesTokens is a conservative, provider-independent request-size estimate. It deliberately counts serialized rich content and tool inputs; counting text alone would underestimate base64 images, documents, and large structured tool results. Exact provider billing remains sourced from usage.

func EstimateTextTokens

func EstimateTextTokens(text string) int

EstimateTextTokens exposes the same conservative estimator for top-level system prompts and serialized tool definitions.

func FileMessageContents

func FileMessageContents(payload map[string]any) map[string]FileMessageContent

FileMessageContents decodes both newly constructed and PostgreSQL JSON payloads into snapshots keyed by the public content-block index.

func HasAnthropicPublicListPrice

func HasAnthropicPublicListPrice(model Model) bool

func IsAgentToolUse

func IsAgentToolUse(t string) bool

IsAgentToolUse reports whether a type is one of the server-emitted tool-call announcements. Both agent.tool_use and agent.mcp_tool_use name a call the runtime made on the model's behalf; agent.custom_tool_use names one the client must execute.

func IsClientSubmittable

func IsClientSubmittable(t string) bool

IsClientSubmittable reports whether a client may POST an event of this type to the send-events endpoint. The set is exactly the documented user.* inputs plus system.message. Agent-, session-, and span-scoped types are server-only and must be rejected; that includes agent.mcp_tool_use and agent.mcp_tool_result, which are emitted by the runtime and never accepted from a caller.

func IsInitialEventType

func IsInitialEventType(t string) bool

IsInitialEventType reports whether a type is allowed in a session's initial_events. Only user.message and user.define_outcome are accepted there; unlike scheduled deployments, initial_events does not accept system.message.

func IsSelfHostedToolCall

func IsSelfHostedToolCall(eventType string, payload map[string]any) bool

IsSelfHostedToolCall uses the server-owned execution marker, never a client assertion, to distinguish external built-ins from server-executed tools.

func IsSessionCredentialEvent

func IsSessionCredentialEvent(t string) bool

IsSessionCredentialEvent reports the client events an untrusted self-hosted execution scope may submit. A Session worker answers tool calls; it cannot inject user instructions or higher-priority system context.

func IsUserEvent

func IsUserEvent(t string) bool

IsUserEvent reports whether t is one of the user.* input event types.

func MCPAddressAllowed

func MCPAddressAllowed(address netip.Addr) bool

MCPAddressAllowed reports whether a resolved MCP endpoint is safe for the default public-internet connector. Private MCP services require a separate tunnel/egress capability; the worker must never reach them directly from a tenant-controlled URL.

func ModelResponseListCostNanoUSDAt

func ModelResponseListCostNanoUSDAt(
	model Model,
	usage TokenUsage,
	stopReason string,
	at time.Time,
) (int64, error)

ModelResponseListCostNanoUSDAt applies response-level billing rules that cannot be inferred from token counters alone. Fable refusals are successful provider responses and remain observable usage, but Anthropic does not bill the refused request.

func ModelUsageListCostNanoUSD

func ModelUsageListCostNanoUSD(
	model Model,
	usage TokenUsage,
) (int64, error)

ModelUsageListCostNanoUSD applies Anthropic's public Messages list rates to provider-reported usage. Unknown/router-defined model names are rejected for budgeted Sessions rather than assigned a guessed fallback price.

func ModelUsageListCostNanoUSDAt

func ModelUsageListCostNanoUSDAt(
	model Model,
	usage TokenUsage,
	_ time.Time,
) (int64, error)

ModelUsageListCostNanoUSDAt accepts the request timestamp so future catalog changes can preserve the price in effect when the provider request completed.

func MonetaryAmountJSON

func MonetaryAmountJSON(nanoUSD int64) map[string]any

MonetaryAmountJSON rounds an exact internal list cost to the nearest whole cent, matching Mango's public projection.

func NormalizeSessionMemoryStoreMountPath

func NormalizeSessionMemoryStoreMountPath(name string) (string, error)

NormalizeSessionMemoryStoreMountPath follows the Managed Agents convention: lowercase the Store name and collapse each run of non-alphanumeric Unicode characters to one hyphen beneath /mnt/memory.

func OutcomeRubricContent

func OutcomeRubricContent(payload map[string]any) (string, bool)

OutcomeRubricContent projects both public rubric variants onto the one text input consumed by the working agent and isolated grader. File rubrics must have been resolved and snapshotted before event admission.

func ParseMCPServers

func ParseMCPServers(raw []any) (map[string]MCPServer, error)

func ProcessedOnReceipt

func ProcessedOnReceipt(t string) bool

ProcessedOnReceipt reports whether an event is stamped processed_at at persist time rather than when a later turn consumes it. Server-only events are already processed when emitted; selected client events are acknowledged on receipt.

func ProjectSessionResourceContext

func ProjectSessionResourceContext(base string, resources []SessionResource) string

ProjectSessionResourceContext tells the model which mounted Memory Stores are available before it chooses a tool. Contents are never injected into the prompt.

func ProjectSessionSkillContext

func ProjectSessionSkillContext(
	base string,
	skills []SkillVersion,
	descriptionCharacterBudget int,
) string

ProjectSessionSkillContext exposes only trusted Skill discovery metadata. Bundle contents stay on disk until the model invokes the runtime's private Skill dispatcher, which injects the selected SKILL.md into the conversation.

func ProjectSkillRuntimeContext

func ProjectSkillRuntimeContext(
	base string,
	runtime SkillRuntime,
	descriptionCharacterBudget int,
) string

ProjectSkillRuntimeContext exposes discovery metadata only for the current resolved Agent scope. Supporting files remain in the shared sandbox, but no other Agent's Skill list enters this Thread's model context.

func ProjectSystemContext

func ProjectSystemContext(base string, events []Event, trigger Event) string

ProjectSystemContext appends persisted mid-conversation system messages to the Agent's top-level system prompt. The current accompanying system.message is causally linked into trigger when it follows that trigger in receipt order and therefore is not yet visible to HistoryThrough.

func RuntimeListCostNanoUSD

func RuntimeListCostNanoUSD(activeSeconds float64) int64

RuntimeListCostNanoUSD prices de-duplicated Session active time. Session timestamps have microsecond precision, so rounding once to nano-dollars is more precise than the public whole-cent projection by several orders of magnitude.

func SessionAgentSkillRoot

func SessionAgentSkillRoot(
	sessionAgentID string,
	sessionAgentVersion int,
	agent Agent,
) string

SessionAgentSkillRoot preserves the Claude Code-compatible flat path for the coordinator and self copies. External roster Agents use a stable opaque namespace so equal Skill names with different Versions cannot collide in the shared Session sandbox.

func SessionUpdatedPayload

func SessionUpdatedPayload(s Session, change SessionChange) map[string]any

SessionUpdatedPayload builds the `session.updated` event payload for an already-applied update. The documented event carries only the fields the request changed; metadata is additionally omitted when the resulting bag is empty.

func ValidateMetadata

func ValidateMetadata(metadata map[string]any) error

ValidateMetadata enforces the public metadata contract on a resolved bag. Callers that accept a per-key patch must merge first and validate the result; a patch may legitimately carry nil values that mean "delete this key" and never reach the stored bag.

func ValidateModel

func ValidateModel(model Model) error

ValidateModel enforces the public model configuration enums. Model support for a particular effort/speed combination remains a provider concern.

func ValidateSkillToolConfiguration

func ValidateSkillToolConfiguration(rawTools []any, hasSkills bool) error

ValidateSkillToolConfiguration checks the agent-runtime capabilities Skills depend on. Skill is a private dispatcher, but its instructions may reference supporting files and scripts, so the public read tool must remain enabled. A user-defined tool named Skill would collide with the runtime dispatcher in the provider request and is therefore reserved only while Skills are active.

func ValidateStoredToolConfiguration

func ValidateStoredToolConfiguration(rawTools, rawServers []any) error

ValidateStoredToolConfiguration checks the executable semantics of an already-persisted Agent snapshot while tolerating unknown historical fields. Admission must use ValidateToolConfiguration instead.

func ValidateToolConfiguration

func ValidateToolConfiguration(rawTools, rawServers []any) error

ValidateToolConfiguration performs control-plane validation that does not require contacting a provider or MCP server. It keeps malformed or internally inconsistent capabilities out of immutable Agent versions and Session snapshots.

func WithFileMessageContents

func WithFileMessageContents(
	payload map[string]any,
	contents []FileMessageContent,
) map[string]any

WithFileMessageContents attaches immutable File text snapshots to a cloned event payload. HTTP projections redact this top-level internal key while the PostgreSQL event ledger preserves it for replay and later turns.

func WithOutcomeRubricContent

func WithOutcomeRubricContent(payload map[string]any, content string) map[string]any

WithOutcomeRubricContent attaches the resolved bytes of a file-backed rubric to a cloned private event payload. The public rubric union remains unchanged; HTTP projections redact this internal field by prefix convention.

Types

type Advisor

type Advisor struct {
	Type  string `json:"type"`
	Model string `json:"model"`
}

Advisor is the resolved public form used by an automatically terminating consultation Thread. It is deliberately not an Agent: it has no mutable resource identity, tools, prompt, or coordinator messaging surface.

type AdvisorConsultation

type AdvisorConsultation struct {
	ThreadID        string
	UsageRequestID  string
	LifecycleIDs    []string
	Model           string
	UsageModel      string
	Usage           TokenUsage
	UsageKnown      bool
	StopReason      string
	PublicContent   []any
	AdviceDelivered bool
}

AdvisorConsultation is the normalized result of one Mango-managed advisor inference. Workflow-assigned identifiers make persistence idempotent across Temporal Activity retries while the ordinary client-tool result remains in the executor's private provider transcript.

type Agent

type Agent struct {
	ID          string
	Version     int
	Name        string
	Model       Model
	System      *string
	Description *string
	Tools       []any
	MCPServers  []any
	Skills      []SkillReference
	Multiagent  *Multiagent
	Metadata    map[string]any
	CreatedAt   time.Time
	UpdatedAt   time.Time
	ArchivedAt  *time.Time
}

func (Agent) Apply

func (a Agent) Apply(p AgentPatch) (Agent, bool, error)

func (Agent) SessionSnapshotJSON

func (a Agent) SessionSnapshotJSON() map[string]any

SessionSnapshotJSON is the public resolved-agent projection embedded in a Session (`session.agent`) and in a `session.updated` event. It omits the agent-resource bookkeeping (created_at/updated_at/archived_at) that the session agent object does not carry. It lives here because the HTTP layer and the durable event ledger must publish exactly the same shape.

func (Agent) WithOverrides

func (a Agent) WithOverrides(o AgentOverrides) Agent

WithOverrides returns a copy of the agent with session-local overrides applied. It does not change version or identity; the returned snapshot still reports the base agent's id and version so a session traces back to it. Each provided field replaces (never merges) the agent's value.

type AgentOverrides

type AgentOverrides struct {
	Model      *Model
	System     *NullableString
	Tools      *[]any
	MCPServers *[]any
	Skills     *[]SkillReference
}

AgentOverrides expresses per-session agent configuration overrides (agent_with_overrides). Each field is applied only when Set is true. For list fields, a nil slice with Set=true clears the field; model is never clearable.

type AgentPatch

type AgentPatch struct {
	Name            *string
	Model           *Model
	System          *NullableString
	Description     *NullableString
	Tools           *[]any
	MCPServers      *[]any
	Skills          *[]SkillReference
	Multiagent      *NullableMultiagent
	Metadata        map[string]any
	ExpectedVersion *int
}

type AgentReference

type AgentReference struct {
	Type       string `json:"type"`
	ID         string `json:"id,omitempty"`
	Version    int    `json:"version,omitempty"`
	Model      string `json:"model,omitempty"`
	StringForm bool   `json:"-"`
}

AgentReference accepts the documented roster input forms while giving the application service one type to resolve. A new persisted reference is always the object form with Type=agent and a positive Version. StringForm preserves the string union variant until resolution and across legacy storage reads.

func (AgentReference) MarshalJSON

func (r AgentReference) MarshalJSON() ([]byte, error)

func (*AgentReference) UnmarshalJSON

func (r *AgentReference) UnmarshalJSON(data []byte) error

type BuiltinConfig

type BuiltinConfig struct {
	Name    string
	Enabled *bool
	Policy  *PermissionPolicy
}

type BuiltinToolset

type BuiltinToolset struct {
	DefaultEnabled bool
	DefaultPolicy  PermissionPolicy
	Configs        []BuiltinConfig
}

type CacheCreationUsage

type CacheCreationUsage struct {
	Ephemeral1hInputTokens int64
	Ephemeral5mInputTokens int64
}

CacheCreationUsage is the prompt-cache creation breakdown exposed by the Mango Session usage object.

type Clock

type Clock interface{ Now() time.Time }

type ContentBlock

type ContentBlock struct {
	Type          string         // typed local blocks plus losslessly preserved provider-native block types
	Text          string         // text blocks; also flattened text of a tool_result
	ToolUseID     string         // tool_use: the event id
	ToolName      string         // tool_use: tool name
	Input         map[string]any // tool_use: arguments
	ToolResultFor string         // tool_result: the tool_use id it answers
	IsError       bool           // tool_result: error flag
	// ResultContent preserves rich user/custom/MCP tool-result items (text,
	// image, document, and search_result) without flattening them. Text remains
	// populated as a convenient projection for existing executors.
	ResultContent []json.RawMessage `json:"result_content,omitempty"`
	// Raw is the complete provider content block. Provider adapters populate it
	// for responses so unknown server-tool, citation, encrypted-continuation,
	// and future fields can be round-tripped without flattening. Locally created
	// blocks leave Raw empty and are encoded from the typed fields above.
	Raw json.RawMessage `json:"raw,omitempty"`
}

type ContextProjection

type ContextProjection struct {
	Compacted                bool `json:"compacted"`
	OriginalEstimatedTokens  int  `json:"original_estimated_tokens"`
	ProjectedEstimatedTokens int  `json:"projected_estimated_tokens"`
	DroppedMessages          int  `json:"dropped_messages"`
}

ContextProjection describes the private request-time projection of the lossless provider transcript. It is intentionally not a public Session resource: compaction changes what one model call sees, not the durable event or transcript history.

type ContextSnapshot

type ContextSnapshot struct {
	ID                        string            `json:"id"`
	SessionID                 string            `json:"session_id"`
	ThreadID                  string            `json:"thread_id"`
	TriggerEventID            string            `json:"trigger_event_id"`
	ParentSnapshotID          *string           `json:"parent_snapshot_id,omitempty"`
	TranscriptTriggerEventIDs []string          `json:"transcript_trigger_event_ids"`
	Messages                  []Message         `json:"messages"`
	Projection                ContextProjection `json:"projection"`
	ContextPolicyVersion      int               `json:"context_policy_version"`
	CreatedAt                 time.Time         `json:"created_at"`
}

ContextSnapshot is an internal immutable record of the compacted message projection used to prepare one Thread turn. It is not part of the public Mango resource model; the public evidence of compaction is the agent.thread_context_compacted event on the owning Thread ledger.

type ContextUsageAnchor

type ContextUsageAnchor struct {
	Usage              ContextWindowUsage `json:"usage"`
	RequestFingerprint string             `json:"request_fingerprint"`
	PrefixFingerprint  string             `json:"prefix_fingerprint"`
	ContentBlocks      int                `json:"content_blocks"`
}

ContextUsageAnchor records the exact size of one completed provider request plus its response. RequestFingerprint protects the baseline when the model, system prompt, tools, or other request settings change. PrefixFingerprint protects it when compaction or another projection changes messages that the provider usage had measured. ContentBlocks marks the response boundary when adjacent assistant messages are merged to preserve role alternation.

type ContextWindowUsage

type ContextWindowUsage struct {
	CacheCreation        CacheCreationUsage
	CacheReadInputTokens int64
	InputTokens          int64
	OutputTokens         int64
}

ContextWindowUsage is the provider usage subset needed to anchor context measurements. Pricing, routing, execution-mode, and server-tool facts do not belong in persisted conversation messages or subsequent model prompts.

func (ContextWindowUsage) ContextTokens

func (u ContextWindowUsage) ContextTokens() int64

ContextTokens returns the provider-measured context immediately after one response. Anthropic reports uncached input, cache creation, and cache reads as disjoint input buckets; all occupy the request context. Output is included because the assistant response becomes input to the next request.

type CredentialAuth

type CredentialAuth struct {
	Type         string              `json:"type"`
	MCPServerURL string              `json:"mcp_server_url"`
	ExpiresAt    *time.Time          `json:"expires_at,omitempty"`
	Refresh      *OAuthRefreshPublic `json:"refresh,omitempty"`
}

CredentialAuth is safe to return from the public API and persist as JSON. It deliberately cannot represent an access token, bearer token, refresh token, or OAuth client secret.

type CustomTool

type CustomTool struct {
	Name        string
	Description string
	InputSchema map[string]any
}

type Deployment

type Deployment struct {
	ID                string
	AgentID           string
	AgentVersion      int
	EnvironmentID     string
	Name              string
	Description       string
	InitialEvents     []EventDraft
	Resources         []DeploymentResource
	VaultIDs          []string
	Budget            *SessionBudget
	Metadata          map[string]string
	Schedule          *DeploymentSchedule
	Status            string
	PausedReason      *DeploymentPausedReason
	CreatedAt         time.Time
	UpdatedAt         time.Time
	ArchivedAt        *time.Time
	ScheduleClaimedAt *time.Time
}

Deployment is the durable autonomous-session template. AgentVersion is always resolved when the deployment is created or explicitly re-pinned so a later Agent update cannot silently alter scheduled work.

type DeploymentPatch

type DeploymentPatch struct {
	AgentID       *string
	AgentVersion  *int
	EnvironmentID *string
	Name          *string
	Description   *string
	InitialEvents *[]EventDraft
	Resources     *[]DeploymentResource
	VaultIDs      *[]string
	Metadata      map[string]*string
	ScheduleSet   bool
	Schedule      *DeploymentSchedule
	BudgetSet     bool
	Budget        *SessionBudget
}

type DeploymentPausedReason

type DeploymentPausedReason struct {
	Type      string
	ErrorType string
}

type DeploymentResource

type DeploymentResource struct {
	Type          string
	MemoryStoreID string
	Access        string
	Instructions  string
}

DeploymentResource is the Memory Store binding retained by a deployment.

type DeploymentRun

type DeploymentRun struct {
	ID           string
	DeploymentID string
	AgentID      string
	AgentVersion int
	SessionID    *string
	ErrorType    string
	ErrorMessage string
	TriggerType  string
	ScheduledAt  *time.Time
	CreatedAt    time.Time
}

type DeploymentSchedule

type DeploymentSchedule struct {
	Expression     string
	Timezone       string
	LastRunAt      *time.Time
	UpcomingRunsAt []time.Time
}

type DomainError

type DomainError struct {
	Kind    ErrKind
	Code    string
	Message string
}

func Conflict

func Conflict(msg string) *DomainError

func MemoryPrecondition

func MemoryPrecondition(msg string) *DomainError

func NotFound

func NotFound(msg string) *DomainError

func Permission

func Permission(msg string) *DomainError

func Precondition

func Precondition(msg string) *DomainError

func TooLarge

func TooLarge(msg string) *DomainError

func Unsupported

func Unsupported(msg string) *DomainError

func Validation

func Validation(msg string) *DomainError

func (*DomainError) Error

func (e *DomainError) Error() string

type Environment

type Environment struct {
	ID          string
	Name        string
	Description string
	Metadata    map[string]any
	Scope       string
	ConfigType  string // "self_hosted"
	Config      map[string]any
	CreatedAt   time.Time
	UpdatedAt   time.Time
	ArchivedAt  *time.Time
}

func (Environment) Apply

func (e Environment) Apply(patch EnvironmentPatch) (Environment, bool)

func (Environment) SessionConfig

func (e Environment) SessionConfig() map[string]any

SessionConfig returns an isolated JSON-shaped copy of the worker configuration captured for a Session.

type EnvironmentPatch

type EnvironmentPatch struct {
	Name        *string
	Description *string
	Metadata    map[string]any
	Scope       *string
	Config      *map[string]any
}

EnvironmentPatch is the domain form of POST /v1/environments/{id}. Nil pointers preserve scalar fields. Metadata is a per-key patch: null and empty string delete a key, matching the public Environment update contract.

type EnvironmentWork

type EnvironmentWork struct {
	ID            string
	EnvironmentID string
	SessionID     string
	Type          string
	ExpiresAt     *time.Time
	Result        *EnvironmentWorkResult
	// Secret is populated only for the worker that tentatively claimed this
	// activation. Persistence stores only its digest, and read/list surfaces
	// redact it.
	Secret            string
	State             EnvironmentWorkState
	Metadata          map[string]string
	CreatedAt         time.Time
	AcknowledgedAt    *time.Time
	StartedAt         *time.Time
	LatestHeartbeatAt *time.Time
	StopRequestedAt   *time.Time
	StoppedAt         *time.Time
	TTLSeconds        int64
}

EnvironmentWork is a durable execution lease for a self-hosted Session or a bounded Environment healthcheck.

type EnvironmentWorkHeartbeat

type EnvironmentWorkHeartbeat struct {
	LastHeartbeat time.Time
	LeaseExtended bool
	State         EnvironmentWorkState
	TTLSeconds    int64
}

type EnvironmentWorkQueueStats

type EnvironmentWorkQueueStats struct {
	Depth          int64
	Pending        int64
	OldestQueuedAt *time.Time
	WorkersPolling int64
}

type EnvironmentWorkResult

type EnvironmentWorkResult struct {
	Status  string `json:"status"`
	Message string `json:"message"`
}

type EnvironmentWorkState

type EnvironmentWorkState string
const (
	EnvironmentWorkQueued   EnvironmentWorkState = "queued"
	EnvironmentWorkStarting EnvironmentWorkState = "starting"
	EnvironmentWorkActive   EnvironmentWorkState = "active"
	EnvironmentWorkStopping EnvironmentWorkState = "stopping"
	EnvironmentWorkStopped  EnvironmentWorkState = "stopped"
)

type ErrKind

type ErrKind int
const (
	KindValidation ErrKind = iota
	KindConflict
	KindNotFound
	KindUnsupported
	KindTooLarge
	KindPrecondition
	KindPermission
)

type Event

type Event struct {
	ID        string
	SessionID string
	// ThreadID is the ledger that owns this event. Sequence remains Session-wide
	// so aggregate ordering and cross-post causality have one durable cursor.
	ThreadID string
	Sequence int64
	Type     string
	Payload  map[string]any
	// TurnEventID is internal causal metadata. A non-nil value means this event
	// was output of that model-driving turn, not a second independent trigger.
	// HTTP projections intentionally omit it.
	TurnEventID *string `json:"-"`
	CreatedAt   time.Time
	ProcessedAt *time.Time
}

Event is the internal representation of a persisted session event. Sequence is an internal ordering key and must never appear on the public wire.

type EventDraft

type EventDraft struct {
	ID      string
	Type    string
	Payload map[string]any
}

EventDraft is an event about to be persisted. Payload holds the type-specific top-level fields (everything except "type"); it is flattened onto the wire object, never nested under a "payload" key.

ID is normally empty: the store assigns the committed id at persist time. A server-side emitter (the runtime sink) may pre-assign the committed id so it can reference the event before the persist transaction runs — for example to correlate a tool_result to its tool_use, or to name the parked agent.custom_tool_use / agent.tool_use events in a requires_action stop reason. Client-submitted events never carry an id (rejected at the edge).

type File

type File struct {
	// SessionID pins generated tool output while its owning Session exists.
	SessionID      string
	ID             string
	CreatedAt      time.Time
	UpdatedAt      time.Time
	Filename       string
	MimeType       string
	SizeBytes      int64
	BlobKey        string
	ChecksumSHA256 string
	State          FileState
}

File is the authoritative metadata projection for one object-store blob. BlobKey and ChecksumSHA256 are persistence/runtime fields and never cross the public wire.

type FileMessageContent

type FileMessageContent struct {
	ContentIndex int
	FileID       string
	Filename     string
	MimeType     string
	Content      string
}

FileMessageContent is the private, admission-time snapshot of one public document source that references a File. The public event retains only the file_id; the provider receives Content as an ordinary text block.

type FileState

type FileState string

FileState is internal lifecycle state. Only ready files are visible through the public API; uploading and deleting rows are durable reconciliation intents.

const (
	FileStateUploading FileState = "uploading"
	FileStateReady     FileState = "ready"
	FileStateDeleting  FileState = "deleting"
)

type FixedClock

type FixedClock struct{ T time.Time }

func (FixedClock) Now

func (c FixedClock) Now() time.Time

type IDGenerator

type IDGenerator interface{ NewID(prefix string) string }

type MCPServer

type MCPServer struct {
	Name string
	URL  string
}

type MCPToolset

type MCPToolset struct {
	ServerName     string
	DefaultEnabled bool
	DefaultPolicy  PermissionPolicy
	Configs        []BuiltinConfig
}

func (MCPToolset) ToolEnabled

func (ts MCPToolset) ToolEnabled(name string) (bool, PermissionPolicy)

type Memory

type Memory struct {
	ID              string
	MemoryStoreID   string
	MemoryVersionID string
	Path            string
	Content         string
	ContentSize     int64
	ContentSHA256   string
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

Memory is the current head of one path-addressed UTF-8 document.

type MemoryActor

type MemoryActor struct {
	Type string
	ID   string
}

type MemoryListItem

type MemoryListItem struct {
	Memory *Memory
	Prefix string
}

type MemoryStore

type MemoryStore struct {
	ID          string
	Name        string
	Description string
	Metadata    map[string]string
	CreatedAt   time.Time
	UpdatedAt   time.Time
	ArchivedAt  *time.Time
}

MemoryStore is the durable, Workspace-scoped container exposed by the Mango Memory API. Ownership stays in the relational root instead of leaking into the CMA wire representation.

type MemoryVersion

type MemoryVersion struct {
	ID            string
	MemoryStoreID string
	MemoryID      string
	Operation     string
	Path          *string
	Content       *string
	ContentSize   *int64
	ContentSHA256 *string
	CreatedAt     time.Time
	CreatedBy     MemoryActor
	RedactedAt    *time.Time
	RedactedBy    *MemoryActor
}

MemoryVersion is one immutable audit snapshot. Delete rows and redacted rows deliberately carry nil content fields while retaining lineage and actors.

type Message

type Message struct {
	Role    Role
	Content []ContentBlock
	// ContextUsage is private continuation metadata. It anchors one provider
	// response to the exact request usage the provider reported, allowing the
	// next request to measure only messages added after that response. Provider
	// adapters intentionally serialize only Role and Content.
	ContextUsage *ContextUsageAnchor `json:"context_usage,omitempty"`
}

func ProjectMessages

func ProjectMessages(events []Event) []Message

ProjectMessages folds an ordered session event log into a Messages-API conversation. User messages, cross-Thread messages, Agent messages, and paired tool calls/results become model input; status, error, and other server-only events are skipped. This is where "the server owns history" is realized: the durable event log is the single truth, projected to the model every turn.

The real Messages API requires strictly alternating roles. Two real flows produce consecutive same-role messages: a user sending several user.message events before drainRuns claims them, and a model turn that emits no text (so no agent.message) leaving two user turns adjacent. To keep the request legal we merge adjacent same-role messages into one, concatenating their content blocks in order. This is a pure transformation of the event log.

type Model

type Model struct {
	ID     string
	Effort string
	Speed  string
	// EffortExplicit and SpeedExplicit distinguish an explicit Agent setting
	// from the Mango defaults echoed in the resolved resource. The
	// Messages adapter uses this distinction to avoid sending preview fields to
	// endpoints when the caller only accepted the platform default.
	EffortExplicit bool
	SpeedExplicit  bool
}

func NormalizeModel

func NormalizeModel(model Model) Model

NormalizeModel fills the defaults the Mango API exposes on a resolved Agent while preserving whether the user supplied each value.

type Multiagent

type Multiagent struct {
	Type   string           `json:"type"`
	Agents []AgentReference `json:"agents"`
	// contains filtered or unexported fields
}

Multiagent is the immutable, version-pinned coordinator roster stored on an Agent Version. New writes contain only concrete agent references. The custom roster-entry decoder keeps Agents written by older Mango releases readable; application admission never treats those unresolved legacy entries as an executable roster.

func (*Multiagent) Advisor

func (m *Multiagent) Advisor() *Advisor

Advisor returns the single resolved advisor roster entry, if configured.

func (*Multiagent) Clone

func (m *Multiagent) Clone() *Multiagent

func (*Multiagent) HasCallableAgents

func (m *Multiagent) HasCallableAgents() bool

HasCallableAgents reports whether the roster contains any ordinary Agent that may be listed or messaged by the coordinator toolset. Advisors are intentionally excluded from that private protocol.

func (*Multiagent) HasExternalAgent

func (m *Multiagent) HasExternalAgent(ownerID string) bool

HasExternalAgent reports whether the resolved roster contains an Agent other than the owning coordinator. Session model overrides also apply to self copies, but never to independently referenced Agents, so callers use this to enforce roster-wide model constraints without resolving immutable versions a second time.

func (*Multiagent) IsLegacy

func (m *Multiagent) IsLegacy() bool

func (*Multiagent) IsResolved

func (m *Multiagent) IsResolved() bool

func (Multiagent) MarshalJSON

func (m Multiagent) MarshalJSON() ([]byte, error)

func (*Multiagent) RebindAgentVersion

func (m *Multiagent) RebindAgentVersion(ownerID string, version int) *Multiagent

RebindAgentVersion returns a copy whose reference to the owning coordinator points at version. Direct references to the owner are rejected during roster resolution, so an owner-ID entry can only have originated from {"type":"self"}.

func (*Multiagent) UnmarshalJSON

func (m *Multiagent) UnmarshalJSON(data []byte) error

type NullableMultiagent

type NullableMultiagent struct {
	Value *Multiagent
}

NullableMultiagent preserves the update tri-state: an omitted patch leaves the roster unchanged, Value=nil clears it, and a non-nil Value replaces it.

type NullableString

type NullableString struct {
	Set   bool
	Value *string
}

type OAuthRefreshPublic

type OAuthRefreshPublic struct {
	ClientID          string  `json:"client_id"`
	TokenEndpoint     string  `json:"token_endpoint"`
	TokenEndpointAuth string  `json:"token_endpoint_auth_type"`
	Resource          *string `json:"resource"`
	Scope             *string `json:"scope"`
}

OAuthRefreshPublic contains only the non-secret part of an OAuth refresh configuration. Refresh tokens and client secrets live exclusively inside the encrypted credential payload.

type OutcomeEvaluation

type OutcomeEvaluation struct {
	OutcomeID   string
	Description string
	Result      string
	Explanation string
	Iteration   int
	CompletedAt *time.Time
}

OutcomeEvaluation is the Session-level projection for one define_outcome event. Span events remain the detailed history; this projection supports polling the Session resource.

type OutcomeSpec

type OutcomeSpec struct {
	OutcomeID     string
	Description   string
	Rubric        map[string]any
	MaxIterations int
}

type PendingAction

type PendingAction struct {
	ID                  string
	SessionID           string
	ThreadID            string
	ActionEventID       string
	ClientActionEventID string
	Kind                PendingActionKind
	// ApprovalEventID is the durable allow receipt for an external tool. It
	// advances the expected response to tool_result without resolving the call.
	ApprovalEventID  *string
	ResolvingEventID *string
	CreatedAt        time.Time
	ResolvedAt       *time.Time
}

PendingAction is a first-class durable record that a run parked awaiting a client response. It is internal-only and never serialized onto the public Mango wire. ResolvedAt is nil while the action still blocks ordinary queued work on its owning Thread.

type PendingActionKind

type PendingActionKind string

PendingActionKind is the next expected response for a parked action. It is derived from the committed action event's type and payload, then may advance after a durable approval — never from an arbitrary caller-provided kind.

const (
	// PendingCustomToolResult is parked by an agent.custom_tool_use event and is
	// resolved by a user.custom_tool_result whose custom_tool_use_id references
	// the parked event.
	PendingCustomToolResult PendingActionKind = "custom_tool_result"
	// PendingToolConfirmation is parked by an always_ask agent.tool_use event and
	// is resolved by a user.tool_confirmation whose tool_use_id references the
	// parked event. Allow executes a server-owned tool or advances an external
	// call to PendingToolResult; deny produces an error result without execution.
	PendingToolConfirmation PendingActionKind = "tool_confirmation"
	// PendingToolResult is parked by a self-hosted agent.tool_use. The client
	// executes the sandbox-routed tool and resolves it with user.tool_result.
	PendingToolResult PendingActionKind = "tool_result"
)

func PendingActionKindForEvent

func PendingActionKindForEvent(eventType string, payload map[string]any) (PendingActionKind, bool)

PendingActionKindForEvent derives the expected response kind for a parked action event from its committed type AND payload. ok is false when the event cannot park a run.

Server-executed agent.tool_use and agent.mcp_tool_use park only for "ask"; permitted calls execute inline and denied calls are not confirmation gates. Self-hosted agent.tool_use parks for confirmation on "ask" or a result on "allow". Execution ownership must never bypass the permission gate. agent.custom_tool_use always parks regardless of payload.

func ResolutionReference

func ResolutionReference(eventType string, payload map[string]any) (actionEventID string, kind PendingActionKind, ok bool)

ResolutionReference reports whether an event resolves a pending action and, if so, the parked action event id it references and the kind it satisfies. The referenced id lives in a type-specific payload field (custom_tool_use_id for user.custom_tool_result, tool_use_id for user.tool_confirmation); a resolution event missing that field returns ok=false.

user.tool_confirmation keeps tool_use_id for both agent.tool_use and agent.mcp_tool_use parks: the documented confirmation input has exactly one id field and never a separate MCP spelling.

type PermissionIntent

type PermissionIntent struct {
	AgentSystem string                  `json:"agent_system"`
	Entries     []PermissionIntentEntry `json:"entries"`
	Complete    bool                    `json:"complete"`
}

PermissionIntent retains original client provenance before working-model projection or compaction. Complete=false never grants automatic authority.

type PermissionIntentEntry

type PermissionIntentEntry struct {
	EventID  string `json:"event_id"`
	ThreadID string `json:"thread_id"`
	Type     string `json:"type"`
	Text     string `json:"text"`
}

type PermissionPolicy

type PermissionPolicy struct{ Type string }

type PreviewFrame

type PreviewFrame struct {
	ThreadID            string // empty for the primary stream; child Thread otherwise
	Kind                string // PreviewEventStart | PreviewEventDelta
	EventID             string // the id of the event being previewed (== the eventual persisted event id)
	EventType           string // event_start: the previewed event's type (e.g. "agent.message")
	ModelRequestStartID string // internal correlation fence; deliberately omitted from WireJSON
	Index               int    // event_delta: content block index
	Text                string // event_delta: incremental text
}

PreviewFrame is a stream-only preview of an event being generated. Preview frames are NEVER persisted and never appear in the event history; they are delivered only to stream subscribers that opted in via event_deltas[].

func (PreviewFrame) WireJSON

func (f PreviewFrame) WireJSON() map[string]any

type ProviderToolUseMapping

type ProviderToolUseMapping struct {
	PublicEventID     string `json:"public_event_id"`
	ProviderToolUseID string `json:"provider_tool_use_id"`
	ToolName          string `json:"tool_name"`
}

ProviderToolUseMapping keeps provider-private tool ids separate from the stable public event ids exposed by Mango.

type ProviderTranscript

type ProviderTranscript struct {
	Messages        []Message                `json:"messages"`
	TriggerEventIDs []string                 `json:"trigger_event_ids"`
	ToolUseMappings []ProviderToolUseMapping `json:"tool_use_mappings"`
}

ProviderTranscript is the committed, lossless model-continuation history for one Session. TriggerEventIDs identifies which public turns are represented so a caller can safely fall back for sessions created before transcript support.

type RandomIDGen

type RandomIDGen struct{}

RandomIDGen produces process-unique ids like "agent_9f8c1a2b3c4d5e6f" using crypto/rand. Suitable for the real server where ids must not collide across restarts (unlike SeqIDGen, whose counter resets each process start).

func NewRandomIDGen

func NewRandomIDGen() *RandomIDGen

func (RandomIDGen) NewID

func (RandomIDGen) NewID(prefix string) string

type Role

type Role string
const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

type RunAttempt

type RunAttempt struct {
	ID         string
	RunID      string
	AttemptNo  int
	State      RunAttemptState
	Error      *string
	CreatedAt  time.Time
	UpdatedAt  time.Time
	FinishedAt *time.Time
}

RunAttempt is internal execution bookkeeping and is never serialized onto the Mango public API.

type RunAttemptState

type RunAttemptState string

RunAttemptState is the durable lifecycle of one execution attempt for a logical SessionRun. A retry creates another attempt; it never rewrites the facts recorded by an earlier attempt.

const (
	RunAttemptActive      RunAttemptState = "active"
	RunAttemptCompleted   RunAttemptState = "completed"
	RunAttemptFailed      RunAttemptState = "failed"
	RunAttemptInterrupted RunAttemptState = "interrupted"
)

type RunState

type RunState string
const (
	RunQueued    RunState = "queued"
	RunRunning   RunState = "running"
	RunCompleted RunState = "completed"
	RunFailed    RunState = "failed"
)

type SecretEnvelope

type SecretEnvelope struct {
	Version    int
	Algorithm  string
	KeyID      string
	Nonce      []byte
	Ciphertext []byte
}

SecretEnvelope is the versioned, authenticated encrypted form persisted in PostgreSQL. KeyID selects a decrypt-only or active key in the process-local keyring; Algorithm and Version make rotations and future format migrations explicit.

type SeqIDGen

type SeqIDGen struct {
	// contains filtered or unexported fields
}

func NewSeqIDGen

func NewSeqIDGen() *SeqIDGen

func (*SeqIDGen) NewID

func (g *SeqIDGen) NewID(prefix string) string

type ServerToolUsage

type ServerToolUsage struct {
	WebFetchRequests  int64
	WebSearchRequests int64
}

ServerToolUsage is the provider-reported count of server-executed tools. Web search has a per-request public list price; web fetch is currently reported for observability but has no separate request fee.

type Session

type Session struct {
	// WorkspaceID is Mango's internal tenant boundary. It is never serialized
	// into the CMA projection or exposed on the public wire.
	WorkspaceID   string `json:"-"`
	ID            string
	AgentID       string
	AgentVersion  int
	EnvironmentID string
	// DeploymentID identifies sessions created by an autonomous Deployment.
	// It is immutable and nil for sessions created directly through /sessions.
	DeploymentID *string
	// EnvironmentType is captured with the session so tool routing remains
	// stable even if the environment resource is later archived. Empty on older
	// sessions means cloud.
	EnvironmentType string
	// EnvironmentConfig is the immutable sandbox configuration captured when
	// the Session is created. It is internal execution state and is not exposed
	// in the public Session response.
	EnvironmentConfig map[string]any
	Status            Status
	Title             string
	Metadata          map[string]any
	// AgentSnapshot is the resolved agent definition captured at session
	// creation time, after version pinning and any per-session overrides. It is
	// the immutable public projection returned as the session's `agent` field.
	// Later updates or archival of the underlying agent must never mutate it.
	AgentSnapshot Agent
	// MultiagentRoster contains the full, immutable Agent snapshots resolved for
	// the coordinator at Session creation time. Agent resources store only
	// version pins in AgentSnapshot.Multiagent; the Session contract expands
	// those pins so child Threads never need to reinterpret "latest" or observe
	// a later Agent mutation. A self entry is copied from AgentSnapshot after
	// Session overrides have been applied.
	MultiagentRoster []Agent
	Usage            TokenUsage
	// ModelListCostNanoUSD is the exact accumulated token and provider-native
	// server-tool list cost. Session runtime is priced live from ActiveSeconds.
	ModelListCostNanoUSD int64
	// ListCostKnown is false when any used model lacks a canonical Anthropic
	// public price, or when legacy usage predates per-request accounting.
	// Budgeted Sessions validate their full roster up front so it remains true.
	ListCostKnown bool
	Budget        *SessionBudget
	Outcomes      []OutcomeEvaluation
	Resources     []SessionResource
	// VaultIDs is the immutable, ordered Vault selection captured when the
	// Session is created. Runtime credential resolution preserves this order.
	VaultIDs []string
	// ActiveSeconds is the completed running time. RunningSince contributes a
	// live suffix while the Session is running. TerminatedAt freezes duration.
	ActiveSeconds float64
	RunningSince  *time.Time
	TerminatedAt  *time.Time
	CreatedAt     time.Time
	UpdatedAt     time.Time
	ArchivedAt    *time.Time
}

func (Session) ActiveOutcome

func (s Session) ActiveOutcome() *OutcomeEvaluation

func (*Session) ApplyOutcomeResult

func (s *Session) ApplyOutcomeResult(
	outcomeID string,
	result string,
	explanation string,
	iteration int,
	now time.Time,
)

func (Session) ApplyUpdate

func (s Session) ApplyUpdate(u SessionUpdate) (Session, SessionChange, error)

ApplyUpdate returns the Session that results from an update request together with the set of fields it changed. It is pure so the storage layer can run it inside the same transaction that holds the per-session admission lock.

The agent portion changes only the Session's resolved snapshot. The stored Agent version it was resolved from is never mutated, matching the documented rule that session updates do not propagate back to the agent.

func (Session) BudgetJSON

func (s Session) BudgetJSON() any

func (Session) BudgetReached

func (s Session) BudgetReached(now time.Time) bool

func (*Session) MarkActiveOutcomeRunning

func (s *Session) MarkActiveOutcomeRunning()

func (Session) ObservableListCostNanoUSD

func (s Session) ObservableListCostNanoUSD(now time.Time) int64

ObservableListCostNanoUSD returns the live Session list cost, including the de-duplicated runtime suffix while the aggregate Session is running.

func (Session) ObservableStats

func (s Session) ObservableStats(now time.Time) (activeSeconds, durationSeconds float64)

ObservableStats returns the current public timing values. Duration continues while a Session is idle and freezes only when it terminates.

func (Session) ResolvedAgentSnapshotJSON

func (s Session) ResolvedAgentSnapshotJSON() map[string]any

ResolvedAgentSnapshotJSON returns the public Session Agent projection. Agent resources expose a coordinator roster as version references, while Sessions expose the full definitions captured in MultiagentRoster. Thread snapshots omit multiagent entirely because roster ownership belongs to the coordinator Session rather than any child execution.

func (*Session) StartOutcome

func (s *Session) StartOutcome(spec OutcomeSpec) error

func (*Session) TransitionStatus

func (s *Session) TransitionStatus(next Status, now time.Time)

TransitionStatus updates the Session's timing projection at the same linearization point as the status change.

func (Session) UsageEventPayload

func (s Session) UsageEventPayload(now time.Time) map[string]any

func (Session) UsageJSON

func (s Session) UsageJSON(now time.Time) map[string]any

UsageJSON is the public cumulative Session usage projection. Runtime cost is included only at Session scope; Thread usage uses its model/tool cost alone.

type SessionBudget

type SessionBudget struct {
	MaxListCostCents int64
}

SessionBudget is the Session-wide public-list-cost ceiling. MonetaryAmount uses minor currency units, so MaxListCostCents is the exact parsed `amount`.

func (SessionBudget) JSON

func (b SessionBudget) JSON() map[string]any

type SessionBudgetUpdate

type SessionBudgetUpdate struct {
	Budget *SessionBudget
}

SessionBudgetUpdate carries the update body's budget tri-state. A nil *SessionBudgetUpdate means omitted; a non-nil update with Budget nil means explicitly remove the existing ceiling.

type SessionChange

type SessionChange struct {
	Title    bool
	Metadata bool
	Agent    bool
	Budget   bool
}

SessionChange records which public fields an update actually changed. The `session.updated` event carries only those fields.

func (SessionChange) Any

func (c SessionChange) Any() bool

type SessionResource

type SessionResource struct {
	ID                     string
	SessionID              string
	ResourceType           string
	MemoryStoreID          string
	MemoryAccess           string
	MemoryInstructions     string
	MemoryStoreName        string
	MemoryStoreDescription string
	MountPath              string
	CreatedAt              time.Time
	UpdatedAt              time.Time
	State                  SessionResourceState
}

SessionResource is a durable Memory Store binding. File and repository staging belong to the operator-owned self-hosted worker workspace.

func (SessionResource) Type

func (r SessionResource) Type() string

type SessionResourceState

type SessionResourceState string
const (
	SessionResourceActive   SessionResourceState = "active"
	SessionResourceDeleting SessionResourceState = "deleting"
)

type SessionRun

type SessionRun struct {
	ID              string
	SessionID       string
	AdmissionSeq    int64
	TriggerEventIDs []string
	// OutputEventIDs are the exact committed event ids this run appended when it
	// closed (agent output plus the run's terminal/status events), persisted in
	// the same transaction that closes the run. Empty until completion. This is
	// internal-only durable state and is never serialized onto the public API.
	OutputEventIDs []string
	State          RunState
	Error          *string
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

SessionRun is an internal durable work item. It is never serialized onto the Mango public API.

type SessionThread

type SessionThread struct {
	ID             string
	SessionID      string
	ParentThreadID *string
	Agent          Agent
	// Advisor is non-nil only for a platform-spawned consultation Thread. Such a
	// Thread never executes the ordinary child Workflow or exposes Agent fields.
	Advisor              *Advisor
	Status               Status
	Usage                TokenUsage
	ModelListCostNanoUSD int64
	ListCostKnown        bool
	BudgetPaused         bool
	ActiveSeconds        float64
	RunningSince         *time.Time
	TerminatedAt         *time.Time
	StartupSeconds       float64
	CreatedAt            time.Time
	UpdatedAt            time.Time
	ArchivedAt           *time.Time
}

SessionThread is a durable execution identity exposed below a Session. Every Thread owns its Agent snapshot, status, timing, and usage projection. A Session aggregates those projections; it is not the storage backing for the primary Thread.

func NewAdvisorSessionThread

func NewAdvisorSessionThread(
	id string,
	sessionID string,
	parentThreadID string,
	advisor Advisor,
	usage TokenUsage,
	listCostNanoUSD int64,
	listCostKnown bool,
	now time.Time,
) SessionThread

NewAdvisorSessionThread returns the final projection of one Mango-managed consultation. The Thread is born and terminates within one private client-tool execution; its lifecycle remains observable through the independent ledger.

func NewChildSessionThread

func NewChildSessionThread(
	id string,
	sessionID string,
	parentThreadID string,
	agent Agent,
	now time.Time,
) SessionThread

NewChildSessionThread captures one callable roster member for independent execution inside a Session. The Agent is already a full Session-owned snapshot; no Agent resource lookup belongs on this path.

func NewPrimarySessionThread

func NewPrimarySessionThread(id string, session Session) SessionThread

NewPrimarySessionThread captures the execution fields of a newly created Session in its primary Thread. Identity and creation time remain stable after this point even as the Session aggregate changes.

func (SessionThread) AgentName

func (t SessionThread) AgentName() string

func (*SessionThread) ApplyIndependentPrimarySessionProjection

func (t *SessionThread) ApplyIndependentPrimarySessionProjection(session Session)

ApplyIndependentPrimarySessionProjection synchronizes Session-owned control fields without replacing the primary Thread's execution projection. In a multi-agent Session, usage, list cost, status, and timing are owned by each Thread and must not be copied back from the Session aggregate.

func (*SessionThread) ApplyPrimarySessionProjection

func (t *SessionThread) ApplyPrimarySessionProjection(session Session)

ApplyPrimarySessionProjection synchronizes the existing single-Thread runtime into its independent primary projection. Once child execution is enabled, child writers update their own Thread first and the Session layer recomputes its aggregate separately; Thread reads remain unchanged.

func (SessionThread) ObservableStats

func (t SessionThread) ObservableStats(now time.Time) (activeSeconds, durationSeconds float64)

ObservableStats returns the live timing projection for a thread. Duration freezes when a thread is archived or terminated.

func (*SessionThread) TransitionStatus

func (t *SessionThread) TransitionStatus(next Status, now time.Time)

TransitionStatus updates a Thread's independent timing projection. Session aggregation is performed by the storage transaction after the owning Thread moves; it must never be copied back into sibling Thread projections.

type SessionUpdate

type SessionUpdate struct {
	// Title replaces the human-readable title when non-nil.
	Title *string
	// Metadata is a per-key patch, not a replacement: a present key with a nil
	// value deletes it and any other value upserts it. A nil map preserves the
	// whole bag. This differs from the create-time metadata bag on purpose.
	Metadata map[string]any
	// AgentTools and AgentMCPServers are session-local full replacements of the
	// resolved snapshot's lists. A non-nil pointer replaces (an empty or nil
	// slice clears); a nil pointer preserves. They never touch the underlying
	// Agent resource or its version.
	AgentTools      *[]any
	AgentMCPServers *[]any
	Budget          *SessionBudgetUpdate
}

SessionUpdate is the domain form of the documented `POST /v1/sessions/{session_id}` body. Each field carries its own tri-state so the transport layer can distinguish "omitted" from "explicitly cleared" without the state machine re-parsing JSON.

`vault_ids` is intentionally absent: the official API documents it as rejected, so it never reaches the domain.

func (SessionUpdate) IsEmpty

func (u SessionUpdate) IsEmpty() bool

IsEmpty reports whether the request carried no update fields at all. Such a request is a plain read and never needs the session's admission lock.

func (SessionUpdate) TouchesAgent

func (u SessionUpdate) TouchesAgent() bool

TouchesAgent reports whether the update carries a mid-session agent configuration change, which the official contract only permits while the Session is idle.

type Skill

type Skill struct {
	ID            string
	CreatedAt     time.Time
	UpdatedAt     time.Time
	DisplayTitle  string
	LatestVersion string
	Source        string
	TitleExplicit bool
	Ready         bool
}

Skill is the stable identity for a custom Skill. LatestVersion is empty when every immutable Version has been deleted.

type SkillReference

type SkillReference struct {
	Type    string `json:"type"`
	SkillID string `json:"skill_id"`
	Version string `json:"version,omitempty"`
}

SkillReference is the resolved Skill configuration stored on an Agent or Session snapshot. Requests may omit Version or send "latest"; application services replace either form with the concrete immutable Version before the resource crosses a persistence boundary.

type SkillRuntime

type SkillRuntime struct {
	Root     string
	Versions []SkillVersion
}

SkillRuntime is the immutable custom Skill surface selected for one Session Agent execution scope. Multiple Threads running the same resolved Agent may share this bundle; their conversation context remains independent.

func (SkillRuntime) SkillPath

func (r SkillRuntime) SkillPath(name string) string

type SkillVersion

type SkillVersion struct {
	ID          string
	SkillID     string
	Version     string
	CreatedAt   time.Time
	Description string
	Directory   string
	Name        string
	BlobKey     string
	SizeBytes   int64
	// UncompressedSizeBytes is the exact byte footprint of the validated
	// canonical bundle before zip compression. Runtime admission uses it to
	// bound per-Session staging independently of compression ratio.
	UncompressedSizeBytes int64
	ChecksumSHA256        string
	State                 SkillVersionState
	Initial               bool
}

SkillVersion is immutable public metadata plus the private archive pointer and reconciliation state needed to keep PostgreSQL and object storage in agreement.

type SkillVersionState

type SkillVersionState string

SkillVersionState is internal lifecycle state around object-store I/O. Only ready Versions cross the public API boundary.

const (
	SkillVersionUploading SkillVersionState = "uploading"
	SkillVersionReady     SkillVersionState = "ready"
	SkillVersionDeleting  SkillVersionState = "deleting"
)

type Status

type Status string
const (
	StatusIdle         Status = "idle"
	StatusRunning      Status = "running"
	StatusRescheduling Status = "rescheduling"
	StatusTerminated   Status = "terminated"
)

func (Status) CanTransitionTo

func (s Status) CanTransitionTo(next Status) bool

type TokenUsage

type TokenUsage struct {
	CacheCreation        CacheCreationUsage
	CacheReadInputTokens int64
	InputTokens          int64
	OutputTokens         int64
	ServerToolUse        ServerToolUsage
	// Speed is the provider-reported inference mode for one model request. It is
	// intentionally not accumulated into Session usage; span events use it to
	// report the actual mode (which may differ from a requested fast fallback).
	Speed string
	// ProviderRegion is the provider-reported region for one model request. It is
	// retained only for internal list-cost accounting and is not accumulated or
	// exposed through Mango's public Agent, Session, or usage resources.
	ProviderRegion string
}

TokenUsage is cumulative model usage. Individual model responses carry a value with the same shape; Workflow code sums every provider round in a public turn and PostgreSQL applies the turn total exactly once.

func (*TokenUsage) Add

func (u *TokenUsage) Add(other TokenUsage)

func (TokenUsage) ForContextWindow

func (u TokenUsage) ForContextWindow() ContextWindowUsage

type ToolPermissionDecision

type ToolPermissionDecision struct {
	Type       string `json:"type"`
	ReasonCode string `json:"reason_code,omitempty"`
}

ToolPermissionDecision is one invocation's judgment, independent of its execution owner. Reason codes are machine-readable audit values.

func (ToolPermissionDecision) Valid

func (d ToolPermissionDecision) Valid() bool

type ToolPermissionEvaluation

type ToolPermissionEvaluation struct {
	Type                string                  `json:"type"`
	EvaluatedPermission *ToolPermissionDecision `json:"evaluated_permission,omitempty"`
}

type ToolPermissionOwner

type ToolPermissionOwner struct {
	SessionID      string `json:"session_id"`
	ThreadID       string `json:"thread_id"`
	TriggerEventID string `json:"trigger_event_id"`
	AttemptID      string `json:"attempt_id"`
}

ToolPermissionOwner identifies one already-established durable turn. A judgment receipt never creates or revives this execution owner.

type ToolPermissionReceipt

type ToolPermissionReceipt struct {
	ToolPermissionOwner
	ToolUseEventID   string                 `json:"tool_use_event_id"`
	ToolName         string                 `json:"tool_name"`
	InvocationHash   string                 `json:"invocation_hash"`
	ContextHash      string                 `json:"context_hash"`
	Decision         ToolPermissionDecision `json:"decision"`
	Model            Model                  `json:"model"`
	Usage            TokenUsage             `json:"usage"`
	StopReason       string                 `json:"stop_reason"`
	ResponseReceived bool                   `json:"response_received"`
}

type ToolSet

type ToolSet struct {
	Builtin *BuiltinToolset
	Custom  []CustomTool
	MCP     []MCPToolset
}

func ParseTools

func ParseTools(raw []any) (ToolSet, error)

func (ToolSet) BuiltinEnabled

func (ts ToolSet) BuiltinEnabled(name string) (bool, PermissionPolicy)

type ToolStep

type ToolStep struct {
	ID             string
	AttemptID      string
	Ordinal        int
	ToolUseEventID string
	ToolName       string
	Input          map[string]any
	State          ToolStepState
	Result         *ToolStepResult
	CreatedAt      time.Time
	UpdatedAt      time.Time
	StartedAt      *time.Time
	FinishedAt     *time.Time
}

ToolStep is an internal durable record of one built-in tool request and its execution boundary. ToolUseEventID is preassigned from the public event ID space so the eventual agent.tool_use and agent.tool_result can use the same stable correlation ID.

type ToolStepResult

type ToolStepResult struct {
	Content []any `json:"content"`
	// FileID references a published textual result File. FullOutput is a private
	// byte receipt retained only until publication; JSON encodes it as base64 so
	// every UTF-8 byte (including NUL) survives PostgreSQL JSONB. It never enters Workflow history.
	FileID     string `json:"file_id,omitempty"`
	FullOutput []byte `json:"full_output,omitempty"`
	IsError    bool   `json:"is_error"`
	// InjectedContent is private provider-continuation content produced by an
	// agent-runtime primitive after its ordinary tool_result. Skill activation
	// uses it to persist the rendered SKILL.md as a sibling user content block,
	// matching Claude Code's context lifecycle without exposing it as a public
	// configurable tool.
	InjectedContent []ContentBlock `json:"injected_content,omitempty"`
	// Events are server-side companion events that must commit with a durable
	// tool result and survive a lost Activity acknowledgement. They are removed
	// from the model-facing result projection.
	Events []EventDraft `json:"events,omitempty"`
	// Raw retains a bounded executor-native result for diagnostics/UI without
	// placing it in model context. Oversized native diagnostics are omitted;
	// FileID retains only the projected model-visible textual result.
	Raw     json.RawMessage `json:"raw,omitempty"`
	RawPath string          `json:"raw_path,omitempty"`
}

type ToolStepState

type ToolStepState string

ToolStepState makes the side-effect uncertainty boundary explicit.

prepared -> started -> completed
                   \-> ambiguous

Prepared means the request is durable but execution has not begun. Started means the executor may have changed the world. Completed carries a durable result. Ambiguous means execution began but no trustworthy result was recorded, so the step must never be silently retried.

const (
	ToolStepPrepared  ToolStepState = "prepared"
	ToolStepStarted   ToolStepState = "started"
	ToolStepCompleted ToolStepState = "completed"
	ToolStepAmbiguous ToolStepState = "ambiguous"
)

type Vault

type Vault struct {
	ID          string
	DisplayName string
	Metadata    map[string]string
	CreatedAt   time.Time
	UpdatedAt   time.Time
	ArchivedAt  *time.Time
}

Vault is a Workspace-scoped container for credentials. Ownership stays in the relational root instead of leaking into the CMA wire representation.

type VaultCredential

type VaultCredential struct {
	ID             string
	VaultID        string
	DisplayName    *string
	Metadata       map[string]string
	Auth           CredentialAuth
	CredentialKey  string
	SecretEnvelope *SecretEnvelope
	Version        int64
	CreatedAt      time.Time
	UpdatedAt      time.Time
	ArchivedAt     *time.Time
}

VaultCredential is the repository representation. Public callers must never serialize SecretEnvelope or CredentialKey.

type Webhook

type Webhook struct {
	ID               string
	URL              string
	EventTypes       []string
	Status           WebhookStatus
	DisabledReason   *string
	SecretEnvelope   *SecretEnvelope
	FailureStartedAt *time.Time
	LastSuccessAt    *time.Time
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

Webhook is a Workspace-scoped outbound notification endpoint. The signing secret is encrypted control-plane state and must never be serialized by an HTTP response.

type WebhookDelivery

type WebhookDelivery struct {
	WebhookID      string
	EventID        string
	URL            string
	SecretEnvelope SecretEnvelope
	Payload        []byte
	AttemptCount   int
	ClaimID        string
	CreatedAt      time.Time
}

WebhookDelivery is one leased endpoint/event pair. Payload contains the exact bytes signed and sent on every attempt; retries change only the attempt timestamp and signature.

type WebhookStatus

type WebhookStatus string
const (
	WebhookStatusEnabled  WebhookStatus = "enabled"
	WebhookStatusDisabled WebhookStatus = "disabled"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL