Documentation
¶
Overview ¶
Package omnigent is a Go client for the omnigent server's session API.
It reaches eight session calls — create, get, update, delete, send input, resolve an elicitation, interrupt, and the event stream — plus the agent and session listings. That is a working subset rather than the API: openapi.json publishes dozens of further session operations (items, resources, policies, permissions, comments, fork, agent swap) that this package does not call.
Quickstart ¶
client, err := omnigent.New(omnigent.DefaultBaseURL)
if err != nil {
return err
}
session, err := client.CreateSession(ctx, omnigent.SessionCreateRequest{AgentID: agentID})
if err != nil {
return err
}
// Open the stream before posting, so the turn's first events cannot be
// missed: the server buffers nothing for absent subscribers. OnSubscribed
// runs once the subscription is live, and only once.
opts := omnigent.StreamOptions{
OnSubscribed: func(ctx context.Context, sub omnigent.Subscription) error {
_, err := client.SendMessage(ctx, sub.SessionID, "hello")
return err
},
}
// Take the deltas as a preview, not as the answer: some harnesses send
// none, and the reply itself is a committed conversation item that can be
// posted after the turn's terminal event. So this loop reads to the end of
// the turn and stops there.
var preview strings.Builder
var responseID string
for event, err := range client.Stream(ctx, session.ID, opts) {
if err != nil {
return err
}
var done bool
switch ev := event.(type) {
case omnigent.OutputTextDeltaEvent:
preview.WriteString(ev.Delta)
case omnigent.ResponseCompletedEvent:
responseID, done = ev.Response.ID, true
case omnigent.ResponseFailedEvent:
responseID, done = ev.Response.ID, true
case omnigent.IncompleteEvent:
responseID, done = ev.Response.ID, true
case omnigent.ResponseCancelledEvent:
responseID, done = ev.Response.ID, true
}
if done {
break
}
}
// Deltas, where a harness sends them, are this turn's by definition, so a
// non-empty preview is already the reply.
if text := preview.String(); strings.TrimSpace(text) != "" {
fmt.Print(text)
return nil
}
// Otherwise the reply is read from the session, and polled for because the
// commit is not ordered against the terminal event. The window is the
// caller's policy; that it is bounded is not, because a reply that never
// commits must not hang the program.
pollCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
for {
snapshot, err := client.GetSession(pollCtx, session.ID, omnigent.GetSessionOptions{
IncludeItems: omnigent.Ptr(true),
IncludeLiveness: omnigent.Ptr(false),
})
if err != nil {
return err
}
if text := assistantText(snapshot.Items, responseID); text != "" {
fmt.Print(text)
return nil
}
select {
case <-time.After(250 * time.Millisecond):
case <-pollCtx.Done():
return pollCtx.Err()
}
}
assistantText is the item read, and "Reading a conversation item" below is where it comes from: a ConversationItem's payload has to be gated on its Type before it is interpreted.
Harnesses, deltas, and where the reply is ¶
A turn's authoritative output is the committed conversation item. The text deltas on the stream are a preview of one, and both halves of that sentence are load-bearing.
Deltas are not promised. The platform declares a streaming flag per harness in the capability table in omnigent/harness_plugins.py, served over GET /v1/harnesses — a route this package does not call. Read the flag as a declaration and not a guarantee: the comment above that table records that only four harnesses have interrupt and streaming verified live by the harness bench — claude-sdk, codex, pi and openai-agents — and that the rest are declared from their integration mode. Three declare no streaming because a live run recorded zero text deltas: cursor-native, kiro-native and qwen-native, and on kiro-native the whole reply arrives as one response.output_item.done. A harness declaring true can still deliver nothing in a given deployment: claude-native's deltas come from a Claude Code MessageDisplay hook appending to a file that its forwarder tails, so a host where that hook has not fired streams no deltas while still declaring them.
The item can arrive after the turn ends. On a harness that runs a resident vendor TUI — the -native family, integration mode native_tui — the reply reaches the session through a forwarder polling the vendor's transcript every 0.25s, and an assistant message is deliberately held back, for up to 2.0s, until its forwarded deltas have gone out ahead of it (omnigent/claude_native_forwarder.py). Nothing orders that post against the turn's terminal event. A loop that returns on ResponseCompletedEvent and reports what it accumulated therefore reports nothing at all, and cannot tell that from an agent that answered with silence. The quickstart's shape is the fix: stop reading at the terminal event, then go and read the item.
Nor is the reply on the terminal event. The server builds that response object from id, status, model, created_at, error and usage, and does not set output, although ResponseObject.Output's description — "empty for non-completed responses" — reads as a promise that a completed one is populated. Reading it is harmless and costs a loop over a nil slice; relying on it is not.
SessionResponse.Harness and AgentObject.Harness name the harness behind a session or an agent, for a program that has to branch on the family. The loop above needs no branch, which is why it does not have one: read the deltas if they come, and read the item either way.
Reading a conversation item ¶
ConversationItem.Data is a union of eleven payloads and the spec gives it no discriminator. The value that says which payload it holds is the sibling ConversationItem.Type, which the generated accessors cannot see, because each is declared on the union field alone and is a plain json.Unmarshal into one variant's struct.
So a successful AsX is not evidence the payload was an X. MessageData and FunctionCallData share no field names, so AsMessageData on a function_call returns a zero-valued MessageData and a nil error. Gate on the type first, and treat the accessor as a decoder rather than as a check:
// Newest first: the agent's last message is its answer, and
// SessionResponse.Items is chronological.
func assistantText(items []omnigent.ConversationItem, responseID string) string {
for i := len(items) - 1; i >= 0; i-- {
item := items[i]
if item.Type != "message" || item.Status != "completed" {
continue
}
// A stamp is the server attesting which turn the item belongs to.
// An unstamped item is admitted, because a harness may leave it
// empty; another turn's stamp is not.
if item.ResponseID != "" && responseID != "" && item.ResponseID != responseID {
continue
}
msg, err := item.Data.AsMessageData()
if err != nil || !strings.EqualFold(string(msg.Role), "assistant") {
continue
}
if text := contentText(msg.Content); text != "" {
return text
}
}
return ""
}
contentText joins the text blocks of MessageData.Content, which are untyped maps of the shape {"type": "output_text", "text": "..."}. It allowlists the block types it reads rather than taking every block with a text key, because reasoning and refusal blocks carry one too; the README spells it out.
Keying on the decoded value alone — "the role is not assistant, so skip it" — happens to filter a function_call out today, because the zero value of MessageData.Role matches nothing. It is an accident that stops holding the moment two variants share a field name, and it silently reads a payload of the wrong kind in the meantime.
Admitting an unstamped item is what a session outliving one turn has to pay for: on a second invocation the loop above can return the *previous* turn's reply. A program that reuses a session needs the ids it had already seen before the turn began and has to skip those too. Three more fields are worth honouring before text is published anywhere — ConversationItem.CreatedBy is non-nil only for a human author, MessageData.IsMeta marks context meant for the agent and not for a transcript, and MessageData.Interrupted marks a partial reply from a turn that was cut short. Each is stamped by the server and cannot be forged by a client, which is what makes them worth reading.
ValidationError.Loc is the other union here and does not have this problem: its two variants are a string and an int, so a failed unmarshal is a real answer about which one arrived.
Send-after-subscribe, and the heartbeat that looks like a signal ¶
The stream buffers nothing for absent subscribers, so input must not be posted until the subscription exists. The obvious-looking way to detect that is to wait for the first SessionHeartbeatEvent and send from there — and it is wrong. The server uses one event, with a byte-identical payload, for two unrelated jobs: the subscription acknowledgement it yields the moment the subscriber slot is registered, and the keepalive it emits every 15 seconds while a stream sits idle between turns. Nothing on the wire tells them apart. A caller that sends on every heartbeat therefore re-sends its message for as long as the stream stays open.
StreamOptions.OnSubscribed is this package's answer: the iterator calls it once, before the first event reaches the caller, and never again for that stream. Where the input can be known up front, SessionCreateRequest.InitialItems is better still — the server queues it at create time, so there is no ordering to get right.
Generated versus hand-written ¶
models.gen.go and events.gen.go are generated from the repository's openapi.json by scripts/gen_go_client.py, together with the type-string dispatch for the 52 variants of the SSE event union. Do not edit them; regenerate instead.
The generated surface is deliberately narrower than the spec. It is the $ref closure of the schemas this package's own API names — SessionResponse, ConversationDeleted, SessionGitOptions, ValidationError, AgentObject, SessionListItem — plus every member of the event union. Generating the whole document would export types named after the server's path-mangled operationIds and a second public representation of what Event already models, neither of which is API this module intends to offer.
Four types are hand-written in session.go because the server documents neither their routes nor their schemas, so openapi.json carries nothing to generate them from and no drift gate covers them: SessionCreateRequest (the create route takes a raw request and dispatches on Content-Type, so FastAPI emits no requestBody for it), and SessionEventInput, EventAccepted and ElicitationResult (the send route is registered with include_in_schema=False, so neither its body nor its responses appear). A server-side change to any of the four breaks this client silently.
Listings ¶
Client.ListAgents and Client.ListSessions page by opaque cursor into a shared Page. Between them they cover the two lookups a program needs before it can do anything else: turning an agent name into the id a create wants, and finding a session it created on an earlier run rather than creating a second one. See Page for the paging loop and ListSessionsOptions for the filters.
Timeouts ¶
Go's http.Client.Timeout is a deadline on the whole exchange including reading the response body, so any non-zero value severs a healthy long-lived stream. This package therefore keeps two clients over one transport: unary calls carry a whole-exchange timeout, and the streaming client's is zero.
The unary bound defaults to 90 seconds, and WithUnaryTimeout moves it. It is that long because the two slowest routes wait on a runner before they answer and neither sends a byte early, so the client's deadline has to clear the server's own inner budgets or it aborts calls the server was still going to answer. Posting an event waits up to 5 seconds for the stream relay to subscribe and then forwards to the runner under a 60-second read timeout — 30 seconds on the native-terminal path. Creating a session notifies the runner (10 seconds) and may wait 30 more for a host to launch one; giving up there is the worse failure, because the id of a session the server goes on to create is lost, which leaks it. A deadline for one call still belongs on that call's context: this bound is the backstop against a wedged connection, not a latency policy.
Liveness on the stream is enforced instead by an idle watchdog — the server emits a heartbeat frame every 15 seconds of queue silence, so a read that blocks for longer than StreamOptions.IdleTimeout means the transport is gone. The watchdog measures time blocked on a read, not wall-clock time: it is suspended while the caller's own loop body runs, so a slow event handler cannot be mistaken for a dead server. Response-header latency stays bounded for both clients by the one transport's ResponseHeaderTimeout, which is the unary bound or a 30-second floor, whichever is larger — the floor because opening a stream waits on the same relay subscription that a post does.
Cancellation ¶
Every call takes a context.Context, and cancelling it is the only way to stop a stream. Note what that does and does not do: dropping the stream ends the *subscription*, not the agent's turn. The turn runs on the server side independently of any subscriber. To actually stop work, post an interrupt with Client.Interrupt.
Errors ¶
Every error this package returns is matchable with errors.Is against one of the sentinels in errors.go, and a server response also unwraps to APIError with errors.As for the status, the server's error code, and the X-Request-Id to quote when reporting it. ErrInvalidArgument is the odd one out: it means this package rejected the call before sending anything.
Security ¶
A client that holds a credential has to be careful about four things, and this package's answer to each is fail-closed rather than best-effort.
Transport. A credential must not cross a network in clear. New therefore refuses a plain-http base URL once an auth option is supplied, unless the host is loopback — which is why DefaultBaseURL works as it is: nothing leaves the machine. A deployment where the plaintext hop is genuinely not a network (a sidecar, a port-forward, a mesh that terminates TLS ahead of you) opts in with WithInsecureCredentialTransport. There is no warn-and-continue option: a library has no logger to warn into, and silence is how a token ends up on a shared segment.
Redirects. Neither of this package's http.Clients follows a redirect off the base URL's host, down from https to http, or across a method rewrite. Go's own rule strips only Authorization, Cookie, Www-Authenticate and Cookie2 on a cross-host hop, which leaves a custom identity header — WithAuthHeader's, the trusted-proxy one — travelling to whatever host the response named; it compares hostnames and not schemes, so an https-to-http hop keeps the credential and loses the encryption; a cross-host 307 or 308 replays the request body, which here is the caller's prompt; and a 302 on a POST becomes a GET, so a dropped write would return 200. All four are ErrUnsafeRedirect. A caller supplying an http.Client with its own CheckRedirect keeps it, and owns that.
Base URLs. A base URL carrying userinfo is rejected rather than quietly becoming Basic auth on every request, and no error from New echoes the base URL's password — the parse-failure path reports the reason without the value, because url.Parse's own error quotes back what it was handed.
Error values. APIError.Error renders the status, the server's error code and message, and the request id, and never the response body: a non-2xx body may come from a proxy rather than this API, and an error string is the one thing that reliably reaches a log aggregator. APIError.Header has the headers that carry a credential by specification removed. See APIError for the detail.
What this package does not do: it never touches TLS configuration. There is no option to skip verification, pin a root, or reach a tls.Config, because a client that can be talked into trusting anything is not a security boundary. A deployment with a private CA configures it where such things belong — the system trust store, or a transport the caller builds and passes to WithHTTPClient.
Reconnection ¶
The stream is live-tail only. There is no resume: the server emits no SSE id: field, honours no Last-Event-ID, and drops events published while nobody is subscribed. When a stream ends with ErrStreamInterrupted or ErrStreamIdle, recover by fetching the snapshot with Client.GetSession, opening a fresh stream, and deduping persisted items by id. Reconnection is routine rather than exceptional — some deployments cap HTTP stream duration at a few minutes.
Index ¶
- Constants
- Variables
- func Ptr[T any](v T) *T
- type APIError
- type AgentObject
- type BrowserActionRequestEvent
- type BrowserActionRequestEventType
- type Client
- func (c *Client) CreateSession(ctx context.Context, req SessionCreateRequest) (*SessionResponse, error)
- func (c *Client) DeleteSession(ctx context.Context, sessionID string, opts DeleteSessionOptions) (*ConversationDeleted, error)
- func (c *Client) GetSession(ctx context.Context, sessionID string, opts GetSessionOptions) (*SessionResponse, error)
- func (c *Client) Interrupt(ctx context.Context, sessionID string) error
- func (c *Client) ListAgents(ctx context.Context, opts ListAgentsOptions) (*Page[AgentObject], error)
- func (c *Client) ListSessionItems(ctx context.Context, sessionID string, opts SessionItemsOptions) (*Page[SessionItem], error)
- func (c *Client) ListSessions(ctx context.Context, opts ListSessionsOptions) (*Page[SessionListItem], error)
- func (c *Client) ResolveElicitation(ctx context.Context, sessionID, elicitationID string, result ElicitationResult) (*EventAccepted, error)
- func (c *Client) ResolveElicitationRequest(ctx context.Context, sessionID string, request ElicitationRequestEvent, ...) (*EventAccepted, error)
- func (c *Client) SendInput(ctx context.Context, sessionID string, input SessionEventInput) (*EventAccepted, error)
- func (c *Client) SendMessage(ctx context.Context, sessionID, text string) (*EventAccepted, error)
- func (c *Client) Stream(ctx context.Context, sessionID string, opts StreamOptions) iter.Seq2[Event, error]
- func (c *Client) UpdateSession(ctx context.Context, sessionID string, req UpdateSessionRequest) (*SessionResponse, error)
- type ClientTaskCancelEvent
- type ClientTaskCancelEventType
- type CompactionCompletedEvent
- type CompactionCompletedEventType
- type CompactionData
- type CompactionFailedEvent
- type CompactionFailedEventType
- type CompactionInProgressEvent
- type CompactionInProgressEventType
- type ConversationDeleted
- type ConversationItem
- type ConversationItem_Data
- func (t ConversationItem_Data) AsCompactionData() (CompactionData, error)
- func (t ConversationItem_Data) AsErrorData() (ErrorData, error)
- func (t ConversationItem_Data) AsFunctionCallData() (FunctionCallData, error)
- func (t ConversationItem_Data) AsFunctionCallOutputData() (FunctionCallOutputData, error)
- func (t ConversationItem_Data) AsMessageData() (MessageData, error)
- func (t ConversationItem_Data) AsNativeToolData() (NativeToolData, error)
- func (t ConversationItem_Data) AsReasoningData() (ReasoningData, error)
- func (t ConversationItem_Data) AsResourceEventData() (ResourceEventData, error)
- func (t ConversationItem_Data) AsRoutingDecisionData() (RoutingDecisionData, error)
- func (t ConversationItem_Data) AsSlashCommandData() (SlashCommandData, error)
- func (t ConversationItem_Data) AsTerminalCommandData() (TerminalCommandData, error)
- func (t *ConversationItem_Data) FromCompactionData(v CompactionData) error
- func (t *ConversationItem_Data) FromErrorData(v ErrorData) error
- func (t *ConversationItem_Data) FromFunctionCallData(v FunctionCallData) error
- func (t *ConversationItem_Data) FromFunctionCallOutputData(v FunctionCallOutputData) error
- func (t *ConversationItem_Data) FromMessageData(v MessageData) error
- func (t *ConversationItem_Data) FromNativeToolData(v NativeToolData) error
- func (t *ConversationItem_Data) FromReasoningData(v ReasoningData) error
- func (t *ConversationItem_Data) FromResourceEventData(v ResourceEventData) error
- func (t *ConversationItem_Data) FromRoutingDecisionData(v RoutingDecisionData) error
- func (t *ConversationItem_Data) FromSlashCommandData(v SlashCommandData) error
- func (t *ConversationItem_Data) FromTerminalCommandData(v TerminalCommandData) error
- func (t ConversationItem_Data) MarshalJSON() ([]byte, error)
- func (t *ConversationItem_Data) MergeCompactionData(v CompactionData) error
- func (t *ConversationItem_Data) MergeErrorData(v ErrorData) error
- func (t *ConversationItem_Data) MergeFunctionCallData(v FunctionCallData) error
- func (t *ConversationItem_Data) MergeFunctionCallOutputData(v FunctionCallOutputData) error
- func (t *ConversationItem_Data) MergeMessageData(v MessageData) error
- func (t *ConversationItem_Data) MergeNativeToolData(v NativeToolData) error
- func (t *ConversationItem_Data) MergeReasoningData(v ReasoningData) error
- func (t *ConversationItem_Data) MergeResourceEventData(v ResourceEventData) error
- func (t *ConversationItem_Data) MergeRoutingDecisionData(v RoutingDecisionData) error
- func (t *ConversationItem_Data) MergeSlashCommandData(v SlashCommandData) error
- func (t *ConversationItem_Data) MergeTerminalCommandData(v TerminalCommandData) error
- func (t *ConversationItem_Data) UnmarshalJSON(b []byte) error
- type ConversationRef
- type DeleteSessionOptions
- type ElicitationAction
- type ElicitationRequestEvent
- type ElicitationRequestEventMethod
- type ElicitationRequestEventType
- type ElicitationRequestParams
- type ElicitationRequestParamsMode
- type ElicitationResolvedEvent
- type ElicitationResolvedEventType
- type ElicitationResult
- type ErrorData
- type ErrorDataSource
- type ErrorDetail
- type ErrorEvent
- type ErrorEventSource
- type ErrorEventType
- type Event
- type EventAccepted
- type FunctionCallData
- type FunctionCallOutputData
- type GetSessionOptions
- type InProgressEvent
- type InProgressEventType
- type IncompleteDetails
- type IncompleteEvent
- type IncompleteEventType
- type ListAgentsOptions
- type ListSessionsOptions
- type MCPServerSummary
- type McpServerStartup
- type McpServerStartupStatus
- type MessageData
- type MessageDataRole
- type ModelUsage
- type NativeModelOption
- type NativeReasoningEffortOption
- func (a NativeReasoningEffortOption) Get(fieldName string) (value interface{}, found bool)
- func (a NativeReasoningEffortOption) MarshalJSON() ([]byte, error)
- func (a *NativeReasoningEffortOption) Set(fieldName string, value interface{})
- func (a *NativeReasoningEffortOption) UnmarshalJSON(b []byte) error
- type NativeToolData
- type Option
- func WithAuthHeader(name, value string) Option
- func WithBearerToken(token string) Option
- func WithHTTPClient(httpClient *http.Client) Option
- func WithInsecureCredentialTransport() Option
- func WithSessionCookie(name, value string) Option
- func WithStreamIdleTimeout(d time.Duration) Option
- func WithUnaryTimeout(d time.Duration) Option
- func WithUserAgent(userAgent string) Option
- type OutputFileDoneEvent
- type OutputFileDoneEventType
- type OutputItemDoneEvent
- type OutputItemDoneEventType
- type OutputTextDeltaEvent
- type OutputTextDeltaEventType
- type Page
- type PolicyDeniedEvent
- type PolicyDeniedEventType
- type PolicySummary
- type PresenceViewer
- type QueuedEvent
- type QueuedEventType
- type ReasoningData
- type ReasoningStartedEvent
- type ReasoningStartedEventType
- type ReasoningSummaryTextDeltaEvent
- type ReasoningSummaryTextDeltaEventType
- type ReasoningTextDeltaEvent
- type ReasoningTextDeltaEventType
- type ResourceEventData
- type ResponseCancelledEvent
- type ResponseCancelledEventType
- type ResponseCompletedEvent
- type ResponseCompletedEventType
- type ResponseCreatedEvent
- type ResponseCreatedEventType
- type ResponseFailedEvent
- type ResponseFailedEventType
- type ResponseHeartbeatEvent
- type ResponseHeartbeatEventType
- type ResponseObject
- type RetryErrorDetail
- type RetryEvent
- type RetryEventSource
- type RetryEventType
- type RoutingDecisionData
- type RoutingDecisionDataScope
- type SandboxStatus
- type SandboxStatusStage
- type SessionAgentChangedEvent
- type SessionAgentChangedEventType
- type SessionChangedFilesInvalidatedEvent
- type SessionChangedFilesInvalidatedEventType
- type SessionChildSessionUpdatedEvent
- type SessionChildSessionUpdatedEventType
- type SessionCollaborationModeEvent
- type SessionCollaborationModeEventType
- type SessionCreateRequest
- type SessionCreatedEvent
- type SessionCreatedEventType
- type SessionEventInput
- type SessionGitOptions
- type SessionHeartbeatEvent
- type SessionHeartbeatEventType
- type SessionInputConsumedEvent
- type SessionInputConsumedEventType
- type SessionInputConsumedPayload
- type SessionInterruptedEvent
- type SessionInterruptedEventType
- type SessionInterruptedPayload
- type SessionItem
- type SessionItemsOptions
- type SessionKind
- type SessionListItem
- type SessionListItemStatus
- type SessionMcpStartupEvent
- type SessionMcpStartupEventType
- type SessionModelEvent
- type SessionModelEventType
- type SessionModelOptionsEvent
- type SessionModelOptionsEventType
- type SessionPresenceEvent
- type SessionPresenceEventType
- type SessionReasoningEffortEvent
- type SessionReasoningEffortEventType
- type SessionResourceCreatedEvent
- type SessionResourceCreatedEventType
- type SessionResourceDeletedEvent
- type SessionResourceDeletedEventType
- type SessionResponse
- type SessionResponseStatus
- type SessionSandboxStatusEvent
- type SessionSandboxStatusEventStage
- type SessionSandboxStatusEventType
- type SessionSkillsEvent
- type SessionSkillsEventType
- type SessionSortBy
- type SessionStatusEvent
- type SessionStatusEventStatus
- type SessionStatusEventType
- type SessionSupersededEvent
- type SessionSupersededEventReason
- type SessionSupersededEventType
- type SessionTerminalActivityEvent
- type SessionTerminalActivityEventType
- type SessionTerminalPendingEvent
- type SessionTerminalPendingEventType
- type SessionTodosEvent
- type SessionTodosEventType
- type SessionUsageEvent
- type SessionUsageEventType
- type SkillSummary
- type SkippedFrame
- type SlashCommandData
- type SlashCommandDataKind
- type SortOrder
- type StreamOptions
- type Subscription
- type TerminalCommandData
- type TerminalCommandDataKind
- type ToolOutputDeltaEvent
- type ToolOutputDeltaEventType
- type TurnCancelledEvent
- type TurnCancelledEventType
- type TurnCompletedEvent
- type TurnCompletedEventType
- type TurnFailedEvent
- type TurnFailedEventType
- type TurnStartedEvent
- type TurnStartedEventType
- type UnknownEvent
- type UpdateSessionRequest
- type Usage
- type UsageDetails
- type ValidationError
- type ValidationErrorLoc0
- type ValidationErrorLoc1
- type ValidationError_Loc_Item
- func (t ValidationError_Loc_Item) AsValidationErrorLoc0() (ValidationErrorLoc0, error)
- func (t ValidationError_Loc_Item) AsValidationErrorLoc1() (ValidationErrorLoc1, error)
- func (t *ValidationError_Loc_Item) FromValidationErrorLoc0(v ValidationErrorLoc0) error
- func (t *ValidationError_Loc_Item) FromValidationErrorLoc1(v ValidationErrorLoc1) error
- func (t ValidationError_Loc_Item) MarshalJSON() ([]byte, error)
- func (t *ValidationError_Loc_Item) MergeValidationErrorLoc0(v ValidationErrorLoc0) error
- func (t *ValidationError_Loc_Item) MergeValidationErrorLoc1(v ValidationErrorLoc1) error
- func (t *ValidationError_Loc_Item) UnmarshalJSON(b []byte) error
Constants ¶
const ( // InputTypeMessage is a conversation turn. Its Data is a role plus content // parts; build one with [UserMessage]. InputTypeMessage = "message" // InputTypeFunctionCallOutput returns the result of a tool the client ran. // Its Data carries call_id and output. InputTypeFunctionCallOutput = "function_call_output" // InputTypeInterrupt cancels the turn in flight. This — not cancelling a // stream's context — is how a caller stops an agent. InputTypeInterrupt = "interrupt" // InputTypeStopSession halts the session. Owner-level access only. InputTypeStopSession = "stop_session" // InputTypeCompact asks the server to compact the conversation history. InputTypeCompact = "compact" // InputTypeApproval answers an outstanding elicitation. Its Data is an // elicitation_id plus the [ElicitationResult] fields; build one with // [ApprovalVerdict], or send it with [Client.ResolveElicitation]. InputTypeApproval = "approval" )
Discriminators for SessionEventInput.Type. The first names an item the session records; the rest are control signals that queue no item.
const DefaultBaseURL = "http://127.0.0.1:6767"
DefaultBaseURL is the server's advertised self-hosted address. It is plain http, which is legitimate because it is loopback: nothing leaves the machine. See the package doc's security notes for what that does and does not permit.
Variables ¶
var ( // ErrInvalidArgument is the one sentinel here that is not a server // response: this package rejected an argument before sending anything. An // empty session id, a create with no agent id, an input with no type, an // option handed a nil or empty value. Retrying cannot help — fix the call. ErrInvalidArgument = errors.New("invalid argument") // ErrInvalidInput is a 400: the request was understood and rejected. ErrInvalidInput = errors.New("invalid input") // was not accepted. Supply credentials with one of the auth options. ErrUnauthorized = errors.New("unauthorized") // ErrForbidden is a 403: the caller is known but lacks the required access // level on the session. Note the asymmetry — reading a session needs less // than sending to it, which needs less than deleting it. ErrForbidden = errors.New("forbidden") // ErrNotFound is a 404, which does NOT prove the session is absent. The // server also answers 404 when the caller has no access at all, so as not // to leak session existence. Treat it as "absent or invisible to you"; do // not paper over a permissions misconfiguration by retrying. ErrNotFound = errors.New("not found") // ErrConflict is a 409: the resource already exists, or the request // conflicts with current state. ErrConflict = errors.New("conflict") // ErrHarnessNotConfigured is a 412: the session's agent has no usable // harness configured server-side. Retrying will not help. ErrHarnessNotConfigured = errors.New("harness not configured") // ErrValidation is a 422: the request body did not match the schema. The // per-field detail is available from [APIError.ValidationErrors]. ErrValidation = errors.New("request validation failed") // serve the request. Usually transient. ErrUnavailable = errors.New("service unavailable") // ErrServer matches any 5xx, including the ones with their own sentinel. ErrServer = errors.New("server error") // ErrStreamInterrupted reports that a stream's body ended without the // server's terminal sentinel. This is the normal failure mode, not an edge // case: it covers a dropped transport, a subscriber-queue overflow (which // deliberately omits the sentinel to signal loss), and deployment-level // caps on stream duration. Events published while nobody was subscribed are // gone, so recover with a snapshot rather than by retrying blind. ErrStreamInterrupted = errors.New("session stream ended without its terminal sentinel") // ErrStreamIdle reports that no frame arrived within the idle timeout. The // server keeps a 15-second heartbeat precisely so this means a dead // transport rather than a slow agent — a turn may legitimately produce no // output for minutes while a tool runs, and the heartbeat continues. // Recover exactly as for [ErrStreamInterrupted]. ErrStreamIdle = errors.New("session stream idle past its timeout") // ErrStreamProtocol reports a frame this package could not parse: a data // payload that is not a JSON object, or one carrying no discriminator. ErrStreamProtocol = errors.New("malformed session stream frame") // ErrStreamFrameTooLarge reports a frame past the size this package will // accumulate. It is a kind of [ErrStreamProtocol] and matches that too: a // well-formed frame ends, and one that does not is either a broken server or // a hostile one. Recover exactly as for [ErrStreamInterrupted]. ErrStreamFrameTooLarge = fmt.Errorf("%w: frame exceeds the client's size limit", ErrStreamProtocol) // ErrUnsafeRedirect reports a redirect this package would not follow: one // leaving the host the base URL named, one stepping down from https to // plain http, one rewriting a write as a read, or a chain that never // arrived anywhere within the hop limit. // // It is not a server error and retrying will not help. For the first two it // means the server — or something in front of it — answered with a location // this client will not carry the caller's credentials to; for the third, that // following it would have reported a dropped write as a success; for the // fourth, that the location chain is looping. Fix the base URL, or the proxy // in front of the server. The package overview, under Redirects, has the // reasoning and what Go's own rule does instead. ErrUnsafeRedirect = errors.New("refused to follow an unsafe redirect") )
Sentinels for the failure classes the server actually distinguishes. Match them with errors.Is against any error this package returns; reach the details with errors.As and APIError.
The set mirrors the server's own error-code table rather than inventing per-resource variants: a 404 is a 404 whatever endpoint produced it.
Functions ¶
Types ¶
type APIError ¶
type APIError struct {
// StatusCode is the HTTP status. It, not the message text, is what the
// sentinels above are matched on.
StatusCode int
// Code is the server's own error code — "not_found", "runner_unavailable",
// and so on — from a {"error": {"code", "message"}} envelope. Empty when
// the response used FastAPI's {"detail": ...} shape or was not JSON.
Code string
// Message is the human-readable message from either envelope. May be empty.
Message string
// Detail is the raw value of a {"detail": ...} envelope. For a 422 it is a
// list; see [APIError.ValidationErrors]. Nil when absent.
Detail json.RawMessage
// Body is the response body, truncated to a bounded size. Retained because
// an auth proxy or gateway ahead of the server may answer with something
// that is not JSON at all, and that is exactly why [APIError.Error] does not
// render it: what a proxy puts in a body is not this API's, and may be a
// credential. Treat it as untrusted bytes to be looked at, not logged.
Body []byte
// ContentType is the response's Content-Type header, useful for telling a
// server error apart from a proxy's HTML interstitial. Shorthand for
// Header.Get("Content-Type").
ContentType string
// RequestID is the server's X-Request-Id, which its middleware stamps on
// every response and logs alongside the failure. Quote it when reporting a
// server-side problem: it is the only handle that ties this error to the
// server's own record of it. Empty if the response never reached the
// server's middleware — a proxy or gateway error, say.
RequestID string
// Header is the response's headers, less the ones that carry a credential:
// see this type's doc. It is here for the correlation and rate-limit headers
// a deployment may add beyond the two called out above. Nil is possible; use
// Header.Get, which tolerates it.
Header http.Header
}
APIError is a non-2xx response from the server.
The server speaks two error envelopes and neither is guaranteed, so read the fields defensively: Code and Message come from the structured envelope, Detail from FastAPI's own, and Body always holds what actually arrived.
What this does not put in a log line ¶
APIError.Error renders the status, the error code and message, and RequestID — what a bug report needs. It never renders Body. A non-2xx body need not come from this API at all: an auth proxy answering 302-to-login or 502 can put a CSRF token, a signed state parameter or an echoed request header in it, and Error's return value is the one string that reliably reaches a log aggregator. Body is still here for the caller who needs to see it, and callers who log it choose to.
Code and Message are parsed out of that same body, so they carry the same caveat one step weaker: they are populated only when the body matched an envelope this API defines, which a foreign responder usually does not produce, and what reaches the log is then two named strings rather than opaque bytes. A proxy that happens to answer in the same shape is rendered — bounded to its code and message.
Header is the response's headers with the ones that carry a credential by specification removed: Set-Cookie and Set-Cookie2, which mint a client credential, and the Authorization pair, which has no business in a response. A deployment's own bespoke secret header is not something this package can enumerate, so treat Header as untrusted for logging too.
func (*APIError) Error ¶
Error implements error. It appends the request id when the server supplied one, so a copied-out error message is enough to find the server-side record.
It renders no part of Body. When the response carried no structured message — the proxy-interstitial case — it says how much body there was and what type it claimed, which is enough to tell "the API rejected this" from "something else answered" without copying bytes of unknown provenance into a log.
func (*APIError) Is ¶
Is reports whether this error matches one of the package sentinels, so that errors.Is(err, ErrNotFound) works on a wrapped *APIError. A 503 matches both ErrUnavailable and the broader ErrServer.
func (*APIError) ValidationErrors ¶
func (e *APIError) ValidationErrors() ([]ValidationError, error)
ValidationErrors decodes a 422's per-field detail. It returns nil, nil when the error carries no detail list, so a caller can ask unconditionally.
type AgentObject ¶
type AgentObject struct {
// Builtin Whether this is a server-*seeded* built-in agent (deterministic, name-derived id) as opposed to an operator/user-registered template (random id, e.g. via `omnigent server --agent`) or a session-scoped upload. The Web UI's new-session picker uses this to decide whether a same-named `omnigent run` upload may shadow the catalog entry: seeded built-ins are protected, while a user-registered template is superseded by a newer same-named upload. Always `False` for session-scoped agents.
Builtin *bool `json:"builtin,omitempty"`
// CreatedAt Unix epoch timestamp of creation.
CreatedAt int `json:"created_at"`
// Description Optional free-text description of the agent's purpose.
Description *string `json:"description,omitempty"`
// Harness The agent's harness/kind, e.g. `"codex"`, `"codex-native"`, or `"claude-native"` for `executor.type: omnigent` agents, otherwise the executor type (`"claude_sdk"`, `"agents_sdk"`). `None` when the bundle cannot be loaded. Lets the Web UI Add Agent picker recognise an agent's kind (Codex vs Claude) without hardcoding by name slug.
Harness *string `json:"harness,omitempty"`
// ID Unique agent identifier, e.g. `"ag_abc123"`.
ID string `json:"id"`
// McpServers MCP servers the agent is connected to (secret fields omitted). Empty list when the spec declares no MCP servers or when the bundle cannot be loaded.
McpServers []MCPServerSummary `json:"mcp_servers,omitempty"`
// McpServersEditable Whether the MCP list can be edited through the session UI. Built-in template agents are read-only; session-scoped uploaded agents are editable.
McpServersEditable *bool `json:"mcp_servers_editable,omitempty"`
// Name Human-readable agent name, e.g. `"research-agent"`.
Name string `json:"name"`
// Object Fixed resource type, always `"agent"`.
Object *string `json:"object,omitempty"`
// Policies Guardrails policies declared on the agent. Each entry summarises the policy name, type, and phases. Empty list when the spec declares no policies or when the bundle cannot be loaded.
Policies []PolicySummary `json:"policies,omitempty"`
// Skills Skills bundled in the agent spec (`skills/<name>/SKILL.md`). Lets the Web UI's new-session composer offer a slash-command menu before a session (and its runner) exists. Host-discovered skills are runner-owned, so they are NOT listed here — the session snapshot's `skills` field carries the merged set once a runner is bound. Empty list when the spec bundles no skills or when the bundle cannot be loaded.
Skills []SkillSummary `json:"skills,omitempty"`
// Terminals Terminal names declared in the spec's `terminals:` block, in declaration order, e.g. `["shell"]`. The Web UI gates its "new terminal" affordance on this list (creation is only offered for agents with terminal access) and offers these names as the launchable choices. Empty list when the spec declares no terminals or when the bundle cannot be loaded.
Terminals []string `json:"terminals,omitempty"`
// UpdatedAt Unix epoch timestamp of the last update, or `None` if never updated.
UpdatedAt *int `json:"updated_at,omitempty"`
// Version Monotonic version counter. Starts at 1, incremented on each update.
Version *int `json:"version,omitempty"`
}
AgentObject API representation of a registered agent.
type BrowserActionRequestEvent ¶
type BrowserActionRequestEvent struct {
// Action The browser action to perform — the `browser_` tool name with the prefix stripped, e.g. `"navigate"`, `"snapshot"`, `"click"`, `"type"`, `"screenshot"`.
Action string `json:"action"`
// ActionID Unique correlation id for this request, e.g. `"baction_abc123"`. Echoed on the claim and result routes.
ActionID string `json:"action_id"`
// Args Action arguments forwarded from the tool call, e.g. `{"url": "https://example.com"}`.
Args map[string]interface{} `json:"args"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"browser.action_request"`.
Type BrowserActionRequestEventType `json:"type"`
}
BrowserActionRequestEvent Request that the desktop renderer perform one browser action.
Emitted by the server `POST /v1/sessions/{id}/browser/action_request` route when a runner-side `browser_*` tool dispatch needs the Omnigent desktop app's embedded browser to act. The event fans out on the session stream to every subscribed renderer; each renderer first POSTs `/browser/action_claim/{action_id}` and only the winning claimant executes the action and POSTs the result back to `/browser/action_result/{action_id}`. The claim lease prevents double execution when more than one renderer is subscribed.
Wire type: "browser.action_request".
type BrowserActionRequestEventType ¶
type BrowserActionRequestEventType string
BrowserActionRequestEventType Always `"browser.action_request"`.
const (
BrowserActionRequestEventTypeBrowserActionRequest BrowserActionRequestEventType = "browser.action_request"
)
Defines values for BrowserActionRequestEventType.
func (BrowserActionRequestEventType) Valid ¶
func (e BrowserActionRequestEventType) Valid() bool
Valid indicates whether the value is a known member of the BrowserActionRequestEventType enum.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to one omnigent server. It is safe for concurrent use, and callers should share a single Client so its connections are pooled.
func New ¶
New returns a Client for the server at baseURL, which may be empty to mean DefaultBaseURL.
The returned Client sends no credentials unless an auth option is supplied. That is deliberate: the server's identity mode is a deployment choice, so there is no scheme to guess. Pick the one matching the deployment with WithAuthHeader, WithBearerToken, or WithSessionCookie.
baseURL must carry no userinfo, and — once an auth option is supplied — must be https unless its host is loopback. Both are rejected here rather than at the first request; see the package doc's security notes for why, and for WithInsecureCredentialTransport, the explicit opt-out of the second.
Errors from here never quote baseURL back verbatim. A base URL is a place a password can hide, and an error message is the least controlled place a credential can end up.
func (*Client) CreateSession ¶
func (c *Client) CreateSession(ctx context.Context, req SessionCreateRequest) (*SessionResponse, error)
CreateSession creates a session bound to an existing agent and returns its snapshot.
func (*Client) DeleteSession ¶
func (c *Client) DeleteSession( ctx context.Context, sessionID string, opts DeleteSessionOptions, ) (*ConversationDeleted, error)
DeleteSession deletes a session and the resources bound to it.
It requires owner-level access, so it can fail with ErrForbidden on a session that Client.GetSession happily returns.
func (*Client) GetSession ¶
func (c *Client) GetSession( ctx context.Context, sessionID string, opts GetSessionOptions, ) (*SessionResponse, error)
GetSession returns a session's snapshot: identity, status, and committed items.
This is the reconciliation half of the stream contract. Because the stream replays nothing, recovering from a drop means calling this, then opening a fresh stream, then deduping persisted items by id — sound because the server persists an item before it publishes it.
What that recovers is bounded by the snapshot's item window: the newest 100, per GetSessionOptions.IncludeItems. A drop that outlasts 100 items, or a session already past them, needs Client.ListSessionItems to read the rest.
func (*Client) Interrupt ¶
Interrupt cancels the turn in flight.
This is real cancellation, unlike cancelling a stream's context: the turn runs server-side and does not care whether anyone is subscribed. The stream then carries a SessionInterruptedEvent and an IncompleteEvent whose reason records the interrupt.
func (*Client) ListAgents ¶
func (c *Client) ListAgents(ctx context.Context, opts ListAgentsOptions) (*Page[AgentObject], error)
ListAgents returns one page of the agents this caller may start a session with, newest first unless ListAgentsOptions.Order says otherwise.
The listing is not only the built-in agents, despite the route's name. It is every agent not scoped to a single session, which covers the ones an operator installed alongside the ones that ship with the server; AgentObject.Builtin tells them apart. Agents created for one session are never listed.
This is the supported way to turn an agent name into the id SessionCreateRequest.AgentID wants. There is no lookup-by-name route, so that means paging until the name matches — worth caching, since an id is stable and a listing is not free.
func (*Client) ListSessionItems ¶
func (c *Client) ListSessionItems( ctx context.Context, sessionID string, opts SessionItemsOptions, ) (*Page[SessionItem], error)
ListSessionItems returns one page of a session's committed items, oldest first unless SessionItemsOptions.Order says otherwise.
This is how a transcript longer than the snapshot's window gets read. The snapshot Client.GetSession returns is built from the newest 100 items and says nothing about what it left out, so on a session that outlives 100 items the item a caller is looking for can sit below that floor — and a session that lives as long as a pull request reaches it in ordinary use. Page here instead, as Page shows, or ask for SortDescending to walk back from the newest.
Items come back as SessionItem, the flat shape this route sends, so a reader written against the snapshot's typed SessionResponse.Items does not carry over to it unchanged.
func (*Client) ListSessions ¶
func (c *Client) ListSessions( ctx context.Context, opts ListSessionsOptions, ) (*Page[SessionListItem], error)
ListSessions returns one page of the sessions this caller may see, newest first unless ListSessionsOptions.Order says otherwise.
Items are summaries, not snapshots: a SessionListItem carries identity, status and labels but no conversation items. Call Client.GetSession for those.
A program that creates sessions can use this to find one it already created instead of creating a second. Filter by ListSessionsOptions.AgentID and match on SessionListItem.Labels, which is why the create request accepts labels: a label the caller controls is what makes its own session recognisable on a later run.
That match has to walk every page, not just this one. There is no server-side label filter, so the label is compared client-side, and the default page holds 20 of an agent's newest sessions — on a program's tenth run its own earlier session is not on the first page. Stopping there finds nothing and creates the duplicate the label existed to prevent, which is the one outcome worth engineering against here, because Client.CreateSession is deliberately not retried. Page as Page shows.
func (*Client) ResolveElicitation ¶
func (c *Client) ResolveElicitation( ctx context.Context, sessionID, elicitationID string, result ElicitationResult, ) (*EventAccepted, error)
ResolveElicitation answers an outstanding elicitation on sessionID. It is Client.SendInput over ApprovalVerdict.
An agent that needs a decision before proceeding parks its turn and publishes an ElicitationRequestEvent. Nothing advances until a verdict arrives, so an unattended program that streams events has to answer these or its session stalls until the server times the elicitation out and synthesises ElicitationCancel.
sessionID must be the session that owns the elicitation, which is not always the session the prompt arrived on: a sub-agent's prompt is mirrored into its ancestors' streams, and ElicitationRequestParams.TargetSessionID then names the owner. The server sets a parked harness Future only for the owner, so a mirrored prompt answered on the stream it was read from is accepted — 202, no error — and can resolve nothing, leaving the sub-agent parked until the elicitation times out. "Can" rather than "does": the verdict is also forwarded to the runner bound to the session it was posted to, and a runner matches its own parked approvals on the elicitation id alone, so a runner-side policy prompt on that runner resolves anyway. That mixture is what makes getting this wrong quiet. Client.ResolveElicitationRequest routes by the event instead.
The server also exposes a dedicated resolve route, which this package does not call. That route is registered include_in_schema=False for an internal flow where the prompt carries the route's own URL for a client to hit directly; its own documentation names this event as the equivalent path with identical resolution semantics, and both do reach the same server-side resolver. Sending the verdict as an input keeps the SDK on one write route instead of two.
func (*Client) ResolveElicitationRequest ¶
func (c *Client) ResolveElicitationRequest( ctx context.Context, sessionID string, request ElicitationRequestEvent, result ElicitationResult, ) (*EventAccepted, error)
ResolveElicitationRequest answers the elicitation one ElicitationRequestEvent asked for, posting to the session that owns it: ElicitationRequestParams.TargetSessionID when the prompt was mirrored from a sub-agent, and sessionID — the stream the event was read from — otherwise.
This is the call to reach for when the verdict answers an event off a stream, because that is where the reader and the owner diverge; see Client.ResolveElicitation for what posting to the reader instead costs. A caller that resolves the target itself is already doing this and gains nothing by switching.
func (*Client) SendInput ¶
func (c *Client) SendInput( ctx context.Context, sessionID string, input SessionEventInput, ) (*EventAccepted, error)
SendInput posts one input to a session and returns the server's acknowledgement.
The call returns as soon as the input is queued; everything the agent does with it arrives on the stream. Send only once the subscription is live, or the turn's first events are published to nobody and lost — the server buffers nothing. There are two ways to get that right, and watching for a SessionHeartbeatEvent is not one of them: the server sends that same event as its idle keepalive too, so a caller that sends on every heartbeat sends forever. Use StreamOptions.OnSubscribed, which fires exactly once, or seed the first turn with SessionCreateRequest.InitialItems and skip the race.
A nil error means the server accepted the input. A redirect cannot make that untrue: 301, 302 and 303 rewrite a POST as a GET, which would drop the body and then decode the GET's 200 into an acknowledgement for a turn nobody queued, so a method-rewriting redirect fails with ErrUnsafeRedirect instead.
func (*Client) SendMessage ¶
SendMessage posts a user message to a session. It is Client.SendInput over UserMessage.
func (*Client) Stream ¶
func (c *Client) Stream(ctx context.Context, sessionID string, opts StreamOptions) iter.Seq2[Event, error]
Stream subscribes to a session's event stream.
Range over the result; each step is one decoded Event or a terminal error:
for event, err := range client.Stream(ctx, sessionID, omnigent.StreamOptions{}) {
if err != nil {
return err
}
// handle event
}
Errors are terminal by construction — an error step is always the last — so the loop needs no break after one. In-stream failures are not errors here: ErrorEvent, RetryEvent and a failed turn all arrive as ordinary events, because none of them ends the subscription. Nor is a frame this build cannot decode: it is skipped, and StreamOptions.OnSkippedFrame is how to see that. Skipping every frame a stream carried is the one exception — that ends in ErrStreamProtocol, so a total decode failure cannot read as a turn that produced nothing.
No I/O happens until the first iteration, and none continues past the last: this spawns no goroutine, so abandoning the loop early cannot leak one. Breaking out of it, or cancelling ctx, closes the response body.
Validation is the one place this package reports an argument error late. Every other entry point returns an error and so rejects a bad argument before doing any work; Stream returns a sequence, which has nowhere to put an error except the sequence itself, so an empty sessionID surfaces as the first and only step — matchable with errors.Is against ErrInvalidArgument.
Ending without an error means the server closed the subscription cleanly. In practice that means the server is shutting down rather than that the turn finished — turn completion is a [CompletedEvent] and its siblings. Every other ending is an error: ErrStreamInterrupted for a body that stopped without the terminal sentinel, ErrStreamIdle for silence past the timeout, ctx's error for cancellation, or an APIError if the subscription was refused outright. Recovery from the first two is snapshot, resubscribe, dedupe — see the package doc.
func (*Client) UpdateSession ¶ added in v0.1.2
func (c *Client) UpdateSession( ctx context.Context, sessionID string, req UpdateSessionRequest, ) (*SessionResponse, error)
UpdateSession changes a session's metadata and returns its updated snapshot. Only the fields set on req are sent, so an unset one is left alone rather than cleared.
This is the non-destructive counterpart to Client.DeleteSession, and the two are not interchangeable for retiring a finished unit of work. Delete cascades: the conversation's items and labels go with it, and so does the sandbox bound to the session. Archiving through UpdateSessionRequest.Archived leaves all of that readable and reusable. Reach for delete when the compute has to stop, and for Archived when only the bookkeeping has to change.
Like Client.SendInput this carries a body, so a method-rewriting redirect would drop the write and decode the resulting GET as if the update had landed. It fails with ErrUnsafeRedirect instead.
A field this cannot express is an explicit null. Absent and null are the same on the wire here, so the overrides whose spec documents null as "clear back to the default" — CostControlModeOverride, SubagentRoutingOverride — can be set and not cleared.
type ClientTaskCancelEvent ¶
type ClientTaskCancelEvent struct {
// CallID Synthetic `call_id` the SDK uses to reconcile the local task; `None` when no pending tool call row exists for the task.
CallID *string `json:"call_id,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// TaskID Identifier of the client-side task being cancelled, e.g. `"resp_async_abc"`.
TaskID string `json:"task_id"`
// Type Always `"response.client_task.cancel"`.
Type ClientTaskCancelEventType `json:"type"`
}
ClientTaskCancelEvent Server-side request that the client cancel a tunneled tool call.
Emitted by the server when a parent cancellation needs to propagate to a long-running async client tool.
Wire type: "response.client_task.cancel".
type ClientTaskCancelEventType ¶
type ClientTaskCancelEventType string
ClientTaskCancelEventType Always `"response.client_task.cancel"`.
const (
ClientTaskCancelEventTypeResponseClientTaskCancel ClientTaskCancelEventType = "response.client_task.cancel"
)
Defines values for ClientTaskCancelEventType.
func (ClientTaskCancelEventType) Valid ¶
func (e ClientTaskCancelEventType) Valid() bool
Valid indicates whether the value is a known member of the ClientTaskCancelEventType enum.
type CompactionCompletedEvent ¶
type CompactionCompletedEvent struct {
CompactedMessages []map[string]interface{} `json:"compacted_messages,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Summary Text summary of the compacted conversation, or `None` for server-side compaction (already persisted).
Summary *string `json:"summary,omitempty"`
// SummaryModel Model used for summarization, or `None` if truncation-based or server-side.
SummaryModel *string `json:"summary_model,omitempty"`
// TotalTokens Tiktoken estimate of the post-compaction message context size, e.g. `8421`. Used by clients to update the context-ring immediately without waiting for the next `response.completed` usage report. `None` when token counting is unavailable.
TotalTokens *int `json:"total_tokens,omitempty"`
// Type Always `"response.compaction.completed"`.
Type CompactionCompletedEventType `json:"type"`
}
CompactionCompletedEvent Conversation history compaction has finished.
Emitted after compaction completes — either by the server after `compact_conversation_now()` (explicit `/compact`), or by a harness that compacted its own internal context. Clients that rendered a "Compacting…" spinner on `CompactionInProgressEvent` should upgrade it to the permanent "Conversation compacted" marker on this event.
When emitted by a harness, `summary` and `summary_model` are populated so the runner can persist a compaction item for session resume. When emitted by the server's explicit `/compact` path, those fields are `None`.
Wire type: "response.compaction.completed".
type CompactionCompletedEventType ¶
type CompactionCompletedEventType string
CompactionCompletedEventType Always `"response.compaction.completed"`.
const (
CompactionCompletedEventTypeResponseCompactionCompleted CompactionCompletedEventType = "response.compaction.completed"
)
Defines values for CompactionCompletedEventType.
func (CompactionCompletedEventType) Valid ¶
func (e CompactionCompletedEventType) Valid() bool
Valid indicates whether the value is a known member of the CompactionCompletedEventType enum.
type CompactionData ¶
type CompactionData struct {
CompactedMessages []map[string]interface{} `json:"compacted_messages,omitempty"`
// LastItemID The item ID (inclusive) of the last conversation item covered by this summary, e.g. `"msg_abc123"`. Items at positions <= this item are summarized and do not need to be loaded for prompt construction.
LastItemID string `json:"last_item_id"`
// Model The model used to generate the summary, e.g. `"openai/gpt-4o"`.
Model *string `json:"model,omitempty"`
// Summary The LLM-generated summary text covering all conversation items up through `last_item_id`, e.g. `"User asked to analyze a dataset. Agent loaded data.csv and computed statistics."`.
Summary string `json:"summary"`
// TokenCount Approximate token count of the summary text, for budget tracking, e.g. `342`.
TokenCount int `json:"token_count"`
WindowID *int `json:"window_id,omitempty"`
}
CompactionData Data payload for a compaction summary item.
Stored as a conversation item of `type="compaction"`. The summary covers all items from the start of the conversation (or the previous compaction item) through the item identified by `last_item_id`.
type CompactionFailedEvent ¶
type CompactionFailedEvent struct {
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.compaction.failed"`.
Type CompactionFailedEventType `json:"type"`
}
CompactionFailedEvent Conversation history compaction failed.
Emitted by the server when `compact_conversation_now()` raises. Clients that rendered a "Compacting…" spinner on `CompactionInProgressEvent` should dismiss it without leaving a permanent marker, since the conversation history was not modified.
Wire type: "response.compaction.failed".
type CompactionFailedEventType ¶
type CompactionFailedEventType string
CompactionFailedEventType Always `"response.compaction.failed"`.
const (
CompactionFailedEventTypeResponseCompactionFailed CompactionFailedEventType = "response.compaction.failed"
)
Defines values for CompactionFailedEventType.
func (CompactionFailedEventType) Valid ¶
func (e CompactionFailedEventType) Valid() bool
Valid indicates whether the value is a known member of the CompactionFailedEventType enum.
type CompactionInProgressEvent ¶
type CompactionInProgressEvent struct {
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.compaction.in_progress"`.
Type CompactionInProgressEventType `json:"type"`
}
CompactionInProgressEvent Conversation history is being compacted.
Emitted by the server while a compaction step runs so clients can render a "summarizing history…" indicator.
Wire type: "response.compaction.in_progress".
type CompactionInProgressEventType ¶
type CompactionInProgressEventType string
CompactionInProgressEventType Always `"response.compaction.in_progress"`.
const (
CompactionInProgressEventTypeResponseCompactionInProgress CompactionInProgressEventType = "response.compaction.in_progress"
)
Defines values for CompactionInProgressEventType.
func (CompactionInProgressEventType) Valid ¶
func (e CompactionInProgressEventType) Valid() bool
Valid indicates whether the value is a known member of the CompactionInProgressEventType enum.
type ConversationDeleted ¶
type ConversationDeleted struct {
// Deleted Always `True`.
Deleted *bool `json:"deleted,omitempty"`
// ID ID of the deleted conversation, e.g. `"conv_abc123"`.
ID string `json:"id"`
// Object Fixed resource type, always `"conversation.deleted"`.
Object *string `json:"object,omitempty"`
}
ConversationDeleted Confirmation payload returned after deleting a conversation.
type ConversationItem ¶
type ConversationItem struct {
// CreatedAt Unix epoch timestamp of creation.
CreatedAt int `json:"created_at"`
// CreatedBy Identity of the human actor who authored this item, or `None` for agent/tool/system items and single-user mode. Lets owner and collaborator messages be distinguished.
CreatedBy *string `json:"created_by,omitempty"`
// Data The typed data payload (MessageData, etc.).
Data ConversationItem_Data `json:"data"`
// ID Store-assigned item ID, e.g. `"msg_abc123"`.
ID string `json:"id"`
// ResponseID The task/response ID this item belongs to.
ResponseID string `json:"response_id"`
// Status Item status, e.g. `"completed"`.
Status string `json:"status"`
// Type Item type, e.g. `"message"`, `"function_call"`.
Type string `json:"type"`
}
ConversationItem A persisted item with a store-assigned ID.
type ConversationItem_Data ¶
type ConversationItem_Data struct {
// contains filtered or unexported fields
}
ConversationItem_Data The typed data payload (MessageData, etc.).
func (ConversationItem_Data) AsCompactionData ¶
func (t ConversationItem_Data) AsCompactionData() (CompactionData, error)
AsCompactionData returns the union data inside the ConversationItem_Data as a CompactionData
func (ConversationItem_Data) AsErrorData ¶
func (t ConversationItem_Data) AsErrorData() (ErrorData, error)
AsErrorData returns the union data inside the ConversationItem_Data as a ErrorData
func (ConversationItem_Data) AsFunctionCallData ¶
func (t ConversationItem_Data) AsFunctionCallData() (FunctionCallData, error)
AsFunctionCallData returns the union data inside the ConversationItem_Data as a FunctionCallData
func (ConversationItem_Data) AsFunctionCallOutputData ¶
func (t ConversationItem_Data) AsFunctionCallOutputData() (FunctionCallOutputData, error)
AsFunctionCallOutputData returns the union data inside the ConversationItem_Data as a FunctionCallOutputData
func (ConversationItem_Data) AsMessageData ¶
func (t ConversationItem_Data) AsMessageData() (MessageData, error)
AsMessageData returns the union data inside the ConversationItem_Data as a MessageData
func (ConversationItem_Data) AsNativeToolData ¶
func (t ConversationItem_Data) AsNativeToolData() (NativeToolData, error)
AsNativeToolData returns the union data inside the ConversationItem_Data as a NativeToolData
func (ConversationItem_Data) AsReasoningData ¶
func (t ConversationItem_Data) AsReasoningData() (ReasoningData, error)
AsReasoningData returns the union data inside the ConversationItem_Data as a ReasoningData
func (ConversationItem_Data) AsResourceEventData ¶
func (t ConversationItem_Data) AsResourceEventData() (ResourceEventData, error)
AsResourceEventData returns the union data inside the ConversationItem_Data as a ResourceEventData
func (ConversationItem_Data) AsRoutingDecisionData ¶
func (t ConversationItem_Data) AsRoutingDecisionData() (RoutingDecisionData, error)
AsRoutingDecisionData returns the union data inside the ConversationItem_Data as a RoutingDecisionData
func (ConversationItem_Data) AsSlashCommandData ¶
func (t ConversationItem_Data) AsSlashCommandData() (SlashCommandData, error)
AsSlashCommandData returns the union data inside the ConversationItem_Data as a SlashCommandData
func (ConversationItem_Data) AsTerminalCommandData ¶
func (t ConversationItem_Data) AsTerminalCommandData() (TerminalCommandData, error)
AsTerminalCommandData returns the union data inside the ConversationItem_Data as a TerminalCommandData
func (*ConversationItem_Data) FromCompactionData ¶
func (t *ConversationItem_Data) FromCompactionData(v CompactionData) error
FromCompactionData overwrites any union data inside the ConversationItem_Data as the provided CompactionData
func (*ConversationItem_Data) FromErrorData ¶
func (t *ConversationItem_Data) FromErrorData(v ErrorData) error
FromErrorData overwrites any union data inside the ConversationItem_Data as the provided ErrorData
func (*ConversationItem_Data) FromFunctionCallData ¶
func (t *ConversationItem_Data) FromFunctionCallData(v FunctionCallData) error
FromFunctionCallData overwrites any union data inside the ConversationItem_Data as the provided FunctionCallData
func (*ConversationItem_Data) FromFunctionCallOutputData ¶
func (t *ConversationItem_Data) FromFunctionCallOutputData(v FunctionCallOutputData) error
FromFunctionCallOutputData overwrites any union data inside the ConversationItem_Data as the provided FunctionCallOutputData
func (*ConversationItem_Data) FromMessageData ¶
func (t *ConversationItem_Data) FromMessageData(v MessageData) error
FromMessageData overwrites any union data inside the ConversationItem_Data as the provided MessageData
func (*ConversationItem_Data) FromNativeToolData ¶
func (t *ConversationItem_Data) FromNativeToolData(v NativeToolData) error
FromNativeToolData overwrites any union data inside the ConversationItem_Data as the provided NativeToolData
func (*ConversationItem_Data) FromReasoningData ¶
func (t *ConversationItem_Data) FromReasoningData(v ReasoningData) error
FromReasoningData overwrites any union data inside the ConversationItem_Data as the provided ReasoningData
func (*ConversationItem_Data) FromResourceEventData ¶
func (t *ConversationItem_Data) FromResourceEventData(v ResourceEventData) error
FromResourceEventData overwrites any union data inside the ConversationItem_Data as the provided ResourceEventData
func (*ConversationItem_Data) FromRoutingDecisionData ¶
func (t *ConversationItem_Data) FromRoutingDecisionData(v RoutingDecisionData) error
FromRoutingDecisionData overwrites any union data inside the ConversationItem_Data as the provided RoutingDecisionData
func (*ConversationItem_Data) FromSlashCommandData ¶
func (t *ConversationItem_Data) FromSlashCommandData(v SlashCommandData) error
FromSlashCommandData overwrites any union data inside the ConversationItem_Data as the provided SlashCommandData
func (*ConversationItem_Data) FromTerminalCommandData ¶
func (t *ConversationItem_Data) FromTerminalCommandData(v TerminalCommandData) error
FromTerminalCommandData overwrites any union data inside the ConversationItem_Data as the provided TerminalCommandData
func (ConversationItem_Data) MarshalJSON ¶
func (t ConversationItem_Data) MarshalJSON() ([]byte, error)
func (*ConversationItem_Data) MergeCompactionData ¶
func (t *ConversationItem_Data) MergeCompactionData(v CompactionData) error
MergeCompactionData performs a merge with any union data inside the ConversationItem_Data, using the provided CompactionData
func (*ConversationItem_Data) MergeErrorData ¶
func (t *ConversationItem_Data) MergeErrorData(v ErrorData) error
MergeErrorData performs a merge with any union data inside the ConversationItem_Data, using the provided ErrorData
func (*ConversationItem_Data) MergeFunctionCallData ¶
func (t *ConversationItem_Data) MergeFunctionCallData(v FunctionCallData) error
MergeFunctionCallData performs a merge with any union data inside the ConversationItem_Data, using the provided FunctionCallData
func (*ConversationItem_Data) MergeFunctionCallOutputData ¶
func (t *ConversationItem_Data) MergeFunctionCallOutputData(v FunctionCallOutputData) error
MergeFunctionCallOutputData performs a merge with any union data inside the ConversationItem_Data, using the provided FunctionCallOutputData
func (*ConversationItem_Data) MergeMessageData ¶
func (t *ConversationItem_Data) MergeMessageData(v MessageData) error
MergeMessageData performs a merge with any union data inside the ConversationItem_Data, using the provided MessageData
func (*ConversationItem_Data) MergeNativeToolData ¶
func (t *ConversationItem_Data) MergeNativeToolData(v NativeToolData) error
MergeNativeToolData performs a merge with any union data inside the ConversationItem_Data, using the provided NativeToolData
func (*ConversationItem_Data) MergeReasoningData ¶
func (t *ConversationItem_Data) MergeReasoningData(v ReasoningData) error
MergeReasoningData performs a merge with any union data inside the ConversationItem_Data, using the provided ReasoningData
func (*ConversationItem_Data) MergeResourceEventData ¶
func (t *ConversationItem_Data) MergeResourceEventData(v ResourceEventData) error
MergeResourceEventData performs a merge with any union data inside the ConversationItem_Data, using the provided ResourceEventData
func (*ConversationItem_Data) MergeRoutingDecisionData ¶
func (t *ConversationItem_Data) MergeRoutingDecisionData(v RoutingDecisionData) error
MergeRoutingDecisionData performs a merge with any union data inside the ConversationItem_Data, using the provided RoutingDecisionData
func (*ConversationItem_Data) MergeSlashCommandData ¶
func (t *ConversationItem_Data) MergeSlashCommandData(v SlashCommandData) error
MergeSlashCommandData performs a merge with any union data inside the ConversationItem_Data, using the provided SlashCommandData
func (*ConversationItem_Data) MergeTerminalCommandData ¶
func (t *ConversationItem_Data) MergeTerminalCommandData(v TerminalCommandData) error
MergeTerminalCommandData performs a merge with any union data inside the ConversationItem_Data, using the provided TerminalCommandData
func (*ConversationItem_Data) UnmarshalJSON ¶
func (t *ConversationItem_Data) UnmarshalJSON(b []byte) error
type ConversationRef ¶
type ConversationRef struct {
// ID Conversation identifier, e.g. `"conv_abc123"`.
ID string `json:"id"`
}
ConversationRef Lightweight reference to a conversation, used in request and response bodies where only the conversation ID is needed.
type DeleteSessionOptions ¶
type DeleteSessionOptions struct {
// DeleteBranch also removes the server-created git worktree and its branch.
// Ignored for sessions without one, and best-effort: a cleanup failure does
// not fail the delete.
DeleteBranch bool
}
DeleteSessionOptions tunes a delete. The zero value leaves any git worktree alone.
type ElicitationAction ¶
type ElicitationAction string
ElicitationAction is a verdict on an outstanding elicitation. The values mirror the Model Context Protocol's ElicitResult.action.
const ( // ElicitationAccept approves: the confirmation was given, or the form was // submitted. Accepting authorises the pending tool to run with the session // owner's execution identity, so the server requires approval access for it // specifically and answers [ErrForbidden] to a caller that only has edit // access. Declining and cancelling need only edit access, so a caller able // to stop an action is not necessarily able to permit one. ElicitationAccept ElicitationAction = "accept" // ElicitationDecline refuses explicitly. ElicitationDecline ElicitationAction = "decline" // ElicitationCancel dismisses without choosing. This is also the verdict the // server synthesises when an elicitation times out, so receiving it does not // prove a client sent it. ElicitationCancel ElicitationAction = "cancel" )
type ElicitationRequestEvent ¶
type ElicitationRequestEvent struct {
// ElicitationID Unique correlation id for this request — appears in the consumer's approval event payload, e.g. `"elicit_abc123"`.
ElicitationID string `json:"elicitation_id"`
// Method MCP method literal — always `"elicitation/create"`.
Method *ElicitationRequestEventMethod `json:"method,omitempty"`
// Params Inner `params` block of a `ElicitationRequestEvent`.
//
// The standard fields (`mode`, `message`, `requestedSchema`,
// `url`) mirror MCP's `ElicitRequestFormParams` /
// `ElicitRequestUrlParams` byte-for-byte (Principle 8 — adopt
// MCP's wire shape verbatim where it overlaps). The
// AP-specific extensions (`phase`, `policy_name`,
// `content_preview`, `target_session_id`) carry policy-engine
// context and mirrored-child routing for the consumer's renderer;
// MCP's `extra="allow"` config permits them under the same params
// block.
Params ElicitationRequestParams `json:"params"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.elicitation_request"`.
Type ElicitationRequestEventType `json:"type"`
}
ElicitationRequestEvent Synchronous request for a decision from upstream.
Emitted by Omnigent (or, under the new contract, by a harness) when the LLM / a tool / a policy needs a verdict before proceeding. The consumer replies via `POST /v1/sessions/{session_id}/events` with `type == "approval"` and `omnigent.server.schemas.ElicitationResult` fields in `data`. This preserves MCP request/reply correlation by id without threading elicitations through PATCH.
Wire type: "response.elicitation_request".
type ElicitationRequestEventMethod ¶
type ElicitationRequestEventMethod string
ElicitationRequestEventMethod MCP method literal — always `"elicitation/create"`.
const (
ElicitationRequestEventMethodElicitationCreate ElicitationRequestEventMethod = "elicitation/create"
)
Defines values for ElicitationRequestEventMethod.
func (ElicitationRequestEventMethod) Valid ¶
func (e ElicitationRequestEventMethod) Valid() bool
Valid indicates whether the value is a known member of the ElicitationRequestEventMethod enum.
type ElicitationRequestEventType ¶
type ElicitationRequestEventType string
ElicitationRequestEventType Always `"response.elicitation_request"`.
const (
ElicitationRequestEventTypeResponseElicitationRequest ElicitationRequestEventType = "response.elicitation_request"
)
Defines values for ElicitationRequestEventType.
func (ElicitationRequestEventType) Valid ¶
func (e ElicitationRequestEventType) Valid() bool
Valid indicates whether the value is a known member of the ElicitationRequestEventType enum.
type ElicitationRequestParams ¶
type ElicitationRequestParams struct {
// ContentPreview Truncated preview of the underlying request payload (≤1024 chars in current AP), for the consumer's renderer.
ContentPreview *string `json:"content_preview,omitempty"`
// Message Human-readable prompt the consumer renders, e.g. `"Approve running 'rm -rf /tmp/cache'?"`.
Message string `json:"message"`
// Mode MCP-standard discriminator. `"form"` collects structured input via `requestedSchema`; `"url"` directs upstream to an external URL for OAuth / out-of-band interaction.
Mode *ElicitationRequestParamsMode `json:"mode,omitempty"`
// Phase Omnigent policy-engine phase the elicitation belongs to, e.g. `"pre_tool_use"`.
Phase *string `json:"phase,omitempty"`
// PolicyName Omnigent policy that triggered the elicitation, e.g. `"approve_shell_commands"`.
PolicyName *string `json:"policy_name,omitempty"`
// RequestedSchema JSON-Schema dict for form mode (or `None` for url mode). camelCase preserved per MCP spec, e.g. `{"type": "object", "properties": {"approve": {"type": "boolean"}}}`.
RequestedSchema map[string]interface{} `json:"requestedSchema,omitempty"`
// TargetSessionID AP session whose resolve endpoint owns this elicitation, e.g. `"conv_child123"`. Present when a child/sub-agent prompt is mirrored into an ancestor stream; `None` means resolve against the current session.
TargetSessionID *string `json:"target_session_id,omitempty"`
// URL External URL for url mode (or `None` for form mode), e.g. `"https://oauth.example.com/authorize?..."`.
URL *string `json:"url,omitempty"`
AdditionalProperties map[string]interface{} `json:"-"`
}
ElicitationRequestParams Inner `params` block of a `ElicitationRequestEvent`.
The standard fields (`mode`, `message`, `requestedSchema`, `url`) mirror MCP's `ElicitRequestFormParams` / `ElicitRequestUrlParams` byte-for-byte (Principle 8 — adopt MCP's wire shape verbatim where it overlaps). The AP-specific extensions (`phase`, `policy_name`, `content_preview`, `target_session_id`) carry policy-engine context and mirrored-child routing for the consumer's renderer; MCP's `extra="allow"` config permits them under the same params block.
func (ElicitationRequestParams) Get ¶
func (a ElicitationRequestParams) Get(fieldName string) (value interface{}, found bool)
Getter for additional properties for ElicitationRequestParams. Returns the specified element and whether it was found
func (ElicitationRequestParams) MarshalJSON ¶
func (a ElicitationRequestParams) MarshalJSON() ([]byte, error)
Override default JSON handling for ElicitationRequestParams to handle AdditionalProperties
func (*ElicitationRequestParams) Set ¶
func (a *ElicitationRequestParams) Set(fieldName string, value interface{})
Setter for additional properties for ElicitationRequestParams
func (*ElicitationRequestParams) UnmarshalJSON ¶
func (a *ElicitationRequestParams) UnmarshalJSON(b []byte) error
Override default JSON handling for ElicitationRequestParams to handle AdditionalProperties
type ElicitationRequestParamsMode ¶
type ElicitationRequestParamsMode string
ElicitationRequestParamsMode MCP-standard discriminator. `"form"` collects structured input via `requestedSchema`; `"url"` directs upstream to an external URL for OAuth / out-of-band interaction.
const ( ElicitationRequestParamsModeForm ElicitationRequestParamsMode = "form" ElicitationRequestParamsModeURL ElicitationRequestParamsMode = "url" )
Defines values for ElicitationRequestParamsMode.
func (ElicitationRequestParamsMode) Valid ¶
func (e ElicitationRequestParamsMode) Valid() bool
Valid indicates whether the value is a known member of the ElicitationRequestParamsMode enum.
type ElicitationResolvedEvent ¶
type ElicitationResolvedEvent struct {
// ElicitationID Correlation id of the elicitation being cleared, e.g. `"elicit_abc123"`. Must match the id of a prior `ElicitationRequestEvent`.
ElicitationID string `json:"elicitation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.elicitation_resolved"`.
Type ElicitationResolvedEventType `json:"type"`
}
ElicitationResolvedEvent Signal that a previously-published elicitation is no longer outstanding, even though no UI `approval` verdict was delivered through `POST /v1/sessions/{id}/events`.
Emitted by the runner when its own internal state Future is popped without a verdict (the runner's wait timed out, the turn was cancelled, the harness exited) so the AP server's `omnigent.runtime.pending_elicitations` index can decrement the sidebar badge in lockstep with the underlying awaiter's lifecycle. Without this signal, the AP server has no way to learn that the prompt is dead and the badge stays stuck.
Idempotent on the consumer side: the Omnigent server's index decrement is a no-op when the id isn't tracked, so the runner can fire-and-forget on every Future cleanup.
Wire type: "response.elicitation_resolved".
type ElicitationResolvedEventType ¶
type ElicitationResolvedEventType string
ElicitationResolvedEventType Always `"response.elicitation_resolved"`.
const (
ElicitationResolvedEventTypeResponseElicitationResolved ElicitationResolvedEventType = "response.elicitation_resolved"
)
Defines values for ElicitationResolvedEventType.
func (ElicitationResolvedEventType) Valid ¶
func (e ElicitationResolvedEventType) Valid() bool
Valid indicates whether the value is a known member of the ElicitationResolvedEventType enum.
type ElicitationResult ¶
type ElicitationResult struct {
// Action is the verdict. Required.
Action ElicitationAction `json:"action"`
// Content carries form values when Action is [ElicitationAccept] and the
// request asked for a schema. Nil for a plain approve/reject, and for
// decline and cancel.
//
// MCP restricts the values to JSON scalars and lists of strings, so a nested
// object or a list of anything else is rejected. The Go type is wider than
// the wire contract because map[string]any is what encoding/json gives a
// caller building one; the server is the enforcement point.
Content map[string]any `json:"content,omitempty"`
}
ElicitationResult is a verdict on one elicitation: the payload half of an InputTypeApproval input.
Hand-written for the same reason as SessionEventInput and EventAccepted: it travels on that same include_in_schema=False route, so openapi.json carries no schema for it and no drift gate covers it. Its field names and semantics mirror MCP's ElicitResult verbatim, which is deliberate on the server's part so an MCP client can bridge without translating.
type ErrorData ¶
type ErrorData struct {
// Code Stable error classifier, e.g. `"native_terminal_start_failed"`.
Code string `json:"code"`
// Message Human-readable error message, e.g. `"Native Codex requires the 'codex' CLI on PATH."`.
Message string `json:"message"`
// Source Error source, e.g. `"execution"`.
Source ErrorDataSource `json:"source"`
}
ErrorData Data for a persisted error banner item.
These items mirror `response.error` events so clients can render the same error banner after reconnect / refresh. They are listed in `NON_CONTENT_ITEM_TYPES` because they are operator-visible transcript metadata, not content the next agent turn should receive.
type ErrorDataSource ¶
type ErrorDataSource string
ErrorDataSource Error source, e.g. `"execution"`.
const ( ErrorDataSourceExecution ErrorDataSource = "execution" ErrorDataSourceLlm ErrorDataSource = "llm" ErrorDataSourceTool ErrorDataSource = "tool" )
Defines values for ErrorDataSource.
func (ErrorDataSource) Valid ¶
func (e ErrorDataSource) Valid() bool
Valid indicates whether the value is a known member of the ErrorDataSource enum.
type ErrorDetail ¶
type ErrorDetail struct {
// Code Error code string, e.g. `"server_error"`, `"invalid_input"`.
Code string `json:"code"`
// Message Human-readable error description.
Message string `json:"message"`
}
ErrorDetail Machine-readable error information attached to a failed response.
type ErrorEvent ¶
type ErrorEvent struct {
// Error Error block carried by `RetryEvent` and `ErrorEvent`.
Error RetryErrorDetail `json:"error"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Source Origin of the error — `"llm"` for LLM-call failures, `"execution"` for timeouts, `"tool"` for tool failures (currently emitted by retry exhaustion paths).
Source ErrorEventSource `json:"source"`
// ToolName Tool identifier when `source == "tool"`; `None` for the other sources.
ToolName *string `json:"tool_name,omitempty"`
// Type Always `"response.error"`.
Type ErrorEventType `json:"type"`
}
ErrorEvent Non-recoverable error reported during the turn.
Emitted from multiple sites in the server — terminal LLM failures, execution timeouts, and the agent-loop catch-all (`except Exception`). Wire shape matches those emits.
Wire type: "response.error".
type ErrorEventSource ¶
type ErrorEventSource string
ErrorEventSource Origin of the error — `"llm"` for LLM-call failures, `"execution"` for timeouts, `"tool"` for tool failures (currently emitted by retry exhaustion paths).
const ( ErrorEventSourceExecution ErrorEventSource = "execution" ErrorEventSourceLlm ErrorEventSource = "llm" ErrorEventSourceTool ErrorEventSource = "tool" )
Defines values for ErrorEventSource.
func (ErrorEventSource) Valid ¶
func (e ErrorEventSource) Valid() bool
Valid indicates whether the value is a known member of the ErrorEventSource enum.
type ErrorEventType ¶
type ErrorEventType string
ErrorEventType Always `"response.error"`.
const (
ErrorEventTypeResponseError ErrorEventType = "response.error"
)
Defines values for ErrorEventType.
func (ErrorEventType) Valid ¶
func (e ErrorEventType) Valid() bool
Valid indicates whether the value is a known member of the ErrorEventType enum.
type Event ¶
type Event interface {
// contains filtered or unexported methods
}
Event is one decoded frame from a session's event stream.
The interface is sealed: its only implementations are the generated event structs in models.gen.go, one per member of the server's discriminated union, plus UnknownEvent. Consume it with a type switch:
switch ev := event.(type) {
case OutputTextDeltaEvent:
fmt.Print(ev.Delta)
case ResponseCompletedEvent:
return nil
}
A minimal correct consumer needs relatively few of the variants. An in-process agent's turn opens at InProgressEvent and closes at exactly one of ResponseCompletedEvent, ResponseFailedEvent, IncompleteEvent or ResponseCancelledEvent. Assistant text arrives as OutputTextDeltaEvent; finished items as OutputItemDoneEvent; session-level state as SessionStatusEvent; and the echo of accepted input as SessionInputConsumedEvent. The rest — elicitation and approval flows, compaction, files, and session-metadata nudges — can be ignored without loss for that scope. That response.* lifecycle is not the whole terminal story; see below.
Five things about the stream shape are easy to get wrong:
ResponseCreatedEvent never arrives on a live turn. The harness emits "response.created" and "response.in_progress" as an inseparable pair, and the server drops the created half at the publish chokepoint that feeds every subscriber — so a subscription sees the in_progress half alone and no created at all. That asymmetry is the design, not a dropped frame; take in_progress, never created, as an in-process turn's opening event.
Every stream opens with a fixed prologue, on every connect. First a SessionHeartbeatEvent, which is the subscription acknowledgement — but note that it is indistinguishable from the keepalive of the same name that the server emits every 15 seconds on an idle stream, so it is a position in the stream and not a payload that marks "ready". Do not act on it; act on StreamOptions.OnSubscribed, which fires once. Then, if a turn is already in flight, a REPLAY of the assistant text so far — already-emitted content, which double-renders if a snapshot was also fetched. Its shape depends on the harness: a message-scoped one (claude-native) replays OutputTextDeltaEvent only, one per in-flight message, while a response-scoped in-process agent's replay is prefixed with a synthesized ResponseCreatedEvent carrying the turn's response object. That prologue is the only place the type is observable. Then a resource snapshot of session.* events. Only then does the live tail begin.
Nothing that arrives in-stream ends the stream. ErrorEvent is non-terminal — the turn may still complete — and RetryEvent is purely informational. A turn ending is not a transport failure, and a transport failure says nothing about the turn, which keeps running server-side.
A turn can end with no response.* event at all, and for some harnesses always does. Two cases, both reached through SessionStatusEvent:
A setup-phase failure — resolving the agent spec, or building the spawn environment — kills the turn before the model stream opens, so no ResponseFailedEvent is ever emitted and the only terminal edge is a Status of "failed". It carries the failure in Error, which the server populates on that status and no other, so Error.Message is the only place the reason appears.
A terminal-backed harness (claude-native) emits no response.completed at all; its turn boundaries are session.* only. The server reads a Status of "idle" or "failed" as "no turn is active", but neither half of that edge resolves a turn on its own. ResponseID names which turn an edge describes and is set on a running edge too, so a turn ends on a terminal Status that also carries one. A running edge carrying a ResponseID is not an end: with BlockedOn set it is parked, and that field names what on. Resolving on ResponseID alone reports a session parked at a permission prompt as a finished turn, and publishes whatever partial reply it had written by then.
In both cases nothing about the transport goes quiet while a consumer waits for a terminal that is not coming: the keepalive SessionHeartbeatEvent holds off ErrStreamIdle, so watching only the response.* terminals turns a fail-fast carrying the server's own message into a hang to the consumer's own deadline. An unattended consumer wants SessionStatusEvent in its terminal switch, and wants Error.Message out of it.
SequenceNumber is not a stream cursor. It is nil on every session.* event and at best restarts from zero each turn on the others. Order by arrival.
Naming ¶
Each variant's doc states its wire type verbatim, and where two namespaces publish the same trailing name both are prefixed with theirs, so no bare name can stand for one of a pair. ResponseHeartbeatEvent is "response.heartbeat" and SessionHeartbeatEvent is "session.heartbeat"; likewise ResponseCreatedEvent against SessionCreatedEvent, and ResponseCompletedEvent, ResponseFailedEvent and ResponseCancelledEvent against their turn.* counterparts. The unprefixed name is nobody's: reaching for the wrong one of a pair now takes a deliberate act rather than a guess.
type EventAccepted ¶
type EventAccepted struct {
// Queued is true when the input became a conversation item, false for a
// control input that queues nothing.
Queued bool `json:"queued"`
// ItemID is the queued item's identifier, present when Queued. It is the
// same id that comes back on the stream as [SessionInputConsumedEvent],
// which makes it the correlation key between a send and its echo.
ItemID string `json:"item_id,omitempty"`
// PendingID identifies a native-terminal message's optimistic placeholder,
// which the consume event later clears. Usually empty.
PendingID string `json:"pending_id,omitempty"`
// Denied reports that the server handled this input synchronously by
// refusing it, rather than queueing a turn for it. It is the difference
// between the two reasons Queued can be false: a control input queues
// nothing by design, while a denied one was rejected and says why in
// [EventAccepted.Reason].
Denied bool `json:"denied,omitempty"`
// Reason is the server's explanation for a denial, e.g.
// "Denied by policy". Empty unless Denied.
//
// Worth reading rather than discarding: without it a refused send is
// indistinguishable from a control input, and a caller that treats every
// unqueued send the same way reports "the server accepted this without
// queueing it" when the server had already said exactly what was wrong.
Reason string `json:"reason,omitempty"`
}
EventAccepted is the acknowledgement a send returns. The server accepts input asynchronously: the turn has been queued, not run.
Hand-written for the same reason as SessionEventInput: it is the response body of the same include_in_schema=False route, so openapi.json documents neither and the drift gate covers neither.
type FunctionCallData ¶
type FunctionCallData struct {
// Arguments JSON-encoded arguments string.
Arguments string `json:"arguments"`
// CallID Unique call identifier from the LLM, e.g. `"call_abc123"`.
CallID string `json:"call_id"`
Model string `json:"model"`
// Name Tool function name, e.g. `"search.web"`.
Name string `json:"name"`
}
FunctionCallData Data for a function_call item.
**Parameters**
- `agent` — Agent name. Serialized as `"model"` in JSON.
type FunctionCallOutputData ¶
type FunctionCallOutputData struct {
// CallID The call_id this output corresponds to, e.g. `"call_abc123"`.
CallID string `json:"call_id"`
// Output The tool's string result.
Output string `json:"output"`
}
FunctionCallOutputData Data for a function_call_output item.
type GetSessionOptions ¶
type GetSessionOptions struct {
// IncludeItems, when false, skips the committed-items read and returns no
// items. It is the most expensive part of building a snapshot, so set it
// false when hydrating the transcript separately.
//
// Leaving it alone does not fetch the whole transcript. The server reads the
// newest 100 items and returns them chronologically, and nothing on the
// response separates a complete transcript from a truncated one, so a
// session that keeps working past 100 items silently loses its oldest.
// [Client.ListSessionItems] is the paged read that reaches them.
IncludeItems *bool
// IncludeLiveness, when false, skips the runner and host liveness lookup.
IncludeLiveness *bool
// RefreshState asks the server to re-derive the session's state before
// answering rather than serving what it has cached.
RefreshState *bool
}
GetSessionOptions tunes what a snapshot includes. A nil field lets the server choose; Ptr makes one. The zero value asks for the server's defaults, which is what reconciling after a dropped stream wants.
type InProgressEvent ¶
type InProgressEvent struct {
// Response API representation of a response (task execution result).
Response ResponseObject `json:"response"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.in_progress"`.
Type InProgressEventType `json:"type"`
}
InProgressEvent Event emitted once the task transitions to in-progress.
Always follows `response.created` (and `response.queued` for background tasks).
Wire type: "response.in_progress".
type InProgressEventType ¶
type InProgressEventType string
InProgressEventType Always `"response.in_progress"`.
const (
InProgressEventTypeResponseInProgress InProgressEventType = "response.in_progress"
)
Defines values for InProgressEventType.
func (InProgressEventType) Valid ¶
func (e InProgressEventType) Valid() bool
Valid indicates whether the value is a known member of the InProgressEventType enum.
type IncompleteDetails ¶
type IncompleteDetails struct {
// Reason Reason the response stopped early, e.g. `"max_output_tokens"`, `"max_tool_calls"`.
Reason string `json:"reason"`
}
IncompleteDetails Details explaining why a response is incomplete.
type IncompleteEvent ¶
type IncompleteEvent struct {
// Response API representation of a response (task execution result).
Response ResponseObject `json:"response"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.incomplete"`.
Type IncompleteEventType `json:"type"`
}
IncompleteEvent Terminal event for a turn that ended without completing (e.g. hit the iteration cap or token budget).
Wire type: "response.incomplete".
type IncompleteEventType ¶
type IncompleteEventType string
IncompleteEventType Always `"response.incomplete"`.
const (
IncompleteEventTypeResponseIncomplete IncompleteEventType = "response.incomplete"
)
Defines values for IncompleteEventType.
func (IncompleteEventType) Valid ¶
func (e IncompleteEventType) Valid() bool
Valid indicates whether the value is a known member of the IncompleteEventType enum.
type ListAgentsOptions ¶
type ListAgentsOptions struct {
// Limit caps the page size. The server accepts 1 to 1000 and defaults to
// 20; zero here sends nothing and takes that default.
Limit int
// After returns the agents following this cursor. Use a previous page's
// [Page.LastID].
After string
// Before returns the agents preceding this cursor. Use a previous page's
// [Page.FirstID].
Before string
// Order is the sort direction. Empty takes the server's default,
// [SortDescending].
Order SortOrder
}
ListAgentsOptions tunes an agent listing. The zero value asks for the server's defaults: the 20 most recently created agents.
type ListSessionsOptions ¶
type ListSessionsOptions struct {
// Limit caps the page size. The server accepts 1 to 1000 and defaults to
// 20; zero here sends nothing and takes that default.
Limit int
// After returns the sessions following this cursor. Use a previous page's
// [Page.LastID].
After string
// Before returns the sessions preceding this cursor. Use a previous page's
// [Page.FirstID].
Before string
// AgentID restricts the listing to one agent by id. This is the filter to
// reach for when reconciling against sessions a program created earlier: it
// is exact, where AgentName resolves through a mutable label.
AgentID string
// AgentName restricts the listing to one agent by name. An agent can be
// renamed, so a program that stores a name rather than an id can start
// matching a different agent, or none.
AgentName string
// Order is the sort direction. Empty takes the server's default,
// [SortDescending].
Order SortOrder
// SortBy is the timestamp to order on. Empty takes the server's default,
// [SessionSortByCreatedAt].
SortBy SessionSortBy
// SearchQuery restricts the listing to sessions matching a free-text
// search. A match populates [SessionListItem.SearchSnippet].
//
// It travels as a query parameter, so it lands in the access log of the
// server and of anything in front of it. Search for a title, not for
// something that would be a problem to find written down.
SearchQuery string
// IncludeArchived also returns archived sessions, which are otherwise
// omitted. [SessionListItem.Archived] tells them apart.
IncludeArchived bool
// Kind selects top-level, sub-agent, or all sessions. Empty takes the
// server's default, [SessionKindDefault].
Kind SessionKind
// Project restricts the listing to one project by id.
Project string
// Pinned restricts the listing to pinned sessions.
Pinned bool
}
ListSessionsOptions tunes a session listing. The zero value asks for the server's defaults: the 20 most recently created top-level sessions the caller can see, excluding archived ones.
The filters combine with AND. AgentID and AgentName both select by agent and are not alternatives to each other: setting both narrows to sessions matching both, which is empty unless they name the same agent.
type MCPServerSummary ¶
type MCPServerSummary struct {
// Args Command-line arguments for `transport="stdio"` servers, e.g. `["mcp-server-github"]`. Empty list when unset.
Args []string `json:"args,omitempty"`
// Command Executable path for `transport="stdio"` servers, e.g. `"uvx"`. `None` for http servers.
Command *string `json:"command,omitempty"`
// Description Optional free-text description from the spec, e.g. `"GitHub MCP server"`. `None` when unset.
Description *string `json:"description,omitempty"`
// Headers HTTP headers for `transport="http"` servers. Values are always `"[REDACTED]"`; only the key names are exposed.
Headers map[string]string `json:"headers,omitempty"`
// Name Server name as declared in the agent spec, e.g. `"github"`.
Name string `json:"name"`
// Transport Transport type — `"stdio"` or `"http"`.
Transport string `json:"transport"`
// URL HTTP(S) endpoint URL for `transport="http"` servers, e.g. `"https://mcp.example.com/sse"`. `None` for stdio servers.
URL *string `json:"url,omitempty"`
}
MCPServerSummary Safe subset of an MCP server's configuration for API exposure.
Header values are redacted (`"[REDACTED]"`) so callers can see which headers are configured without leaking the actual secrets. `env` is still fully excluded.
type McpServerStartup ¶
type McpServerStartup struct {
// Error Failure detail when `status == "failed"`, e.g. `"handshaking with MCP server failed"`. `None` otherwise.
Error *string `json:"error,omitempty"`
// Status Latest startup state reported by the harness, mirroring Codex's `McpServerStartupState` enum.
Status McpServerStartupStatus `json:"status"`
}
McpServerStartup One MCP server's startup state within a `session.mcp_startup` event.
type McpServerStartupStatus ¶
type McpServerStartupStatus string
McpServerStartupStatus Latest startup state reported by the harness, mirroring Codex's `McpServerStartupState` enum.
const ( McpServerStartupStatusCancelled McpServerStartupStatus = "cancelled" McpServerStartupStatusFailed McpServerStartupStatus = "failed" McpServerStartupStatusReady McpServerStartupStatus = "ready" McpServerStartupStatusStarting McpServerStartupStatus = "starting" )
Defines values for McpServerStartupStatus.
func (McpServerStartupStatus) Valid ¶
func (e McpServerStartupStatus) Valid() bool
Valid indicates whether the value is a known member of the McpServerStartupStatus enum.
type MessageData ¶
type MessageData struct {
// Content Heterogeneous content blocks, e.g. `[{"type": "input_text", "text": "Hello"}]`.
Content []map[string]interface{} `json:"content"`
// Interrupted `True` when an assistant message is a durable partial response from an interrupted external-native turn, e.g. Codex `turn/completed` with status `"interrupted"`. Defaults to `False` and is omitted from serialized payloads in that case.
Interrupted *bool `json:"interrupted,omitempty"`
// IsMeta `True` for durable context that must be replayed to agents but hidden from user-facing transcripts, e.g. injected skill instructions. Defaults to `False` and is omitted from serialized payloads in that case.
IsMeta *bool `json:"is_meta,omitempty"`
Model *string `json:"model,omitempty"`
// Role `"user"` or `"assistant"`.
Role MessageDataRole `json:"role"`
}
MessageData Data for a message item (user or assistant).
**Parameters**
- `agent` — Agent name (required for assistant messages, absent for user). Serialized as `"model"` in JSON.
type MessageDataRole ¶
type MessageDataRole string
MessageDataRole `"user"` or `"assistant"`.
const ( MessageDataRoleAssistant MessageDataRole = "assistant" MessageDataRoleUser MessageDataRole = "user" )
Defines values for MessageDataRole.
func (MessageDataRole) Valid ¶
func (e MessageDataRole) Valid() bool
Valid indicates whether the value is a known member of the MessageDataRole enum.
type ModelUsage ¶
type ModelUsage struct {
// CacheCreationInputTokens Cumulative tokens written to the prompt cache, e.g. `2000`. `None` when not recorded.
CacheCreationInputTokens *int `json:"cache_creation_input_tokens,omitempty"`
// CacheReadInputTokens Cumulative tokens read from the prompt cache, e.g. `8000`. `None` when not recorded.
CacheReadInputTokens *int `json:"cache_read_input_tokens,omitempty"`
// InputTokens Cumulative non-cached input (prompt) tokens for this model over the subtree, e.g. `12000`. `None` when not recorded.
InputTokens *int `json:"input_tokens,omitempty"`
// OutputTokens Cumulative output (completion) tokens, e.g. `3400`. `None` when not recorded.
OutputTokens *int `json:"output_tokens,omitempty"`
// TotalCostUsd Cumulative USD spend attributed to this model, e.g. `0.42`. Present **only when this model's turns were priced** (same "priced ⟺ key present" contract as the session total); `None` when the model is unpriced, so the sum of priced per-model costs equals the session `total_cost_usd`.
TotalCostUsd *float32 `json:"total_cost_usd,omitempty"`
// TotalTokens Cumulative total tokens (counts cache buckets too, as the harness reports), e.g. `15400`. `None` when not recorded.
TotalTokens *int `json:"total_tokens,omitempty"`
}
ModelUsage Cumulative token/cost usage attributed to a single LLM model.
One value in the `usage_by_model` map on `SessionResponse` / `SessionUsageEvent`, keyed by the raw harness-reported model id (e.g. `"claude-sonnet-4-6"`, `"databricks-gpt-5-5"`). Counts are summed over the session's subtree (itself + sub-agent descendants), so a parent folds in sub-agents that ran a different model. Token buckets mirror the flat per-session breakdown.
type NativeModelOption ¶
type NativeModelOption struct {
DefaultReasoningEffort *string `json:"defaultReasoningEffort,omitempty"`
DisplayName *string `json:"displayName,omitempty"`
ID string `json:"id"`
IsDefault *bool `json:"isDefault,omitempty"`
Model *string `json:"model,omitempty"`
SupportedReasoningEfforts []NativeReasoningEffortOption `json:"supportedReasoningEfforts,omitempty"`
AdditionalProperties map[string]interface{} `json:"-"`
}
NativeModelOption One runner-owned native model-picker row.
func (NativeModelOption) Get ¶
func (a NativeModelOption) Get(fieldName string) (value interface{}, found bool)
Getter for additional properties for NativeModelOption. Returns the specified element and whether it was found
func (NativeModelOption) MarshalJSON ¶
func (a NativeModelOption) MarshalJSON() ([]byte, error)
Override default JSON handling for NativeModelOption to handle AdditionalProperties
func (*NativeModelOption) Set ¶
func (a *NativeModelOption) Set(fieldName string, value interface{})
Setter for additional properties for NativeModelOption
func (*NativeModelOption) UnmarshalJSON ¶
func (a *NativeModelOption) UnmarshalJSON(b []byte) error
Override default JSON handling for NativeModelOption to handle AdditionalProperties
type NativeReasoningEffortOption ¶
type NativeReasoningEffortOption struct {
Description *string `json:"description,omitempty"`
ReasoningEffort string `json:"reasoningEffort"`
AdditionalProperties map[string]interface{} `json:"-"`
}
NativeReasoningEffortOption Reasoning-effort metadata advertised by a native model catalog.
func (NativeReasoningEffortOption) Get ¶
func (a NativeReasoningEffortOption) Get(fieldName string) (value interface{}, found bool)
Getter for additional properties for NativeReasoningEffortOption. Returns the specified element and whether it was found
func (NativeReasoningEffortOption) MarshalJSON ¶
func (a NativeReasoningEffortOption) MarshalJSON() ([]byte, error)
Override default JSON handling for NativeReasoningEffortOption to handle AdditionalProperties
func (*NativeReasoningEffortOption) Set ¶
func (a *NativeReasoningEffortOption) Set(fieldName string, value interface{})
Setter for additional properties for NativeReasoningEffortOption
func (*NativeReasoningEffortOption) UnmarshalJSON ¶
func (a *NativeReasoningEffortOption) UnmarshalJSON(b []byte) error
Override default JSON handling for NativeReasoningEffortOption to handle AdditionalProperties
type NativeToolData ¶
type NativeToolData struct {
// Item The raw dict from the Responses API output, e.g. `{"type": "web_search_call", "id": "ws_abc", "status": "completed", "action": {...}}`.
Item map[string]interface{} `json:"item"`
}
NativeToolData A provider-native tool output item (e.g. `web_search_call`).
These are executed server-side by the LLM provider and returned as opaque dicts. Agent-plane persists and replays them so the LLM sees its own tool results on subsequent iterations.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option customises a Client during New.
The interface is sealed: its only implementations are this package's With* functions. That keeps the option set something this package can reason about — every option's effect is visible here — and leaves room to change what an option configures without changing what an option is.
func WithAuthHeader ¶
WithAuthHeader sends name: value on every request.
Use it for the trusted-proxy identity header, whose name is a deployment setting rather than a constant — X-Forwarded-Email is only the default.
Note that net/http does not strip a custom header across a redirect, the way it strips Authorization and Cookie. This package's redirect policy is what keeps that from mattering; see ErrUnsafeRedirect.
func WithBearerToken ¶
WithBearerToken sends token as an Authorization: Bearer header, the fallback the server accepts from non-browser clients in its OIDC and accounts modes.
func WithHTTPClient ¶
WithHTTPClient makes the Client issue its requests through httpClient.
The Client copies httpClient rather than holding it, and derives its streaming client from that copy by clearing Timeout — so a timeout set here applies to unary calls only and never truncates a stream. Set Transport.ResponseHeaderTimeout if header latency should stay bounded; the transport is the caller's here, so this package does not touch it.
A Timeout on httpClient stands unless WithUnaryTimeout is also given, which outranks it. Note what that bound has to clear either way: the server awaits a runner before it answers a session create, and again when it forwards an event to one, so a half-minute Timeout carried over from another API client aborts calls this server is still legitimately serving.
A nil CheckRedirect is replaced with this package's policy, which refuses to carry credentials off the base URL's host or down to plain http; see ErrUnsafeRedirect. Setting CheckRedirect yourself keeps yours, including nothing at all, and with it the responsibility for what the credentials do.
func WithInsecureCredentialTransport ¶
func WithInsecureCredentialTransport() Option
WithInsecureCredentialTransport permits sending a credential over plain http to a host that is not loopback, which New otherwise refuses.
It exists because "refuse" is the only fail-closed answer available to a library: a warning has nowhere to go — there is no logger here, and writing to stderr from a package is not this package's call — and silence is how a token ends up on a shared network. Refusing by default puts the decision where the deployment knowledge is, and this option is how a caller records having made it.
The legitimate cases are ones where the plaintext hop is not really a network: a sidecar on the same pod, a port-forward, a mesh that terminates TLS for you. On anything reachable by a third party it is not a trade-off, it is a leak.
func WithSessionCookie ¶
WithSessionCookie sends value as the server's session cookie, which an interactive login mints. name is the cookie's name: ap_session over plain HTTP, __Host-ap_session under HTTPS.
Applying it more than once appends to the single Cookie header rather than emitting a second one, which is what RFC 6265 requires of a client and what the server's ASGI framework reads.
func WithStreamIdleTimeout ¶
WithStreamIdleTimeout sets how long Client.Stream tolerates silence before treating the transport as dead. Zero restores the default of three heartbeat intervals. A per-call StreamOptions.IdleTimeout overrides it.
func WithUnaryTimeout ¶
WithUnaryTimeout sets how long one whole non-streaming exchange may take — connect, request, response headers and body — on every call except Client.Stream, which carries no whole-exchange deadline at all: a stream's liveness is WithStreamIdleTimeout and its deadline is the caller's context. Zero restores the default.
The response-header bound on the transport this package builds follows this value, because it covers the same wait and a tighter one would decide the deadline instead. It does not follow the value below the floor a stream open needs: a Client's streaming and unary calls share one transport, and the server withholds a stream's first byte until the event relay has subscribed.
Under WithHTTPClient the transport belongs to the caller, so this sets the whole-exchange timeout alone — outranking any Timeout on the supplied client, whichever order the two options are written in — and leaves Transport.ResponseHeaderTimeout as the caller set it.
Prefer a context deadline for anything call-specific. This is one value for every unary call; its job is to stop a wedged connection hanging forever rather than to express a latency policy.
func WithUserAgent ¶
WithUserAgent sets the User-Agent header on every request.
type OutputFileDoneEvent ¶
type OutputFileDoneEvent struct {
// ContentType MIME content type if the annotation supplied one, e.g. `"application/pdf"`. `None` otherwise.
ContentType *string `json:"content_type,omitempty"`
// FileID Identifier of the materialized file, e.g. `"file_abc123"`.
FileID string `json:"file_id"`
// Filename Original filename if the annotation supplied one, e.g. `"report.pdf"`. `None` otherwise.
Filename *string `json:"filename,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.output_file.done"`.
Type OutputFileDoneEventType `json:"type"`
}
OutputFileDoneEvent A streamed file output completed materializing.
Emitted by the server once per file annotation in the assistant's output. `filename` and `content_type` are only populated when the originating annotation carried them.
Wire type: "response.output_file.done".
type OutputFileDoneEventType ¶
type OutputFileDoneEventType string
OutputFileDoneEventType Always `"response.output_file.done"`.
const (
OutputFileDoneEventTypeResponseOutputFileDone OutputFileDoneEventType = "response.output_file.done"
)
Defines values for OutputFileDoneEventType.
func (OutputFileDoneEventType) Valid ¶
func (e OutputFileDoneEventType) Valid() bool
Valid indicates whether the value is a known member of the OutputFileDoneEventType enum.
type OutputItemDoneEvent ¶
type OutputItemDoneEvent struct {
// Item The completed item dict. Heterogeneous and item-type-specific; see the server for the per-type `*Data` shapes that drive serialization. Example for a function_call item: `{"id": "fc_abc123", "type": "function_call", "status": "action_required", "name": "search.web", "arguments": "{\"q\": \"foo\"}", "call_id": "call_xyz"}`.
Item map[string]interface{} `json:"item"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.output_item.done"`.
Type OutputItemDoneEventType `json:"type"`
}
OutputItemDoneEvent A conversation output item completed during the turn.
Carries any item type the conversation persists (message, function_call, function_call_output, reasoning, compaction, native_tool, …). The `item` payload's wire shape merges common fields (`id`, `type`, `status`) with the type-specific data fields — it is NOT nested as `{type, data}`.
Wire type: "response.output_item.done".
type OutputItemDoneEventType ¶
type OutputItemDoneEventType string
OutputItemDoneEventType Always `"response.output_item.done"`.
const (
OutputItemDoneEventTypeResponseOutputItemDone OutputItemDoneEventType = "response.output_item.done"
)
Defines values for OutputItemDoneEventType.
func (OutputItemDoneEventType) Valid ¶
func (e OutputItemDoneEventType) Valid() bool
Valid indicates whether the value is a known member of the OutputItemDoneEventType enum.
type OutputTextDeltaEvent ¶
type OutputTextDeltaEvent struct {
// Delta The text fragment for this chunk, e.g. `"Hello"`.
Delta string `json:"delta"`
// Final `True` on the last chunk of a terminal-observed message; `None` otherwise. Signals the web UI that no further chunks for `message_id` will arrive.
Final *bool `json:"final,omitempty"`
// Index 0-based chunk order within the message, e.g. `3`. `None` when not terminal-observed streaming.
Index *int `json:"index,omitempty"`
// MessageID For terminal-observed streaming (claude-native), the vendor's stable per-message id, e.g. `"2ca51d97-2f0f-493a-aed7-85a5b56c5747"`. Lets the web UI scope an in-flight buffer to one assistant message and reconcile it against the final item. `None` for ordinary in-process task streaming, where deltas already group by the active response.
MessageID *string `json:"message_id,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.output_text.delta"`.
Type OutputTextDeltaEventType `json:"type"`
}
OutputTextDeltaEvent Incremental assistant-text token emitted during streaming.
Wire type: "response.output_text.delta".
type OutputTextDeltaEventType ¶
type OutputTextDeltaEventType string
OutputTextDeltaEventType Always `"response.output_text.delta"`.
const (
OutputTextDeltaEventTypeResponseOutputTextDelta OutputTextDeltaEventType = "response.output_text.delta"
)
Defines values for OutputTextDeltaEventType.
func (OutputTextDeltaEventType) Valid ¶
func (e OutputTextDeltaEventType) Valid() bool
Valid indicates whether the value is a known member of the OutputTextDeltaEventType enum.
type Page ¶
type Page[T any] struct { // Data is this page's items, in the requested order. Empty on the last page // of an exhausted listing, and empty rather than nil when the server sends // an empty array. Data []T `json:"data"` // FirstID is the id of Data's first item, the cursor for paging backwards. // Empty when Data is. FirstID string `json:"first_id,omitempty"` // LastID is the id of Data's last item, the cursor for paging forwards. // Empty when Data is. LastID string `json:"last_id,omitempty"` // HasMore reports whether more items exist beyond this page in the requested // direction — the direction is baked in, because the server applies the // cursor comparison and the ordering together. // // It is the loop condition, and a full page does not imply another one: the // server asks for one row more than the limit and reports whether it got it. // That also means a true HasMore beside an empty Data is not something this // server produces. Terminate on both anyway, per the loop above — an empty // page carries an empty LastID, so a caller that trusts HasMore alone re-reads // the first page for as long as a proxy or a future server keeps saying yes. HasMore bool `json:"has_more"` }
Page is one page of a cursor-paginated listing.
Every listing shares this envelope because the server does: GET /v1/agents, GET /v1/sessions and GET /v1/sessions/{id}/items return the same four fields around a differently-typed Page.Data. The server also sends a constant "object": "list" alongside them, which the Go type already conveys, so it is not carried here.
Paging is by opaque cursor, not offset. To walk a listing, pass the previous page's Page.LastID as the next request's After while Page.HasMore is true:
opts := omnigent.ListSessionsOptions{AgentID: agentID}
for {
page, err := client.ListSessions(ctx, opts)
if err != nil {
return err
}
for _, s := range page.Data {
// ...
}
// Two conditions, not one. HasMore is the server's answer; the empty
// check is what makes the loop terminate on its own rather than on the
// server's good behaviour. An empty page yields an empty LastID, so
// continuing would re-request the first page forever.
if !page.HasMore || len(page.Data) == 0 {
break
}
opts.After = page.LastID
}
Reversing that walk means Before and Page.FirstID instead. Do not derive a cursor from an item yourself: the ids are the server's and only the ones it hands back are guaranteed to page correctly under a given Order.
type PolicyDeniedEvent ¶
type PolicyDeniedEvent struct {
// ConversationID Session/conversation id the DENY applies to, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
// Phase The policy phase the DENY landed on, e.g. `"tool_call"`.
Phase *string `json:"phase,omitempty"`
// Reason Human-readable deny reason from the deciding policy, e.g. `"Blocked by policy."`.
Reason *string `json:"reason,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.policy_denied"`.
Type PolicyDeniedEventType `json:"type"`
}
PolicyDeniedEvent Signal that a policy DENY was enforced on a native harness turn.
A native harness (Claude Code, Codex,...) routes each tool call and prompt through Omnigent's policy engine via the vendor command-hook (`POST /v1/sessions/{id}/policies/evaluate`). The DENY verdict is returned synchronously to that hook, so unlike the SDK/wrap path there is no stream-visible signal that a native action was blocked — only the *effect* (the blocked tool never runs). This event surfaces the decision itself on the session stream so observers (the web UI, the capability bench) can see a native DENY as a positive signal rather than infer it from an absence.
Fire-and-forget and observational: it does not gate the turn (the hook response already did that) and carries no correlation id.
Wire type: "response.policy_denied".
type PolicyDeniedEventType ¶
type PolicyDeniedEventType string
PolicyDeniedEventType Always `"response.policy_denied"`.
const (
PolicyDeniedEventTypeResponsePolicyDenied PolicyDeniedEventType = "response.policy_denied"
)
Defines values for PolicyDeniedEventType.
func (PolicyDeniedEventType) Valid ¶
func (e PolicyDeniedEventType) Valid() bool
Valid indicates whether the value is a known member of the PolicyDeniedEventType enum.
type PolicySummary ¶
type PolicySummary struct {
// Description Short detail string about the policy implementation. For function policies: the callable dotted path. For prompt policies: the first line of the prompt. `None` when not available.
Description *string `json:"description,omitempty"`
// Name Policy name as declared in the agent spec, e.g. `"block_long_sleep"`.
Name string `json:"name"`
// On List of phase selectors the policy fires on, e.g. `["tool_call"]` or `["request", "response"]`.
On []string `json:"on"`
// Type Policy type discriminator — `"function"` or `"prompt"`.
Type string `json:"type"`
}
PolicySummary Safe subset of a policy's spec for API exposure.
Exposes the policy name, type, and phases so the UI can display which guardrails are active on an agent. The full policy body (prompt text, callable path, label conditions) is intentionally excluded — this is a summary for display, not a full spec.
type PresenceViewer ¶
type PresenceViewer struct {
// Idle Whether every stream the user holds reports an idle (backgrounded) tab. The web greys idle viewers' avatars.
Idle *bool `json:"idle,omitempty"`
// JoinedAt ISO 8601 UTC timestamp of when the user joined, e.g. `"2026-06-10T17:00:00Z"`. Stable across reconnects within the server's leave-grace window.
JoinedAt string `json:"joined_at"`
// UserID The viewer's authenticated identity, e.g. `"alice@example.com"`. Never the reserved single-user `"local"` sentinel — presence only tracks distinct human actors (see `attribution_user`).
UserID string `json:"user_id"`
}
PresenceViewer One user currently viewing a session (holding its SSE stream open).
type QueuedEvent ¶
type QueuedEvent struct {
// Response API representation of a response (task execution result).
Response ResponseObject `json:"response"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.queued"`.
Type QueuedEventType `json:"type"`
}
QueuedEvent Optional event emitted between `created` and `in_progress` for background tasks that are queued before they start.
Foreground streaming responses skip this event.
Wire type: "response.queued".
type QueuedEventType ¶
type QueuedEventType string
QueuedEventType Always `"response.queued"`.
const (
QueuedEventTypeResponseQueued QueuedEventType = "response.queued"
)
Defines values for QueuedEventType.
func (QueuedEventType) Valid ¶
func (e QueuedEventType) Valid() bool
Valid indicates whether the value is a known member of the QueuedEventType enum.
type ReasoningData ¶
type ReasoningData struct {
// Content Raw reasoning content blocks, or `None` if redacted.
Content []map[string]string `json:"content,omitempty"`
// EncryptedContent Encrypted reasoning content, or `None`.
EncryptedContent *string `json:"encrypted_content,omitempty"`
Model string `json:"model"`
// Summary Summary text blocks, e.g. `[{"type": "summary_text", "text": "..."}]`.
Summary []map[string]string `json:"summary"`
}
ReasoningData Data for a reasoning item.
**Parameters**
- `agent` — Agent name. Serialized as `"model"` in JSON.
type ReasoningStartedEvent ¶
type ReasoningStartedEvent struct {
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.reasoning.started"`.
Type ReasoningStartedEventType `json:"type"`
}
ReasoningStartedEvent Marker emitted once when a reasoning block begins.
Fired even when the reasoning content itself is encrypted / redacted (so no delta events follow), letting clients render a "thinking…" indicator regardless of provider verification status.
Wire type: "response.reasoning.started".
type ReasoningStartedEventType ¶
type ReasoningStartedEventType string
ReasoningStartedEventType Always `"response.reasoning.started"`.
const (
ReasoningStartedEventTypeResponseReasoningStarted ReasoningStartedEventType = "response.reasoning.started"
)
Defines values for ReasoningStartedEventType.
func (ReasoningStartedEventType) Valid ¶
func (e ReasoningStartedEventType) Valid() bool
Valid indicates whether the value is a known member of the ReasoningStartedEventType enum.
type ReasoningSummaryTextDeltaEvent ¶
type ReasoningSummaryTextDeltaEvent struct {
// Delta The summary text fragment, e.g. `"Will use the search tool to gather context."`.
Delta string `json:"delta"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.reasoning_summary_text.delta"`.
Type ReasoningSummaryTextDeltaEventType `json:"type"`
}
ReasoningSummaryTextDeltaEvent Incremental reasoning-summary token.
Emitted when `reasoning.summary` is configured on the request.
Wire type: "response.reasoning_summary_text.delta".
type ReasoningSummaryTextDeltaEventType ¶
type ReasoningSummaryTextDeltaEventType string
ReasoningSummaryTextDeltaEventType Always `"response.reasoning_summary_text.delta"`.
const (
ReasoningSummaryTextDeltaEventTypeResponseReasoningSummaryTextDelta ReasoningSummaryTextDeltaEventType = "response.reasoning_summary_text.delta"
)
Defines values for ReasoningSummaryTextDeltaEventType.
func (ReasoningSummaryTextDeltaEventType) Valid ¶
func (e ReasoningSummaryTextDeltaEventType) Valid() bool
Valid indicates whether the value is a known member of the ReasoningSummaryTextDeltaEventType enum.
type ReasoningTextDeltaEvent ¶
type ReasoningTextDeltaEvent struct {
// Delta The reasoning text fragment, e.g. `"Considering the user's intent..."`.
Delta string `json:"delta"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.reasoning_text.delta"`.
Type ReasoningTextDeltaEventType `json:"type"`
}
ReasoningTextDeltaEvent Incremental reasoning-text token (full chain-of-thought).
Only emitted by providers that surface reasoning content (e.g. OpenAI o-series with appropriate verification). Wire shape matches the server.
Wire type: "response.reasoning_text.delta".
type ReasoningTextDeltaEventType ¶
type ReasoningTextDeltaEventType string
ReasoningTextDeltaEventType Always `"response.reasoning_text.delta"`.
const (
ReasoningTextDeltaEventTypeResponseReasoningTextDelta ReasoningTextDeltaEventType = "response.reasoning_text.delta"
)
Defines values for ReasoningTextDeltaEventType.
func (ReasoningTextDeltaEventType) Valid ¶
func (e ReasoningTextDeltaEventType) Valid() bool
Valid indicates whether the value is a known member of the ReasoningTextDeltaEventType enum.
type ResourceEventData ¶
type ResourceEventData struct {
// EventType The SSE event type literal, e.g. `"session.resource.created"` or `"session.resource.deleted"`.
EventType string `json:"event_type"`
// Resource Full resource object dict for `created` events. `None` for `deleted` events.
Resource map[string]interface{} `json:"resource,omitempty"`
// ResourceID Opaque id of the affected resource, e.g. `"terminal_bash_s1"` or `"file_abc123"`.
ResourceID string `json:"resource_id"`
// ResourceType Kind of resource, e.g. `"terminal"`, `"file"`, `"environment"`.
ResourceType string `json:"resource_type"`
}
ResourceEventData Data payload for a persisted resource lifecycle event.
These items are written to the conversation store when a session resource is created or deleted, so reconnecting clients can discover resource history without replaying the live SSE stream. The agent loop filters them out of the LLM's message context (they are metadata, not conversation content).
type ResponseCancelledEvent ¶
type ResponseCancelledEvent struct {
// Response API representation of a response (task execution result).
Response ResponseObject `json:"response"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.cancelled"`.
Type ResponseCancelledEventType `json:"type"`
}
ResponseCancelledEvent Terminal event for a turn cancelled before completion.
Wire type: "response.cancelled".
type ResponseCancelledEventType ¶
type ResponseCancelledEventType string
ResponseCancelledEventType Always `"response.cancelled"`.
const (
ResponseCancelledEventTypeResponseCancelled ResponseCancelledEventType = "response.cancelled"
)
Defines values for ResponseCancelledEventType.
func (ResponseCancelledEventType) Valid ¶
func (e ResponseCancelledEventType) Valid() bool
Valid indicates whether the value is a known member of the ResponseCancelledEventType enum.
type ResponseCompletedEvent ¶
type ResponseCompletedEvent struct {
// Response API representation of a response (task execution result).
Response ResponseObject `json:"response"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.completed"`.
Type ResponseCompletedEventType `json:"type"`
}
ResponseCompletedEvent Terminal event for a successfully completed turn.
Carries the final `omnigent.server.schemas.ResponseObject`.
Wire type: "response.completed".
type ResponseCompletedEventType ¶
type ResponseCompletedEventType string
ResponseCompletedEventType Always `"response.completed"`.
const (
ResponseCompletedEventTypeResponseCompleted ResponseCompletedEventType = "response.completed"
)
Defines values for ResponseCompletedEventType.
func (ResponseCompletedEventType) Valid ¶
func (e ResponseCompletedEventType) Valid() bool
Valid indicates whether the value is a known member of the ResponseCompletedEventType enum.
type ResponseCreatedEvent ¶
type ResponseCreatedEvent struct {
// Response API representation of a response (task execution result).
Response ResponseObject `json:"response"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.created"`.
Type ResponseCreatedEventType `json:"type"`
}
ResponseCreatedEvent Initial event emitted at the start of every streaming response.
Carries the freshly-allocated `omnigent.server.schemas.ResponseObject` (status will be `"queued"` or `"in_progress"` depending on whether the task started immediately).
Wire type: "response.created".
type ResponseCreatedEventType ¶
type ResponseCreatedEventType string
ResponseCreatedEventType Always `"response.created"`.
const (
ResponseCreatedEventTypeResponseCreated ResponseCreatedEventType = "response.created"
)
Defines values for ResponseCreatedEventType.
func (ResponseCreatedEventType) Valid ¶
func (e ResponseCreatedEventType) Valid() bool
Valid indicates whether the value is a known member of the ResponseCreatedEventType enum.
type ResponseFailedEvent ¶
type ResponseFailedEvent struct {
// Response API representation of a response (task execution result).
Response ResponseObject `json:"response"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.failed"`.
Type ResponseFailedEventType `json:"type"`
}
ResponseFailedEvent Terminal event for a turn that ended with an error.
Carries the final `omnigent.server.schemas.ResponseObject` whose `error` field describes the failure.
Wire type: "response.failed".
type ResponseFailedEventType ¶
type ResponseFailedEventType string
ResponseFailedEventType Always `"response.failed"`.
const (
ResponseFailedEventTypeResponseFailed ResponseFailedEventType = "response.failed"
)
Defines values for ResponseFailedEventType.
func (ResponseFailedEventType) Valid ¶
func (e ResponseFailedEventType) Valid() bool
Valid indicates whether the value is a known member of the ResponseFailedEventType enum.
type ResponseHeartbeatEvent ¶
type ResponseHeartbeatEvent struct {
// LastEventSeq Sequence number of the last non- heartbeat event seen on the same stream, e.g. `42`. `None` before any user-visible event has fired (first heartbeat of the turn, before deltas land), or when the producer chose not to populate it.
LastEventSeq *int `json:"last_event_seq,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// ServerTime ISO 8601 UTC timestamp at emission, e.g. `"2026-04-27T15:30:00Z"`. `None` when the producer chose not to populate it (legacy emitters).
ServerTime *string `json:"server_time,omitempty"`
// Type Always `"response.heartbeat"`.
Type ResponseHeartbeatEventType `json:"type"`
}
ResponseHeartbeatEvent Keepalive event emitted on a fixed cadence during streaming.
Lets consumers detect stalled producers via missed-interval timing. Cadence is set by the server (15 seconds at the time of writing).
Per `designs/SERVER_HARNESS_CONTRACT.md` §Heartbeats, the event MAY carry timing metadata so consumers can do richer dead-detection than "did anything arrive":
- `server_time` is the producer's wall-clock at emission, letting consumers detect clock drift between producer and consumer.
- `last_event_seq` is the `sequence_number` of the most recent NON-heartbeat event (or `None` when this is the first heartbeat before any user-visible event), letting consumers detect dropped events on reconnect.
Both fields are optional on the wire (`None` round-trips as omitted) so older AP→harness pairs that pre-date the field addition still parse cleanly.
Wire type: "response.heartbeat".
type ResponseHeartbeatEventType ¶
type ResponseHeartbeatEventType string
ResponseHeartbeatEventType Always `"response.heartbeat"`.
const (
ResponseHeartbeatEventTypeResponseHeartbeat ResponseHeartbeatEventType = "response.heartbeat"
)
Defines values for ResponseHeartbeatEventType.
func (ResponseHeartbeatEventType) Valid ¶
func (e ResponseHeartbeatEventType) Valid() bool
Valid indicates whether the value is a known member of the ResponseHeartbeatEventType enum.
type ResponseObject ¶
type ResponseObject struct {
// Background Whether this response was created as a background task.
Background *bool `json:"background,omitempty"`
// CompletedAt Unix epoch timestamp of completion, or `None` if not yet complete.
CompletedAt *int `json:"completed_at,omitempty"`
// Conversation Lightweight reference to a conversation, used in request and
// response bodies where only the conversation ID is needed.
Conversation *ConversationRef `json:"conversation,omitempty"`
// CreatedAt Unix epoch timestamp of creation.
CreatedAt int `json:"created_at"`
// Error Machine-readable error information attached to a failed response.
Error *ErrorDetail `json:"error,omitempty"`
// ID Unique response identifier, e.g. `"resp_abc123"`.
ID string `json:"id"`
// IncompleteDetails Details explaining why a response is incomplete.
IncompleteDetails *IncompleteDetails `json:"incomplete_details,omitempty"`
// Instructions Per-request system instructions override, or `None`.
Instructions *string `json:"instructions,omitempty"`
// Model Agent name that produced this response, e.g. `"research-agent"`.
Model string `json:"model"`
// Object Fixed resource type, always `"response"`.
Object *string `json:"object,omitempty"`
// Output Heterogeneous output items (messages, reasoning, function_calls) serialized as dicts; shape varies by item type. Empty for non-completed responses.
Output []map[string]interface{} `json:"output,omitempty"`
// PreviousResponseID ID of the prior response in the conversation thread, or `None` for the first turn.
PreviousResponseID *string `json:"previous_response_id,omitempty"`
// Reasoning Reasoning configuration, e.g. `{"effort": "medium"}`.
Reasoning map[string]string `json:"reasoning,omitempty"`
// Status Lifecycle status, one of `"queued"`, `"in_progress"`, `"completed"`, `"failed"`, `"incomplete"`, `"cancelled"`.
Status string `json:"status"`
// Store Whether this response is persisted. Always `True`.
Store *bool `json:"store,omitempty"`
// Usage Token usage statistics for a response.
Usage *Usage `json:"usage,omitempty"`
}
ResponseObject API representation of a response (task execution result).
type RetryErrorDetail ¶
type RetryErrorDetail struct {
// Code Stable error classifier, e.g. `"timeout"`, `"rate_limit"`.
Code string `json:"code"`
// Detail Optional provider-specific structured fields (e.g. `{"status_code": 429, "retry_after": 5}`); `None` when the classifier had no extra context.
Detail map[string]interface{} `json:"detail,omitempty"`
// Message Human-readable summary, e.g. `"Connection timed out after 30s"`.
Message string `json:"message"`
}
RetryErrorDetail Error block carried by `RetryEvent` and `ErrorEvent`.
type RetryEvent ¶
type RetryEvent struct {
// Attempt 1-based count of the upcoming attempt (i.e. attempt that will run AFTER this delay), e.g. `2` for the first retry.
Attempt int `json:"attempt"`
// DelaySeconds Seconds the producer will sleep before retrying, rounded to two decimals, e.g. `1.5`.
DelaySeconds float32 `json:"delay_seconds"`
// Error Error block carried by `RetryEvent` and `ErrorEvent`.
Error RetryErrorDetail `json:"error"`
// MaxAttempts Total tries allowed by the retry policy, e.g. `3`. Lets clients render "attempt 2 of 3".
MaxAttempts int `json:"max_attempts"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Source Origin of the retried failure — `"llm"` for LLM-call retries, `"tool"` for tool-call retries.
Source RetryEventSource `json:"source"`
// ToolName Tool identifier when `source == "tool"`, e.g. `"search.web"`. `None` for LLM retries.
ToolName *string `json:"tool_name,omitempty"`
// Type Always `"response.retry"`.
Type RetryEventType `json:"type"`
}
RetryEvent A retryable failure was caught and a retry is scheduled.
Wire type: "response.retry".
type RetryEventSource ¶
type RetryEventSource string
RetryEventSource Origin of the retried failure — `"llm"` for LLM-call retries, `"tool"` for tool-call retries.
const ( RetryEventSourceLlm RetryEventSource = "llm" RetryEventSourceTool RetryEventSource = "tool" )
Defines values for RetryEventSource.
func (RetryEventSource) Valid ¶
func (e RetryEventSource) Valid() bool
Valid indicates whether the value is a known member of the RetryEventSource enum.
type RetryEventType ¶
type RetryEventType string
RetryEventType Always `"response.retry"`.
const (
RetryEventTypeResponseRetry RetryEventType = "response.retry"
)
Defines values for RetryEventType.
func (RetryEventType) Valid ¶
func (e RetryEventType) Valid() bool
Valid indicates whether the value is a known member of the RetryEventType enum.
type RoutingDecisionData ¶
type RoutingDecisionData struct {
Agent *string `json:"agent,omitempty"`
// Applied `True` when the brain actually ran on `model` this turn (optimize mode, no user pin); `False` when the router only WOULD have picked it (advise/shadow mode, or a user model pin won) — the UI renders "would have picked".
Applied bool `json:"applied"`
// AttemptedOverride Model the spawning agent asked for and the router overrode, e.g. `"databricks-gpt-5-5"` — an LLM-supplied `args.model` on a child session, or a native spawn's own `requested_model`. `None` when nothing was asked for, or when the router's pick names the same arm as the ask.
AttemptedOverride *string `json:"attempted_override,omitempty"`
// DecisionID Router decision identifier, e.g. `"3f1c…"`. Correlates the transcript item with the routing telemetry event and the child-sessions API row. `None` for decisions made before decision ids existed.
DecisionID *string `json:"decision_id,omitempty"`
// Harness Harness the decision applies to, e.g. `"claude-native"` or `"codex"`. `None` when the decision picked a model only (no harness dimension).
Harness *string `json:"harness,omitempty"`
// Model The concrete brain model the router chose, e.g. `"databricks-claude-opus-4-8"`.
Model string `json:"model"`
// Rationale The router's one-line explanation, shown as muted secondary text, e.g. `"Multi-file refactor needs deep reasoning."`.
Rationale string `json:"rationale"`
// RawModel The router-vocabulary pick before resolution to a servable catalog id, e.g. `"gpt-5-6-sol"`. `None` when the pick needed no resolution.
RawModel *string `json:"raw_model,omitempty"`
// RouterSource Which router produced the decision — `"databricks-aigw"` for the external AI-Gateway `task_v1` service, `"oss-llm"` for the built-in judge. Deliberately a plain `str` rather than a `Literal`: a source added later must still round-trip through stored rows and the wire instead of failing validation. `None` on rows written before the field existed.
RouterSource *string `json:"router_source,omitempty"`
// Scope What the decision governs — `"session"` (auto-harness session routing), `"turn"` (per-turn routing), `"child_session"` (an Omnigent-spawned sub-agent) or `"native_subagent"` (a Task / `spawn_agent` spawn routed inside the harness). Defaults to `"turn"` so rows persisted before this field deserialize.
Scope *RoutingDecisionDataScope `json:"scope,omitempty"`
}
RoutingDecisionData Data payload for an intelligent model-router decision item.
Emitted by the server-side smart routing path at the START of an advised turn and persisted as a display-only transcript item so the model the router chose shows in the conversation flow the moment the turn begins. Listed in `NON_CONTENT_ITEM_TYPES` so the agent loop's history filter skips it — the brain never sees (or answers) its own router note. The runner's harness-input builder also drops every non message/function_call type, a second guarantee it stays out of the model's context.
type RoutingDecisionDataScope ¶ added in v0.1.2
type RoutingDecisionDataScope string
RoutingDecisionDataScope What the decision governs — `"session"` (auto-harness session routing), `"turn"` (per-turn routing), `"child_session"` (an Omnigent-spawned sub-agent) or `"native_subagent"` (a Task / `spawn_agent` spawn routed inside the harness). Defaults to `"turn"` so rows persisted before this field deserialize.
const ( RoutingDecisionDataScopeChildSession RoutingDecisionDataScope = "child_session" RoutingDecisionDataScopeNativeSubagent RoutingDecisionDataScope = "native_subagent" RoutingDecisionDataScopeSession RoutingDecisionDataScope = "session" RoutingDecisionDataScopeTurn RoutingDecisionDataScope = "turn" )
Defines values for RoutingDecisionDataScope.
func (RoutingDecisionDataScope) Valid ¶ added in v0.1.2
func (e RoutingDecisionDataScope) Valid() bool
Valid indicates whether the value is a known member of the RoutingDecisionDataScope enum.
type SandboxStatus ¶
type SandboxStatus struct {
// Error Failure detail when `stage == "failed"`, e.g. `"managed sandbox launch failed: spend limit reached"`. `None` otherwise.
Error *string `json:"error,omitempty"`
// Stage Current launch stage, e.g. `"provisioning"` — one of `SandboxLaunchStage`, in pipeline order: `provisioning` (creating the sandbox) → `cloning` (cloning the repository workspace; skipped when the session has none) → `starting` (starting the in-sandbox host) → `connecting` (launching the agent runner) → `ready` / `failed`.
Stage SandboxStatusStage `json:"stage"`
}
SandboxStatus Managed-sandbox launch progress for a `host_type="managed"` session.
Carried on the session snapshot only while the session's background sandbox launch is in flight or has failed; `None` for sessions without a managed launch and once the launch succeeds (the session then looks like any host-bound session).
type SandboxStatusStage ¶
type SandboxStatusStage string
SandboxStatusStage Current launch stage, e.g. `"provisioning"` — one of `SandboxLaunchStage`, in pipeline order: `provisioning` (creating the sandbox) → `cloning` (cloning the repository workspace; skipped when the session has none) → `starting` (starting the in-sandbox host) → `connecting` (launching the agent runner) → `ready` / `failed`.
const ( SandboxStatusStageCloning SandboxStatusStage = "cloning" SandboxStatusStageConnecting SandboxStatusStage = "connecting" SandboxStatusStageFailed SandboxStatusStage = "failed" SandboxStatusStageProvisioning SandboxStatusStage = "provisioning" SandboxStatusStageReady SandboxStatusStage = "ready" SandboxStatusStageStarting SandboxStatusStage = "starting" )
Defines values for SandboxStatusStage.
func (SandboxStatusStage) Valid ¶
func (e SandboxStatusStage) Valid() bool
Valid indicates whether the value is a known member of the SandboxStatusStage enum.
type SessionAgentChangedEvent ¶
type SessionAgentChangedEvent struct {
// AgentID The session-scoped clone now bound to the session, e.g. `"ag_abc123"`.
AgentID string `json:"agent_id"`
// AgentName Display name of the agent the session now runs, e.g. `"claude-native-ui"`. Deliberately the clean target-agent name — not the clone row's `"… (switch ag_…)"` disambiguation name — because clients render it verbatim. Category: **transient** (SSE-only). The switch is persisted on the conversation row, so on reconnect clients read the new binding from the session snapshot rather than from a replayed event.
AgentName string `json:"agent_name"`
// ConversationID Session identifier, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.agent_changed"`.
Type SessionAgentChangedEventType `json:"type"`
}
SessionAgentChangedEvent Bound-agent change on a live session.
Emitted by the switch-agent route after the session's agent binding is rewritten in place. Connected clients re-derive their cached session state (harness presentation labels, bound agent id/name) from a fresh snapshot — the chat UI's native-vs-SDK message lifecycle depends on those labels, so a stale cache drops the first post-switch message (it reappears only when the transcript round-trip lands).
Wire type: "session.agent_changed".
type SessionAgentChangedEventType ¶
type SessionAgentChangedEventType string
SessionAgentChangedEventType Always `"session.agent_changed"`.
const (
SessionAgentChangedEventTypeSessionAgentChanged SessionAgentChangedEventType = "session.agent_changed"
)
Defines values for SessionAgentChangedEventType.
func (SessionAgentChangedEventType) Valid ¶
func (e SessionAgentChangedEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionAgentChangedEventType enum.
type SessionChangedFilesInvalidatedEvent ¶
type SessionChangedFilesInvalidatedEvent struct {
// EnvironmentID Environment whose changes were invalidated, e.g. `"default"`.
EnvironmentID *string `json:"environment_id,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// SessionID Owning session/conversation id.
SessionID string `json:"session_id"`
// Type Always `"session.changed_files.invalidated"`.
Type SessionChangedFilesInvalidatedEventType `json:"type"`
}
SessionChangedFilesInvalidatedEvent The session's changed-files list may have changed — refetch it.
A coarse "something changed" signal (per-file events aren't available for git-mode workspaces) emitted by the runner after a file-mutating tool. The web treats it as a refetch trigger for the changed-files panel; transient (not persisted — the REST list is source of truth).
Wire type: "session.changed_files.invalidated".
type SessionChangedFilesInvalidatedEventType ¶
type SessionChangedFilesInvalidatedEventType string
SessionChangedFilesInvalidatedEventType Always `"session.changed_files.invalidated"`.
const (
SessionChangedFilesInvalidatedEventTypeSessionChangedFilesInvalidated SessionChangedFilesInvalidatedEventType = "session.changed_files.invalidated"
)
Defines values for SessionChangedFilesInvalidatedEventType.
func (SessionChangedFilesInvalidatedEventType) Valid ¶
func (e SessionChangedFilesInvalidatedEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionChangedFilesInvalidatedEventType enum.
type SessionChildSessionUpdatedEvent ¶
type SessionChildSessionUpdatedEvent struct {
// Child A PARTIAL `ChildSessionSummary` — the snapshot-on-connect sends the full summary, while live runner deltas carry only the fields that changed (a status delta omits `last_message_preview`; a preview delta carries only it). The web merges present fields over the cached row, so the payload is an open dict rather than the strict model.
Child map[string]interface{} `json:"child"`
// ChildSessionID The child session id, e.g. `"conv_child_abc123"`.
ChildSessionID string `json:"child_session_id"`
// ConversationID The PARENT (carrier) session id.
ConversationID string `json:"conversation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.child_session.updated"`.
Type SessionChildSessionUpdatedEventType `json:"type"`
}
SessionChildSessionUpdatedEvent A child (sub-agent) session's status changed — pushed to the PARENT.
Lets the parent's resource rail update a child's status without polling `GET …/child_sessions`. Carries the full `ChildSessionSummary` so the web patches its cache directly.
Wire type: "session.child_session.updated".
type SessionChildSessionUpdatedEventType ¶
type SessionChildSessionUpdatedEventType string
SessionChildSessionUpdatedEventType Always `"session.child_session.updated"`.
const (
SessionChildSessionUpdatedEventTypeSessionChildSessionUpdated SessionChildSessionUpdatedEventType = "session.child_session.updated"
)
Defines values for SessionChildSessionUpdatedEventType.
func (SessionChildSessionUpdatedEventType) Valid ¶
func (e SessionChildSessionUpdatedEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionChildSessionUpdatedEventType enum.
type SessionCollaborationModeEvent ¶
type SessionCollaborationModeEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
// Mode The active collaboration mode string, e.g. `"plan"` or `"default"`. Category: **transient** (SSE-only). The server also writes `omnigent.codex_native.collaboration_mode` on the conversation labels, so reconnect clients restore the same state from the session snapshot.
Mode string `json:"mode"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.collaboration_mode"`.
Type SessionCollaborationModeEventType `json:"type"`
}
SessionCollaborationModeEvent Active collaboration-mode update from a Codex-native session.
Emitted after the web UI toggles Codex collaboration mode, and after the Codex forwarder observes a `thread/settings/updated` notification from the native Codex TUI. Lets connected clients show a clear Plan-mode indicator without a reload.
Wire type: "session.collaboration_mode".
type SessionCollaborationModeEventType ¶
type SessionCollaborationModeEventType string
SessionCollaborationModeEventType Always `"session.collaboration_mode"`.
const (
SessionCollaborationModeEventTypeSessionCollaborationMode SessionCollaborationModeEventType = "session.collaboration_mode"
)
Defines values for SessionCollaborationModeEventType.
func (SessionCollaborationModeEventType) Valid ¶
func (e SessionCollaborationModeEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionCollaborationModeEventType enum.
type SessionCreateRequest ¶
type SessionCreateRequest struct {
// AgentID is the durable identifier of the agent to bind, e.g. "ag_abc123".
// Required, and matched by ID rather than by name.
AgentID string `json:"agent_id"`
// InitialItems seeds the session's input queue, typically with a single
// user message. Seeding the first turn here avoids a follow-up send — and
// with it the race against opening the stream.
InitialItems []SessionEventInput `json:"initial_items,omitempty"`
// Title is a human-readable session title.
Title string `json:"title,omitempty"`
// Labels are initial guardrail labels for the session.
Labels map[string]string `json:"labels,omitempty"`
// ParentSessionID makes this a sub-agent session of that parent, inheriting
// its runner affinity.
ParentSessionID string `json:"parent_session_id,omitempty"`
// SubAgentName selects a sub-agent type within the parent's spec tree.
SubAgentName string `json:"sub_agent_name,omitempty"`
// HostType is "external" (the default: the caller manages the host) or
// "managed" (the server provisions a sandbox, in the background — HostID
// and Workspace must be empty, and appear on the snapshot once it
// registers).
HostType string `json:"host_type,omitempty"`
// HostID launches the runner on a registered host. Requires Workspace.
HostID string `json:"host_id,omitempty"`
// Workspace is where the session works: an absolute path on the host when
// HostID is set, or for a managed host optionally a repository URL to clone.
// Tilde and relative paths are rejected server-side.
Workspace string `json:"workspace,omitempty"`
// Git asks the server to run the session in a git worktree it creates on the
// host, with Workspace read as the source repository. Requires HostID.
Git *SessionGitOptions `json:"git,omitempty"`
// TerminalLaunchArgs are pass-through CLI arguments for a native terminal
// harness. Count and length are bounded server-side.
TerminalLaunchArgs []string `json:"terminal_launch_args,omitempty"`
// ModelOverride persists a per-session model override at create time, so it
// is on the session row before the harness launches.
ModelOverride string `json:"model_override,omitempty"`
// ReasoningEffort persists a per-session reasoning-effort override.
// Provider support is enforced later, at launch.
ReasoningEffort string `json:"reasoning_effort,omitempty"`
// CostControlModeOverride is "on" or "off"; empty defers to the spec.
CostControlModeOverride string `json:"cost_control_mode_override,omitempty"`
// HarnessOverride selects a harness other than the agent spec's. Create-time
// only — the harness process spawns on the first turn.
HarnessOverride string `json:"harness_override,omitempty"`
}
SessionCreateRequest is the JSON body of session create.
Hand-written: the create route takes a raw request and dispatches on Content-Type, so FastAPI documents no requestBody for it and openapi.json carries no schema. It mirrors the server's SessionCreateRequest and is not covered by the openapi.json drift gate.
This is the JSON create path, which binds an already-registered agent and returns the full session snapshot. The same endpoint also accepts a multipart bundled create that uploads an agent — a different contract returning a different, smaller body — which this package does not implement.
type SessionCreatedEvent ¶
type SessionCreatedEvent struct {
// AgentID Registered agent id the child runs as, e.g. `"agent_xyz"`. `None` is permitted only for legacy spawn paths that did not record an agent id; new code MUST set it.
AgentID *string `json:"agent_id,omitempty"`
// ChildSessionID The newly-created child session id, e.g. `"conv_child456"`. Same as `conversation_id` on the child's own stream when consumers pivot to it.
ChildSessionID string `json:"child_session_id"`
// ConversationID The PARENT session/conversation id — this event rides the parent's stream, e.g. `"conv_parent123"`.
ConversationID string `json:"conversation_id"`
// ParentSessionID Echo of `conversation_id` for consumers that key on a dedicated "parent" field rather than the carrier `conversation_id`. Always equal to `conversation_id`; included for forward-compat with clients that may relay these events across stream boundaries. Category: **transient** (SSE-only). The corresponding durable record of "a child session exists" lives in the conversation store as the child conversation row itself (`parent_conversation_id` foreign key) and the parent's tunneled `function_call` item — reconnecting clients discover children by walking the parent's persisted history, not by replaying this event.
ParentSessionID *string `json:"parent_session_id,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.created"`.
Type SessionCreatedEventType `json:"type"`
}
SessionCreatedEvent A child (sub-agent) session was spawned from this session.
Emitted by the server onto the **parent** session's conversation stream after the child conversation row is created and the child task has been started. Per the session-rearchitecture spec §3 ("Event types and direction") and §7 ("Flow: client interacts with sub-agent"), this lets clients watching the parent session's SSE subscribe directly to the child's stream without polling history for the tunneled `function_call` item.
The wire shape is FLAT (not enveloped): `{"type": "session.created", "conversation_id": <parent>, "child_session_id": <child>, "agent_id": <agent or None>, "parent_session_id": <parent>, "sequence_number": null}`.
The existing tunneled `function_call` ConversationItem (carried inside `OutputItemDoneEvent`) is retained for compatibility — clients that don't yet implement the "subscribe to child stream" pattern can keep rendering sub- agent calls from the parent's persistent history.
Wire type: "session.created".
type SessionCreatedEventType ¶
type SessionCreatedEventType string
SessionCreatedEventType Always `"session.created"`.
const (
SessionCreatedEventTypeSessionCreated SessionCreatedEventType = "session.created"
)
Defines values for SessionCreatedEventType.
func (SessionCreatedEventType) Valid ¶
func (e SessionCreatedEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionCreatedEventType enum.
type SessionEventInput ¶
type SessionEventInput struct {
// Type is the input's discriminator; see the InputType constants. Required.
Type string `json:"type"`
// Data is the type-specific payload. The server validates its shape against
// Type and rejects a mismatch with 422. Control inputs take an empty Data.
Data map[string]any `json:"data,omitempty"`
// ModelOverride substitutes for the agent spec's model on the turn this
// input starts. Ignored when the input steers an already-running turn.
ModelOverride string `json:"model_override,omitempty"`
// Tools registers function tools for the turn this input starts, in
// OpenAI's function-tool shape. Ignored when steering a running turn, whose
// tool set is fixed at start.
Tools []map[string]any `json:"tools,omitempty"`
}
SessionEventInput is one client-submitted input for a session: the body of a send, and the element type of SessionCreateRequest.InitialItems.
Hand-written, and unusually exposed: its route is registered with include_in_schema=False, so neither the path nor this schema appears in openapi.json and no drift gate covers either. It mirrors the server's SessionEventInput. A server-side change to it breaks this client silently.
func ApprovalVerdict ¶
func ApprovalVerdict(elicitationID string, result ElicitationResult) SessionEventInput
ApprovalVerdict builds the input that answers an outstanding elicitation.
The elicitation id comes from the ElicitationRequestEvent that asked, or from SessionResponse.PendingElicitations after a reconnect. It correlates the answer with the question, which is why it rides beside the verdict rather than inside it: ElicitationResult is MCP's shape, and the correlation key is this API's.
Either source also names the session that owns the elicitation, when that is not the session it was read from: ElicitationRequestParams.TargetSessionID on the event, and params.target_session_id inside the snapshot's entries, which are those same events as raw dicts. Posting the verdict to the wrong one of the two is what Client.ResolveElicitationRequest exists to prevent.
This builder validates nothing — an empty id or action is assembled as given and refused by the server. Client.ResolveElicitation checks both before sending, so prefer it unless you are batching inputs yourself.
func UserMessage ¶
func UserMessage(text string) SessionEventInput
UserMessage builds a user-role message input carrying one text part.
type SessionGitOptions ¶
type SessionGitOptions struct {
// BaseBranch Optional base ref to branch from, e.g. `"main"` or `"origin/main"`. `None` branches from the source repository's current `HEAD`. Create mode only — invalid with `existing_worktree`.
BaseBranch *string `json:"base_branch,omitempty"`
// BranchName In create mode, the new branch to create and check out, e.g. `"feature/login"`. In bind mode, the branch already checked out in the existing worktree. Validated against git ref-format rules; invalid names fail with `invalid_input`.
BranchName string `json:"branch_name"`
// ExistingWorktree When `True`, bind to the pre-existing worktree at `workspace` instead of creating one (see above).
ExistingWorktree *bool `json:"existing_worktree,omitempty"`
}
SessionGitOptions Git worktree options for `POST /v1/sessions`.
Requires `host_id` to be set (and therefore `workspace`, which is interpreted as the source repository directory). Two modes, selected by `existing_worktree`:
- **create** (default): the server creates a git worktree on the host for a new branch and starts the runner in that worktree instead of the picked directory.
- **bind** (`existing_worktree=True`): `workspace` already IS a pre-existing worktree; no worktree is created. `branch_name` is recorded as the session's `git_branch` for display and opt-in cleanup, and `base_branch` must not be set.
See designs/SESSION_GIT_WORKTREE.md.
type SessionHeartbeatEvent ¶
type SessionHeartbeatEvent struct {
SequenceNumber *int `json:"sequence_number,omitempty"`
// ServerTime ISO 8601 UTC timestamp at emission, e.g. `"2026-05-25T10:30:00Z"`. `None` when the producer chose not to populate it.
ServerTime *string `json:"server_time,omitempty"`
// Type Always `"session.heartbeat"`.
Type SessionHeartbeatEventType `json:"type"`
}
SessionHeartbeatEvent Idle-stream keepalive on `GET /v1/sessions/{id}/stream`.
Emitted by the session-stream route on a fixed cadence whenever the underlying publish queue has been quiet (no turn in flight, no resource events). Distinct from `HeartbeatEvent` (`response.heartbeat`), which is per-turn and is driven by the runtime workflow while a response is producing output.
Why this exists: the session stream stays open across many turns and through idle periods (waiting for the user to type). Without a periodic emit, intermediate proxies, OS-level sockets, and the client's SSE read-timeout can leave a half-open stream undetected for minutes after a network event (laptop sleep, Wi-Fi handoff). The heartbeat puts a regular byte on the wire so the client's read-timeout and the server's `request.is_disconnected()` check both fire promptly.
Consumers MAY ignore the payload entirely (the bytes crossing the wire are sufficient). The optional `server_time` mirrors `HeartbeatEvent` for symmetry and debugging.
Wire type: "session.heartbeat".
type SessionHeartbeatEventType ¶
type SessionHeartbeatEventType string
SessionHeartbeatEventType Always `"session.heartbeat"`.
const (
SessionHeartbeatEventTypeSessionHeartbeat SessionHeartbeatEventType = "session.heartbeat"
)
Defines values for SessionHeartbeatEventType.
func (SessionHeartbeatEventType) Valid ¶
func (e SessionHeartbeatEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionHeartbeatEventType enum.
type SessionInputConsumedEvent ¶
type SessionInputConsumedEvent struct {
// Data Inner payload of a `SessionInputConsumedEvent`.
//
// Emitted by the sessions route handler at the moment a client
// input is persisted into `conversation_items`. Carries the
// persisted-item shape so clients can render the input (e.g.
// the user's message bubble) at the moment of acceptance.
Data SessionInputConsumedPayload `json:"data"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.input.consumed"`.
Type SessionInputConsumedEventType `json:"type"`
}
SessionInputConsumedEvent A queued input item was materialized into conversation history.
Emitted by `POST /v1/sessions/{id}/events` once per accepted input item at the moment it is persisted into conversation history (either onto a steered active turn or as the seed item of a freshly-started one). Wire shape uses the NESTED envelope: `{"type": "session.input.consumed", "data": <SessionInputConsumedPayload>, "sequence_number": null}`.
The event name is **provisional** — it may be renamed in a future revision. Consumers should reference `SessionInputConsumedEvent` (or its `type` literal) rather than hardcoding the wire string.
Wire type: "session.input.consumed".
type SessionInputConsumedEventType ¶
type SessionInputConsumedEventType string
SessionInputConsumedEventType Always `"session.input.consumed"`.
const (
SessionInputConsumedEventTypeSessionInputConsumed SessionInputConsumedEventType = "session.input.consumed"
)
Defines values for SessionInputConsumedEventType.
func (SessionInputConsumedEventType) Valid ¶
func (e SessionInputConsumedEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionInputConsumedEventType enum.
type SessionInputConsumedPayload ¶
type SessionInputConsumedPayload struct {
// ClearedPendingID When this consumed message drains a `omnigent.runtime.pending_inputs` entry (a native- terminal web message round-tripping back from the transcript), the drained entry's id, e.g. `"pending_a1b2c3"`. Lets a client drop the matching optimistic bubble by id instead of by position. `None` for non-native messages and for messages that matched no pending entry (e.g. typed directly in the TUI).
ClearedPendingID *string `json:"cleared_pending_id,omitempty"`
// CreatedBy Email of the human actor who posted the item, e.g. `"alice@example.com"`. `None` for agent/tool/system items and single-user mode. Mirrors `ConversationItem.to_api_dict` for live attribution.
CreatedBy *string `json:"created_by,omitempty"`
// Data Decoded item payload, e.g. `{"role": "user", "content": [{"type": "input_text", "text": "Hello"}]}`. Heterogeneous and `type`-specific.
Data map[string]interface{} `json:"data"`
// ItemID Stable identifier of the conversation item just persisted, e.g. `"item_abc123"`.
ItemID string `json:"item_id"`
// Type The item type discriminator — `"message"` for user messages, `"function_call_output"` for tool results, etc. Mirrors `omnigent.server.schemas.SessionEventInput`'s `type` field.
Type string `json:"type"`
}
SessionInputConsumedPayload Inner payload of a `SessionInputConsumedEvent`.
Emitted by the sessions route handler at the moment a client input is persisted into `conversation_items`. Carries the persisted-item shape so clients can render the input (e.g. the user's message bubble) at the moment of acceptance.
type SessionInterruptedEvent ¶
type SessionInterruptedEvent struct {
// Data Inner payload of a `SessionInterruptedEvent`.
//
// Built by the server.
Data SessionInterruptedPayload `json:"data"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.interrupted"`.
Type SessionInterruptedEventType `json:"type"`
}
SessionInterruptedEvent User-triggered cancel reached the loop.
Emitted by the server when a client posts a `{"type": "interrupt"}` to `POST /v1/sessions/{id}/events`. Co-emitted with `IncompleteEvent` (with the underlying response carrying `incomplete_details.reason == "user_interrupt"`) so off-the- shelf Responses parsers still close cleanly. Wire shape uses the NESTED envelope verbatim from the existing emit site.
Wire type: "session.interrupted".
type SessionInterruptedEventType ¶
type SessionInterruptedEventType string
SessionInterruptedEventType Always `"session.interrupted"`.
const (
SessionInterruptedEventTypeSessionInterrupted SessionInterruptedEventType = "session.interrupted"
)
Defines values for SessionInterruptedEventType.
func (SessionInterruptedEventType) Valid ¶
func (e SessionInterruptedEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionInterruptedEventType enum.
type SessionInterruptedPayload ¶
type SessionInterruptedPayload struct {
// RequestedAt Unix epoch seconds when the interrupt request reached the server, e.g. `1704067200`.
RequestedAt int `json:"requested_at"`
// ResponseID Optional active response id for terminal-backed integrations, e.g. `"codex_turn_abc123"`.
ResponseID *string `json:"response_id,omitempty"`
}
SessionInterruptedPayload Inner payload of a `SessionInterruptedEvent`.
Built by the server.
type SessionItem ¶
SessionItem is one item from Client.ListSessionItems.
It is untyped because the route sends the server's flatten-for-API shape rather than the ConversationItem a snapshot carries: id, response_id, type and status sit beside the typed payload's own fields — role and content on a message, name and arguments on a function call — spread onto the same object, with absent optional fields left out and no created_at at all. openapi.json declares this page's elements untyped, so there is nothing generated to decode them into either.
An alias rather than a defined type, so it interchanges with the same flat shape on the stream, OutputItemDoneEvent.Item.
type SessionItemsOptions ¶
type SessionItemsOptions struct {
// Limit caps the page size. The server accepts 1 to 1000 and defaults to
// 100; zero here sends nothing and takes that default.
Limit int
// After returns the items following this cursor. Use a previous page's
// [Page.LastID].
After string
// Before returns the items preceding this cursor. Use a previous page's
// [Page.FirstID]. Set beside After it narrows to the window between the two
// rather than replacing it, because the server applies both comparisons.
Before string
// Order is the sort direction, and both cursors are read relative to it.
// Empty takes this route's default, [SortAscending] — chronological, and
// not the [SortDescending] the agent and session listings default to.
Order SortOrder
}
SessionItemsOptions tunes a session-items listing. The zero value asks for the server's defaults: the session's oldest 100 items, chronologically.
type SessionKind ¶
type SessionKind string
SessionKind selects which sessions a listing includes.
const ( // SessionKindDefault includes only top-level sessions. The server's // default: sub-agent sessions are an implementation detail of the parent // turn, so they stay out unless asked for. SessionKindDefault SessionKind = "default" // SessionKindSubAgent includes only sub-agent sessions. SessionKindSubAgent SessionKind = "sub_agent" // SessionKindAny includes both. SessionKindAny SessionKind = "any" )
type SessionListItem ¶
type SessionListItem struct {
// AgentID Durable identifier of the bound agent.
AgentID string `json:"agent_id"`
// AgentName Human-readable name of the bound agent, e.g. `"research-agent"`. `None` when the agent row cannot be found.
AgentName *string `json:"agent_name,omitempty"`
// Archived Whether the session is archived. Archived sessions are returned by `GET /v1/sessions` only when the request passes `include_archived=true`; the sidebar groups them into a dedicated "Archived" section. `False` for normal sessions.
Archived *bool `json:"archived,omitempty"`
// CommentsCount Total number of review comments (any status) on this session. Together with `comments_updated_at` it forms a change fingerprint: an add or edit bumps the timestamp, a delete changes the count, so the web client can invalidate its cached comment list when either field changes in a `WS /v1/sessions/updates` frame. `0` when the session has no comments or the server has no comment store wired.
CommentsCount *int `json:"comments_count,omitempty"`
// CommentsUpdatedAt Unix epoch **microseconds** of the most recently mutated comment on this session (max `updated_at` across its comments). Microsecond precision keeps back-to-back mutations within one second distinguishable while staying an exact integer in JavaScript; clients only compare it for change. `None` when the session has no comments or the server has no comment store wired.
CommentsUpdatedAt *int `json:"comments_updated_at,omitempty"`
// CreatedAt Unix epoch seconds of creation.
CreatedAt int `json:"created_at"`
// ExternalSessionID Runtime-native session id this conversation wraps, e.g. a Claude Code session uuid for `omnigent claude` sessions. `None` for regular AP-only conversations. Lets the sidebar / picker render a runtime badge without a follow-up GET.
ExternalSessionID *string `json:"external_session_id,omitempty"`
// GitBranch Git branch checked out in the session's worktree, e.g. `"feature/login"`. Set only when the session was created with a server-created git worktree; `None` otherwise. The Web UI uses a non-`None` value to offer the "delete local branch" cleanup checkbox on session delete. See designs/SESSION_GIT_WORKTREE.md.
GitBranch *string `json:"git_branch,omitempty"`
// HostID Host that launched the runner for this session.
HostID *string `json:"host_id,omitempty"`
// HostOnline Whether the session's host tunnel is live (status online and fresh within the host liveness TTL). `None` when the session has no `host_id` (CLI/local). Distinguishes "runner down but host can relaunch" from "host offline" for the open-session view; not used by the sidebar.
HostOnline *bool `json:"host_online,omitempty"`
// ID Session/conversation identifier, e.g. `"conv_abc123"`.
ID string `json:"id"`
// Labels Session-scoped guardrails labels.
Labels map[string]string `json:"labels,omitempty"`
// Owner The user_id of the session owner, or `None` when permissions are disabled. Included so the sidebar can display the owner without a separate API call.
Owner *string `json:"owner,omitempty"`
ParentSessionID *string `json:"parent_session_id,omitempty"`
// PendingElicitationsCount Number of approval prompts currently waiting on this session. Powers the sidebar's "needs attention" badge so a user with several sessions running can tell which ones are blocked on them without opening each chat. Sourced from the Omnigent server's in-memory `omnigent.runtime.pending_elicitations` index, which mirrors every `response.elicitation_request` event passing through `session_stream` and decrements when a verdict is dispatched. `0` when the session has no outstanding elicitations.
PendingElicitationsCount *int `json:"pending_elicitations_count,omitempty"`
// PermissionLevel The requesting user's numeric permission level on this session: `1` = read, `2` = edit, `3` = manage. `None` when permissions are disabled.
PermissionLevel *int `json:"permission_level,omitempty"`
ProjectID *string `json:"project_id,omitempty"`
// ReasoningEffort Per-session reasoning-effort hint.
ReasoningEffort *string `json:"reasoning_effort,omitempty"`
// RunnerID Runner currently bound to the session.
RunnerID *string `json:"runner_id,omitempty"`
// RunnerOnline Strict runner liveness — `True` iff a runner tunnel is currently registered for this session. Matches `GET /health`'s `runner_online` value. Strict: a dead runner on a live host reads `False` here (no host-relaunch optimism folded in), unlike the legacy conflated value. `None` when the server has no runner liveness lookup wired.
RunnerOnline *bool `json:"runner_online,omitempty"`
// SearchSnippet Excerpt of the chat content that matched the request's `search_query`, centered on the match with `…` marking elided ends, so the search UI can show *where* a session matched in its body. Present whenever the query hit an item body (even if the title also matched); `None` on non-search reads and when only the title matched.
SearchSnippet *string `json:"search_snippet,omitempty"`
// Status Derived session lifecycle status.
Status SessionListItemStatus `json:"status"`
// Title Optional human-readable title.
Title *string `json:"title,omitempty"`
// UpdatedAt Unix epoch seconds of last update.
UpdatedAt int `json:"updated_at"`
// ViewerLastSeen The *requesting user's* "last seen" wall-clock baseline in seconds for this session, or `None` when they have never seen it. Per-viewer (built from the server's in-memory per-user read-state, written by `PUT /v1/sessions/{id}/read-state`); the unread dot shows when `updated_at > viewer_last_seen` and the session is finished. In-memory only — resets on a server restart.
ViewerLastSeen *int `json:"viewer_last_seen,omitempty"`
// ViewerUnread Whether the *requesting user* explicitly marked this session unread. Per-viewer; lifts the active-row dot suppression on the client. `False` by default.
ViewerUnread *bool `json:"viewer_unread,omitempty"`
// Workspace Absolute path on disk where the runner cd's, e.g. `"/path/to/workspace"`. `None` for sessions that haven't been bound to a host workspace.
Workspace *string `json:"workspace,omitempty"`
}
SessionListItem Lightweight session summary for `GET /v1/sessions` list responses.
Same shape as `SessionResponse` minus `items`.
type SessionListItemStatus ¶
type SessionListItemStatus string
SessionListItemStatus Derived session lifecycle status.
const ( SessionListItemStatusFailed SessionListItemStatus = "failed" SessionListItemStatusIdle SessionListItemStatus = "idle" SessionListItemStatusRunning SessionListItemStatus = "running" SessionListItemStatusWaiting SessionListItemStatus = "waiting" )
Defines values for SessionListItemStatus.
func (SessionListItemStatus) Valid ¶
func (e SessionListItemStatus) Valid() bool
Valid indicates whether the value is a known member of the SessionListItemStatus enum.
type SessionMcpStartupEvent ¶
type SessionMcpStartupEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Servers Latest per-server startup map, e.g. `{"safe": {"status": "starting", "error": None}}`. Category: **transient** (SSE + snapshot cache). Not persisted; a client connecting mid-startup seeds from the session snapshot's `mcp_startup` field and updates live off this event.
Servers map[string]McpServerStartup `json:"servers"`
// Type Always `"session.mcp_startup"`.
Type SessionMcpStartupEventType `json:"type"`
}
SessionMcpStartupEvent Per-MCP-server startup progress for a native harness session.
A codex-native session brings up its configured MCP servers when its Codex thread starts; slow or failing servers previously left the web session looking hung with no signal. The native forwarder mirrors Codex's `mcpServer/startupStatus/updated` notifications as `external_mcp_startup` posts, republished here so the web UI can show which servers are still starting and which failed or were cancelled.
Wire type: "session.mcp_startup".
type SessionMcpStartupEventType ¶
type SessionMcpStartupEventType string
SessionMcpStartupEventType Always `"session.mcp_startup"`.
const (
SessionMcpStartupEventTypeSessionMcpStartup SessionMcpStartupEventType = "session.mcp_startup"
)
Defines values for SessionMcpStartupEventType.
func (SessionMcpStartupEventType) Valid ¶
func (e SessionMcpStartupEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionMcpStartupEventType enum.
type SessionModelEvent ¶
type SessionModelEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
// Model Tier alias the session is now on, e.g. `"opus"` — Claude Code's version-agnostic alias, matching the picker's vocabulary (not a pinned `"claude-opus-4-8"` id). Category: **transient** (SSE-only). The server also writes `model_override` on the conversation, so on reconnect clients restore the selection from the snapshot's `model_override` rather than from a replayed event.
Model string `json:"model"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.model"`.
Type SessionModelEventType `json:"type"`
}
SessionModelEvent Active-model update from a terminal-backed integration.
Emitted after an `external_model_change` POST from the `omnigent claude` transcript forwarder when the model is switched inside the Claude Code terminal (a `/model` command or the in-TUI picker). Lets the web model picker reflect a TUI-side switch without a reload.
Wire type: "session.model".
type SessionModelEventType ¶
type SessionModelEventType string
SessionModelEventType Always `"session.model"`.
const (
SessionModelEventTypeSessionModel SessionModelEventType = "session.model"
)
Defines values for SessionModelEventType.
func (SessionModelEventType) Valid ¶
func (e SessionModelEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionModelEventType enum.
type SessionModelOptionsEvent ¶
type SessionModelOptionsEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`. Category: **transient** (SSE-only). On reconnect, clients seed Native model / effort controls from the session snapshot.
ConversationID string `json:"conversation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.model_options"`.
Type SessionModelOptionsEventType `json:"type"`
}
SessionModelOptionsEvent Signal that a native session's model catalog has resolved.
Model options are fetched from the bound runner and cached on the session snapshot. The initial snapshot can return an empty list while this background fetch is in flight; this event tells connected clients to re-read the snapshot and apply its now-populated `model_options`.
Carries no payload beyond the conversation id. The snapshot's `model_options` field remains the source of truth.
Wire type: "session.model_options".
type SessionModelOptionsEventType ¶
type SessionModelOptionsEventType string
SessionModelOptionsEventType Always `"session.model_options"`.
const (
SessionModelOptionsEventTypeSessionModelOptions SessionModelOptionsEventType = "session.model_options"
)
Defines values for SessionModelOptionsEventType.
func (SessionModelOptionsEventType) Valid ¶
func (e SessionModelOptionsEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionModelOptionsEventType enum.
type SessionPresenceEvent ¶
type SessionPresenceEvent struct {
// ConversationID The conversation whose stream delivered this event — the root or a sub-agent conversation, e.g. `"conv_abc123"`. Matches the streamed conversation (not necessarily the tree's root) so clients can guard events by the conversation they are viewing.
ConversationID string `json:"conversation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.presence"`.
Type SessionPresenceEventType `json:"type"`
// Viewers All users currently viewing any conversation in the session tree (including the receiving user — the web filters self out for display), ordered by join time.
Viewers []PresenceViewer `json:"viewers"`
}
SessionPresenceEvent The session's viewer list changed — full state, not a delta.
Emitted on `GET /v1/sessions/{id}/stream` whenever a user joins, leaves (after the server-side grace window absorbs reconnect churn), or flips their idle aggregate, and once to each newly-connected stream as a snapshot-on-connect. Every event carries the COMPLETE viewer list so clients replace their state wholesale — missed events self-heal on the next event or reconnect. Viewers are scoped to the session *tree* (the root conversation and every sub-agent conversation under it), so a user on a sub-agent page and a user on the root page appear in each other's lists. See the server and `designs/UI/PRESENCE.md`.
Wire type: "session.presence".
type SessionPresenceEventType ¶
type SessionPresenceEventType string
SessionPresenceEventType Always `"session.presence"`.
const (
SessionPresenceEventTypeSessionPresence SessionPresenceEventType = "session.presence"
)
Defines values for SessionPresenceEventType.
func (SessionPresenceEventType) Valid ¶
func (e SessionPresenceEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionPresenceEventType enum.
type SessionReasoningEffortEvent ¶
type SessionReasoningEffortEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
// ReasoningEffort Reasoning effort now active for the session, e.g. `"medium"`, or `None` when Codex cleared to its default. Category: **transient** (SSE-only). The server also writes `reasoning_effort` on the conversation, so on reconnect clients restore the selection from the session snapshot rather than from a replayed event.
ReasoningEffort *string `json:"reasoning_effort,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.reasoning_effort"`.
Type SessionReasoningEffortEventType `json:"type"`
}
SessionReasoningEffortEvent Active reasoning-effort update from a terminal-backed integration.
Emitted after an `external_reasoning_effort_change` POST from a native terminal forwarder when the user changes the thinking level inside the terminal UI. Lets the web effort picker reflect a TUI-side switch without a reload.
Wire type: "session.reasoning_effort".
type SessionReasoningEffortEventType ¶
type SessionReasoningEffortEventType string
SessionReasoningEffortEventType Always `"session.reasoning_effort"`.
const (
SessionReasoningEffortEventTypeSessionReasoningEffort SessionReasoningEffortEventType = "session.reasoning_effort"
)
Defines values for SessionReasoningEffortEventType.
func (SessionReasoningEffortEventType) Valid ¶
func (e SessionReasoningEffortEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionReasoningEffortEventType enum.
type SessionResourceCreatedEvent ¶
type SessionResourceCreatedEvent struct {
// Resource The newly created resource object.
Resource map[string]interface{} `json:"resource"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.resource.created"`.
Type SessionResourceCreatedEventType `json:"type"`
}
SessionResourceCreatedEvent A session resource was created.
Emitted when a terminal is launched, a file is uploaded, or any other resource is materialized under a session. Wire shape is FLAT: `{"type": "session.resource.created", "resource": <SessionResourceObject-like dict>}`.
Wire type: "session.resource.created".
type SessionResourceCreatedEventType ¶
type SessionResourceCreatedEventType string
SessionResourceCreatedEventType Always `"session.resource.created"`.
const (
SessionResourceCreatedEventTypeSessionResourceCreated SessionResourceCreatedEventType = "session.resource.created"
)
Defines values for SessionResourceCreatedEventType.
func (SessionResourceCreatedEventType) Valid ¶
func (e SessionResourceCreatedEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionResourceCreatedEventType enum.
type SessionResourceDeletedEvent ¶
type SessionResourceDeletedEvent struct {
// ResourceID Opaque id of the deleted resource.
ResourceID string `json:"resource_id"`
// ResourceType Type of the deleted resource, e.g. `"terminal"`, `"file"`.
ResourceType string `json:"resource_type"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// SessionID Owning session/conversation id.
SessionID string `json:"session_id"`
// Type Always `"session.resource.deleted"`.
Type SessionResourceDeletedEventType `json:"type"`
}
SessionResourceDeletedEvent A session resource was deleted.
Emitted when a terminal is closed, a file is deleted, or any other resource is removed from a session.
Wire type: "session.resource.deleted".
type SessionResourceDeletedEventType ¶
type SessionResourceDeletedEventType string
SessionResourceDeletedEventType Always `"session.resource.deleted"`.
const (
SessionResourceDeletedEventTypeSessionResourceDeleted SessionResourceDeletedEventType = "session.resource.deleted"
)
Defines values for SessionResourceDeletedEventType.
func (SessionResourceDeletedEventType) Valid ¶
func (e SessionResourceDeletedEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionResourceDeletedEventType enum.
type SessionResponse ¶
type SessionResponse struct {
// ActiveResponseID Response id of the turn currently in flight, or `None` when the session is idle. Sourced from the server's internal state at snapshot build time so a client connecting mid-turn can reopen a streaming `activeResponse` — the SSE stream is snapshot + live tail with no replay, so the turn-start `running` edge that carried this id is not re-sent on reconnect. Today only native-terminal forwarders (claude-native) stamp a turn id on their status edges; other harnesses leave this `None`.
ActiveResponseID *string `json:"active_response_id,omitempty"`
// AgentID Durable identifier of the bound agent, e.g. `"ag_abc123"`. Stable across renames of the agent.
AgentID string `json:"agent_id"`
// AgentName Human-readable name of the bound agent, e.g. `"research-agent"`. Loaded from the agent row at snapshot-build time. `None` when the agent row cannot be found (deleted or orphaned session).
AgentName *string `json:"agent_name,omitempty"`
// Archived Whether the session is archived. Archived sessions are hidden from the default sidebar listing and surface only behind the "Show archived" toggle. `False` for normal sessions. Toggled via `PATCH /v1/sessions/{id}`.
Archived *bool `json:"archived,omitempty"`
// BackgroundTaskCount Background shells (claude-native) still running as of the last status edge, so a reload re-shows "N shells still running" even though the session has settled to `"idle"`. `None` (the default / omitted) when no shells are tracked.
BackgroundTaskCount *int `json:"background_task_count,omitempty"`
// ContextWindow The model's context window size in tokens as looked up server-side from litellm's registry (or from the `AP_CONTEXT_WINDOW_OVERRIDE` env var), e.g. `200_000`. `None` when the model is not in litellm's registry and no override is set.
ContextWindow *int `json:"context_window,omitempty"`
// CostControlModeOverride Per-session cost-control switch: `"on"` activates the spec's configured cost-control mode, `"off"` disables cost control for this session. `None` means no override is active (the spec default applies). Set at create time or via `PATCH /v1/sessions/{id}` (the web "Cost Optimized" toggle); read by the cost-control advisor pipeline.
CostControlModeOverride *string `json:"cost_control_mode_override,omitempty"`
// CreatedAt Unix epoch seconds of creation.
CreatedAt int `json:"created_at"`
// ExternalSessionID Runtime-native session id this conversation wraps, e.g. a Claude Code session uuid for `omnigent claude` sessions. `None` for regular AP-only conversations. Populated by the wrapper bridge.
ExternalSessionID *string `json:"external_session_id,omitempty"`
// GitBranch Git branch checked out in the session's worktree, e.g. `"feature/login"`. Set only when the session was created with a server-created git worktree; `None` otherwise. The Web UI uses a non-`None` value to offer the "delete local branch" cleanup checkbox on session delete. See designs/SESSION_GIT_WORKTREE.md.
GitBranch *string `json:"git_branch,omitempty"`
// Harness The bound agent's canonical harness, e.g. `"claude-sdk"` or `"openai-agents"`. Lets the client render the active credential for the correct provider family instead of inferring it from the model string (which is wrong when the agent declares no model). `None` when the agent cannot be looked up.
Harness *string `json:"harness,omitempty"`
// HostID Host that launched (or should launch) the runner for this session, e.g. `"host_a1b2c3d4..."`. `None` for CLI-initiated sessions.
HostID *string `json:"host_id,omitempty"`
// HostOnline Whether the session's host tunnel is live (status online and fresh within the host liveness TTL). `None` when the session has no `host_id` (CLI/local). Used only to choose what the open view shows when `runner_online` is `False` — host alive ⇒ "send a message to wake the runner"; host dead ⇒ "reconnect / fork". Never participates in the reachability decision.
HostOnline *bool `json:"host_online,omitempty"`
// HostResumable Whether this session is bound to a dormant managed host the server can wake in place (its provider sets `SandboxLauncher.can_resume`). The open view reads it only when `host_online` is `False`, to split a confirmed host-down into a recoverable "asleep" state (send a message — the relaunch path resumes the sandbox) versus the terminal `host_offline` dead-end (reconnect from your machine / fork). `False` for non-managed or non-resumable hosts.
HostResumable *bool `json:"host_resumable,omitempty"`
// ID Unique session identifier (also the underlying conversation ID), e.g. `"conv_abc123"`.
ID string `json:"id"`
// Items Committed conversation items in chronological order. Empty for a freshly created session.
Items []ConversationItem `json:"items,omitempty"`
Kind *string `json:"kind,omitempty"`
// Labels Session-scoped guardrails labels. Empty dict when no labels have been written.
Labels map[string]string `json:"labels,omitempty"`
// LastTaskError Error details from the most recently failed task. Only present when `status == "failed"` and the task stored an error. Lets clients display the failure reason on historical load without relying on the transient `response.error` SSE event (which may have been emitted before the web client subscribed). Format mirrors the `RetryErrorDetail` SSE shape: `{"code": "executor_error", "message": "..."}`. `None` in all other cases.
LastTaskError map[string]string `json:"last_task_error,omitempty"`
// LastTotalTokens Total token count (input + output) from the most recently completed task's `usage`, e.g. `45231`. `None` when no task has completed yet. Lets clients seed their context-ring on conversation resume without waiting for the next `response.completed` SSE event.
LastTotalTokens *int `json:"last_total_tokens,omitempty"`
// LlmModel The LLM model identifier from the bound agent's spec, e.g. `"anthropic/claude-sonnet-4-6"`. `None` when the agent has no explicit `llm:` block or the agent cannot be looked up.
LlmModel *string `json:"llm_model,omitempty"`
McpStartup map[string]McpServerStartup `json:"mcp_startup,omitempty"`
// ModelOptions Runner-owned model-picker options for native sessions. Claude supplies launch-time gateway aliases; Codex includes each model's supported reasoning efforts. Empty while unavailable.
ModelOptions []NativeModelOption `json:"model_options,omitempty"`
// ModelOverride Per-session LLM model override, e.g. `"claude-opus-4-7"`. `None` means no override is active (the agent's `llm_model` applies). Set via `PATCH /v1/sessions/{id}` or the REPL's `/model` command; both write the same column so the web UI and the TUI stay in sync.
ModelOverride *string `json:"model_override,omitempty"`
// ParentSessionID For sub-agent sessions, the parent conversation's id, e.g. `"conv_parent987"`. `None` for top-level sessions. Lets clients identify a session as a child and link back to its parent without an extra round-trip — the same conversation row exposes this via `parent_conversation_id` internally.
ParentSessionID *string `json:"parent_session_id,omitempty"`
// PendingElicitations Outstanding approval prompts on this session at the moment the snapshot was built — the original `response.elicitation_request` event dicts. Lets the UI render the ApprovalCard on cold load, since the live SSE stream has no replay and a prompt emitted before the user opened the chat would otherwise vanish. Empty list when no prompts are outstanding. Sourced from the Omnigent server's in-memory `omnigent.runtime.pending_elicitations` index.
PendingElicitations []map[string]interface{} `json:"pending_elicitations,omitempty"`
// PendingInputs Un-consumed web-composer user messages on native-terminal (claude-native / codex-native) sessions at snapshot time, each `{"pending_id", "content"}`. Native sessions don't persist a web message at POST time (the transcript forwarder is the single writer), so a client that posted then navigated away / rebound would lose its optimistic bubble; replaying these re-hydrates it. Empty list otherwise. Sourced from the in-memory `omnigent.runtime.pending_inputs` index.
PendingInputs []map[string]interface{} `json:"pending_inputs,omitempty"`
// PermissionLevel The requesting user's numeric permission level on this session: `1` = read, `2` = edit, `3` = manage. `None` when permissions are disabled (single-user mode without a permission store).
PermissionLevel *int `json:"permission_level,omitempty"`
ProjectID *string `json:"project_id,omitempty"`
// ReasoningEffort Per-session reasoning-effort hint. Accepted metadata values are `"none"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, and `"max"`. Provider-specific support is validated when a turn executes. `None` means use the agent default.
ReasoningEffort *string `json:"reasoning_effort,omitempty"`
// RootConversationID The id of this session's spawn-tree root, e.g. `"conv_root1"`. Equals `id` for top-level sessions; for sub-agents it points at the top-level ancestor. Lets orchestration tools (e.g. `sys_session_close`) confirm a target shares the caller's spawn tree over the REST path. `None` only when the underlying row predates the `root_conversation_id` column (not expected post-migration).
RootConversationID *string `json:"root_conversation_id,omitempty"`
// RunnerID Runner currently bound to this session, e.g. `"runner_abc123"`. `None` until a client binds one via `PATCH /v1/sessions/{id}`.
RunnerID *string `json:"runner_id,omitempty"`
// RunnerOnline Strict runner liveness — `True` iff a runner tunnel is currently registered for this session. This is the sole reachability signal: `True` means the client can chat normally. It does **not** fold in host-relaunch optimism (a dead runner on a live host reads `False` here, not `True`) — the open-session view pairs it with `host_online` to decide what to show. `None` when the server has no runner liveness lookup wired.
RunnerOnline *bool `json:"runner_online,omitempty"`
// SandboxStatus Managed-sandbox launch progress for a `host_type="managed"` session.
//
// Carried on the session snapshot only while the session's
// background sandbox launch is in flight or has failed; `None`
// for sessions without a managed launch and once the launch
// succeeds (the session then looks like any host-bound session).
SandboxStatus *SandboxStatus `json:"sandbox_status,omitempty"`
// Skills Skills the bound agent has access to — the merged result of the agent spec's bundled `skills` and the host-scope skills discovered along the agent workdir / `~/.claude/skills/` (subject to the spec's `skills_filter`). Mirrors what the TUI passes to the runner at startup. Empty list when the agent spec cannot be loaded, or when bundled + host discovery yields nothing.
Skills []SkillSummary `json:"skills,omitempty"`
// Status Session lifecycle status. One of `"idle"` (no loop running), `"running"` (loop executing), `"waiting"` (loop parked on background work / sub-agents), or `"failed"` (terminal failure). Current read paths collapse `"waiting"` -> `"running"` before building this snapshot; the literal stays a superset of what the runtime can produce so a server that forwards the raw status never 500s on serialization.
Status SessionResponseStatus `json:"status"`
// SubAgentName For sub-agent sessions, the sub-agent type name within the parent's spec tree, e.g. `"summarizer"`. `None` for top-level sessions.
SubAgentName *string `json:"sub_agent_name,omitempty"`
// SubagentRoutingOverride Per-session subagent-routing switch, two-state: `"on"` routes subagent spawns, and `"off"` or `None` (unset) both leave them unrouted — the in-session "Subagent routing" row renders either as "Default". `None` on a row created before this became explicit inherits nothing. Stamped `"on"` at create for Smart Routing sessions; also set via `PATCH /v1/sessions/{id}`.
SubagentRoutingOverride *string `json:"subagent_routing_override,omitempty"`
// TerminalLaunchArgs Pass-through CLI args the native terminal wrapper (claude / codex) was launched with, e.g. `["--dangerously-skip-permissions"]`. `None` for non-native sessions or a native session launched with none. Lets the launcher reproduce the command on resume.
TerminalLaunchArgs []string `json:"terminal_launch_args,omitempty"`
// TerminalPending `True` while the runner is auto-creating a terminal-first session's terminal (claude-native / codex-native), so the Web UI shows a spinner on the Terminal pill instead of a silent greyed-out button. Cleared to `False` once the terminal lands or auto-create fails; from then on the client relies purely on whether a terminal resource exists. Sourced from the Omnigent server's in-memory internal state at snapshot build time, so a client connecting mid-spin-up still sees the spinner.
TerminalPending *bool `json:"terminal_pending,omitempty"`
// Title Optional human-readable title, e.g. `"debugging auth flow"`. `None` when unset.
Title *string `json:"title,omitempty"`
// Todos Current Claude Code todo list items for `omnigent claude` sessions, as raw dicts from Claude's todo JSON file. Each dict has `content`, `status`, and `activeForm` keys. Empty list for non-claude-native sessions or when no todos have been reported yet. Sourced from the Omnigent server's in-memory internal state.
Todos []map[string]interface{} `json:"todos,omitempty"`
// TotalCostUsd Cumulative LLM spend for this session in USD, e.g. `0.42`. `None` when the session is **unpriced** — no turn has been priced yet (the model is absent from the pricing catalog, or no usage has been recorded) — so clients render "—" rather than a misleading `$0.00`. Server-computed (cache-aware for relay/codex, exact billing for claude-native), the same total the cost-budget policy gates on. Lets clients seed their cost indicator on resume without waiting for the next `session.usage` SSE event.
TotalCostUsd *float32 `json:"total_cost_usd,omitempty"`
// UpdatedAt Unix epoch timestamp of the last persisted session activity. Advances when conversation items are appended and on session metadata edits (rename, agent switch, archive); a mid-stall rename therefore resets the clock, so an orchestrator treating this as a pure item-append heartbeat should account for that. Can be compared across snapshots independently of lifecycle status.
UpdatedAt *int `json:"updated_at,omitempty"`
// UsageByModel Per-model breakdown of the same subtree usage, keyed by the raw harness model id, e.g. `{"claude-sonnet-4-6": ModelUsage(input_tokens=12000,...)}`. `None` when no per-model usage has been recorded (older sessions recorded before this field existed, or before the first turn). Lets the UI show which models a session spent its tokens / budget on.
UsageByModel map[string]ModelUsage `json:"usage_by_model,omitempty"`
// Workspace Absolute path on disk where the runner cd's, e.g. `"/path/to/workspace"`. Set when the session was bound to a host workspace at create-time, or when the CLI captured `os.getcwd()` at session-create. Always `None` when not yet validated against a host. When a git worktree was created for the session, this is the worktree directory path.
Workspace *string `json:"workspace,omitempty"`
}
SessionResponse API representation of a session.
Returned by `POST /v1/sessions`, `GET /v1/sessions/{id}`, and `PATCH /v1/sessions/{id}`.
type SessionResponseStatus ¶
type SessionResponseStatus string
SessionResponseStatus Session lifecycle status. One of `"idle"` (no loop running), `"running"` (loop executing), `"waiting"` (loop parked on background work / sub-agents), or `"failed"` (terminal failure). Current read paths collapse `"waiting"` -> `"running"` before building this snapshot; the literal stays a superset of what the runtime can produce so a server that forwards the raw status never 500s on serialization.
const ( SessionResponseStatusFailed SessionResponseStatus = "failed" SessionResponseStatusIdle SessionResponseStatus = "idle" SessionResponseStatusRunning SessionResponseStatus = "running" SessionResponseStatusWaiting SessionResponseStatus = "waiting" )
Defines values for SessionResponseStatus.
func (SessionResponseStatus) Valid ¶
func (e SessionResponseStatus) Valid() bool
Valid indicates whether the value is a known member of the SessionResponseStatus enum.
type SessionSandboxStatusEvent ¶
type SessionSandboxStatusEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
// Error Failure detail when `stage == "failed"`, e.g. `"managed sandbox launch failed: spend limit reached"`. `None` otherwise. Category: **transient** (SSE-only). On reconnect, clients seed the progress indicator from the session snapshot's `sandbox_status` field, which is populated by the server at snapshot build time.
Error *string `json:"error,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Stage The launch stage just entered, e.g. `"provisioning"` — see `SandboxStatus` for the full pipeline order.
Stage SessionSandboxStatusEventStage `json:"stage"`
// Type Always `"session.sandbox_status"`.
Type SessionSandboxStatusEventType `json:"type"`
}
SessionSandboxStatusEvent Managed-sandbox launch progress for a `host_type="managed"` session.
A managed create returns before its sandbox exists; the Omnigent server emits this event as the background launch pipeline advances so the Web UI can show live provisioning progress on the session page instead of a silent dead chat: sandbox provision → repository clone → host startup → runner connect → ready, or a terminal failure with the reason.
Wire type: "session.sandbox_status".
type SessionSandboxStatusEventStage ¶
type SessionSandboxStatusEventStage string
SessionSandboxStatusEventStage The launch stage just entered, e.g. `"provisioning"` — see `SandboxStatus` for the full pipeline order.
const ( SessionSandboxStatusEventStageCloning SessionSandboxStatusEventStage = "cloning" SessionSandboxStatusEventStageConnecting SessionSandboxStatusEventStage = "connecting" SessionSandboxStatusEventStageFailed SessionSandboxStatusEventStage = "failed" SessionSandboxStatusEventStageProvisioning SessionSandboxStatusEventStage = "provisioning" SessionSandboxStatusEventStageReady SessionSandboxStatusEventStage = "ready" SessionSandboxStatusEventStageStarting SessionSandboxStatusEventStage = "starting" )
Defines values for SessionSandboxStatusEventStage.
func (SessionSandboxStatusEventStage) Valid ¶
func (e SessionSandboxStatusEventStage) Valid() bool
Valid indicates whether the value is a known member of the SessionSandboxStatusEventStage enum.
type SessionSandboxStatusEventType ¶
type SessionSandboxStatusEventType string
SessionSandboxStatusEventType Always `"session.sandbox_status"`.
const (
SessionSandboxStatusEventTypeSessionSandboxStatus SessionSandboxStatusEventType = "session.sandbox_status"
)
Defines values for SessionSandboxStatusEventType.
func (SessionSandboxStatusEventType) Valid ¶
func (e SessionSandboxStatusEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionSandboxStatusEventType enum.
type SessionSkillsEvent ¶
type SessionSkillsEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`. Category: **transient** (SSE-only). On reconnect, clients seed the menu from the session snapshot's `skills` field, which is populated by the runner-skills cache at snapshot build time.
ConversationID string `json:"conversation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.skills"`.
Type SessionSkillsEventType `json:"type"`
}
SessionSkillsEvent Signal that a session's runner-owned skills have resolved.
Skills are discovered against the bound runner's filesystem and fetched off the session-snapshot hot path: the snapshot kicks a single background fetch and serves `[]` until it lands. This event fires the moment that background fetch populates the per-session skills cache, so a connected web client can re-read the snapshot and fill its slash-command menu instead of waiting for the next bind.
Carries no payload beyond the conversation id — it is a "skills are ready, re-read the snapshot" nudge, mirroring the invalidate-then-refetch shape used by `SessionChangedFilesInvalidatedEvent`. The snapshot's `skills` field (now cache-backed) stays the source of truth.
Wire type: "session.skills".
type SessionSkillsEventType ¶
type SessionSkillsEventType string
SessionSkillsEventType Always `"session.skills"`.
const (
SessionSkillsEventTypeSessionSkills SessionSkillsEventType = "session.skills"
)
Defines values for SessionSkillsEventType.
func (SessionSkillsEventType) Valid ¶
func (e SessionSkillsEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionSkillsEventType enum.
type SessionSortBy ¶
type SessionSortBy string
SessionSortBy is the timestamp a session listing orders on.
const ( // SessionSortByCreatedAt orders on creation time. The server's default, and // the stable choice for paging: an update mid-walk cannot reorder items // underneath the cursor. SessionSortByCreatedAt SessionSortBy = "created_at" // SessionSortByUpdatedAt orders on last-activity time, which is what a // recency-ordered list wants. Because activity reorders items, a long walk // under this can revisit or skip one. SessionSortByUpdatedAt SessionSortBy = "updated_at" )
type SessionStatusEvent ¶
type SessionStatusEvent struct {
BackgroundTaskCount *int `json:"background_task_count,omitempty"`
// BlockedOn Short human phrase naming what a still-`running` session is parked on, e.g. `"permission prompt"` or `"dialog open"`. Set by terminal-backed integrations whose agent can block on a dialog the web UI does not mirror, so the client can say *why* nothing is moving instead of showing a bare spinner. `None` whenever the session is not parked. Unrelated to the `waiting` status above, which means the turn has ended and only background work remains. Category: **transient** (SSE-only). Status is rederived on reconnect from the cached last-relayed turn lifecycle event or by re-querying the runner; not persisted by the runtime.
BlockedOn *string `json:"blocked_on,omitempty"`
// ConversationID The conversation/session identifier whose status changed, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
// Error Machine-readable error information attached to a failed response.
Error *ErrorDetail `json:"error,omitempty"`
// ResponseID Optional active response id for terminal-backed integrations, e.g. `"codex_turn_abc123"`. Clients use it to associate coarse session status edges with the assistant bubble they describe. `None` for ordinary in-process runtime edges.
ResponseID *string `json:"response_id,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Status New session status. `"launching"` (session or child task created, but no concrete harness start observed), `"idle"` (no loop running), `"running"` (loop executing), `"waiting"` (parent turn parked on the async-work drain), or `"failed"` (terminal failure).
Status SessionStatusEventStatus `json:"status"`
// Type Always `"session.status"`.
Type SessionStatusEventType `json:"type"`
}
SessionStatusEvent Session lifecycle status transition.
Emitted by the runtime / session route handler at every transition between `launching` / `running` / `waiting` / `idle` / `failed`. Wire shape is FLAT (not enveloped): `{"type": "session.status", "conversation_id": "...", "status": "...", "sequence_number": null}`.
The `waiting` value is emitted by the runtime's parent agent loop when it parks on the `async_work_complete` drain — i.e. while the parent turn is suspended waiting for background tools or sub-agents to complete. Per the session-rearchitecture spec §3 ("Event types and direction"), `waiting` is the session-status companion of the spec's `turn.waiting` transient — clients should render the session as actively blocked-on-async-work, distinct from `running`. When the drain wakes (a child completed), the runtime emits a follow-up `running` to resume.
Wire type: "session.status".
type SessionStatusEventStatus ¶
type SessionStatusEventStatus string
SessionStatusEventStatus New session status. `"launching"` (session or child task created, but no concrete harness start observed), `"idle"` (no loop running), `"running"` (loop executing), `"waiting"` (parent turn parked on the async-work drain), or `"failed"` (terminal failure).
const ( SessionStatusEventStatusFailed SessionStatusEventStatus = "failed" SessionStatusEventStatusIdle SessionStatusEventStatus = "idle" SessionStatusEventStatusLaunching SessionStatusEventStatus = "launching" SessionStatusEventStatusRunning SessionStatusEventStatus = "running" SessionStatusEventStatusWaiting SessionStatusEventStatus = "waiting" )
Defines values for SessionStatusEventStatus.
func (SessionStatusEventStatus) Valid ¶
func (e SessionStatusEventStatus) Valid() bool
Valid indicates whether the value is a known member of the SessionStatusEventStatus enum.
type SessionStatusEventType ¶
type SessionStatusEventType string
SessionStatusEventType Always `"session.status"`.
const (
SessionStatusEventTypeSessionStatus SessionStatusEventType = "session.status"
)
Defines values for SessionStatusEventType.
func (SessionStatusEventType) Valid ¶
func (e SessionStatusEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionStatusEventType enum.
type SessionSupersededEvent ¶
type SessionSupersededEvent struct {
// ConversationID The superseded (old) conversation id this event rides the stream of, e.g. `"conv_old"`.
ConversationID string `json:"conversation_id"`
// Reason Why the session was superseded. Currently always `"clear"` (a Claude Code `/clear`); kept as a field so the client can branch on future supersession causes.
Reason *SessionSupersededEventReason `json:"reason,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// TargetConversationID The conversation to follow to, e.g. `"conv_new"`.
TargetConversationID string `json:"target_conversation_id"`
// Type Always `"session.superseded"`.
Type SessionSupersededEventType `json:"type"`
}
SessionSupersededEvent This conversation was superseded by another and clients should follow to it.
Emitted by the server when the claude-native forwarder rotates a session away on a Claude `/clear` (the old conversation keeps its history but the live terminal moves to a fresh conversation). A client actively viewing the superseded conversation auto-redirects to `target_conversation_id`.
Category: **transient** (SSE-only), live-only by design. There is no SSE replay: a client that connects after the rotation does not get this event. The durable counterpart is the persisted notice message appended to the old conversation (a `message` item linking to the new conversation), which a reloading client renders instead of being force-redirected.
The wire shape is FLAT (not enveloped): `{"type": "session.superseded", "conversation_id": <old>, "target_conversation_id": <new>, "reason": "clear"}`.
Wire type: "session.superseded".
type SessionSupersededEventReason ¶
type SessionSupersededEventReason string
SessionSupersededEventReason Why the session was superseded. Currently always `"clear"` (a Claude Code `/clear`); kept as a field so the client can branch on future supersession causes.
const (
SessionSupersededEventReasonClear SessionSupersededEventReason = "clear"
)
Defines values for SessionSupersededEventReason.
func (SessionSupersededEventReason) Valid ¶
func (e SessionSupersededEventReason) Valid() bool
Valid indicates whether the value is a known member of the SessionSupersededEventReason enum.
type SessionSupersededEventType ¶
type SessionSupersededEventType string
SessionSupersededEventType Always `"session.superseded"`.
const (
SessionSupersededEventTypeSessionSuperseded SessionSupersededEventType = "session.superseded"
)
Defines values for SessionSupersededEventType.
func (SessionSupersededEventType) Valid ¶
func (e SessionSupersededEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionSupersededEventType enum.
type SessionTerminalActivityEvent ¶
type SessionTerminalActivityEvent struct {
SequenceNumber *int `json:"sequence_number,omitempty"`
// SessionID Owning session/conversation id.
SessionID string `json:"session_id"`
// TerminalID Opaque terminal resource id, e.g. `"terminal_zsh_s1"`.
TerminalID string `json:"terminal_id"`
// Type Always `"session.terminal.activity"`.
Type SessionTerminalActivityEventType `json:"type"`
}
SessionTerminalActivityEvent A terminal's pane produced output (runner-determined activity pulse).
Powers the web "active" badge for any terminal without a client PTY attach — the runner's per-terminal pane watcher emits this when the pane content changes. Transient (a live pulse; not persisted, not in the connect snapshot).
Wire type: "session.terminal.activity".
type SessionTerminalActivityEventType ¶
type SessionTerminalActivityEventType string
SessionTerminalActivityEventType Always `"session.terminal.activity"`.
const (
SessionTerminalActivityEventTypeSessionTerminalActivity SessionTerminalActivityEventType = "session.terminal.activity"
)
Defines values for SessionTerminalActivityEventType.
func (SessionTerminalActivityEventType) Valid ¶
func (e SessionTerminalActivityEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionTerminalActivityEventType enum.
type SessionTerminalPendingEvent ¶
type SessionTerminalPendingEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
// Pending `True` while the terminal is being created; `False` once it lands or auto-create fails. Category: **transient** (SSE-only). On reconnect, clients seed the spinner from the session snapshot's `terminal_pending` field, which is populated by the server at snapshot build time.
Pending bool `json:"pending"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"session.terminal_pending"`.
Type SessionTerminalPendingEventType `json:"type"`
}
SessionTerminalPendingEvent Terminal spin-up status for a terminal-first session.
Two sources emit this event:
- The Omnigent server at `POST /v1/sessions` for host-launched terminal-first sessions — the earliest possible point, before the runner even starts, so the spinner appears immediately on session create rather than after the runner boots.
- The Omnigent relay when the runner's `session.terminal_pending` frame arrives — covers non-host-launched sessions (e.g. server-dispatched sub-agents) and carries the authoritative `pending=False` clear emitted by the runner's `finally` block.
Together they allow web to show a spinner on the Terminal pill while the backend boots the terminal instead of a silent greyed-out button, and to distinguish "still starting up" from "no terminal" (killed or never created).
Wire type: "session.terminal_pending".
type SessionTerminalPendingEventType ¶
type SessionTerminalPendingEventType string
SessionTerminalPendingEventType Always `"session.terminal_pending"`.
const (
SessionTerminalPendingEventTypeSessionTerminalPending SessionTerminalPendingEventType = "session.terminal_pending"
)
Defines values for SessionTerminalPendingEventType.
func (SessionTerminalPendingEventType) Valid ¶
func (e SessionTerminalPendingEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionTerminalPendingEventType enum.
type SessionTodosEvent ¶
type SessionTodosEvent struct {
// ConversationID Session identifier, e.g. `"conv_abc123"`.
ConversationID string `json:"conversation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Todos Current todo items read from Claude's todo file. Each entry is a raw dict with `content` (str), `status` (`"pending"` | `"in_progress"` | `"completed"`), and `activeForm` (str, the gerund form) keys, e.g. `[{"content": "Fix the bug", "status": "in_progress", "activeForm": "Fixing the bug"}]`. Category: **transient** (SSE-only). On reconnect, clients seed the panel from the session snapshot's `todos` field, which is populated by the server at snapshot build time.
Todos []map[string]interface{} `json:"todos"`
// Type Always `"session.todos"`.
Type SessionTodosEventType `json:"type"`
}
SessionTodosEvent Todo-list update from a Claude Code terminal-backed session.
Emitted after an `external_session_todos` POST from the `omnigent claude` transcript forwarder, which captures todo updates via `PostToolUse`/`TodoWrite` hook events from Claude Code and forwards them to the Omnigent server. Lets web render a live todo panel in the right column without polling.
Wire type: "session.todos".
type SessionTodosEventType ¶
type SessionTodosEventType string
SessionTodosEventType Always `"session.todos"`.
const (
SessionTodosEventTypeSessionTodos SessionTodosEventType = "session.todos"
)
Defines values for SessionTodosEventType.
func (SessionTodosEventType) Valid ¶
func (e SessionTodosEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionTodosEventType enum.
type SessionUsageEvent ¶
type SessionUsageEvent struct {
// ContextTokens `input + cache_creation + cache_read` from the latest assistant `message.usage`. `None` on a window-only broadcast.
ContextTokens *int `json:"context_tokens,omitempty"`
// ContextWindow Resolved window in tokens (e.g. 200_000 normally, 1_000_000 with `opus[1m]` / `sonnet[1m]`). `None` on a tokens-only broadcast.
ContextWindow *int `json:"context_window,omitempty"`
// ConversationID Session identifier.
ConversationID string `json:"conversation_id"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// TotalCostUsd Cumulative session spend in USD after this update, e.g. `0.42` — the server-computed total the cost-budget policy gates on. Present **only when the session is priced**; omitted (`None`, stripped by `exclude_none`) when unpriced or on a broadcast that carries no cost change, so the client keeps its prior value (the snapshot seeds the initial "—" for an unpriced session). Once a session is priced the total only grows, so it never reverts to unpriced.
TotalCostUsd *float32 `json:"total_cost_usd,omitempty"`
// Type Always `"session.usage"`.
Type SessionUsageEventType `json:"type"`
// UsageByModel Per-model breakdown of the same subtree usage after this update, keyed by raw harness model id, e.g. `{"claude-sonnet-4-6": ModelUsage(input_tokens=12000,...)}`. `None` (stripped by `exclude_none`) on a broadcast that carries no per-model change, so the client keeps its cached map. Category: **transient** (SSE-only). On reconnect, clients seed the ring from the session snapshot's `last_total_tokens` and `context_window`, the cost indicator from `total_cost_usd`, and the per-model token breakdown from `usage_by_model`.
UsageByModel map[string]ModelUsage `json:"usage_by_model,omitempty"`
}
SessionUsageEvent Token-usage update from a terminal-backed integration.
Emitted after an `external_session_usage` POST from an out-of-AP runtime (e.g. the `omnigent claude` transcript forwarder). Either field may be absent; clients should leave cached values untouched for missing fields.
Wire type: "session.usage".
type SessionUsageEventType ¶
type SessionUsageEventType string
SessionUsageEventType Always `"session.usage"`.
const (
SessionUsageEventTypeSessionUsage SessionUsageEventType = "session.usage"
)
Defines values for SessionUsageEventType.
func (SessionUsageEventType) Valid ¶
func (e SessionUsageEventType) Valid() bool
Valid indicates whether the value is a known member of the SessionUsageEventType enum.
type SkillSummary ¶
type SkillSummary struct {
// Description One-line summary from the SKILL.md frontmatter, e.g. `"Triage open GitHub issues in the repo."`.
Description string `json:"description"`
// Name Skill identifier as parsed from the SKILL.md frontmatter, e.g. `"triage-issues"`. Lowercase kebab-case.
Name string `json:"name"`
}
SkillSummary Safe subset of a discovered skill for API exposure.
Surfaces the skill name and one-line description so clients (e.g. the web composer's slash-command menu) can list which skills the session has access to. The full skill `content` is intentionally omitted — it's only loaded server-side when the harness invokes the skill, and it can be large.
type SkippedFrame ¶
type SkippedFrame struct {
// SessionID is the session whose stream carried the frame.
SessionID string
// Name is the frame's event: line, empty when it carried none. Note that
// dispatch prefers the payload's own type field, so this is not necessarily
// what decoding was attempted against.
Name string
// Payload is the frame's data: lines, rejoined. It is bounded only by
// maxFrameBytes, so bound it again before logging it.
Payload string
// Err is why the frame could not be decoded: [ErrStreamProtocol] for a
// payload that is not JSON or carries no discriminator, otherwise a
// field-level decode failure naming the event type it was decoded as.
Err error
}
SkippedFrame describes a frame Client.Stream dropped because it could not be decoded, reported to StreamOptions.OnSkippedFrame.
Fields will be added to it. Construct one with field names — go vet's composites check enforces that for a struct from another package — and it stays source-compatible as it grows.
type SlashCommandData ¶
type SlashCommandData struct {
// Arguments Raw `<command-args>` text. Empty when none.
Arguments string `json:"arguments"`
// Kind `"skill"` for plugin/Skill invocations, `"command"` for surfaced CLI built-ins (`/effort`, `/clear`, `/compact`, `/model`, `/ultrareview`). The web renderer uses this to pick the prefix label and icon. Defaults to `"skill"` so persisted items predating this field deserialize without backfill.
Kind *SlashCommandDataKind `json:"kind,omitempty"`
Model string `json:"model"`
// Name Command name with leading `/` stripped, e.g. `"dev-productivity:simplify"`.
Name string `json:"name"`
// Output `<local-command-stdout>` text when present, else `None` (the common case — Skills act via the next assistant turn, not stdout).
Output *string `json:"output,omitempty"`
}
SlashCommandData Data payload for a slash-command invocation observed in a harness transcript (today: Claude Code's embedded TUI).
Listed in `NON_CONTENT_ITEM_TYPES` so the agent loop's history filter skips it — a downstream LLM never sees this as a phantom tool call. Field names mirror `function_call` so the web renderer can reuse the tool-card layout.
**Parameters**
- `agent` — Harness/agent name, e.g. `"claude-native-ui"`. Serialized as `"model"` for parity with other items.
type SlashCommandDataKind ¶
type SlashCommandDataKind string
SlashCommandDataKind `"skill"` for plugin/Skill invocations, `"command"` for surfaced CLI built-ins (`/effort`, `/clear`, `/compact`, `/model`, `/ultrareview`). The web renderer uses this to pick the prefix label and icon. Defaults to `"skill"` so persisted items predating this field deserialize without backfill.
const ( SlashCommandDataKindCommand SlashCommandDataKind = "command" SlashCommandDataKindSkill SlashCommandDataKind = "skill" )
Defines values for SlashCommandDataKind.
func (SlashCommandDataKind) Valid ¶
func (e SlashCommandDataKind) Valid() bool
Valid indicates whether the value is a known member of the SlashCommandDataKind enum.
type SortOrder ¶
type SortOrder string
SortOrder is the direction a listing returns its items in.
const ( // SortDescending returns newest first. The server's default on the agent and // session listings. SortDescending SortOrder = "desc" // SortAscending returns oldest first. The server's default on the items // listing, whose chronological order is the transcript's own. SortAscending SortOrder = "asc" )
type StreamOptions ¶
type StreamOptions struct {
// Idle marks this subscriber as present but inattentive, which co-viewers
// see on their own streams as a presence edge. Flipping it means
// reconnecting with the new value; there is no update path.
Idle bool
// IdleTimeout overrides the client's default tolerance for silence, which
// means time with no bytes arriving. The server heartbeats every 15 seconds,
// so this bounds transport death detection — not agent latency, and not how
// long one large frame may take to arrive. Zero uses the client's setting.
IdleTimeout time.Duration
// OnSubscribed runs once the subscription is live, before the first event
// reaches the caller, and is the supported way to post the input that
// starts a turn. It runs on the caller's goroutine, so it must return
// promptly; the idle watchdog is suspended while it does.
//
// It exists because the acknowledgement cannot be recognised by inspecting
// events. The server sends the identical {"type": "session.heartbeat"}
// payload for two different things — the subscription acknowledgement, and
// the keepalive it emits every 15 seconds while a stream sits idle — so
// "send when I see a heartbeat" sends again on every keepalive, forever.
// This hook is called exactly once per stream, whatever the frames look
// like — or not at all, if the stream ends before delivering an event.
// Returning an error ends the stream with that error wrapped.
//
// Seeding the first turn through [SessionCreateRequest.InitialItems] avoids
// needing this at all; it is the second and later turns that do.
//
// The second parameter is a struct rather than a growing parameter list
// because this is the package's headline hook: its signature is the one thing
// here that cannot be extended later without breaking every caller. What a
// subscription is worth telling a caller about will grow; see [Subscription].
OnSubscribed func(ctx context.Context, sub Subscription) error
// OnSkippedFrame runs for a frame this build could not decode. The frame is
// dropped and the subscription continues, so one unreadable frame degrades a
// turn rather than ending it — which is also what the Python client does with
// one. Leaving this nil still skips the frame; the hook is how a caller sees
// that it happened.
//
// Nothing this server sends reaches it today. The stream route validates every
// event against its event union before serializing it, and these types are
// generated from that union's published schema, so a frame that made it onto
// the wire has already been proven to fit. What reaches it is spec drift: a
// field whose type changed under a client generated from an older schema. An
// unrecognised event *type* is not that case — that surfaces as
// [UnknownEvent] and is not an error at all.
//
// Like [StreamOptions.OnSubscribed] it runs on the caller's goroutine with
// the idle watchdog suspended, so it must return promptly. Returning an error
// ends the stream with that error wrapped, which is how a caller opts back
// into treating an undecodable frame as fatal.
//
// A transport failure is a different thing and stays terminal: this hook sees
// frames that arrived and could not be read, never a stream that stopped
// arriving.
OnSkippedFrame func(ctx context.Context, frame SkippedFrame) error
}
StreamOptions configures one call to Client.Stream.
type Subscription ¶
type Subscription struct {
// SessionID is the session this stream is subscribed to, so a hook shared
// between streams does not need to close over it.
SessionID string
// Idle mirrors [StreamOptions.Idle]: whether this subscriber declared itself
// present but inattentive.
Idle bool
}
Subscription describes the live subscription an StreamOptions.OnSubscribed hook was called for.
Fields will be added to it. Construct one with field names — go vet's composites check enforces that for a struct from another package — and it stays source-compatible as it grows.
type TerminalCommandData ¶
type TerminalCommandData struct {
// Input The raw command string, e.g. `"pwd"`. Present when `kind="input"`, `None` otherwise.
Input *string `json:"input,omitempty"`
// Kind `"input"` for the command text, `"output"` for the combined stdout/stderr result.
Kind TerminalCommandDataKind `json:"kind"`
// Stderr Captured stderr text. Present when `kind="output"`, `None` otherwise.
Stderr *string `json:"stderr,omitempty"`
// Stdout Captured stdout text. Present when `kind="output"`, `None` otherwise.
Stdout *string `json:"stdout,omitempty"`
}
TerminalCommandData Data payload for a runner-side terminal command (`!cmd`) observed in a harness transcript (today: Claude Code's embedded TUI).
Listed in `NON_CONTENT_ITEM_TYPES` so the agent loop never injects this as phantom content into the LLM's message history.
Claude Code writes two sibling transcript records per `!cmd` invocation: one `<bash-input>` record and one combined `<bash-stdout>`/`<bash-stderr>` record. Each maps to one `terminal_command` item with `kind="input"` or `kind="output"` respectively.
type TerminalCommandDataKind ¶
type TerminalCommandDataKind string
TerminalCommandDataKind `"input"` for the command text, `"output"` for the combined stdout/stderr result.
const ( TerminalCommandDataKindInput TerminalCommandDataKind = "input" TerminalCommandDataKindOutput TerminalCommandDataKind = "output" )
Defines values for TerminalCommandDataKind.
func (TerminalCommandDataKind) Valid ¶
func (e TerminalCommandDataKind) Valid() bool
Valid indicates whether the value is a known member of the TerminalCommandDataKind enum.
type ToolOutputDeltaEvent ¶
type ToolOutputDeltaEvent struct {
// CallID Function-call correlation id.
CallID string `json:"call_id"`
// Delta Command stdout/stderr fragment.
Delta string `json:"delta"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// Type Always `"response.function_call_output.delta"`.
Type ToolOutputDeltaEventType `json:"type"`
}
ToolOutputDeltaEvent Incremental output from an in-progress function call.
Wire type: "response.function_call_output.delta".
type ToolOutputDeltaEventType ¶
type ToolOutputDeltaEventType string
ToolOutputDeltaEventType Always `"response.function_call_output.delta"`.
const (
ToolOutputDeltaEventTypeResponseFunctionCallOutputDelta ToolOutputDeltaEventType = "response.function_call_output.delta"
)
Defines values for ToolOutputDeltaEventType.
func (ToolOutputDeltaEventType) Valid ¶
func (e ToolOutputDeltaEventType) Valid() bool
Valid indicates whether the value is a known member of the ToolOutputDeltaEventType enum.
type TurnCancelledEvent ¶
type TurnCancelledEvent struct {
SequenceNumber *int `json:"sequence_number,omitempty"`
// SessionID Session/conversation identifier, e.g. `"conv_abc123"`.
SessionID string `json:"session_id"`
// Type Fixed literal `"turn.cancelled"`.
Type TurnCancelledEventType `json:"type"`
}
TurnCancelledEvent Emitted when a turn is interrupted by the user or system.
Wire type: "turn.cancelled".
type TurnCancelledEventType ¶
type TurnCancelledEventType string
TurnCancelledEventType Fixed literal `"turn.cancelled"`.
const (
TurnCancelledEventTypeTurnCancelled TurnCancelledEventType = "turn.cancelled"
)
Defines values for TurnCancelledEventType.
func (TurnCancelledEventType) Valid ¶
func (e TurnCancelledEventType) Valid() bool
Valid indicates whether the value is a known member of the TurnCancelledEventType enum.
type TurnCompletedEvent ¶
type TurnCompletedEvent struct {
SequenceNumber *int `json:"sequence_number,omitempty"`
// SessionID Session/conversation identifier, e.g. `"conv_abc123"`.
SessionID string `json:"session_id"`
// Type Fixed literal `"turn.completed"`.
Type TurnCompletedEventType `json:"type"`
}
TurnCompletedEvent Emitted when a turn finishes successfully with no pending work.
Wire type: "turn.completed".
type TurnCompletedEventType ¶
type TurnCompletedEventType string
TurnCompletedEventType Fixed literal `"turn.completed"`.
const (
TurnCompletedEventTypeTurnCompleted TurnCompletedEventType = "turn.completed"
)
Defines values for TurnCompletedEventType.
func (TurnCompletedEventType) Valid ¶
func (e TurnCompletedEventType) Valid() bool
Valid indicates whether the value is a known member of the TurnCompletedEventType enum.
type TurnFailedEvent ¶
type TurnFailedEvent struct {
// Error Error details, e.g. `{"message": "LLM timeout", "type": "TimeoutError"}`.
Error map[string]interface{} `json:"error,omitempty"`
SequenceNumber *int `json:"sequence_number,omitempty"`
// SessionID Session/conversation identifier, e.g. `"conv_abc123"`.
SessionID string `json:"session_id"`
// Type Fixed literal `"turn.failed"`.
Type TurnFailedEventType `json:"type"`
}
TurnFailedEvent Emitted when a turn fails due to an LLM error, timeout, or crash.
Wire type: "turn.failed".
type TurnFailedEventType ¶
type TurnFailedEventType string
TurnFailedEventType Fixed literal `"turn.failed"`.
const (
TurnFailedEventTypeTurnFailed TurnFailedEventType = "turn.failed"
)
Defines values for TurnFailedEventType.
func (TurnFailedEventType) Valid ¶
func (e TurnFailedEventType) Valid() bool
Valid indicates whether the value is a known member of the TurnFailedEventType enum.
type TurnStartedEvent ¶
type TurnStartedEvent struct {
SequenceNumber *int `json:"sequence_number,omitempty"`
// SessionID Session/conversation identifier, e.g. `"conv_abc123"`.
SessionID string `json:"session_id"`
// Type Fixed literal `"turn.started"`.
Type TurnStartedEventType `json:"type"`
}
TurnStartedEvent Emitted when the runner starts a new turn for a session.
Wire type: "turn.started".
type TurnStartedEventType ¶
type TurnStartedEventType string
TurnStartedEventType Fixed literal `"turn.started"`.
const (
TurnStartedEventTypeTurnStarted TurnStartedEventType = "turn.started"
)
Defines values for TurnStartedEventType.
func (TurnStartedEventType) Valid ¶
func (e TurnStartedEventType) Valid() bool
Valid indicates whether the value is a known member of the TurnStartedEventType enum.
type UnknownEvent ¶
type UnknownEvent struct {
// Type is the frame's discriminator, e.g. "session.something.new".
Type string
// Raw is the frame's JSON payload, owned by the caller.
Raw []byte
}
UnknownEvent carries a frame whose discriminator this build does not know.
It is not an error. The server's event schemas ignore unknown fields by contract so a new field cannot break an older parser, and this is the same guarantee one level up: a client built against an older openapi.json surfaces a newly added event type here and keeps streaming.
type UpdateSessionRequest ¶ added in v0.1.2
type UpdateSessionRequest struct {
// Archived New archived state. `True` archives (hides the session from the default sidebar listing), `False` unarchives, `None` leaves unchanged. Owner-only (unlike `title`, which needs only edit access).
Archived *bool `json:"archived,omitempty"`
// CollaborationMode Codex-native collaboration-mode string. `"plan"` enters Plan mode and `"default"` returns to Default mode for subsequent Codex turns. Only valid for sessions stamped with the codex-native wrapper label. Omitted leaves unchanged.
CollaborationMode *string `json:"collaboration_mode,omitempty"`
// CostControlModeOverride Per-session cost-control switch: `"on"` activates the spec's configured cost-control mode, `"off"` disables cost control for this session. Explicit JSON `null` clears the override back to the spec default; omitting the field leaves it unchanged (`"off"` is a real value here, so the field's *presence* — not a clear alias — is the clear signal, unlike `model_override`).
CostControlModeOverride *string `json:"cost_control_mode_override,omitempty"`
// ExternalSessionID Runtime-native session id captured by a wrapper bridge (e.g. Claude Code's session uuid for `omnigent claude` sessions). Idempotent on same-value writes; the server rejects attempts to overwrite an already-set different value with `invalid_input` to surface programmer errors. `None` leaves unchanged.
ExternalSessionID *string `json:"external_session_id,omitempty"`
// Labels Guardrails labels to upsert. Merges with existing labels; keys not present are left untouched.
Labels map[string]string `json:"labels,omitempty"`
// ModelOverride Per-session LLM model override, e.g. `"claude-opus-4-7"`. The value is forwarded as-is to the executor at turn start; the server does not enumerate valid models. Clear aliases such as `"default"`, `"off"`, or `"reset"` remove the override (matching the REPL's `/model` semantics). `None` leaves unchanged.
ModelOverride *string `json:"model_override,omitempty"`
// ProjectID File this session into a first-class project (see `designs/PROJECTS_PRD.md`). A non-empty id moves the session into that project; the empty string `""` unfiles it. **Omitting** the field leaves membership unchanged; an explicit `null` is rejected (400) so it can't silently unfile. Owner-only: because projects are owner-private, only the session owner may file it, and only into a project they own — the server verifies both. Independent of the legacy `omni_project` label, which is set via `labels`.
ProjectID *string `json:"project_id,omitempty"`
// ReasoningEffort Per-session reasoning-effort hint. Accepted metadata values are `"none"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, and `"max"`. Provider-specific support is validated when a turn executes. Clear aliases such as `"default"` remove the session override. `None` leaves unchanged.
ReasoningEffort *string `json:"reasoning_effort,omitempty"`
// RunnerID Identifier of a registered runner, e.g. `"runner_abc123"`. `None` leaves runner binding unchanged.
RunnerID *string `json:"runner_id,omitempty"`
// Silent When `True`, persist metadata changes but skip the runner-side side effects — specifically the native `/effort` / `/model` / Codex collaboration-mode forwards into the live runtime. Used by automatic bind-time handoffs (web's sticky-pref apply on session switch, the REPL's pre-create `/model` snapshot) where injecting a visible slash command into a freshly-spawned pane would render as an unexpected "Command model X" item before the user has sent anything. Default `False` preserves the user-driven picker / `/model` behaviour where the live forward IS the desired feedback.
Silent *bool `json:"silent,omitempty"`
// SubagentRoutingOverride Per-session subagent-routing switch: `"on"` routes subagent spawns, `"off"` leaves them unrouted. Explicit JSON `null` clears the override, which lands the session on Default (the same behavior as `"off"` — nothing is inherited); omitting the field leaves it unchanged (same presence-is-the-clear-signal rule as `cost_control_mode_override`). Effective on the next spawn, so it can be changed at any point in a session.
SubagentRoutingOverride *string `json:"subagent_routing_override,omitempty"`
// TerminalLaunchArgs Per-session native-terminal pass-through args, e.g. `["--dangerously-skip-permissions"]`. A list (including `[]`) replaces the stored value wholesale — resume is last-write-wins, never an append. Bounds (count / length) are validated server-side. `None` leaves unchanged.
TerminalLaunchArgs []string `json:"terminal_launch_args,omitempty"`
// Title New title, e.g. `"debugging auth flow"`. `None` leaves unchanged.
Title *string `json:"title,omitempty"`
}
UpdateSessionRequest Request body for `PATCH /v1/sessions/{id}`.
The Alpha runner-state pivot makes this endpoint the mutable session affinity primitive when `runner_id` is provided. The server validates that the runner is online, then replaces `conversations.runner_id`. Existing session metadata updates remain supported for clients that update title, labels, or reasoning effort through the sessions API.
type Usage ¶
type Usage struct {
// CacheCreationInputTokens Prompt tokens written to the provider prompt cache (cache creation), billed at a premium rate. Like `cache_read_input_tokens`, this is separate from `input_tokens`; `0` when not reported.
CacheCreationInputTokens *int `json:"cache_creation_input_tokens,omitempty"`
// CacheReadInputTokens Prompt tokens served from a provider prompt cache (cache hit), billed at a reduced rate. Reported by Anthropic-style providers as a count *separate* from `input_tokens` (which carries only the non-cached portion); `0` when the provider does not break out cache usage. Consumed by the cache-aware server-side cost path.
CacheReadInputTokens *int `json:"cache_read_input_tokens,omitempty"`
// ContextTokens Context-fill estimate for the next turn — set only by executors that make multiple LLM sub-calls per turn (e.g. `openai-agents`). For single-call executors this is absent and `total_tokens` serves the same purpose. The toolbar context ring and `/context` command use this field when present, falling back to `total_tokens`.
ContextTokens *int `json:"context_tokens,omitempty"`
// CostUsd Authoritative per-turn cost in USD reported directly by the harness/provider (e.g. GitHub Copilot's AI-credit total). When present, the server-side cost path uses it in preference to the catalog token-price estimate; `None` when the harness doesn't report a cost (the common case, where cost is computed from token counts x catalog pricing).
CostUsd *float32 `json:"cost_usd,omitempty"`
// InputTokens Number of input (prompt) tokens consumed.
InputTokens *int `json:"input_tokens,omitempty"`
// Model The LLM model the harness actually used for this turn, e.g. `"claude-opus-4-8"` or `"databricks-gpt-5-5"`. Reported by relay executors so the server-side cost path can price the turn even when the agent spec pins no `llm.model` (e.g. supervisors that delegate / use the harness default). `None` when the executor doesn't report it; the cost path then falls back to the session override / spec model.
Model *string `json:"model,omitempty"`
// OutputTokens Number of output (completion) tokens generated.
OutputTokens *int `json:"output_tokens,omitempty"`
// OutputTokensDetails Breakdown of output token usage.
OutputTokensDetails *UsageDetails `json:"output_tokens_details,omitempty"`
// TotalTokens Sum of input and output tokens across all LLM sub-calls for this turn (billing total).
TotalTokens *int `json:"total_tokens,omitempty"`
}
Usage Token usage statistics for a response.
type UsageDetails ¶
type UsageDetails struct {
// ReasoningTokens Number of tokens consumed by chain-of-thought reasoning.
ReasoningTokens *int `json:"reasoning_tokens,omitempty"`
}
UsageDetails Breakdown of output token usage.
type ValidationError ¶
type ValidationError struct {
Ctx map[string]interface{} `json:"ctx,omitempty"`
Input interface{} `json:"input,omitempty"`
Loc []ValidationError_Loc_Item `json:"loc"`
Msg string `json:"msg"`
Type string `json:"type"`
}
ValidationError defines model for ValidationError.
type ValidationErrorLoc0 ¶
type ValidationErrorLoc0 = string
ValidationErrorLoc0 defines model for .
type ValidationError_Loc_Item ¶
type ValidationError_Loc_Item struct {
// contains filtered or unexported fields
}
ValidationError_Loc_Item defines model for ValidationError.loc.Item.
func (ValidationError_Loc_Item) AsValidationErrorLoc0 ¶
func (t ValidationError_Loc_Item) AsValidationErrorLoc0() (ValidationErrorLoc0, error)
AsValidationErrorLoc0 returns the union data inside the ValidationError_Loc_Item as a ValidationErrorLoc0
func (ValidationError_Loc_Item) AsValidationErrorLoc1 ¶
func (t ValidationError_Loc_Item) AsValidationErrorLoc1() (ValidationErrorLoc1, error)
AsValidationErrorLoc1 returns the union data inside the ValidationError_Loc_Item as a ValidationErrorLoc1
func (*ValidationError_Loc_Item) FromValidationErrorLoc0 ¶
func (t *ValidationError_Loc_Item) FromValidationErrorLoc0(v ValidationErrorLoc0) error
FromValidationErrorLoc0 overwrites any union data inside the ValidationError_Loc_Item as the provided ValidationErrorLoc0
func (*ValidationError_Loc_Item) FromValidationErrorLoc1 ¶
func (t *ValidationError_Loc_Item) FromValidationErrorLoc1(v ValidationErrorLoc1) error
FromValidationErrorLoc1 overwrites any union data inside the ValidationError_Loc_Item as the provided ValidationErrorLoc1
func (ValidationError_Loc_Item) MarshalJSON ¶
func (t ValidationError_Loc_Item) MarshalJSON() ([]byte, error)
func (*ValidationError_Loc_Item) MergeValidationErrorLoc0 ¶
func (t *ValidationError_Loc_Item) MergeValidationErrorLoc0(v ValidationErrorLoc0) error
MergeValidationErrorLoc0 performs a merge with any union data inside the ValidationError_Loc_Item, using the provided ValidationErrorLoc0
func (*ValidationError_Loc_Item) MergeValidationErrorLoc1 ¶
func (t *ValidationError_Loc_Item) MergeValidationErrorLoc1(v ValidationErrorLoc1) error
MergeValidationErrorLoc1 performs a merge with any union data inside the ValidationError_Loc_Item, using the provided ValidationErrorLoc1
func (*ValidationError_Loc_Item) UnmarshalJSON ¶
func (t *ValidationError_Loc_Item) UnmarshalJSON(b []byte) error