Documentation
¶
Overview ¶
Package wire holds the uniform error shapes, raw-event framing, and reserved literal rules every sibling answers with.
Index ¶
- Constants
- Variables
- func AccountUsageAdvertisement(method string, scope AccountUsageScope, providers ...string) map[string]any
- func AccountUsageTime(at time.Time) string
- func AcquireSessionGate(gate chan struct{}, limit string) (func(), error)
- func AgentClosed() *acp.RequestError
- func AudienceIsUserOnly(annotations *acp.Annotations) bool
- func AuthenticateRefused(params acp.AuthenticateRequest) *acp.RequestError
- func Backpressure(limit string) *acp.RequestError
- func CallAndAnnounce[T any](ctx context.Context, transport *Transport, meta map[string]any, ...) (T, error)
- func CancelRequest(sessionID acp.SessionId) acp.CancelNotification
- func CancelledResponse(params acp.PromptRequest) acp.PromptResponse
- func CheckReservedMeta(meta map[string]any) error
- func CheckSessionID(id acp.SessionId) *acp.RequestError
- func CloneMap(values map[string]any) map[string]any
- func CloneValue(value any) any
- func CompactionCarrier(sessionID acp.SessionId, value Compaction) acp.SessionNotification
- func ContextResourceText(uri string, text string) string
- func DeleteSessionRequest(sessionID acp.SessionId) acp.UnstableDeleteSessionRequest
- func HoldSessionGate(gate chan struct{}) func()
- func InternalFailure(vendor, class string) *acp.RequestError
- func InvalidOptions(vendor, field string) *acp.RequestError
- func LifecycleCarrier(sessionID acp.SessionId, envelope map[string]any) acp.SessionNotification
- func ListSessionsRequest(opts ...ListSessionsRequestOption) acp.ListSessionsRequest
- func LoadSessionRequest(sessionID acp.SessionId, cwd string, opts ...SessionRequestOption) acp.LoadSessionRequest
- func MergeMap(base map[string]any, overlay map[string]any) map[string]any
- func MetaOptionPath(vendor, key string) string
- func Missing(field string) *acp.RequestError
- func ModelSelectOptions(vendor, current string, native []ModelRow, configured []string) acp.SessionConfigSelectOptionsUngrouped
- func NativeSessionMeta(vendor, nativeID string) map[string]any
- func NewSessionRequest(cwd string, opts ...SessionRequestOption) acp.NewSessionRequest
- func NormalizeTitle(text string) string
- func PaginateSessions(sessions []acp.SessionInfo, cursor *string) ([]acp.SessionInfo, *string, error)
- func ParamRefusal(err *lifecycle.ParamError) *acp.RequestError
- func PromptRequest(sessionID acp.SessionId, blocks ...acp.ContentBlock) acp.PromptRequest
- func PromptTitle(prompt []acp.ContentBlock) string
- func RefuseSessionMeta(meta map[string]any) *acp.RequestError
- func RestoreFailed(vendor string) *acp.RequestError
- func RestoreRefused(ctx context.Context, logger *slog.Logger, vendor string, ...) *acp.RequestError
- func ResumeSessionRequest(sessionID acp.SessionId, cwd string, opts ...SessionRequestOption) acp.ResumeSessionRequest
- func RuntimeUnavailable(vendor string) *acp.RequestError
- func SeedFileRefusal(err error) *acp.RequestError
- func SelectPositionEncoding(encodings []acp.PositionEncodingKind) acp.PositionEncodingKind
- func SessionPoisoned(vendor, cause string) *acp.RequestError
- func SetConfigOptionRequest(sessionID acp.SessionId, configID acp.SessionConfigId, ...) acp.SetSessionConfigOptionRequest
- func StringMapOption(value any, path string) (map[string]string, *acp.RequestError)
- func StringSliceOption(value any, path string) ([]string, *acp.RequestError)
- func StructuredOutputAdvertisement(vendor string) map[string]any
- func TextPromptRequest(sessionID acp.SessionId, text string) acp.PromptRequest
- func TurnFailed(vendor string, failure TurnFailure) *acp.RequestError
- func UnknownSession() *acp.RequestError
- func Unsupported(field string) *acp.RequestError
- func ValidCommandName(name string) bool
- func ValidateConcurrencyLimits(maxActiveSessions, maxConcurrentClientCalls int) error
- func ValidateConfiguredModels(ids []string) error
- func ValidateSessionEnvironment(env map[string]string, dirs []string, path string) *acp.RequestError
- type AccountUsageBalance
- type AccountUsageLimit
- type AccountUsageMoney
- type AccountUsageRequest
- type AccountUsageRequestLimit
- type AccountUsageResponse
- type AccountUsageScope
- type CallUsage
- type Compaction
- type Compactions
- type LineReader
- type ListSessionsRequestOption
- type ModelRow
- type Notifier
- type RawEvents
- type SessionMeta
- type SessionRequestConfig
- type SessionRequestOption
- type SessionRequests
- type StreamedText
- type Transport
- func (t *Transport) AwaitSession(ctx context.Context, sessionID acp.SessionId) error
- func (t *Transport) Close()
- func (t *Transport) Reader() io.Reader
- func (t *Transport) RegisterHook(ctx context.Context, sessionID acp.SessionId, hook func(context.Context)) error
- func (t *Transport) RequestContext(ctx context.Context, meta map[string]any) context.Context
- func (t *Transport) Start()
- func (t *Transport) TakeRaw(key string) json.RawMessage
- func (t *Transport) TakeRawPrompt(sessionID acp.SessionId, meta map[string]any) json.RawMessage
- func (t *Transport) Writer() io.Writer
- type TurnFailure
Constants ¶
const ( // AccountUsageNotAuthenticated means the harness reports no authenticated // account. AccountUsageNotAuthenticated = "not_authenticated" // AccountUsageNotReported means the harness reports no allowance window for // its current credential. AccountUsageNotReported = "not_reported" )
Reasons an account-usage read answers unavailable.
const ( CompactionInProgress = "in_progress" CompactionCompleted = "completed" CompactionFailed = "failed" CompactionCancelled = "cancelled" CompactionTriggerAuto = "auto" CompactionTriggerManual = "manual" )
const ( FieldError = "error" FieldField = "field" FieldCause = "cause" FieldMessage = "message" FieldClass = "class" FieldLimit = "limit" FieldRecovery = "recovery" )
Data member names shared by every uniform error.
const ( VerdictUnsupported = "unsupported" VerdictMissing = "missing" )
Invalid-params verdicts.
const ( RecoveryRecovered = "recovered" RecoveryFailed = "failed" )
Outcomes of the recovery a sibling runs after a turn failure so the next prompt can succeed.
const ( CauseProcessExit = "process_exit" CauseTransport = "transport" CauseProvider = "provider" )
Turn failure causes.
const ( TokenInvalidOptions = "invalid_options" TokenRestoreFailed = "restore_failed" TokenSessionPoisoned = "session_poisoned" TokenInternalFailure = "internal_failure" TokenTurnFailed = "turn_failed" )
Off-prompt -32603 token suffixes. A sibling prefixes each with its vendor key.
const ( MediaEnvelopeKey = "acp-go.dev/mediaEnvelope" HandoffKey = "acp-go.dev/handoff" LifecycleKey = lifecycle.MetaKey // CallUsageKey is the usage_update _meta member carrying the token // breakdown of the model call the update reports. CallUsageKey = "acp-go.dev/callUsage" // CompactionKey carries live compaction on session notification metadata. CompactionKey = "acp-go.dev/compaction" )
Family-global reserved literals.
const AccountUsageCapabilityKey = "accountUsage"
AccountUsageCapabilityKey is the _meta.<vendor> member advertising the account-usage read.
const AccountUsageReadTimeout = 30 * time.Second
AccountUsageReadTimeout bounds the native reads behind one account-usage request.
const CauseNativeSessionIdentityDrift = "native_session_identity_drift"
CauseNativeSessionIdentityDrift is the poison cause of an unexpected native session id change.
const ClassNativeStart = "native_start"
ClassNativeStart is the internal-failure class of a native process that failed to start.
const NativeLineMaxBytes = 64 << 20
NativeLineMaxBytes is the family bound on one LF-delimited record a native harness writes to its stdout. Records may carry base64 images and large tool output; a longer record breaks the stream.
const RawEventMaxBytes = 64 * 1024
RawEventMaxBytes bounds one raw-event notification payload.
const SessionIDMaxBytes = 4096
SessionIDMaxBytes bounds a session id on every session-addressed request. Siblings mint ids far below it; a longer id names no session and is refused before any lookup or retention.
const SessionMetaKey = "acp-go.dev/session"
SessionMetaKey is the host-owned _meta namespace a session/new carries.
Variables ¶
var ErrLineTooLong = errors.New("native record exceeds its line bound")
ErrLineTooLong reports a record longer than the reader's bound.
var ReservedLiterals = []string{MediaEnvelopeKey, HandoffKey, LifecycleKey, CallUsageKey, CompactionKey}
ReservedLiterals lists every family-global reserved literal.
Functions ¶
func AccountUsageAdvertisement ¶
func AccountUsageAdvertisement(method string, scope AccountUsageScope, providers ...string) map[string]any
AccountUsageAdvertisement is the _meta.<vendor>.accountUsage value a sibling that implements the read advertises at initialize.
func AccountUsageTime ¶
AccountUsageTime renders one instant in the response's fixed form. An instant outside years 0001 through 9999 has no such form and renders empty, so a caller omits the member.
func AcquireSessionGate ¶
AcquireSessionGate excludes prompts and restores while an operation owns the session. Its release function is safe to call more than once.
func AgentClosed ¶
func AgentClosed() *acp.RequestError
AgentClosed refuses a request that arrived after the agent stopped serving.
func AudienceIsUserOnly ¶
func AudienceIsUserOnly(annotations *acp.Annotations) bool
AudienceIsUserOnly reports whether a block's annotations address only the user, which keeps it out of the harness prompt.
func AuthenticateRefused ¶
func AuthenticateRefused(params acp.AuthenticateRequest) *acp.RequestError
AuthenticateRefused answers every authenticate request: the harness authenticates itself, outside ACP. A reserved lifecycle key in the request metadata is refused first.
func Backpressure ¶
func Backpressure(limit string) *acp.RequestError
Backpressure refuses admission at a concurrency limit.
func CallAndAnnounce ¶
func CallAndAnnounce[T any](ctx context.Context, transport *Transport, meta map[string]any, send func(context.Context, map[string]any) (T, error), announce func()) (T, error)
CallAndAnnounce sends an action-correlated request and announces it only after its complete frame is written. Incarnation ids MUST be unique on the connection. A request that fails before writing has no announcement. With no transport, an embedded client owns request registration and ordering.
func CancelRequest ¶
func CancelRequest(sessionID acp.SessionId) acp.CancelNotification
CancelRequest constructs a session/cancel notification.
func CancelledResponse ¶
func CancelledResponse(params acp.PromptRequest) acp.PromptResponse
CancelledResponse answers a prompt whose turn ended by cancellation.
func CheckReservedMeta ¶
CheckReservedMeta refuses a host-supplied _meta map carrying any reserved literal. Family builders call it before merging caller metadata into a request.
func CheckSessionID ¶
func CheckSessionID(id acp.SessionId) *acp.RequestError
CheckSessionID refuses an id past SessionIDMaxBytes as an unknown session.
func CloneValue ¶
CloneValue copies mutable JSON values and typed string maps and slices.
func CompactionCarrier ¶
func CompactionCarrier(sessionID acp.SessionId, value Compaction) acp.SessionNotification
CompactionCarrier carries compaction without changing session info or usage.
func ContextResourceText ¶
ContextResourceText renders an embedded text resource as the context envelope a harness receives inside the prompt text.
func DeleteSessionRequest ¶
func DeleteSessionRequest(sessionID acp.SessionId) acp.UnstableDeleteSessionRequest
DeleteSessionRequest constructs a session/delete request.
func HoldSessionGate ¶
func HoldSessionGate(gate chan struct{}) func()
HoldSessionGate takes an unpublished session's foreground gate, which must be free. Its release function is safe to call more than once.
func InternalFailure ¶
func InternalFailure(vendor, class string) *acp.RequestError
InternalFailure reports a failure the sibling cannot classify. class is an optional closed token the sibling documents.
func InvalidOptions ¶
func InvalidOptions(vendor, field string) *acp.RequestError
InvalidOptions reports a construction verdict. field names the refused option when the sibling refuses one at a time and is empty otherwise.
func LifecycleCarrier ¶
LifecycleCarrier builds the notification one lifecycle envelope rides: an identity-only session_info_update with the envelope on its _meta.
func ListSessionsRequest ¶
func ListSessionsRequest(opts ...ListSessionsRequestOption) acp.ListSessionsRequest
ListSessionsRequest constructs a session/list request.
func LoadSessionRequest ¶
func LoadSessionRequest(sessionID acp.SessionId, cwd string, opts ...SessionRequestOption) acp.LoadSessionRequest
LoadSessionRequest constructs a session/load request.
func MetaOptionPath ¶
MetaOptionPath names a vendor option member for a refusal, or the options object itself when key is empty.
func Missing ¶
func Missing(field string) *acp.RequestError
Missing refuses a request that omitted a value the contract requires.
func ModelSelectOptions ¶
func ModelSelectOptions(vendor, current string, native []ModelRow, configured []string) acp.SessionConfigSelectOptionsUngrouped
ModelSelectOptions builds the model menu: native rows first, then each configured id the rows lack, then the current model when nothing else names it. Duplicates and empty ids are dropped; a native row publishes modelId with its metadata, a configured or current entry publishes the id alone.
func NativeSessionMeta ¶
NativeSessionMeta names the native conversation backing an ACP session.
func NewSessionRequest ¶
func NewSessionRequest(cwd string, opts ...SessionRequestOption) acp.NewSessionRequest
NewSessionRequest constructs a session/new request. It always carries an empty mcpServers array: MCP is not supported.
func NormalizeTitle ¶
NormalizeTitle collapses whitespace and bounds the title to sessionTitleMaxRunes runes, ending a truncated title with an ellipsis.
func PaginateSessions ¶
func PaginateSessions(sessions []acp.SessionInfo, cursor *string) ([]acp.SessionInfo, *string, error)
PaginateSessions orders sessions newest first, then by id, and returns the page selected by a raw URL-base64 offset cursor.
func ParamRefusal ¶
func ParamRefusal(err *lifecycle.ParamError) *acp.RequestError
ParamRefusal maps a lifecycle negotiation or correlation refusal to the uniform invalid-params shape.
func PromptRequest ¶
func PromptRequest(sessionID acp.SessionId, blocks ...acp.ContentBlock) acp.PromptRequest
PromptRequest constructs a session/prompt request.
func PromptTitle ¶
func PromptTitle(prompt []acp.ContentBlock) string
PromptTitle derives the session title from the first text block that normalizes to a non-empty string.
func RefuseSessionMeta ¶
func RefuseSessionMeta(meta map[string]any) *acp.RequestError
RefuseSessionMeta refuses the namespace on a session/load or session/resume: those name a session the store holds, which an ephemeral session never is, so the host has nothing to state there.
func RestoreFailed ¶
func RestoreFailed(vendor string) *acp.RequestError
RestoreFailed reports a store entry that could not be restored.
func RestoreRefused ¶
func RestoreRefused(ctx context.Context, logger *slog.Logger, vendor string, sessionID acp.SessionId, err error) *acp.RequestError
RestoreRefused logs why the stored session sessionID could not be restored and returns the uniform restore failure; the reason stays in the log.
func ResumeSessionRequest ¶
func ResumeSessionRequest(sessionID acp.SessionId, cwd string, opts ...SessionRequestOption) acp.ResumeSessionRequest
ResumeSessionRequest constructs a session/resume request.
func RuntimeUnavailable ¶
func RuntimeUnavailable(vendor string) *acp.RequestError
RuntimeUnavailable reports a shared runtime that is gone and could not be replaced.
func SeedFileRefusal ¶
func SeedFileRefusal(err error) *acp.RequestError
SeedFileRefusal maps an invalid seed file to the uniform refusal naming seedFiles. Any other error yields nil so the caller classifies it.
func SelectPositionEncoding ¶
func SelectPositionEncoding(encodings []acp.PositionEncodingKind) acp.PositionEncodingKind
SelectPositionEncoding picks UTF-8 when the client offers it and UTF-16 otherwise.
func SessionPoisoned ¶
func SessionPoisoned(vendor, cause string) *acp.RequestError
SessionPoisoned reports a session that refuses every operation but close and delete. cause is a closed token the sibling documents.
func SetConfigOptionRequest ¶
func SetConfigOptionRequest( sessionID acp.SessionId, configID acp.SessionConfigId, value acp.SessionConfigValueId, ) acp.SetSessionConfigOptionRequest
SetConfigOptionRequest constructs a value-id session/set_config_option request.
func StringMapOption ¶
StringMapOption validates a string map and copies it at the request boundary.
func StringSliceOption ¶
func StringSliceOption(value any, path string) ([]string, *acp.RequestError)
StringSliceOption validates and copies an ordered string list.
func StructuredOutputAdvertisement ¶
StructuredOutputAdvertisement is the _meta.<vendor>.structuredOutput capability: where the schema is configured, where the parsed answer rides on the prompt response, and the schema dialect.
func TextPromptRequest ¶
func TextPromptRequest(sessionID acp.SessionId, text string) acp.PromptRequest
TextPromptRequest constructs a session/prompt request with one text block.
func TurnFailed ¶
func TurnFailed(vendor string, failure TurnFailure) *acp.RequestError
TurnFailed renders the <vendor>_turn_failed error. Message carries the real native cause as bounded valid UTF-8; process exits retain the full stderr tail.
func UnknownSession ¶
func UnknownSession() *acp.RequestError
UnknownSession answers a session-scoped request that found no eligible session.
func Unsupported ¶
func Unsupported(field string) *acp.RequestError
Unsupported refuses a value that is present and refused, naming its path.
func ValidCommandName ¶
ValidCommandName is the one sanitizer for advertised slash-command names. It rejects an empty name, a name containing a slash, invalid UTF-8, and any Unicode whitespace, control, or format rune.
func ValidateConcurrencyLimits ¶
ValidateConcurrencyLimits refuses negative session and client-call bounds.
func ValidateConfiguredModels ¶
ValidateConfiguredModels refuses a host-listed model id that is empty, has surrounding whitespace, or is listed twice.
func ValidateSessionEnvironment ¶
func ValidateSessionEnvironment(env map[string]string, dirs []string, path string) *acp.RequestError
ValidateSessionEnvironment maps environment and PATH validation to owned fields.
Types ¶
type AccountUsageBalance ¶
type AccountUsageBalance struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
ObservedAt string `json:"observedAt"`
Used *AccountUsageMoney `json:"used,omitempty"`
Limit *AccountUsageMoney `json:"limit,omitempty"`
Remaining *AccountUsageMoney `json:"remaining,omitempty"`
Uncapped bool `json:"uncapped,omitempty"`
ResetInterval string `json:"resetInterval,omitempty"`
ResetsAt string `json:"resetsAt,omitempty"`
}
AccountUsageBalance reports one spending cap or account credit balance. Uncapped explicitly describes a key without a spending cap; an account credit balance has neither Uncapped nor Limit. Remaining may be negative.
type AccountUsageLimit ¶
type AccountUsageLimit struct {
// ObservedAt is when the harness supplied this window.
ObservedAt string `json:"observedAt"`
// ID is unique within one response and stable across reads of the same
// account.
ID string `json:"id"`
// Label is the harness's human name for the window, when it has one.
Label string `json:"label,omitempty"`
// WindowSeconds is the window length; zero means the harness did not say.
WindowSeconds int64 `json:"windowSeconds,omitempty"`
// UsedPercent is the harness's own utilization figure and may exceed 100.
UsedPercent float64 `json:"usedPercent"`
// UsageAllowed is the provider's explicit status for this window, when reported.
UsageAllowed *bool `json:"usageAllowed,omitempty"`
// ResetsAt is an RFC 3339 UTC instant with whole seconds, when known.
ResetsAt string `json:"resetsAt,omitempty"`
}
AccountUsageLimit is one allowance window as the harness reports it.
type AccountUsageMoney ¶
AccountUsageMoney is an observed amount in major units of its uppercase currency.
type AccountUsageRequest ¶
type AccountUsageRequest struct {
// SessionID is empty only on an agent-scoped read that named no session.
SessionID acp.SessionId
// ProviderID selects a provider advertised by a provider-aware reader.
ProviderID string
// Meta is the request's _meta as sent; the sibling opens its span with it
// so the host's trace keys propagate as on every request.
Meta map[string]any
}
AccountUsageRequest is one decoded _<vendor>/accountUsage request.
func DecodeAccountUsageRequest ¶
func DecodeAccountUsageRequest(params json.RawMessage, scope AccountUsageScope) (AccountUsageRequest, *acp.RequestError)
DecodeAccountUsageRequest reads the params of one account-usage request. The only members are sessionId, providerId, and _meta; anything else, and any repeated member, is refused naming the member. Only the agent scope accepts a request without sessionId; every other scope value, including an unset one, requires it. _meta is decoded first, so every refusal after it returns the decoded Meta beside the error and the sibling still opens its span with the host's trace keys.
type AccountUsageRequestLimit ¶
type AccountUsageRequestLimit struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
ObservedAt string `json:"observedAt"`
Used int64 `json:"used"`
Limit int64 `json:"limit"`
Remaining int64 `json:"remaining"`
ResetInterval string `json:"resetInterval,omitempty"`
ResetsAt string `json:"resetsAt,omitempty"`
}
AccountUsageRequestLimit reports the provider's count and ceiling for a request class.
type AccountUsageResponse ¶
type AccountUsageResponse struct {
Available bool `json:"available"`
// Reason is present only when Available is false.
Reason string `json:"reason,omitempty"`
// Plan is the harness's plan or subscription name, when it reports one.
Plan string `json:"plan,omitempty"`
// UsageAllowed is the harness's own statement of whether the account may
// run ordinary inference now; nil when it makes none. It is never derived
// from the windows.
UsageAllowed *bool `json:"usageAllowed,omitempty"`
// Limits contains observed percentage windows.
Limits []AccountUsageLimit `json:"limits,omitempty"`
// Balances distinguish spending caps from account credit balances.
Balances []AccountUsageBalance `json:"balances,omitempty"`
// RequestLimits are provider-reported request counters and ceilings.
RequestLimits []AccountUsageRequestLimit `json:"requestLimits,omitempty"`
}
AccountUsageResponse is one _<vendor>/accountUsage result.
func AccountUsageUnavailable ¶
func AccountUsageUnavailable(reason string) AccountUsageResponse
AccountUsageUnavailable answers a read that completed with nothing to report.
func (AccountUsageResponse) Validate ¶
func (r AccountUsageResponse) Validate() error
Validate reports the first way the response departs from the contract shape.
type AccountUsageScope ¶
type AccountUsageScope string
AccountUsageScope names what a sibling's account-usage read is bound to.
const ( // AccountUsageScopeSession reads through a loaded session's native process. AccountUsageScopeSession AccountUsageScope = "session" // AccountUsageScopeAgent reads through the shared native runtime. AccountUsageScopeAgent AccountUsageScope = "agent" )
The two account-usage scopes.
type CallUsage ¶
type CallUsage struct {
// ResponseID is the id the model gateway returned for the call's response,
// empty when the harness does not expose it.
ResponseID string `json:"responseId,omitempty"`
// InputTokens is the input the call sent that was neither read from nor
// written to a prompt cache.
InputTokens *int `json:"inputTokens,omitempty"`
// CachedReadTokens is the input the call read from a prompt cache.
CachedReadTokens *int `json:"cachedReadTokens,omitempty"`
// CachedWriteTokens is the input the call wrote to a prompt cache.
CachedWriteTokens *int `json:"cachedWriteTokens,omitempty"`
// OutputTokens is what the call generated, reasoning included.
OutputTokens *int `json:"outputTokens,omitempty"`
}
CallUsage is one model call's token breakdown as the harness reported it. A nil member is a figure the harness did not report for the call.
func (CallUsage) Apply ¶
Apply writes the member onto a usage_update's meta, allocating it when nil, and returns the map. A breakdown that is not Known writes nothing.
type Compaction ¶
type Compaction struct {
CompactionID string `json:"compactionId"`
Status string `json:"status"`
Trigger string `json:"trigger,omitempty"`
ContextBefore *int `json:"contextBefore,omitempty"`
ContextAfter *int `json:"contextAfter,omitempty"`
}
Compaction describes one top-level context compaction attempt.
type Compactions ¶
type Compactions struct {
// contains filtered or unexported fields
}
Compactions correlates native attempt keys and publishes each transition once. Its zero value is ready to use. Callers supply events in native order and keep keys distinct across native runs. Empty keys represent uncorrelated outcomes.
func (*Compactions) Publish ¶
func (c *Compactions) Publish(ctx context.Context, client interface { SessionUpdate(context.Context, acp.SessionNotification) error }, sessionID acp.SessionId, key string, value Compaction) error
Publish assigns an opaque ID and retains reported facts across transitions. Publication does not inherit request cancellation. Failed delivery is not retried.
type LineReader ¶
type LineReader struct {
// contains filtered or unexported fields
}
LineReader reads LF-delimited records from a native stream. LF is the only delimiter, so U+2028 and U+2029 inside JSON strings never split a record, and one trailing CR is removed. Its read buffer is fixed: each record is a fresh allocation the caller owns, so an oversized record never leaves a grown buffer behind.
func NewLineReader ¶
func NewLineReader(r io.Reader, maxBytes int) *LineReader
NewLineReader reads records of at most maxBytes from r; a non-positive maxBytes means NativeLineMaxBytes.
func (*LineReader) Next ¶
func (l *LineReader) Next() ([]byte, error)
Next returns the next record without its delimiter. It returns io.EOF at a record boundary, io.ErrUnexpectedEOF for an unterminated final record, and ErrLineTooLong for a record past the bound; both end the stream.
type ListSessionsRequestOption ¶
type ListSessionsRequestOption func(*acp.ListSessionsRequest)
ListSessionsRequestOption configures an embedded-Go session/list request.
func WithListSessionsCursor ¶
func WithListSessionsCursor(cursor string) ListSessionsRequestOption
WithListSessionsCursor sets the pagination cursor.
func WithListSessionsCwd ¶
func WithListSessionsCwd(cwd string) ListSessionsRequestOption
WithListSessionsCwd filters session/list by cwd.
func WithListSessionsMeta ¶
func WithListSessionsMeta(meta map[string]any) ListSessionsRequestOption
WithListSessionsMeta sets host metadata on a session/list request, refusing reserved literals like WithSessionMeta.
type ModelRow ¶
type ModelRow struct {
// ID is the invokable model id and the select value.
ID string
// Name is the display name; empty falls back to ID.
Name string
// Description is attached when non-empty.
Description string
// Meta holds the authoritative model metadata published under
// _meta.<vendor> beside modelId; nil carries none.
Meta map[string]any
}
ModelRow is one model the harness enumerated for itself.
type RawEvents ¶
type RawEvents struct {
// contains filtered or unexported fields
}
RawEvents emits one session's raw events with a per-session sequence that starts at 1 and advances only on successful delivery.
func NewRawEvents ¶
NewRawEvents builds the emitter for one session.
type SessionMeta ¶
type SessionMeta struct {
// Ephemeral marks a session the host deletes without ever needing it back.
// The sibling never writes it to the store and never lists it.
Ephemeral bool
}
SessionMeta is what a host states about a session it opens.
func DecodeSessionMeta ¶
func DecodeSessionMeta(meta map[string]any) (SessionMeta, *acp.RequestError)
DecodeSessionMeta reads the host-owned namespace from a session/new _meta. An absent namespace is the zero value; a namespace that is not an object, a field it does not define, or a non-boolean ephemeral is unsupported, naming its path.
type SessionRequestConfig ¶
SessionRequestConfig accumulates the members a session lifecycle request builder sets. A sibling's vendor option constructors merge into Meta.
type SessionRequestOption ¶
type SessionRequestOption func(*SessionRequestConfig)
SessionRequestOption configures an embedded-Go session lifecycle request.
func WithSessionAdditionalDirectories ¶
func WithSessionAdditionalDirectories(paths ...string) SessionRequestOption
WithSessionAdditionalDirectories sets additional workspace directories.
func WithSessionMeta ¶
func WithSessionMeta(meta map[string]any) SessionRequestOption
WithSessionMeta merges host metadata into a session lifecycle request. A key matching a family-reserved literal panics rather than merging: those namespaces are stamped by the sibling alone.
func WithSessionMetaValue ¶
func WithSessionMetaValue(meta map[string]any) SessionRequestOption
WithSessionMetaValue merges one already-validated vendor metadata object. Sibling option constructors use it to add their own namespace.
type SessionRequests ¶
type SessionRequests struct {
// contains filtered or unexported fields
}
SessionRequests reserves session identities while an establishing request is in flight. Its zero value is ready to use.
func (*SessionRequests) Acquire ¶
func (r *SessionRequests) Acquire(id acp.SessionId) (func(), error)
Acquire refuses a concurrent restore of the same session before either request can hydrate or bind its native state. The caller releases the reservation after publication has been arranged or the request has failed.
type StreamedText ¶
type StreamedText struct {
// contains filtered or unexported fields
}
StreamedText accumulates, per native item, the assistant text a turn has streamed, so a terminal full-message frame emits only the suffix its deltas did not carry. Text grows in a strings.Builder, so a long stream costs linear copying. The zero value is ready; it is not safe for concurrent use.
func (*StreamedText) Add ¶
func (s *StreamedText) Add(key, delta string)
Add records a delta streamed for key.
func (*StreamedText) Forget ¶
func (s *StreamedText) Forget(key string)
Forget releases key's text once its item is complete.
func (*StreamedText) Suffix ¶
func (s *StreamedText) Suffix(key, final string) string
Suffix returns the part of final not yet streamed for key and records it as streamed. A final text that does not extend what was streamed yields nothing, so assistant text stays append-only.
func (*StreamedText) Text ¶
func (s *StreamedText) Text(key string) string
Text returns everything streamed for key.
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
Transport wraps the JSON-RPC streams Serve hands to the SDK. It reads every inbound frame to keep the raw params the lifecycle strictness needs and the request ids the establishing responses answer, and it watches every outbound frame so a session's opening publication runs only after its establishing response is on the wire and an action announcement only after its request.
func NewTransport ¶
NewTransport prepares streams that remain unread until Start.
func (*Transport) AwaitSession ¶
AwaitSession waits until the establishing response and opening publications have been written, before admitting work that can produce session events.
func (*Transport) Close ¶
func (t *Transport) Close()
Close ends the connection's opening publications and releases every waiter.
func (*Transport) RegisterHook ¶
func (t *Transport) RegisterHook(ctx context.Context, sessionID acp.SessionId, hook func(context.Context)) error
RegisterHook schedules a publication after this handler's establishing response is written. RequestContext supplies the identity. Successive publications for one session wait for their predecessors to finish.
func (*Transport) RequestContext ¶
RequestContext removes the transport's private establishing-request marker from decoded metadata and binds its response identity to the handler context. Establishing handlers MUST call it before inspecting or forwarding metadata.
func (*Transport) Start ¶
func (t *Transport) Start()
Start releases inbound reads after the SDK connection and its handler are configured.
func (*Transport) TakeRaw ¶
func (t *Transport) TakeRaw(key string) json.RawMessage
TakeRaw returns the oldest raw params recorded under key.
func (*Transport) TakeRawPrompt ¶
TakeRawPrompt returns the recorded raw params of the prompt whose decoded lifecycle value equals meta's, so concurrent prompts on one session cannot swap correlations.
type TurnFailure ¶
type TurnFailure struct {
Cause string
Message string
StatusCode int
ProviderCode string
// Recovery is RecoveryRecovered or RecoveryFailed when the sibling ran a
// recovery after the failure, and empty otherwise.
Recovery string
// Stage, Reason, SizeBytes, and MaxBytes appear only on image output
// failures.
Stage string
Reason string
SizeBytes int64
MaxBytes int64
}
TurnFailure describes a native turn that ended without a stop reason.
func TransportFailure ¶
func TransportFailure(ctx context.Context, proc *process.Process, name string, err error, streamErr func() error) TurnFailure
TransportFailure waits briefly for a process exit, then reports its status and stderr tail or the native transport's error. streamErr is read after the wait so a read loop can finish recording its cause.