Documentation
¶
Overview ¶
Package llm defines the public, dialect-neutral contracts used by HumanLLM.
The package deliberately owns its canonical message and event types. A custom codec can therefore implement the public ports without importing an internal package or depending on a built-in OpenAI/Anthropic dialect.
Index ¶
- Constants
- Variables
- func CallerTransportRequirements() framework.Requirements
- func QualifiedToolName(namespace, name string) string
- func RequiredCodecContract() framework.Requirements
- func StoreRequirements() framework.Requirements
- func ValidateToolIdentity(namespace, name string) error
- func WorkerTransportRequirements() framework.Requirements
- type AdmissionContext
- type AdmissionError
- type AdmissionFailure
- type AdmissionPolicy
- type AdmissionPolicyDecision
- type AdmissionPolicyFunc
- type AdmissionRequest
- type AdmissionResult
- type Assignment
- type AssignmentBoundary
- type AuthenticatedWorker
- type Block
- type BlockType
- type CallerEndpoint
- type CallerID
- type CallerTransport
- type CallerTransportDescription
- type CallerTransportRuntime
- type CapabilityTier
- type Clock
- type ClockFunc
- type Codec
- type CodecDescription
- type CodecFingerprint
- type CodecID
- type CodecLimits
- type CodecRegistration
- type CodecSnapshot
- type CompletionIdentity
- type Config
- type Encoder
- type EncoderSession
- type Event
- type EventSeed
- type EventSeedContext
- type EventType
- type ExpiryPolicy
- type ExpiryResult
- type HostedCapability
- type IDKind
- type IDSource
- type IDSourceFunc
- type IdempotencyKey
- type Message
- type OpaqueInput
- type ProtectionReadPolicy
- type Request
- type ResponseDecision
- type ResponseMode
- type ResponsePage
- type ResponseQuery
- type RetentionPolicy
- type RetentionResult
- type Role
- type SeedContext
- type SeedSource
- type Service
- func (service *Service) Admit(ctx context.Context, input AdmissionRequest) (AdmissionResult, error)
- func (service *Service) DetachCaller(ctx context.Context, identity CompletionIdentity)
- func (service *Service) Done() <-chan struct{}
- func (service *Service) Err() error
- func (service *Service) OpenWorker(ctx context.Context, principal AuthenticatedWorker) (WorkerConnection, error)
- func (service *Service) ReadResponse(ctx context.Context, query ResponseQuery) (ResponsePage, error)
- func (service *Service) RunExpiry(ctx context.Context, policy ExpiryPolicy) (ExpiryResult, error)
- func (service *Service) RunRetention(ctx context.Context, policy RetentionPolicy) (RetentionResult, error)
- func (service *Service) Shutdown(ctx context.Context) error
- func (service *Service) Status(ctx context.Context) (ServiceStatus, error)
- func (service *Service) WaitResponse(ctx context.Context, query ResponseQuery) (ResponsePage, error)
- type ServiceStatus
- type SessionSeed
- type Store
- type StoreBinding
- type StoreCommitUnknownError
- type StoreConflictError
- type StoreConstraint
- type StoreCorruptError
- type StoreDescription
- type StoreDigest
- type StoreLimitError
- type StoreNotFoundError
- type StoreReadLimit
- type StoreRecordKind
- type StoreRecoveryCursor
- type StoreRecoveryRecord
- type StoreRecoveryScan
- type StoreRequestHead
- type StoreRequestKey
- type StoreRequestMutation
- type StoreRequestRecord
- type StoreResponseDecision
- type StoreResponseEventKind
- type StoreResponseEventRecord
- type StoreResponseEventScan
- type StoreRetentionCandidate
- type StoreRetentionCursor
- type StoreRetentionScan
- type StoreTaskAffinity
- type StoreTaskKey
- type StoreTaskMutation
- type StoreTaskRecord
- type StoreToolExecutionKey
- type StoreToolExecutionMutation
- type StoreToolExecutionRecord
- type StoreToolExecutionScan
- type StoreTx
- type StoreView
- type StoreWorkerReceiptRecord
- type TaskContext
- type TaskID
- type TaskState
- type Tool
- type ToolAuthorization
- type ToolAuthorizer
- type ToolAuthorizerFunc
- type ToolCall
- type ToolCallID
- type ToolCallPolicy
- type ToolExecutionState
- type ToolInputKind
- type WireEvent
- type WorkerAssignmentDelivery
- type WorkerConnection
- type WorkerConnectionError
- type WorkerDeliveryError
- type WorkerDeliveryID
- type WorkerEndpoint
- type WorkerEventDecision
- type WorkerEventDelivery
- type WorkerEventReceipt
- type WorkerID
- type WorkerLease
- type WorkerLeaseID
- type WorkerNotice
- type WorkerNoticer
- type WorkerRejectionCode
- type WorkerRouteRequest
- type WorkerRouter
- type WorkerRouterFunc
- type WorkerSessionID
- type WorkerTransport
- type WorkerTransportDescription
- type WorkerTransportRuntime
Constants ¶
const ( // CallerTransportContractID names the authenticated HumanLLM caller-side // transport contract. It describes admission and exact response replay, not a // particular wire protocol such as HTTP, gRPC, or a message queue. CallerTransportContractID framework.ContractID = "human.llm.caller.transport" // CallerTransportContractMajor includes authenticated caller identity, // durable admission, cursor-based exact replay, and disconnect-independent // completion lifetime. CallerTransportContractMajor uint16 = 1 )
const ( // CodecContractID is the public protocol implemented by HumanLLM codecs. CodecContractID framework.ContractID = "human.llm.codec" // CodecContractMajor is the exact base contract third-party codecs declare. CodecContractMajor uint16 = 1 )
const ( // WorkerTransportContractID names the authenticated HumanLLM worker // transport contract. It describes completion delivery and settlement // semantics, not a particular wire protocol. WorkerTransportContractID framework.ContractID = "human.llm.worker.transport" // WorkerTransportContractMajor includes exact assignment redelivery, // commit-before-ACK, deterministic NACK, and explicit connection lifetime. WorkerTransportContractMajor uint16 = 1 )
const StoreContractID framework.ContractID = "human.llm.store"
StoreContractID names the semantic persistence contract implemented by a HumanLLM Store. It is independent of a database product, physical schema, serialization format, or deployment topology.
const StoreContractMajor uint16 = 1
StoreContractMajor changes when an implementation must change its atomicity, ordering, snapshot, recovery, or byte-ownership behavior to remain correct.
Variables ¶
var ( // ErrCallerTransportContractMismatch aliases the framework-wide construction // error so composition roots can classify incompatible adapters uniformly. ErrCallerTransportContractMismatch = framework.ErrContractMismatch ErrCallerTransportDescription = errors.New("llm: invalid caller transport description") )
var ( ErrInvalidServiceConfig = errors.New("llm: invalid service configuration") ErrServiceClosed = errors.New("llm: service is closed") ErrIdempotencyConflict = errors.New("llm: idempotency key conflicts with another request") ErrReplayExpired = errors.New("llm: exact replay payload has expired") ErrTaskConflict = errors.New("llm: task state conflicts with the request") ErrWorkerRouteDenied = errors.New("llm: worker routing was denied") // ErrWorkerRouterRequired is a deployment configuration error, not a // temporary capacity condition: more than one worker is connected and no // WorkerRouter was configured to make the selection explicit. ErrWorkerRouterRequired = errors.New("llm: multiple workers are connected and no WorkerRouter is configured") ErrResponseNotFound = errors.New("llm: response is not found") ErrResponseDigest = errors.New("llm: response digest does not match") )
var ( // ErrStoreContractMismatch aliases the framework construction error for // callers that classify failures at the HumanLLM Store boundary. ErrStoreContractMismatch = framework.ErrContractMismatch // ErrStoreDescription means a Store returned missing, malformed, or unsafe // static metadata. Descriptions must never disclose a DSN or credential. ErrStoreDescription = errors.New("llm: invalid store description") // ErrStoreRecordNotFound reports that one logical record is absent from the // transaction snapshot. ErrStoreRecordNotFound = errors.New("llm: store record not found") // ErrStoreConflict reports a logical uniqueness, immutability, or // compare-and-swap conflict. StoreConflictError identifies the rule. ErrStoreConflict = errors.New("llm: store conflict") // ErrStoreCommitUnknown is the only valid result when a Store cannot prove // whether an Update committed. HumanLLM must reconcile durable request or // worker-event identity before retrying any effects. ErrStoreCommitUnknown = errors.New("llm: store commit outcome is unknown") // ErrStoreClosed means the resource behind Store no longer accepts work. // Store itself deliberately has no lifecycle method. ErrStoreClosed = errors.New("llm: store is closed") // ErrStoreRecordTooLarge means a bounded materialization was refused. ErrStoreRecordTooLarge = errors.New("llm: store record exceeds read budget") // ErrStoreInvalidArgument means a Store primitive received a malformed key, // cursor, limit, mutation, or nil callback. It is part of the portable port // contract so custom adapters do not need to expose driver-specific argument // errors. ErrStoreInvalidArgument = errors.New("llm: invalid store argument") // ErrStoreCorruptRecord means physical data could not be represented as the // typed logical record promised by this contract. It is distinct from an // invalid canonical payload, which HumanLLM core detects and quarantines. ErrStoreCorruptRecord = errors.New("llm: corrupt store record") )
var ( // ErrWorkerTransportContractMismatch aliases the framework-wide // construction error so callers can classify incompatible adapters without // parsing a HumanLLM-specific message. ErrWorkerTransportContractMismatch = framework.ErrContractMismatch ErrWorkerTransportDescription = errors.New("llm: invalid worker transport description") ErrWorkerPrincipal = errors.New("llm: invalid authenticated worker principal") ErrWorkerDelivery = errors.New("llm: invalid worker delivery") // Runtime errors below settle neither an assignment nor an event. In // particular, a durable worker outbox must retain an event whenever // CommitEvent returns an error instead of a valid ACK or NACK receipt. ErrWorkerTransportClosed = errors.New("llm: worker transport is closed") ErrWorkerConnectionClosed = errors.New("llm: worker connection is closed") ErrWorkerConnectionConflict = errors.New("llm: worker connection conflicts with an active session") ErrWorkerBackpressure = errors.New("llm: worker transport is backpressured") ErrWorkerDeliveryNotFound = errors.New("llm: worker delivery is not known to this connection") ErrWorkerDeliveryConflict = errors.New("llm: worker delivery identity was reused with different content") ErrWorkerDeliveryIndeterminate = errors.New("llm: worker delivery commit outcome is indeterminate") )
var ErrInvalidCodecContract = errors.New("llm: invalid codec contract")
ErrInvalidCodecContract means a codec descriptor or encoder output violates the public Codec contract.
Functions ¶
func CallerTransportRequirements ¶
func CallerTransportRequirements() framework.Requirements
CallerTransportRequirements returns a fresh copy of the contract required by the HumanLLM core.
func QualifiedToolName ¶
QualifiedToolName returns the reversible human-facing spelling of a tool.
func RequiredCodecContract ¶
func RequiredCodecContract() framework.Requirements
RequiredCodecContract returns a fresh copy of HumanLLM's base requirements. Exact replay, explicit deterministic seeds, and both encoder modes are base major-version semantics rather than optional features.
func StoreRequirements ¶
func StoreRequirements() framework.Requirements
StoreRequirements returns HumanLLM core's immutable base requirements. Strict serializability, atomic receipts, stable snapshots, bounded scans, exact byte preservation, and durable restart visibility are major-contract semantics, not optional features.
func ValidateToolIdentity ¶
ValidateToolIdentity ensures QualifiedToolName remains reversible without imposing a provider-specific character set.
func WorkerTransportRequirements ¶
func WorkerTransportRequirements() framework.Requirements
WorkerTransportRequirements returns a fresh copy of the HumanLLM worker transport contract required by the core.
Types ¶
type AdmissionContext ¶
type AdmissionContext struct {
CallerID CallerID
IdempotencyKey IdempotencyKey
Codec CodecDescription
Request Request
Task TaskContext
// CallerAttributes is an independent top-level copy per policy call; the
// attribute values themselves are borrowed and must not be mutated.
CallerAttributes map[string]any
}
type AdmissionError ¶
type AdmissionError struct {
Failure AdmissionFailure
ContentType string
RetryAfter string
Body []byte
Cause error
}
AdmissionError is safe for a caller transport to project directly. Cause is retained for local classification but must not be exposed by an adapter.
func (*AdmissionError) Error ¶
func (failure *AdmissionError) Error() string
func (*AdmissionError) Unwrap ¶
func (failure *AdmissionError) Unwrap() error
type AdmissionFailure ¶
AdmissionFailure is a safe, already-classified pre-response failure. Message may be exposed to the caller; a codec must not inspect or reveal an underlying implementation error through AdmissionError.
func (AdmissionFailure) Validate ¶
func (failure AdmissionFailure) Validate() error
Validate checks the transport-neutral admission error input.
type AdmissionPolicy ¶
type AdmissionPolicy interface {
Admit(context.Context, AdmissionContext) (AdmissionPolicyDecision, error)
}
AdmissionPolicy runs before durable admission and assignment. Input is borrowed for the call; implementations must not retain or mutate its maps, slices, or RawMessage values. Implementations must be concurrency-safe and honor cancellation; any error fails admission without durable effects.
Admission is a required deployment choice: NewService rejects a nil policy instead of silently allowing every request. AdmitAll is the explicit, auditable allow-everything policy for deployments where transport authentication is the only gate.
func AdmitAll ¶
func AdmitAll() AdmissionPolicy
AdmitAll returns the explicit allow-everything AdmissionPolicy. It admits every structurally valid, authenticated request; use it only when transport authentication and the ToolAuthorizer are the deployment's real gates.
type AdmissionPolicyDecision ¶
type AdmissionPolicyDecision struct {
Allowed bool
Failure AdmissionFailure
RetryAfter time.Duration
}
type AdmissionPolicyFunc ¶
type AdmissionPolicyFunc func(context.Context, AdmissionContext) (AdmissionPolicyDecision, error)
func (AdmissionPolicyFunc) Admit ¶
func (policy AdmissionPolicyFunc) Admit(ctx context.Context, input AdmissionContext) (AdmissionPolicyDecision, error)
type AdmissionRequest ¶
type AdmissionRequest struct {
CallerID CallerID
IdempotencyKey IdempotencyKey
CodecID CodecID
Body []byte
Task TaskContext
CallerAttributes map[string]any
}
AdmissionRequest is the transport-neutral caller boundary. CallerID must come from authentication; Body is borrowed only for Admit's duration.
CallerAttributes carries advisory claims of the authenticated principal (organization, roles, entitlements) for AdmissionPolicy and WorkerRouter. They never enter correctness identity: the request digest, idempotency comparison, persistence records, and worker assignments ignore them, so an exact retry may carry different attributes and still replay byte-for-byte. The map is borrowed only for Admit's duration; the core copies the top-level map before each policy call and never retains the values.
type AdmissionResult ¶
type AdmissionResult struct {
Identity CompletionIdentity
RequestDigest StoreDigest
Replay bool
Response ResponsePage
}
type Assignment ¶
type Assignment struct {
Identity CompletionIdentity `json:"identity"`
Lease WorkerLease `json:"lease"`
Boundary AssignmentBoundary `json:"boundary"`
// Task is authenticated logical workspace/capability context. It carries no
// caller filesystem coordinates.
Task TaskContext `json:"task"`
Request Request `json:"request"`
}
Assignment is a codec-neutral, response-oriented unit of Human work. It is not a HumanAgent Task claim: a terminal Event ends this response, while a later tool-result continuation is a new RequestID/IdempotencyKey that may retain the same TaskID and WorkspaceKey.
func (Assignment) ValidateFor ¶
func (assignment Assignment) ValidateFor(principal AuthenticatedWorker) error
ValidateFor verifies canonical request ownership and the admission/response gate. Streaming work cannot become visible at the weaker admission-only boundary; aggregate work cannot claim that its still-undecided terminal HTTP response was already committed.
type AssignmentBoundary ¶
type AssignmentBoundary string
AssignmentBoundary records which caller-visible durability boundary the core crossed before making an assignment observable to a transport.
const ( // AssignmentAfterAdmission is used for aggregate/non-streaming requests: the // request and response mode are durable, but the one HTTP decision is not // committed until a terminal worker event. AssignmentAfterAdmission AssignmentBoundary = "admission_committed" // AssignmentAfterResponse is required for streaming requests: the response // status and deterministic stream-start frames are durable before assignment. AssignmentAfterResponse AssignmentBoundary = "response_committed" )
type AuthenticatedWorker ¶
type AuthenticatedWorker struct {
WorkerID WorkerID `json:"-"`
SessionID WorkerSessionID `json:"-"`
}
AuthenticatedWorker is constructed from a verified transport principal. Both fields are deliberately excluded from serialized worker payloads: a WorkerEvent is always bound to WorkerID by the opened WorkerConnection.
func (AuthenticatedWorker) Validate ¶
func (principal AuthenticatedWorker) Validate() error
Validate checks the stable principal and ephemeral connection identity.
type Block ¶
type Block struct {
Type BlockType `json:"type"`
Text string `json:"text,omitempty"`
ImageURL string `json:"image_url,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
// ToolNamespace and ToolName form one correctness identity. Consumers must
// never match a namespaced tool on Name alone.
ToolNamespace string `json:"tool_namespace,omitempty"`
ToolName string `json:"tool_name,omitempty"`
Input map[string]any `json:"input,omitempty"`
// TextInput carries the opaque freeform payload of a text-input tool call.
// It is a pointer so an intentionally empty payload remains distinguishable
// from a JSON-input tool call.
TextInput *string `json:"text_input,omitempty"`
Output any `json:"output,omitempty"`
IsError bool `json:"is_error,omitempty"`
}
Block is a dialect-neutral message content block.
func (Block) QualifiedToolName ¶
QualifiedToolName returns the complete identity of a tool-use block.
type CallerEndpoint ¶
type CallerEndpoint interface {
Admit(context.Context, AdmissionRequest) (AdmissionResult, error)
ReadResponse(context.Context, ResponseQuery) (ResponsePage, error)
WaitResponse(context.Context, ResponseQuery) (ResponsePage, error)
}
CallerEndpoint is the complete transport-neutral caller surface. HTTP, authentication, headers, and listener ownership belong to adapters which construct AdmissionRequest from an authenticated principal. Implementations are safe for concurrent calls; operation contexts never own the endpoint lifetime and cancellation does not imply that an ambiguous durable commit was rolled back.
type CallerTransport ¶
type CallerTransport interface {
Description() CallerTransportDescription
Start(context.Context, CallerEndpoint) (CallerTransportRuntime, error)
}
CallerTransport authenticates callers and projects a wire protocol onto CallerEndpoint. Start borrows endpoint and uses ctx only to bound initialization. The returned runtime owns all listener/session/background lifetime. Shutdown must stop new admission, unblock active waits, and join its goroutines; it must never shut down endpoint or resources reachable through it. It must project only the safe fields of AdmissionError. A caller disconnect never cancels durable work: exact retry resumes response replay from a cursor.
type CallerTransportDescription ¶
type CallerTransportDescription struct {
Contract framework.Contract
Provider string
Version string
}
CallerTransportDescription is immutable, non-secret adapter metadata. Provider identifies the implementation and Version identifies that implementation, not the model API projected by a Codec.
func NegotiateCallerTransport ¶
func NegotiateCallerTransport( description CallerTransportDescription, ) (CallerTransportDescription, error)
NegotiateCallerTransport validates a description and returns an independent frozen copy. Composition roots must cache this value once rather than calling Description again after Start.
func ValidateCallerTransport ¶
func ValidateCallerTransport( transport CallerTransport, ) (CallerTransportDescription, error)
ValidateCallerTransport rejects typed-nil adapters and returns their frozen negotiated description. It does not start network listeners.
func (CallerTransportDescription) Validate ¶
func (description CallerTransportDescription) Validate() error
type CallerTransportRuntime ¶
CallerTransportRuntime separates reusable adapter configuration from one running instance.
type CapabilityTier ¶
type CapabilityTier string
CapabilityTier is the authority boundary selected before admission.
const ( TierChat CapabilityTier = "chat" TierRemoteTools CapabilityTier = "remote_tools" TierWorkspace CapabilityTier = "workspace" )
type Clock ¶
Clock supplies all core-owned wall-clock values. Implementations must be safe for concurrent use and must not return the zero time.
type Codec ¶
type Codec interface {
Description() CodecDescription
Decode(body []byte) (Request, error)
NewStream(session EncoderSession) (Encoder, error)
NewAggregate(session EncoderSession) (Encoder, error)
AdmissionError(failure AdmissionFailure) ([]byte, error)
}
Codec is a pure wire projection port. Implementations are borrowed until Service.Done and must allow concurrent calls to every Codec method. They may parse and encode a custom model API, but must not perform transport, persistence, authentication, clock, random, or other external I/O through this interface. Description must always report the same value. Decode and AdmissionError must be deterministic functions of their arguments.
Decode borrows body only for the duration of the call. It must neither mutate nor retain body, and the returned Request must own all mutable slices, maps, and RawMessage values and pass Request.Validate. AdmissionError transfers ownership of its returned body to the caller. Encoder factory arguments are likewise borrowed; an encoder must copy any mutable value it retains. A registered Codec is borrowed for the Service lifetime and every method may be called concurrently. Each returned Encoder, however, belongs to exactly one response and is driven serially; encoders need not support concurrent Start/Encode calls. Any method error fails the current request/event and must not hide externally visible side effects because codecs are pure.
type CodecDescription ¶
type CodecDescription struct {
Contract framework.Contract
ID CodecID
Version string
Fingerprint CodecFingerprint
Limits CodecLimits
OverloadedStatus int
}
CodecDescription is immutable for the lifetime of a registered codec.
ID identifies the logical protocol. Version is an immutable, human-readable release identifier: an (ID, Version) pair must never be reused for different behavior. Fingerprint pins the exact byte-affecting implementation and configuration. Contract versions describe this Go port, not the wire API.
func NegotiateCodec ¶
func NegotiateCodec(description CodecDescription) (CodecDescription, error)
NegotiateCodec validates a descriptor, negotiates its framework contract, and returns an independent frozen copy. Applications should do this exactly once during composition and persist the returned identity with every request.
func ValidateCodec ¶
func ValidateCodec(codec Codec) (CodecDescription, error)
ValidateCodec negotiates a codec's descriptor. A typed-nil implementation is rejected before any method call. The returned descriptor, not later calls to Description, is the immutable value a runtime must cache and persist.
type CodecFingerprint ¶
type CodecFingerprint string
CodecFingerprint is a SHA-256 pin for every implementation and configuration input that can affect decoded canonical values or encoded bytes.
func Fingerprint ¶
func Fingerprint(manifest []byte) CodecFingerprint
Fingerprint returns the canonical fingerprint spelling for a codec manifest. A manifest should include implementation source/build identity and all byte-affecting configuration; hashing configuration alone is insufficient.
type CodecID ¶
type CodecID string
CodecID is a stable logical wire-protocol identity, for example "openai.chat". It must not contain deployment-specific values.
type CodecLimits ¶
type CodecLimits struct {
MaxRequestBytes int64
MaxStreamFrameBytes int64
MaxStreamFramesPerStep int
MaxAggregateBytes int64
MaxAdmissionErrorBytes int64
}
CodecLimits are hard maxima advertised by a codec. The runtime checks the request before Decode and every returned byte slice after an encoder call. A codec must fail rather than return output above its own advertised limits.
func (CodecLimits) CheckAdmissionError ¶
func (limits CodecLimits) CheckAdmissionError(body []byte) error
CheckAdmissionError enforces the advertised admission-error body limit.
func (CodecLimits) CheckAggregateFrames ¶
func (limits CodecLimits) CheckAggregateFrames(frames [][]byte, done bool) error
CheckAggregateFrames enforces aggregate visibility and size invariants.
func (CodecLimits) CheckRequestSize ¶
func (limits CodecLimits) CheckRequestSize(size int64) error
CheckRequestSize enforces a codec's advertised decode input limit.
func (CodecLimits) CheckStreamFrames ¶
func (limits CodecLimits) CheckStreamFrames(frames [][]byte) error
CheckStreamFrames enforces the advertised per-call stream limits. Buffer ownership is a behavioral requirement verified by codec conformance tests.
type CodecRegistration ¶
type CodecRegistration struct {
Codec Codec
StreamContentType string
AggregateContentType string
SuccessStatus int
}
CodecRegistration binds a validated pure Codec to caller transport metadata. Content types are response metadata only; no HTTP listener is owned here.
type CodecSnapshot ¶
type CodecSnapshot struct {
Contract framework.Contract
ID CodecID
Version string
Fingerprint CodecFingerprint
}
CodecSnapshot is the exact negotiated codec identity persisted with every Task and Request. Contract is a frozen snapshot of the Go port contract; Version and Fingerprint pin wire behavior. A Store must preserve the feature map as an independently owned value.
func NewCodecSnapshot ¶
func NewCodecSnapshot(description CodecDescription) (CodecSnapshot, error)
NewCodecSnapshot validates a complete CodecDescription and returns the immutable identity that persistence and recovery must use. Runtime byte limits and overload policy are intentionally not part of stored identity; byte-producing behavior is pinned by Version and Fingerprint.
func (CodecSnapshot) Equal ¶
func (snapshot CodecSnapshot) Equal(other CodecSnapshot) bool
Equal reports semantic identity for recovery. Feature-map insertion order and nil-versus-empty maps do not change a framework contract. A runtime must use this full comparison, never ID or Version alone, before decoding persisted canonical payload or reconstructing response bytes.
func (CodecSnapshot) Validate ¶
func (snapshot CodecSnapshot) Validate() error
Validate verifies a persisted snapshot without requiring current runtime limits. Recovery must additionally locate a registered Codec whose freshly negotiated snapshot is exactly equal to this value; matching ID alone is insufficient.
type CompletionIdentity ¶
type CompletionIdentity struct {
CallerID CallerID `json:"caller_id"`
RequestID string `json:"request_id"`
TaskID TaskID `json:"task_id"`
WorkspaceKey string `json:"workspace_key,omitempty"`
IdempotencyKey IdempotencyKey `json:"idempotency_key"`
}
CompletionIdentity contains every stable routing identity for one HumanLLM response. TaskID may span multiple completion requests. RequestID identifies one admitted request; IdempotencyKey controls exact caller replay. WorkspaceKey is empty only for a chat-only request. Lease identity is kept separately so a new lease cannot silently reuse an old outbox event.
func (CompletionIdentity) Validate ¶
func (identity CompletionIdentity) Validate() error
Validate checks the stable completion namespace. Session IDs, socket sequence numbers, and token text are intentionally absent.
type Config ¶
type Config struct {
DeploymentID string
Store framework.Resource[Store]
Protector protect.Resource
// ProtectionReadPolicy defaults to requiring sealed records whenever a
// Protector is configured. AllowPlain is an explicit migration escape hatch;
// it must never be enabled merely to recover from authentication failures.
ProtectionReadPolicy ProtectionReadPolicy
Codecs []CodecRegistration
Clock Clock
IDs IDSource
Seeds SeedSource
Router WorkerRouter
Admission AdmissionPolicy
ToolAuthorizer ToolAuthorizer
// Observer receives telemetry events (admission outcomes, worker sessions,
// event settlements). Nil is a no-op. Events are emitted after their
// durable decision and outside Store callbacks; a slow or panicking
// Observer cannot affect correctness (see the observe package contract).
Observer observe.Observer
AssignmentBuffer int
// WorkerPayloadLimitBytes is the maximum transport-neutral JSON assignment
// or worker event, including a small envelope reserve. It must be no larger
// than the configured worker transport/client write/read limit.
WorkerPayloadLimitBytes int64
ReadLimitBytes int64
// ReleaseTimeout bounds each owned Store/Protector release independently.
// The runtime reaches Done even if a broken custom release callback ignores
// cancellation; such an adapter goroutine is then the adapter's leak.
ReleaseTimeout time.Duration
}
Config composes the transport-neutral HumanLLM correctness core. DeploymentID is a non-secret persistence namespace, not caller authority. Protection AAD binds each blob to its authenticated CallerID and durable Task/Request key.
Store and Protector are explicit Resources: ownership transfers to NewService even when construction fails, while borrowed values must remain valid until Service.Done. Other ports are borrowed for the runtime lifetime and must satisfy their documented concurrency contracts. No default database, network transport, authentication provider, or key provider is selected here. Store binding is namespace identity rather than an HA lease; without external fencing, only one active Service may drive one Store/DeploymentID pair.
type Encoder ¶
type Encoder interface {
Start() (frames [][]byte, err error)
Encode(event Event, seed EventSeed) (frames [][]byte, done bool, err error)
}
Encoder is a single-session deterministic state machine. A runtime creates a fresh instance per response and calls its methods sequentially: Start exactly once, then Encode in durable event order until done. It is not required to be concurrency-safe and must never be reused for another response.
Start and Encode return newly owned buffers. After return, the caller may mutate or retain them and the encoder must never mutate them again. Inputs are borrowed for the call only. Given the same codec descriptor, EncoderSession, ordered Events, and EventSeeds, a reconstructed encoder must return byte-for- byte identical outputs without consulting a clock, random source, or I/O.
For a stream encoder, Start and each Encode return zero or more frames. For an aggregate encoder, Start and non-terminal Encode calls return no bytes, and the terminal Encode returns exactly one body. Transport-level keepalive is deliberately outside this deterministic response projection.
type EncoderSession ¶
type EncoderSession struct {
ResponseID string
Model string
Seed SessionSeed
}
EncoderSession contains every per-response value that may influence encoded bytes. It must be durable before Start output becomes observable.
func (EncoderSession) Validate ¶
func (session EncoderSession) Validate() error
Validate checks the mode-independent encoder inputs. A codec must additionally reject a missing seed field that its wire representation requires.
type Event ¶
type Event struct {
ID string `json:"id,omitempty"`
Type EventType `json:"type"`
WorkerID string `json:"worker_id,omitempty"`
Text string `json:"text,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Error string `json:"error,omitempty"`
}
Event is the dialect-neutral input consumed by an Encoder.
func (Event) EndsResponse ¶
EndsResponse reports whether the event is terminal for this model response.
type EventSeed ¶
type EventSeed struct {
EncodedAtUnix int64 `json:"encoded_at_unix"`
Entropy []byte `json:"entropy,omitempty"`
Opaque json.RawMessage `json:"opaque,omitempty"`
}
EventSeed supplies every event-local clock, entropy, or codec-specific input that may affect observable bytes. It must be persisted with the event before those bytes become visible.
type EventSeedContext ¶
type EventSeedContext struct {
Identity CompletionIdentity
Event Event
}
type EventType ¶
type EventType string
EventType is a canonical Human response event.
const ( EventAccepted EventType = "accepted" EventProgress EventType = "progress" EventFinal EventType = "final" EventClarification EventType = "clarification" EventToolCalls EventType = "tool_calls" EventRejected EventType = "rejected" EventExpired EventType = "expired" EventFailed EventType = "failed" )
type ExpiryPolicy ¶
ExpiryPolicy is an explicit host decision for incomplete model responses. Service owns the durable state transition and deterministic response bytes; the embedding host owns the wall-clock schedule and deadline. Keeping the sweep out of an internal goroutine makes the same mechanism usable by local, clustered, and test hosts without hidden lifecycle work.
type ExpiryResult ¶
ExpiryResult reports one sweep. Deferred records raced another durable transition or were not in a state where an expiry event could be committed; a later sweep may inspect them again.
type HostedCapability ¶
type HostedCapability struct {
Type string `json:"type"`
Configuration json.RawMessage `json:"configuration"`
}
HostedCapability records a provider-executed tool that must participate in exact request identity but is not offered as a caller-executed function.
type IDSource ¶
IDSource creates stable, opaque identifiers. Implementations are borrowed, must be concurrency-safe until Service.Done closes, and must honor context cancellation. Calls happen outside Store callbacks, so an implementation may use an HSM or network allocator. An error aborts the operation before its new Task/Request identity is persisted.
type IDSourceFunc ¶
IDSourceFunc adapts a function to IDSource.
type IdempotencyKey ¶
type IdempotencyKey string
type OpaqueInput ¶
OpaqueInput records a fingerprint of provider-private request state. The raw private bytes are not part of the Human transcript.
type ProtectionReadPolicy ¶
type ProtectionReadPolicy string
const ( ProtectionRequireSealed ProtectionReadPolicy = "require_sealed" ProtectionAllowPlain ProtectionReadPolicy = "allow_plain" )
type Request ¶
type Request struct {
Model string `json:"model"`
Stream bool `json:"stream"`
System string `json:"system,omitempty"`
Messages []Message `json:"messages"`
Tools []Tool `json:"tools,omitempty"`
ToolCallPolicy ToolCallPolicy `json:"tool_call_policy,omitempty"`
HostedCapabilities []HostedCapability `json:"hosted_capabilities,omitempty"`
OpaqueInput []OpaqueInput `json:"opaque_input,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
Request is the canonical output of Codec.Decode. Codec identity is not a field of Request: the runtime must bind the request to the negotiated codec ID, version, fingerprint, and contract version in its persistence record.
type ResponseDecision ¶
ResponseDecision contains caller-visible, already-unprotected bytes.
type ResponseMode ¶
type ResponseMode string
ResponseMode is immutable request metadata needed before canonical payload decoding and after retention has replaced that payload with a tombstone.
const ( ResponseStream ResponseMode = "stream" ResponseAggregate ResponseMode = "aggregate" )
type ResponsePage ¶
type ResponsePage struct {
Identity CompletionIdentity
RequestDigest StoreDigest
Mode ResponseMode
DecisionCommitted bool
Decision ResponseDecision
Complete bool
Events []WireEvent
Cursor uint64
}
ResponsePage is an ordered, cursor-based exact replay projection. Cursor is the highest persisted event sequence inspected, including private checkpoint records; callers must pass it back unchanged rather than derive it from the visible WireEvents slice.
type ResponseQuery ¶
type ResponseQuery struct {
CallerID CallerID
IdempotencyKey IdempotencyKey
RequestDigest StoreDigest
After uint64
Limit int
MaxBytes int64
}
type RetentionPolicy ¶
type RetentionPolicy struct {
CompletedBefore time.Time
BatchSize int
// RetainToolResults preserves completed task-ledger result payloads. The
// default false prunes them once their task is terminal; compact identities,
// digests and settlement receipts remain.
RetainToolResults bool
}
RetentionPolicy is an explicit host decision. Service owns the correctness of tombstoning, while the embedding host owns when to run it and how long replay payloads remain available. This keeps wall-clock scheduling out of the transport-neutral core and gives custom hosts the same operation used by the reference local runtime.
type RetentionResult ¶
type RetentionResult struct {
Scanned uint64
RequestsPruned uint64
EventsDeleted uint64
ToolResultsPruned uint64
Deferred uint64
}
RetentionResult reports durable work performed by one sweep.
type Role ¶
type Role string
Role is the canonical author of a message after a wire request is decoded.
type SeedContext ¶
type SeedContext struct {
Identity CompletionIdentity
Request Request
}
type SeedSource ¶
type SeedSource interface {
SessionSeed(context.Context, SeedContext) (SessionSeed, error)
EventSeed(context.Context, EventSeedContext) (EventSeed, error)
}
SeedSource supplies every deterministic codec seed before persistence. Implementations are borrowed, concurrency-safe until Service.Done, and honor context cancellation. It is never called from inside a Store callback. The resulting seed, not the source, is replayed after restart. Ownership of returned Entropy and Opaque buffers transfers to the core; an implementation must not mutate them after return (including from another goroutine).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the transport-neutral HumanLLM correctness core. It owns no HTTP listener. Caller transports invoke Admit/ReadResponse/WaitResponse; worker transports borrow it through WorkerEndpoint.
func NewService ¶
NewService validates every injected contract, recovers durable in-flight responses, and returns an active transport-neutral core. ctx bounds only construction and recovery.
func (*Service) Admit ¶
func (service *Service) Admit(ctx context.Context, input AdmissionRequest) (AdmissionResult, error)
Admit durably decides one canonical model response before making its assignment visible. Exact retries return the original response projection and never enqueue a second assignment.
func (*Service) DetachCaller ¶
func (service *Service) DetachCaller(ctx context.Context, identity CompletionIdentity)
DetachCaller records that the in-flight request holding a task has lost its caller: the request socket went away before a durable completion. This is the single caller-liveness signal behind both availability scenarios, unifying what were two half-features:
- Scenario C (takeover): it gates AdmitPreemptDetached — a resuming completion preempts the task ONLY because its prior caller is gone, never a live caller or a transport retry. This mirrors the formal callerDetached precondition in HumanLLM.tla.
- Scenario B (banner): it raises the human-facing "caller disconnected" notice so the operator does not reply into the void.
It is advisory in-memory state: a lost mark is safe because a restart drops every caller socket and the next completion is treated as a fresh top-level turn. It is cleared when the task is reconciled (taken over or advanced).
func (*Service) OpenWorker ¶
func (service *Service) OpenWorker(ctx context.Context, principal AuthenticatedWorker) (WorkerConnection, error)
func (*Service) ReadResponse ¶
func (service *Service) ReadResponse(ctx context.Context, query ResponseQuery) (ResponsePage, error)
ReadResponse returns the current exact durable response projection without waiting for another event.
func (*Service) RunExpiry ¶
func (service *Service) RunExpiry(ctx context.Context, policy ExpiryPolicy) (ExpiryResult, error)
RunExpiry durably completes eligible requests with EventExpired. It is safe to call repeatedly and concurrently: each expiry has a deterministic event identity and uses the normal worker-event commit path, so response encoding, receipts, revision CAS, commit-unknown reconciliation, waiter wakeups, and assignment cleanup remain one correctness implementation.
func (*Service) RunRetention ¶
func (service *Service) RunRetention(ctx context.Context, policy RetentionPolicy) (RetentionResult, error)
RunRetention replaces eligible completed request payloads with immutable replay-expired tombstones. It is safe to call repeatedly and concurrently; revision CAS makes a racing request/event transition win without data loss, and a later sweep retries the candidate.
func (*Service) Status ¶
func (service *Service) Status(ctx context.Context) (ServiceStatus, error)
Status verifies that the Store still accepts a serializable read and returns the current worker-session count. NewService completes recovery before it returns, so every successful status has RecoveryComplete=true.
func (*Service) WaitResponse ¶
func (service *Service) WaitResponse(ctx context.Context, query ResponseQuery) (ResponsePage, error)
WaitResponse waits until the response advances beyond query.After, commits a decision, or completes. Notifications are hints only; every return value is reconstructed from Store, so process restart and lost wakeups are harmless.
type ServiceStatus ¶
ServiceStatus is the transport-neutral readiness projection used by hosts to build HTTP probes, metrics, or native health APIs. It contains no database implementation detail and does not prescribe an endpoint shape.
type SessionSeed ¶
type SessionSeed struct {
CreatedAtUnix int64 `json:"created_at_unix"`
Entropy []byte `json:"entropy,omitempty"`
Opaque json.RawMessage `json:"opaque,omitempty"`
ToolCallPolicy ToolCallPolicy `json:"tool_call_policy,omitempty"`
}
SessionSeed supplies deterministic clock and entropy inputs. Opaque is a codec-owned JSON value for additional deterministic inputs. The runtime owns and persists all three fields; a codec must never fill missing values from a clock or random source.
type Store ¶
type Store interface {
// Description is static, non-secret metadata. It must not perform I/O and
// remains safe to call while the containing resource is being released.
Description() StoreDescription
// Bind atomically records the first binding. Repeating the exact binding is
// idempotent; every different binding must return StoreConflictError with
// StoreConstraintDeploymentBinding and leave the first binding unchanged.
// It honors cancellation. A result which may have committed must match
// ErrStoreCommitUnknown; repeating the exact binding is its reconciliation.
// Bind does not acquire a live runtime lease; see StoreBinding.
Bind(context.Context, StoreBinding) error
View(context.Context, func(StoreView) error) error
Update(context.Context, func(StoreTx) error) error
}
Store is the complete persistence consistency boundary for HumanLLM. Tasks, completion requests, canonical payloads, response wire events, durable worker receipts, tool execution ledgers, retention tombstones, and recovery scans deliberately share one Store. Splitting them across independently committed implementations would invalidate exact replay and ACK safety.
View must call fn exactly once with one stable read snapshot. Update must call fn exactly once in one strictly serializable transaction. Implementations must never retry either callback: HumanLLM callbacks may create timestamps, deterministic codec seeds, and exact conflict results from their snapshot. A callback and its StoreView or StoreTx are valid only until the enclosing method returns and must not be retained or used concurrently.
If an Update callback returns an error, none of its writes may become visible. If it returns nil, every write becomes visible atomically or none does. A definite commit failure returns an ordinary error and guarantees no commit. A result that may have committed must match ErrStoreCommitUnknown. The core then reconciles the request key or worker-event receipt; it must not blindly repeat an observable response or tool side effect.
The following correctness boundaries are composed by HumanLLM inside one Update, rather than implemented as driver-specific commands:
- admission: optional Task creation/reconciliation plus Request insertion;
- pre-stream failure: retry grant plus finite immutable HTTP decision;
- worker event: Task transition, tool-ledger entries, exact wire events, terminal response state, and the WorkerReceipt used to ACK the outbox;
- recovery quarantine: finite response, optional terminal wire event, Task repair, and quarantine marker;
- retention: request tombstone, response-event deletion, and eligible terminal tool-result pruning.
Successful Update effects are durable across process restart. Bind, View, and Update are safe for concurrent callers; Description is immutable and safe throughout the borrowed resource lifetime. Implementations own independent copies of every byte slice, map, CodecSnapshot contract feature map, and nested mutable value after a successful write and return caller-owned copies from reads.
Store intentionally has no Close method. Composition receives it through a framework.Resource[Store], making borrowed versus owned lifetime and release explicit without contaminating this business port.
type StoreBinding ¶
type StoreBinding struct {
DeploymentID string
}
StoreBinding permanently assigns one Store resource to one HumanLLM deployment correctness namespace. DeploymentID is not repeated in every logical key: applications that need multi-tenant sharing provide one isolated Store resource per deployment (or an adapter which applies that namespace internally).
Binding is persistent namespace identity, not a live-owner lease or an HA fencing token. Unless an embedding application adds external coordination, exactly one active Service may drive a bound correctness namespace. A serializable Store prevents duplicate commits but cannot by itself prevent two Service processes from presenting the same assignment to two Humans.
func (StoreBinding) Validate ¶
func (binding StoreBinding) Validate() error
Validate lets custom Store implementations enforce the public binding shape without importing an adapter-specific validator.
type StoreCommitUnknownError ¶
type StoreCommitUnknownError struct {
Cause error
}
StoreCommitUnknownError preserves an infrastructure cause while supporting errors.Is for both ErrStoreCommitUnknown and that cause.
func (*StoreCommitUnknownError) Error ¶
func (failure *StoreCommitUnknownError) Error() string
func (*StoreCommitUnknownError) Unwrap ¶
func (failure *StoreCommitUnknownError) Unwrap() []error
type StoreConflictError ¶
type StoreConflictError struct {
Constraint StoreConstraint
Key string
}
StoreConflictError reports a typed logical conflict and supports errors.Is(err, ErrStoreConflict).
func (*StoreConflictError) Error ¶
func (failure *StoreConflictError) Error() string
func (*StoreConflictError) Unwrap ¶
func (*StoreConflictError) Unwrap() error
type StoreConstraint ¶
type StoreConstraint string
StoreConstraint identifies one logical uniqueness or immutability rule. Adapter errors must use these values instead of leaking index names or relying on parsed vendor error text.
const ( StoreConstraintDeploymentBinding StoreConstraint = "deployment_binding" StoreConstraintTaskKey StoreConstraint = "task_key" StoreConstraintOpenAffinity StoreConstraint = "open_task_affinity" StoreConstraintRequestKey StoreConstraint = "request_key" StoreConstraintActiveRequest StoreConstraint = "active_request_per_task" StoreConstraintResponseSequence StoreConstraint = "response_event_sequence" StoreConstraintWorkerEvent StoreConstraint = "worker_event_identity" StoreConstraintWorkerReceipt StoreConstraint = "worker_receipt_identity" StoreConstraintToolCall StoreConstraint = "tool_call_identity" StoreConstraintImmutableRecord StoreConstraint = "immutable_record" StoreConstraintCompareAndSwap StoreConstraint = "compare_and_swap" )
type StoreCorruptError ¶
type StoreCorruptError struct {
Record StoreRecordKind
Key string
Cause error
}
StoreCorruptError classifies a physically malformed logical record without leaking a database location or query. Cause is retained for operators.
func (*StoreCorruptError) Error ¶
func (failure *StoreCorruptError) Error() string
func (*StoreCorruptError) Unwrap ¶
func (failure *StoreCorruptError) Unwrap() []error
type StoreDescription ¶
StoreDescription is static, non-secret implementation metadata. Provider identifies the adapter (for example "sqlite" or a Go module path); Version is the adapter release or schema family, not a database address.
func (StoreDescription) Validate ¶
func (description StoreDescription) Validate() error
Validate checks the implementation metadata and semantic contract.
type StoreDigest ¶
type StoreDigest string
StoreDigest is an opaque core-owned digest. A Store preserves it exactly and never recalculates it using adapter-specific serialization.
type StoreLimitError ¶
type StoreLimitError struct {
Record StoreRecordKind
Limit int64
}
StoreLimitError describes a bounded read refusal and supports errors.Is(err, ErrStoreRecordTooLarge).
func (*StoreLimitError) Error ¶
func (failure *StoreLimitError) Error() string
func (*StoreLimitError) Unwrap ¶
func (*StoreLimitError) Unwrap() error
type StoreNotFoundError ¶
type StoreNotFoundError struct {
Record StoreRecordKind
Key string
}
StoreNotFoundError adds a logical kind and safe stable key to ErrStoreRecordNotFound. Implementations may return the sentinel directly when no safe key is available.
func (*StoreNotFoundError) Error ¶
func (failure *StoreNotFoundError) Error() string
func (*StoreNotFoundError) Unwrap ¶
func (*StoreNotFoundError) Unwrap() error
type StoreReadLimit ¶
type StoreReadLimit struct {
MaxBytes int64
}
StoreReadLimit is a hard aggregate byte budget for one method call. MaxBytes must be positive and counts every returned CanonicalPayload, response Body, response-event Data, and tool Result byte. It is never interpreted as unlimited. A single-record method fails with ErrStoreRecordTooLarge. A scan does the same when its first record cannot fit; after at least one record fits it returns the largest ordered contiguous prefix within the budget.
type StoreRecordKind ¶
type StoreRecordKind string
StoreRecordKind identifies a logical record without exposing a table, collection, key prefix, or vendor schema name.
const ( StoreRecordTask StoreRecordKind = "task" StoreRecordRequest StoreRecordKind = "request" StoreRecordResponseEvent StoreRecordKind = "response_event" StoreRecordWorkerReceipt StoreRecordKind = "worker_receipt" StoreRecordToolExecution StoreRecordKind = "tool_execution" StoreRecordRecoveryCursor StoreRecordKind = "recovery_cursor" )
type StoreRecoveryCursor ¶
type StoreRecoveryCursor struct {
CreatedAt time.Time
Caller CallerID
IdempotencyKey IdempotencyKey
}
StoreRecoveryCursor orders candidates by CreatedAt, Caller, and idempotency key, all ascending.
type StoreRecoveryRecord ¶
type StoreRecoveryRecord struct {
Task StoreTaskRecord
Request StoreRequestRecord
}
type StoreRecoveryScan ¶
type StoreRecoveryScan struct {
After *StoreRecoveryCursor
Limit int
ReadLimit StoreReadLimit
}
StoreRecoveryScan selects every non-quarantined request whose response is incomplete, plus any request with a worker-associated response event lacking its matching receipt. The latter clause preserves recovery from adapters migrated from the old staged protocol; a conforming new core normally commits event effects and receipt atomically. Results contain Task and full Request from the same View snapshot in cursor order.
type StoreRequestHead ¶
type StoreRequestHead struct {
Key StoreRequestKey
Task StoreTaskKey
RequestID string
ResponseID string
RequestDigest StoreDigest
Codec CodecSnapshot
Mode ResponseMode
DecisionStatus int
DecisionContentType string
DecisionRetryAfter string
ResponseComplete bool
RecoveryQuarantined bool
LastEventSequence uint64
Revision uint64
CreatedAt time.Time
CompletedAt *time.Time
PayloadPrunedAt *time.Time
}
StoreRequestHead is a payload-free projection for hot-path state checks, recovery cursors, and retention scans. Decision omits Body by construction.
type StoreRequestKey ¶
type StoreRequestKey struct {
Caller CallerID
IdempotencyKey IdempotencyKey
}
type StoreRequestMutation ¶
type StoreRequestMutation struct {
Key StoreRequestKey
ExpectedRevision uint64
Next StoreRequestRecord
}
StoreRequestMutation replaces mutable response/recovery/retention state when ExpectedRevision matches. Key, Task, RequestID, ResponseID, RequestDigest, Codec, Mode, CreatedAt, and the pre-tombstone CanonicalPayload identity are immutable. Core must increment Revision exactly once for each successful replacement.
type StoreRequestRecord ¶
type StoreRequestRecord struct {
Key StoreRequestKey
Task StoreTaskKey
// RequestID is the stable assignment identity. ResponseID is the exact
// codec encoder identity. Both are allocated before dispatch and remain
// immutable so crash recovery can rebuild the same worker assignment and
// byte-identical response stream.
RequestID string
ResponseID string
RequestDigest StoreDigest
Codec CodecSnapshot
Mode ResponseMode
CanonicalPayload []byte
Decision StoreResponseDecision
ResponseComplete bool
RecoveryQuarantined bool
LastEventSequence uint64
Revision uint64
CreatedAt time.Time
CompletedAt *time.Time
PayloadPrunedAt *time.Time
}
StoreRequestRecord owns the idempotency tombstone and exact replay material. RequestDigest binds the canonical plaintext represented by CanonicalPayload to Codec, including its full contract snapshot. CanonicalPayload itself is a core-owned opaque at-rest representation; Store preserves but never opens, encrypts, or computes a digest from it. PayloadPrunedAt is immutable once set, and then CanonicalPayload and Decision.Body are empty while identity, status metadata, receipts, and the digest remain durable.
type StoreResponseDecision ¶
type StoreResponseDecision struct {
StatusCode int
ContentType string
RetryAfter string
Body []byte
}
StoreResponseDecision is the immutable HTTP boundary for one request. A zero StatusCode means no response is committed. Streaming normally commits a 200 with no Body before dispatch; aggregate mode commits status and Body together at the terminal event. Body is the core-owned opaque at-rest representation of exact wire bytes (plain or protected StoredValue framing); Store preserves it without interpreting or encrypting it.
type StoreResponseEventKind ¶
type StoreResponseEventKind string
StoreResponseEventKind identifies append-only exact-replay material. A checkpoint represents core-owned deterministic encoder session metadata; wire represents exact caller-visible bytes. Data is a core-owned opaque at-rest representation, so Store adapters never call a Protector. Worker/WorkerEventID/WorkerEventDigest bind every frame produced for one authenticated worker event to its durable ACK receipt. All three are empty for session/start/quarantine material and all three are non-empty together for worker-produced checkpoints and wire frames.
const ( StoreEventCheckpoint StoreResponseEventKind = "checkpoint" StoreEventWire StoreResponseEventKind = "wire" )
type StoreResponseEventRecord ¶
type StoreResponseEventRecord struct {
Request StoreRequestKey
Sequence uint64
Kind StoreResponseEventKind
Worker WorkerID
WorkerEventID string
WorkerEventDigest StoreDigest
Data []byte
CreatedAt time.Time
}
type StoreResponseEventScan ¶
type StoreResponseEventScan struct {
Request StoreRequestKey
After uint64
Kinds []StoreResponseEventKind
WorkerEventID string
Limit int
ReadLimit StoreReadLimit
}
StoreResponseEventScan returns events in Sequence order strictly after After. Kinds empty means all kinds. WorkerEventID empty means all worker events.
type StoreRetentionCandidate ¶
type StoreRetentionCandidate struct {
Request StoreRequestHead
EffectiveCompletedAt time.Time
UnacknowledgedWorkerEvent bool
}
type StoreRetentionCursor ¶
type StoreRetentionCursor struct {
CompletedAt time.Time
Caller CallerID
IdempotencyKey IdempotencyKey
}
StoreRetentionCursor orders candidates by effective completion time, Caller, and idempotency key, all ascending.
type StoreRetentionScan ¶
type StoreRetentionScan struct {
CompletedBefore time.Time
After *StoreRetentionCursor
Limit int
}
StoreRetentionScan selects complete, non-tombstoned requests whose effective completion time (CompletedAt, otherwise CreatedAt for malformed legacy data) is at or before CompletedBefore. The core must not tombstone an ordinary candidate with UnacknowledgedWorkerEvent=true. A RecoveryQuarantined request is already a durable terminal adjudication: stores report its marker as false so corrupt/orphan worker history cannot retain private payload forever.
type StoreTaskAffinity ¶
type StoreTaskAffinity struct {
Caller CallerID
WorkspaceKey string
HarnessID string
HarnessVersion string
HarnessSessionID string
}
StoreTaskAffinity names one exact non-chat harness conversation. Every field is required. Chat completions deliberately have no stable affinity and must never be looked up or made unique through this type: each one owns a fresh Task even when another completion from the same Caller remains active.
type StoreTaskKey ¶
type StoreTaskMutation ¶
type StoreTaskMutation struct {
Key StoreTaskKey
ExpectedRevision uint64
Next StoreTaskRecord
}
StoreTaskMutation replaces one Task when ExpectedRevision still matches. Key and every immutable identity field in Next must equal the stored record. A false result means a CAS miss and changes nothing. Store does not decide whether Next.State is a legal HumanLLM transition.
type StoreTaskRecord ¶
type StoreTaskRecord struct {
Key StoreTaskKey
WorkspaceKey string
CapabilityTier CapabilityTier
Codec CodecSnapshot
HarnessID string
HarnessVersion string
HarnessSessionID string
ExecAllowed bool
State TaskState
LeaseOwner WorkerID
LeaseID WorkerLeaseID
Revision uint64
CreatedAt time.Time
UpdatedAt time.Time
}
StoreTaskRecord is the durable multi-turn completion aggregate. Codec is pinned for the Task lifetime; every Request must carry an equal snapshot.
type StoreToolExecutionKey ¶
type StoreToolExecutionKey struct {
Task StoreTaskKey
ToolCallID ToolCallID
}
type StoreToolExecutionMutation ¶
type StoreToolExecutionMutation struct {
Key StoreToolExecutionKey
ExpectedRevision uint64
Next StoreToolExecutionRecord
}
StoreToolExecutionMutation completes or retention-prunes one ledger row by revision CAS. Key, InputDigest, and CreatedAt are immutable.
type StoreToolExecutionRecord ¶
type StoreToolExecutionRecord struct {
Key StoreToolExecutionKey
InputDigest StoreDigest
State ToolExecutionState
Result []byte
IsError bool
Revision uint64
CreatedAt time.Time
CompletedAt *time.Time
ResultPrunedAt *time.Time
}
StoreToolExecutionRecord is the task-wide at-most-once ledger. InputDigest binds a ToolCallID to one canonical call. Result is the core-owned opaque at-rest representation of canonical caller-reported JSON. ResultPrunedAt distinguishes retention from a legitimate empty result.
type StoreToolExecutionScan ¶
type StoreToolExecutionScan struct {
Task StoreTaskKey
State ToolExecutionState
After ToolCallID
Limit int
ReadLimit StoreReadLimit
}
StoreToolExecutionScan returns ToolCallID-ascending records strictly after After. State empty means both states.
type StoreTx ¶
type StoreTx interface {
StoreView
InsertTask(StoreTaskRecord) error
CompareAndSwapTask(StoreTaskMutation) (bool, error)
InsertRequest(StoreRequestRecord) error
CompareAndSwapRequest(StoreRequestMutation) (bool, error)
InsertResponseEvent(StoreResponseEventRecord) error
InsertWorkerReceipt(StoreWorkerReceiptRecord) error
InsertToolExecution(StoreToolExecutionRecord) error
CompareAndSwapToolExecution(StoreToolExecutionMutation) (bool, error)
DeleteTombstonedResponseEvents(StoreRequestKey) (uint64, error)
}
StoreTx extends one StoreView with typed, non-committing primitives. Immutable inserts return ErrStoreConflict on any collision, including an exact replay; HumanLLM core loads and compares the existing record to decide idempotency. CAS methods return (false, nil) on an expected-revision miss.
DeleteTombstonedResponseEvents may delete only events owned by a Request whose PayloadPrunedAt is non-nil in this same transaction. It leaves worker receipts intact so delayed durable-outbox duplicates remain ACKable. It returns the number of deleted records. All retention decisions remain in core.
type StoreView ¶
type StoreView interface {
LoadTask(StoreTaskKey) (StoreTaskRecord, error)
// FindOpenTask resolves only TierRemoteTools/TierWorkspace Tasks. An empty or
// partial affinity returns ErrStoreInvalidArgument; absence returns
// ErrStoreRecordNotFound.
FindOpenTask(StoreTaskAffinity) (StoreTaskRecord, error)
FindActiveRequest(StoreTaskKey) (StoreRequestHead, error)
LoadRequestHead(StoreRequestKey) (StoreRequestHead, error)
LoadRequest(StoreRequestKey, StoreReadLimit) (StoreRequestRecord, error)
LoadResponseDecision(StoreRequestKey, StoreReadLimit) (StoreResponseDecision, error)
LoadWorkerReceipt(StoreRequestKey, string) (StoreWorkerReceiptRecord, error)
LoadToolExecution(StoreToolExecutionKey, StoreReadLimit) (StoreToolExecutionRecord, error)
ScanResponseEvents(StoreResponseEventScan) ([]StoreResponseEventRecord, error)
ScanToolExecutions(StoreToolExecutionScan) ([]StoreToolExecutionRecord, error)
ScanRecovery(StoreRecoveryScan) ([]StoreRecoveryRecord, error)
ScanRetention(StoreRetentionScan) ([]StoreRetentionCandidate, error)
}
StoreView is a transaction-bound logical snapshot. It exposes no SQL, collection, driver cursor, or transport type. Absence matches ErrStoreRecordNotFound; every returned mutable value belongs to the caller.
type StoreWorkerReceiptRecord ¶
type StoreWorkerReceiptRecord struct {
Request StoreRequestKey
EventID string
Worker WorkerID
Digest StoreDigest
CreatedAt time.Time
}
StoreWorkerReceiptRecord is the durable ACK oracle. It may be inserted only in the same Update as all Task, tool-ledger, response-wire, and terminal effects of that worker event. Therefore observing a matching receipt proves those effects are durable after a crash.
type TaskContext ¶
type TaskContext struct {
TaskID TaskID `json:"task_id,omitempty"`
WorkspaceKey string `json:"workspace_key,omitempty"`
CapabilityTier CapabilityTier `json:"capability_tier"`
HarnessID string `json:"harness_id,omitempty"`
HarnessVersion string `json:"harness_version,omitempty"`
HarnessSessionID string `json:"harness_session_id,omitempty"`
ExecAllowed bool `json:"exec_allowed,omitempty"`
}
TaskContext carries correctness identity selected by an authenticated caller transport. A chat request must leave every field except CapabilityTier empty. For remote-tools/workspace requests, TaskID may name an existing Task or a new caller-selected Task; an empty TaskID asks the core to allocate one.
type TaskState ¶
type TaskState string
TaskState is HumanLLM core's reachable durable task state. The implementation may atomically refine across conceptual protocol steps such as admitted or reconciled when no crash/retry boundary can observe them; those TLA+ states are intentionally not imposed on third-party Store implementations.
const ( TaskLeased TaskState = "leased" TaskAwaitingHuman TaskState = "awaiting_human" TaskAwaitingCaller TaskState = "awaiting_caller" TaskAwaitingResults TaskState = "awaiting_results" TaskCompleted TaskState = "completed" TaskRejected TaskState = "rejected" TaskExpired TaskState = "expired" TaskFailed TaskState = "failed" )
type Tool ¶
type Tool struct {
Namespace string `json:"namespace,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
InputKind ToolInputKind `json:"input_kind,omitempty"`
InputSchema json.RawMessage `json:"input_schema,omitempty"`
// InputFormat preserves a provider's validated text format contract (for
// example a Responses grammar object) as part of request identity.
InputFormat json.RawMessage `json:"input_format,omitempty"`
}
Tool is a caller-executed operation made available to HumanLLM. JSON-input tools map to ordinary OpenAI/Anthropic functions. Text-input tools map to Responses custom tools such as Codex's freeform apply_patch.
func (Tool) QualifiedName ¶
QualifiedName returns the complete tool identity.
type ToolAuthorization ¶
type ToolAuthorization struct {
CallerID CallerID
Task StoreTaskRecord
Request Request
Call ToolCall
}
type ToolAuthorizer ¶
type ToolAuthorizer interface {
AuthorizeTool(context.Context, ToolAuthorization) error
}
ToolAuthorizer is the fail-closed authority boundary for caller-executed tools. Nil permits only chat-tier tool calls; other tiers require an explicit authorizer. Calls happen outside Store callbacks. Input is borrowed for the call; implementations must not retain or mutate its nested mutable values. Implementations must be concurrency-safe until Service.Done and honor cancellation. Calls are retryable protocol work and may repeat when a prior attempt produced no durable WorkerReceipt, so implementations must be reentrant and must not consume one-shot authority as an untracked side effect. Only a framework Fault with CodeForbidden and RetryNever is a proved deterministic denial and produces a terminal worker NACK. CodeUnavailable, cancellation, and unclassified infrastructure errors fail closed without settling the durable worker outbox record, allowing an exact retry.
type ToolAuthorizerFunc ¶
type ToolAuthorizerFunc func(context.Context, ToolAuthorization) error
func (ToolAuthorizerFunc) AuthorizeTool ¶
func (authorizer ToolAuthorizerFunc) AuthorizeTool(ctx context.Context, input ToolAuthorization) error
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Namespace string `json:"namespace,omitempty"`
Name string `json:"name"`
Input map[string]any `json:"input,omitempty"`
TextInput *string `json:"text_input,omitempty"`
}
ToolCall requests one caller-side tool invocation.
func (ToolCall) QualifiedName ¶
QualifiedName returns the complete tool identity.
type ToolCallID ¶
type ToolCallID string
type ToolCallPolicy ¶
type ToolCallPolicy string
ToolCallPolicy is the caller's explicit scheduling contract for one model response. An empty value means the wire protocol did not express a policy.
const ( // ToolCallsDisabled means the caller explicitly prohibited tool use for this // response, even if its provider request carried tool definitions. ToolCallsDisabled ToolCallPolicy = "disabled" ToolCallsSerial ToolCallPolicy = "serial" ToolCallsParallel ToolCallPolicy = "parallel" )
type ToolExecutionState ¶
type ToolExecutionState string
const ( ToolExecutionPending ToolExecutionState = "pending" ToolExecutionCompleted ToolExecutionState = "completed" )
type ToolInputKind ¶
type ToolInputKind string
ToolInputKind identifies how a caller-executed tool receives its input. The zero value is JSON for backwards compatibility with function tools.
const ( ToolInputJSON ToolInputKind = "" ToolInputText ToolInputKind = "text" )
type WorkerAssignmentDelivery ¶
type WorkerAssignmentDelivery struct {
ID WorkerDeliveryID `json:"delivery_id"`
Assignment Assignment `json:"assignment"`
}
WorkerAssignmentDelivery is one ACKable delivery of a committed Assignment. Exact repetition with the same ID is normal across disconnects.
func CloneWorkerAssignmentDelivery ¶
func CloneWorkerAssignmentDelivery(delivery WorkerAssignmentDelivery) WorkerAssignmentDelivery
CloneWorkerAssignmentDelivery and CloneWorkerEventDelivery make ownership explicit at asynchronous adapter boundaries. Returned slices, maps, and raw JSON values do not alias their inputs.
func (WorkerAssignmentDelivery) ValidateFor ¶
func (delivery WorkerAssignmentDelivery) ValidateFor(principal AuthenticatedWorker) error
ValidateFor checks both delivery identity and authenticated assignment ownership. SessionID is intentionally not compared.
type WorkerConnection ¶
type WorkerConnection interface {
framework.Runtime
Principal() AuthenticatedWorker
Assignments() <-chan WorkerAssignmentDelivery
AckAssignment(context.Context, WorkerDeliveryID) error
CommitEvent(context.Context, WorkerEventDelivery) (WorkerEventReceipt, error)
}
WorkerConnection binds all completion operations to one authenticated principal.
Assignments has one sender and closer: the connection. The transport is its only receiver. A delivery remains owned by the endpoint until AckAssignment succeeds or the connection ends. The transport may call AckAssignment only after the remote worker has durably stored the exact assignment. A missing or lost ACK permits value-equivalent redelivery with the same delivery ID on this or a later session of the same WorkerID.
CommitEvent is the only event-to-wire-settlement boundary. It returns ACK only after every response frame/decision caused by the event and the exact worker-event receipt are durable, or after exact replay proves that boundary was crossed earlier. A deterministic NACK proves the event had no new effect and terminally removes that exact outbox record. An error settles nothing; transient cancellation after a possibly committed write must be reconciled before CommitEvent may return ACK, NACK, or ErrWorkerDeliveryIndeterminate.
Calls to CommitEvent on one connection are ordered. A transport must not dequeue the next durable outbox record before the current call settles. When the remote peer or endpoint is slow, it must propagate bounded backpressure by pausing reads rather than dropping an assignment/event, acknowledging it early, growing an unbounded queue, or destroying an otherwise healthy connection.
type WorkerConnectionError ¶
type WorkerConnectionError struct {
Principal AuthenticatedWorker
Cause error
}
WorkerConnectionError adds authenticated session context while preserving errors.Is/errors.As classification through Cause. Authorization failures which could target another worker are connection errors, never NACKs that erase the suspect outbox record.
func (*WorkerConnectionError) Error ¶
func (failure *WorkerConnectionError) Error() string
func (*WorkerConnectionError) Unwrap ¶
func (failure *WorkerConnectionError) Unwrap() error
type WorkerDeliveryError ¶
type WorkerDeliveryError struct {
Delivery WorkerDeliveryID
EventID string
Cause error
}
WorkerDeliveryError identifies an unsettled delivery while preserving its typed cause. ErrWorkerDeliveryIndeterminate requires exact replay or reconciliation and must never be translated into ACK or NACK by an adapter.
func (*WorkerDeliveryError) Error ¶
func (failure *WorkerDeliveryError) Error() string
func (*WorkerDeliveryError) Unwrap ¶
func (failure *WorkerDeliveryError) Unwrap() error
type WorkerDeliveryID ¶
type WorkerDeliveryID string
WorkerDeliveryID identifies one transport delivery. It is distinct from an idempotency key and worker event ID, and remains stable across retransmission.
type WorkerEndpoint ¶
type WorkerEndpoint interface {
OpenWorker(context.Context, AuthenticatedWorker) (WorkerConnection, error)
}
WorkerEndpoint is the narrow HumanLLM-core surface borrowed by a transport. OpenWorker is called only after transport authentication and policy checks. Its context bounds initialization only; the returned connection has an independent lifecycle. The transport shuts down that connection when the wire session ends, but never shuts down the endpoint itself. Implementations are safe for concurrent OpenWorker calls. A failed call returns no live connection and transfers no lifecycle obligation to the caller.
type WorkerEventDecision ¶
type WorkerEventDecision string
WorkerEventDecision is a terminal transport settlement. Both values permit deletion of the exact event from a durable worker outbox; a CommitEvent error does not.
const ( WorkerEventACK WorkerEventDecision = "ack" WorkerEventNACK WorkerEventDecision = "nack" )
type WorkerEventDelivery ¶
type WorkerEventDelivery struct {
ID WorkerDeliveryID `json:"delivery_id"`
Identity CompletionIdentity `json:"identity"`
LeaseID WorkerLeaseID `json:"lease_id"`
Event Event `json:"event"`
}
WorkerEventDelivery is one durable worker-outbox item. Identity and LeaseID are repeated explicitly so a reconnect never routes by socket-local state. Event.WorkerID must be empty; CommitEvent binds the event to WorkerConnection.Principal().WorkerID.
func CloneWorkerEventDelivery ¶
func CloneWorkerEventDelivery(delivery WorkerEventDelivery) WorkerEventDelivery
func (WorkerEventDelivery) Validate ¶
func (delivery WorkerEventDelivery) Validate() error
Validate checks the transport-neutral shape. Deterministic failures are valid reasons for a NACK; a transport must not close the whole connection or retry a known poison item forever merely because this method returns an error.
func (WorkerEventDelivery) ValidateFor ¶
func (delivery WorkerEventDelivery) ValidateFor(principal AuthenticatedWorker) error
ValidateFor additionally verifies that no worker identity arrived through the payload. Authorization of Identity/LeaseID to the authenticated worker is performed by the core at CommitEvent against its durable assignment record.
type WorkerEventReceipt ¶
type WorkerEventReceipt struct {
Delivery WorkerDeliveryID `json:"delivery_id"`
EventID string `json:"event_id"`
Decision WorkerEventDecision `json:"decision"`
Code WorkerRejectionCode `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
WorkerEventReceipt is exact-retry stable and is the only authority for a wire ACK/NACK. ACK means the exact event's response output and event receipt are durable. NACK means the event was deterministically rejected before any new effect became durable.
For a terminal event that arrives after a response closed, an exact event matching an existing durable receipt is replayed as ACK. An unknown late event is NACKed with WorkerRejectResponseClosed; a reused event ID with a different digest is NACKed with WorkerRejectEventConflict. None of those outcomes reopens the response or tears down unrelated work.
func (WorkerEventReceipt) ValidateFor ¶
func (receipt WorkerEventReceipt) ValidateFor(delivery WorkerEventDelivery) error
ValidateFor prevents a cumulative, reordered, or stale wire acknowledgement from settling the wrong durable outbox record. A malformed event may be NACKed if it still has stable delivery/event IDs, but it can never be ACKed.
type WorkerLease ¶
type WorkerLease struct {
ID WorkerLeaseID `json:"id"`
Owner WorkerID `json:"owner"`
}
WorkerLease is the stable completion ownership generation. ID changes when ownership is re-granted, while Owner remains the authenticated WorkerID. Neither value is a connection/session identity.
type WorkerLeaseID ¶
type WorkerLeaseID string
WorkerLeaseID identifies one durable HumanLLM assignment generation. It is not a socket/session identity and must be checked at the same commit boundary as LeaseOwner before accepting a worker event.
type WorkerNotice ¶
type WorkerNotice struct {
Code string
Message string
Caller CallerID
TaskID TaskID
RequestID string
}
WorkerNotice is a transport-level alert the worker's human must see — for example, the caller holding an in-flight request disconnected. It is advisory (a UI hint), never a correctness signal: dropping one changes no durable state and is always safe.
type WorkerNoticer ¶
type WorkerNoticer interface {
Notices() <-chan WorkerNotice
}
WorkerNoticer is an optional WorkerConnection capability. A connection may surface transport-level notices (a caller disconnect, say) that a transport adapter forwards to the human side. It is discovered by type assertion, so a WorkerConnection that does not implement it simply carries no notices and nothing breaks. The abstraction is the product; whether and how a given connection detects such events is that implementation's own concern.
type WorkerRejectionCode ¶
type WorkerRejectionCode string
WorkerRejectionCode is selected by WorkerEndpoint. Message is diagnostics only and must never be parsed for protocol behavior.
const ( WorkerRejectInvalid WorkerRejectionCode = "invalid" WorkerRejectForbidden WorkerRejectionCode = "forbidden" WorkerRejectNotFound WorkerRejectionCode = "not_found" WorkerRejectStaleLease WorkerRejectionCode = "stale_lease" WorkerRejectResponseClosed WorkerRejectionCode = "response_closed" WorkerRejectEventConflict WorkerRejectionCode = "event_conflict" WorkerRejectStateConflict WorkerRejectionCode = "state_conflict" WorkerRejectToolConflict WorkerRejectionCode = "tool_conflict" )
type WorkerRouteRequest ¶
type WorkerRouteRequest struct {
CallerID CallerID
IdempotencyKey IdempotencyKey
TaskID TaskID
Request Request
Task TaskContext
Candidates []WorkerID
// CallerAttributes is an independent top-level copy per route call carrying
// the authenticated principal's advisory claims; the attribute values are
// borrowed and must not be mutated. Attributes never enter routing
// correctness state: the selected WorkerID alone is persisted.
CallerAttributes map[string]any
}
type WorkerRouter ¶
type WorkerRouter interface {
RouteWorker(context.Context, WorkerRouteRequest) (WorkerID, error)
}
WorkerRouter selects a stable authenticated WorkerID. Returning an empty ID is equivalent to ErrWorkerUnavailable. It may deliberately route to a known but currently disconnected worker so durable work waits for reconnection. The borrowed implementation must be concurrency-safe until Service.Done, honor context cancellation, and not retain/mutate WorkerRouteRequest values.
A Router is optional only for single-worker deployments: with a nil Router the core routes to the sole connected worker and fails closed with ErrWorkerRouterRequired as soon as a second worker connects.
type WorkerRouterFunc ¶
type WorkerRouterFunc func(context.Context, WorkerRouteRequest) (WorkerID, error)
func (WorkerRouterFunc) RouteWorker ¶
func (router WorkerRouterFunc) RouteWorker(ctx context.Context, input WorkerRouteRequest) (WorkerID, error)
type WorkerSessionID ¶
type WorkerSessionID string
WorkerSessionID identifies one live transport connection only. It changes on reconnect and never participates in request, lease, delivery, or outbox correctness identity.
type WorkerTransport ¶
type WorkerTransport interface {
Description() WorkerTransportDescription
Start(context.Context, WorkerEndpoint) (WorkerTransportRuntime, error)
}
WorkerTransport authenticates remote workers and projects a wire protocol onto WorkerEndpoint. It owns its listeners, sessions, and background delivery loops, but only borrows endpoint.
Start's context bounds initialization only. After Start succeeds, the returned runtime owns the adapter lifetime. Shutdown must stop accepting new workers, shut down every WorkerConnection opened through endpoint, wait for adapter goroutines, and then return. It must never close endpoint or any Store or Protector reachable through endpoint.
The transport, rather than an inbound payload, constructs AuthenticatedWorker after authentication. It may send a wire ACK/NACK only from the corresponding result of WorkerConnection.CommitEvent; accepting a frame into an in-memory queue is not an acknowledgement boundary.
type WorkerTransportDescription ¶
type WorkerTransportDescription struct {
Contract framework.Contract
Provider string
Version string
}
WorkerTransportDescription is immutable, non-secret adapter metadata. Provider identifies the implementation (for example "websocket" or "grpc") and Version identifies that implementation, not its wire protocol.
func NegotiateWorkerTransport ¶
func NegotiateWorkerTransport( description WorkerTransportDescription, ) (WorkerTransportDescription, error)
NegotiateWorkerTransport validates a description and returns an independent frozen copy. A composition root must cache this result once; runtime behavior must not depend on later mutations to Description().Contract.Features.
func ValidateWorkerTransport ¶
func ValidateWorkerTransport(transport WorkerTransport) (WorkerTransportDescription, error)
ValidateWorkerTransport rejects typed-nil adapters and returns their frozen negotiated description. It does not start network listeners.
func (WorkerTransportDescription) Validate ¶
func (description WorkerTransportDescription) Validate() error
Validate negotiates the base contract and validates the adapter metadata.
type WorkerTransportRuntime ¶
WorkerTransportRuntime is separated from WorkerTransport so a reusable adapter configuration is not confused with one running instance.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package builtin exposes HumanLLM's built-in model-API codecs through the public llm.Codec port.
|
Package builtin exposes HumanLLM's built-in model-API codecs through the public llm.Codec port. |
|
Package callerhttp provides the official HTTP caller transport for HumanLLM.
|
Package callerhttp provides the official HTTP caller transport for HumanLLM. |
|
bearerauth
Package bearerauth is HumanLLM's basic caller Authenticator: it accepts a single shared token using the OpenAI Authorization bearer convention or the Anthropic X-Api-Key convention, and attributes every accepted request to one fixed CallerID.
|
Package bearerauth is HumanLLM's basic caller Authenticator: it accepts a single shared token using the OpenAI Authorization bearer convention or the Anthropic X-Api-Key convention, and attributes every accepted request to one fixed CallerID. |
|
harnessresolver
Package harnessresolver is HumanLLM's basic caller-side RequestResolver: it maps the exact session identity emitted by recognized coding harnesses onto the transport-neutral llm.TaskContext, and derives a stable idempotency key for a harness turn so a dropped-socket retry dedups instead of forking work.
|
Package harnessresolver is HumanLLM's basic caller-side RequestResolver: it maps the exact session identity emitted by recognized coding harnesses onto the transport-neutral llm.TaskContext, and derives a stable idempotency key for a harness turn so a dropped-socket retry dedups instead of forking work. |
|
Package sqlite is HumanLLM's official single-process SQLite Store adapter.
|
Package sqlite is HumanLLM's official single-process SQLite Store adapter. |
|
Package workerws implements the official WebSocket adapter for the public HumanLLM WorkerTransport port.
|
Package workerws implements the official WebSocket adapter for the public HumanLLM WorkerTransport port. |
|
sqlite
Package sqlite provides the official durable SQLite implementation of the HumanLLM remote-worker Journal port.
|
Package sqlite provides the official durable SQLite implementation of the HumanLLM remote-worker Journal port. |