nativecodex

package
v0.0.0-...-eeaec4b Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package nativecodex implements the local app-server protocol boundary. It does not attest model capacity, start model turns, or enable native delivery.

Index

Constants

View Source
const ModelWindowNativeVersion = "0.157.1"

ModelWindowNativeVersion is the native implementation this resolver follows.

Variables

View Source
var (
	ErrProtocol = errors.New("native codex RPC protocol error")
	ErrClosed   = errors.New("native codex RPC transport closed")
)
View Source
var ErrCalibrationPersistence = errors.New("native Codex input feedback was not confirmed saved")

Feedback storage is separate from the model turn's outcome. A cache outage must be reported without terminating a productive native conversation.

View Source
var ErrClientExit = errors.New("native Codex client exited")

ErrClientExit means the owned TUI acknowledged unsubscribe and then closed its connection. It says nothing about input acceptance or model completion.

View Source
var ErrModelWindow = errors.New("native Codex 0.157.1 model window is unavailable")

ErrModelWindow means the supplied metadata cannot establish a packing window. Errors never include catalog contents, configuration values, or credentials.

View Source
var ErrState = errors.New("native Codex session state does not allow this operation")

Functions

func StartWindowBound

func StartWindowBound(ctx context.Context, opts Options, threadOpts ThreadOptions) (*Session, Thread, WindowBinding, error)

StartWindowBound uses a discovery process to read native's effective static catalog selection. It then starts a fresh execution process with unchanged options/environment. Config and catalog bytes are captured before execution startup: the native manager retains its startup catalog even if config/read later sees a changed file. No discovery thread or model turn is created.

Refreshable catalogs need an owned-runtime descriptor API; debug/cache reads cannot prove their binding. Revalidation detects observed drift, not atomic filesystem isolation (including an ABA edit entirely between observations).

func StartWindowEstimated

func StartWindowEstimated(ctx context.Context, opts Options, threadOpts ThreadOptions) (*Session, Thread, WindowEstimate, error)

StartWindowEstimated requires a dynamic catalog and exact native-acknowledged model/provider. Missing, malformed, stale or nonmatching evidence is unknown (an error and zero estimate), never a bundled/default model or invented window. Startup issues no inference or injection and writes no config/auth/catalog. The stock process itself can perform its normal catalog refresh at startup.

func StartWindowPolicy

func StartWindowPolicy(ctx context.Context, opts Options, threadOpts ThreadOptions) (*Session, Thread, WindowPolicy, error)

StartWindowPolicy dispatches from acknowledged effective config, never from a failed static binding. An explicit but invalid static catalog stays an error. The returned ModelWindow does not apply CXT's 80% input/reserve policy.

func SupportedHostIdentity

func SupportedHostIdentity(host string) bool

SupportedHostIdentity checks the build-version component of native's initialize userAgent. In 0.157.1 the originator before '/' can be overridden by the desktop environment (including spaces); it is not the build version. Keep the full identity in runtime bindings. This is protocol compatibility, not binary attestation, and never supplies model/window evidence by itself.

Types

type GenerationObservation

type GenerationObservation struct {
	ThreadID, TurnID      string
	Outcome               string // completed, input_rejected, initial_compaction, unknown
	ExecutionKnown        bool
	ExecutionStarted      bool
	UsageKnown            bool
	UsageBeforeCompaction bool
	TotalInputTokens      int
	ModelContextWindow    int
	ModelRerouted         bool
	Ineligible            bool
}

GenerationObservation contains only metadata for the submitted initial turn. ModelContextWindow is native telemetry, never proof of provider capacity. Ineligible means the parent must not submit this observation for calibration.

type Handoff

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

Handoff is a one-client transport, not a general RPC proxy. OpenHandoff only permits inspection and one resume. OpenGenerationHandoff additionally gates the exact first question on application preparation and source revalidation.

func (*Handoff) Close

func (h *Handoff) Close() error

func (*Handoff) GoString

func (h *Handoff) GoString() string

func (*Handoff) String

func (*Handoff) String() string

func (*Handoff) URL

func (h *Handoff) URL() string

URL is for the owned TUI's --remote argument, never for a shared receipt.

func (*Handoff) Wait

func (h *Handoff) Wait(ctx context.Context) (HandoffReceipt, error)

Wait observes live readiness. Cancellation closes the handoff; an old receipt is not reusable after disconnect. The returned receipt remains historical.

func (*Handoff) WaitGeneration

func (h *Handoff) WaitGeneration(ctx context.Context) (GenerationObservation, error)

WaitGeneration returns a correlated first-turn observation, not a promise that all history was consumed or that the model's answer is correct.

func (*Handoff) WaitLifecycle

func (h *Handoff) WaitLifecycle(ctx context.Context) error

WaitLifecycle waits for the one-client transport or its owned native session to close, including after a successful first turn. Unlike WaitGeneration it never returns for a historical outcome. Canceling this waiter does not close the runtime; the owner remains responsible for Close and Session.Close.

type HandoffReceipt

type HandoffReceipt struct {
	ThreadID           string `json:"thread_id"`
	PayloadHash        string `json:"payload_hash"`
	SettingsHash       string `json:"settings_hash"`
	ResumeAcknowledged bool   `json:"resume_acknowledged"`
	ProviderAcceptance string `json:"provider_acceptance"`
}

HandoffReceipt proves that a matching resume response was forwarded on the requesting client's private connection. It is not proof of rendered pixels, available model capacity, or provider acceptance. Injection bytes remain private.

type HistoryMessage

type HistoryMessage struct {
	Role string
	Text string
}

HistoryMessage only allows quoted conversation text. Instructions and tool calls require separate authority/pairing contracts and cannot enter here.

type InjectionReceipt

type InjectionReceipt struct {
	ThreadID           string `json:"thread_id"`
	PayloadHash        string `json:"payload_hash"`
	Items              int    `json:"items"`
	UTF8Bytes          int    `json:"utf8_bytes"`
	Acknowledged       bool   `json:"acknowledged"`
	ProviderAcceptance string `json:"provider_acceptance"`
}

type ModelWindow

type ModelWindow struct {
	NativeVersion                 string
	Model                         string
	ModelProvider                 string
	BaseContextWindow             int64
	ResolvedContextWindow         int64
	EffectiveContextWindowPercent int64
	PackingUsableWindow           int64
	NativeUsableWindow            int64
	// AutoCompactTokenLimit is the unbuffered native scope-relative threshold.
	// Only scope "total" can bound full initial input. "body_after_prefix"
	// counts tokens after the prefix; neither scope overrides NativeUsableWindow.
	// Native token-budget fallback buffers and post-turn triggers are separate.
	AutoCompactTokenLimit      int64
	AutoCompactTokenLimitScope string
}

ModelWindow separates a conservative packing policy from native telemetry. It is a calculation from caller-supplied evidence, not provider entitlement or proof that the running thread used that evidence. All counts are tokens.

func ResolveModelWindow

func ResolveModelWindow(thread Thread, catalogProvider string, catalogModel, effectiveConfig json.RawMessage) (ModelWindow, error)

ResolveModelWindow follows rust-v0.157.1 models-manager/src/model_info.rs, protocol/src/openai_models.rs and core/src/session/context_window.rs. catalogModel must be an exact catalog entry, before native config overrides; effectiveConfig must be the native startup configuration object (not its RPC envelope). The caller must establish their provenance, native version and binding to this owned thread. This function does no I/O and changes no state.

Provider and slug must match exactly. No prefix, namespace or fallback lookup is performed. Missing/null Option<i64> fields mean absent, as in native Rust; an omitted effective_context_window_percent defaults to 95, but null is invalid. Explicit numeric values must be positive int64 integers; percentages must be 1..100. Overflow is rejected instead of relying on native saturation/wrapping.

Packing follows native resolution when the bound catalog explicitly supplies a maximum. Without a catalog maximum, an override may shrink but cannot enlarge packing beyond the base usable window. A maximum alone does not select it. NativeUsableWindow reflects the override (clamped to max_context_window when present) and is the telemetry comparator. The resolver does not apply CXTHub's 80% input policy or hidden-input reserve.

type Options

type Options struct {
	Executable   string
	Cwd          string
	Env          []string
	ConfigArgs   []string
	StrictConfig bool
}

Options describes an owned local app-server. ConfigArgs must contain only native config/feature overrides; an arbitrary listener or command is rejected. The wrapper must still preserve original launch arguments before using this adapter in production. No runtime capacity evidence is manufactured here.

type PreparedGeneration

type PreparedGeneration struct {
	History  []HistoryMessage                                   `json:"-"`
	Validate func(context.Context) error                        `json:"-"`
	Observe  func(context.Context, GenerationObservation) error `json:"-"`
	// BeforeRelease optionally persists the acknowledged injection before the
	// first turn is forwarded. It runs once, must honor its bounded context,
	// and is followed by another Validate. Errors stop release without retry.
	BeforeRelease func(context.Context, InjectionReceipt) error `json:"-"`
}

PreparedGeneration is invocation-private. The application owns exact text accounting, active model/window evidence, latest-main authorization and final source/config checks. Neither a callback nor an injection ACK proves model acceptance. History and callback errors must never enter routine receipts.

func (PreparedGeneration) GoString

func (p PreparedGeneration) GoString() string

func (PreparedGeneration) String

func (PreparedGeneration) String() string

type Session

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

Session owns its process and fresh thread. There is deliberately no resume, attach-to-existing, turn/start or arbitrary RPC entry point. Generation is available only through a separately prepared handoff on this owned thread.

func Start

func Start(ctx context.Context, opts Options) (*Session, error)

func (*Session) Close

func (s *Session) Close() error

Close interrupts reads before waiting for the owned process. It never needs the operation mutex, so cancellation cannot deadlock behind an awaiting RPC.

func (*Session) HostIdentity

func (s *Session) HostIdentity() string

func (*Session) InjectHistory

func (s *Session) InjectHistory(ctx context.Context, messages []HistoryMessage) (InjectionReceipt, error)

InjectHistory is one-shot. A failed or lost ACK is ambiguous; it must never be retried on the same thread, since the first request may have persisted.

func (*Session) OpenGenerationHandoff

func (s *Session) OpenGenerationHandoff(ctx context.Context, prepare func(context.Context, Thread, string) (PreparedGeneration, error)) (*Handoff, error)

OpenGenerationHandoff defers preparation until the real initial question is known. A single injected history is released to one fresh owned thread. The inspection-only OpenHandoff keeps its original no-generation contract.

func (*Session) OpenHandoff

func (s *Session) OpenHandoff(ctx context.Context) (*Handoff, error)

OpenHandoff requires a successful one-shot injection. Omitted native search configuration is inherited from the prepared thread, never guessed locally.

func (*Session) StartThread

func (s *Session) StartThread(ctx context.Context, opts ThreadOptions) (Thread, error)

type Thread

type Thread struct {
	ID            string `json:"id"`
	Model         string `json:"model"`
	ModelProvider string `json:"model_provider"`
	Cwd           string `json:"cwd"`
	// SettingsHash covers the native response's effective settings, not the
	// contents of instruction files, hidden tools, capacity, or token counts.
	SettingsHash string `json:"settings_hash"`
}

Thread is the identity acknowledged by a fresh thread/start, not evidence that a model has accepted any input or that a TUI has attached.

type ThreadOptions

type ThreadOptions struct {
	Model          string
	ModelProvider  string
	Sandbox        string
	ApprovalPolicy string
	Ephemeral      bool
}

type WindowBinding

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

WindowBinding is an invocation-local binding to native's configured packing policy, not an account entitlement or a claim that inference will accept it. Only StartWindowBound or StartWindowPolicy can create a usable binding. Private config/catalog contents and paths are never returned, serialized, or included in errors.

func (WindowBinding) GoString

func (b WindowBinding) GoString() string

func (WindowBinding) ModelWindow

func (b WindowBinding) ModelWindow() ModelWindow

func (WindowBinding) RuntimeScope

func (b WindowBinding) RuntimeScope() string

func (WindowBinding) String

func (WindowBinding) String() string

func (WindowBinding) Validate

func (b WindowBinding) Validate(ctx context.Context, thread Thread) error

type WindowEstimate

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

WindowEstimate is a read-only observation of the actual native home's model cache and effective configuration for an acknowledged thread. It is NEVER a WindowBinding: native can retain, merge, refresh or ignore this cache. Its opaque auth identity is fingerprinted, not independently authenticated; no credentials are read. Neither runtime adoption nor entitlement is attested. Only StartWindowEstimated or StartWindowPolicy creates a usable estimate.

func (WindowEstimate) CatalogClientVersion

func (e WindowEstimate) CatalogClientVersion() string

CatalogClientVersion identifies the cache writer, independently of the pinned executing host. A reviewed foreign writer is still only estimate evidence.

func (WindowEstimate) CatalogHash

func (e WindowEstimate) CatalogHash() string

CatalogHash fingerprints the selected entry and opaque cache identity. Compatible writers, timestamp/ETag refreshes and other models do not invalidate it.

func (WindowEstimate) Estimated

func (WindowEstimate) Estimated() bool

func (WindowEstimate) Evidence

func (WindowEstimate) Evidence() string

func (WindowEstimate) GoString

func (e WindowEstimate) GoString() string

func (WindowEstimate) ModelWindow

func (e WindowEstimate) ModelWindow() ModelWindow

func (WindowEstimate) ObservedAt

func (e WindowEstimate) ObservedAt() string

ObservedAt is the catalog's fetched_at timestamp, not the time CXT read it.

func (WindowEstimate) RuntimeScope

func (e WindowEstimate) RuntimeScope() string

func (WindowEstimate) Source

func (WindowEstimate) Source() string

func (WindowEstimate) String

func (WindowEstimate) String() string

func (WindowEstimate) Validate

func (e WindowEstimate) Validate(ctx context.Context, thread Thread) error

Validate rechecks liveness, thread identity, effective config, exact cache selected entry/provenance and freshness immediately before injection. It detects observed drift, not atomic filesystem isolation or unexposed in-memory/auth changes in native.

type WindowPolicy

type WindowPolicy interface {
	ModelWindow() ModelWindow
	RuntimeScope() string
	Validate(context.Context, Thread) error
}

WindowPolicy exposes invocation-local packing evidence. Callers must retain the concrete type: only WindowBinding binds native's static catalog policy; WindowEstimate is unverified catalog evidence for a separate reserve policy.

Jump to

Keyboard shortcuts

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