engine

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 14 Imported by: 1 module, 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 engine is the Go binding to the shared CloakAPI client-side engine (packages/cloak-engine-ffi, cdylib libcloak_engine) over its tiny C ABI.

It turns raw file bytes + MIME, or a plain-text prompt, into TOKENISED markdown (+ a LOCAL token map) ENTIRELY on the customer's machine, so an attachment or a prompt can be protected before a single byte egresses to the gateway. This mirrors the Python reference binding (sdk/python/cloakapi/engine.py): the same three C symbols and the same runtime library-location order.

The engine is loaded at runtime via dlopen (cgo, no extra dependency, offline) from ONE configured file:

  1. the path in CLOAKAPI_ENGINE_LIB, used only when CLOAKAPI_ENGINE_SHA256_PIN equals the SHA-256 of that file, or
  2. `_lib/libcloak_engine.so` beside the running program, used only when it is the engine build of this SDK release.

The file is read once, hashed, and a private copy of those bytes is loaded. The engine must also report the rule set this SDK was built for. When any of that does not hold, Available() is false, Issue() gives the reason, and the SDK uses its built-in rules and says so; it never stops a request for it.

The native engine is built for Linux x86-64 and arm64 with glibc 2.39 or newer. A build with CGO_ENABLED=0, and every other platform, uses the rules.

Index

Constants

View Source
const (
	// KindNoEngine — the native engine could not be loaded at all (LANE B).
	KindNoEngine = "no-engine"
	// KindNoNER — the engine loaded, but Layer B (NER) is unavailable (LANE A).
	KindNoNER = "no-ner"
	// KindNoModel — O261 name for the same lane as KindNoNER: the `.so` loaded,
	// the ONNX file did not. Identical string so there is ONE operator vocabulary
	// (python KIND_NO_NER, rust ReducedKind::ModelUnavailable, this gate).
	KindNoModel = KindNoNER
)

What is missing. The two lanes have different remedies, so they carry different messages.

View Source
const (
	ReasonEngineMissing    = "engine_missing"
	ReasonEngineUnloadable = "engine_unloadable"
	ReasonPinMissing       = "pin_missing"
	ReasonPinMismatch      = "pin_mismatch"
	ReasonRulesetMismatch  = "ruleset_mismatch"
	ReasonModelMissing     = "model_missing"
)

Reasons the native engine is not in use. They are the `reason` of a `reduced_coverage` notice.

View Source
const (
	EnvEngineLib = "CLOAKAPI_ENGINE_LIB"
	EnvEnginePin = "CLOAKAPI_ENGINE_SHA256_PIN"
)

Environment variables read once, when the engine is first needed.

View Source
const EnvAllowReduced = "CLOAKAPI_ALLOW_REDUCED"

EnvAllowReduced selects strict handling for the falsy aliases; truthy legacy values do not opt a caller out of the standard warning-and-send policy.

View Source
const RulesetHash = "8660b7abe553154802c9d27888a144863bcceaa3703517b8401cc56c590df2f9"

RulesetHash is the SHA-256 of the complete canonical patterns.json file. Keep it in lockstep with the generated pins in the TypeScript SDK. The Go binding checks the loaded native engine's reported ruleset identity against this value before any request egresses.

View Source
const RulesetVersion = "1.6.1"

RulesetVersion is the canonical shared-ruleset (fasit) semver this SDK's tokeniser targets. It MUST track shared/pii-patterns/patterns.json "version" and mirrors the Python/TypeScript reference bindings (engine.py RULESET_VERSION / engine.ts RULESET_VERSION). relayHeaders emits it as X-Cloak-Engine-Version only when the native engine is in use (engine.WireIdentity returns both a version and a hash). A request prepared by the built-in rules omits the header and says coverage=rules_only. A missing version is not, by itself, sent on every relay.

DRIFT GUARD: this value was hand-typed and silently fell behind the fasit (it still said 1.4.29 after the ruleset moved to 1.6.0), so the SDK declared a ruleset it was not running. `go:embed` cannot reach the fasit (it lives outside this module's root), so the binding is enforced by TEST instead: tests/canonical_ruleset_test.go TestRulesetVersionMatchesCanonical reads shared/pii-patterns/patterns.json and FAILS the build the moment this constant differs from its "version" field. Never edit this by hand without running `go test ./tests/`.

Variables

View Source
var ErrEngineUnavailable error = engineUnavailableError{}

ErrEngineUnavailable is returned when the shared engine library could not be located or loaded. Callers should treat it as "engine absent" and MAY fall back to a pure-regex tokeniser. It must NOT be confused with *EngineError.

View Source
var ErrReducedCoverage = &ReducedCoverageError{Msg: "cloakapi: reduced coverage"}

ErrReducedCoverage is the sentinel value for errors.Is.

View Source
var ErrUntrustedEngine = errors.New("cloakapi/engine: untrusted local engine identity")

ErrUntrustedEngine indicates that the loaded engine does not match this SDK's pinned canonical ruleset.

Functions

func AssertFullCoverage

func AssertFullCoverage(meta map[string]any) error

AssertFullCoverage marks an engine result as rules-only when name detection is unavailable. The historical one-argument signature is retained for source compatibility; it follows the standard warn-and-continue policy.

func AssertFullCoverageStrict

func AssertFullCoverageStrict(meta map[string]any) error

AssertFullCoverageStrict is AssertFullCoverage with refusal enabled for callers that must not accept reduced name detection.

func Available

func Available() bool

Available reports whether the native engine is in use in this process: it was loaded, the loaded bytes match the pin, and it reports this SDK's rule set. Cached after the first call. Issue() says why when it is false.

func BinaryHash

func BinaryHash() string

BinaryHash returns the lowercase hex SHA-256 of the engine bytes that were loaded: the X-Cloak-Engine-Hash value. Returns "" when the native engine is not in use.

func CheckRulesetPin

func CheckRulesetPin(version, hash string) error

CheckRulesetPin rejects missing, malformed, or drifted native ruleset identities. Error text intentionally contains no engine supplied values.

func EnvironmentForcesStrict

func EnvironmentForcesStrict() bool

EnvironmentForcesStrict reports whether the host selected strict handling for reduced text coverage. Empty and unrecognised values retain standard mode.

func GuardReducedCoverage

func GuardReducedCoverage(operation, kind string) error

GuardReducedCoverage warns and continues on a reduced lane. The historical two-argument signature is retained for source compatibility.

func GuardReducedCoverageStrict

func GuardReducedCoverageStrict(operation, kind string) error

GuardReducedCoverageStrict refuses a reduced lane. Call this before any text is tokenised when the caller explicitly selected strict behavior.

func Identity

func Identity() (version, hash string)

Identity returns the canonical engine identity for the ADR-0014 enforcement headers: version (the ruleset semver, ALWAYS present) and hash (the sha256 of the client-side engine binary that ran, or "" when only the pure-regex fallback is available — an honest "no binary engine to attest"). Mirrors the Python engine_identity() / TypeScript engineIdentity().

func Issue

func Issue() string

Issue returns "" when the native engine is in use, and otherwise the reason it is not: engine_missing, engine_unloadable, pin_missing, pin_mismatch or ruleset_mismatch. The answer is fixed for the life of the process.

func IssueMessage

func IssueMessage() string

IssueMessage is one plain-English sentence for Issue(), or "" when the engine is in use. It contains no file path and no text from any request.

func ReducedAllowed

func ReducedAllowed() bool

ReducedAllowed reports whether standard reduced-coverage sends are enabled. This remains true by default; callers can select strict handling with Config.StrictReducedCoverage or CLOAKAPI_ALLOW_REDUCED.

func ReducedMessage

func ReducedMessage(operation, kind string) string

ReducedMessage is the warning. A refusal uses ReducedRefusalMessage.

func ReducedRefusalMessage

func ReducedRefusalMessage(operation, kind string) string

ReducedRefusalMessage says the send was refused. It does not say the call continues.

func ReleaseEngineSHA256

func ReleaseEngineSHA256(platform string) string

ReleaseEngineSHA256 returns the SHA-256 of the native engine build that belongs to this SDK release on the given platform ("linux/amd64"), or "" when the release has no native engine for it.

func ReportedRulesetHash

func ReportedRulesetHash() string

ReportedRulesetHash returns the hash of the canonical patterns file that the engine in use reports, or "" when the native engine is not in use.

func TokeniseFile

func TokeniseFile(data []byte, mime, filename string, names []string) (string, map[string]string, []string, map[string]any, error)

TokeniseFile converts raw file bytes to tokenised markdown ENTIRELY on-device. Returns (markdown, full-token->original map, categories, engine meta, err). Only the markdown is meant to egress; the map stays LOCAL to detokenise the reply. The meta object (mime, extractor, pii_count, needs_ocr, chars, engine_version) is the engine's honest record of what ran on-device.

func TokeniseText

func TokeniseText(text string, names []string) (string, map[string]string, []string, error)

TokeniseText tokenises a plain-text prompt ENTIRELY on-device through the shared engine (fasit ruleset + checksum validators + native NER), exactly like the drop-in proxy / desktop app. Text is fed as text/plain through the file-pipeline. Returns (tokenised, full-token->original map, categories, err).

Returns ErrEngineUnavailable if the library is absent, or *EngineError if the engine is present but refuses — in the latter case the caller MUST NOT then send the raw text.

func TokeniseTextSeed

func TokeniseTextSeed(text string, names []string, seedHex string) (string, map[string]string, []string, error)

TokeniseTextSeed is TokeniseText with the C21b continuity seed threaded to the engine as opts.seed_hex — so the same original maps to the same surrogate id across sessions. Forward-safe: an engine that predates the key ignores it (the byte-exact <<CLOAK:…>> ids are unchanged when seedHex == "").

func VerifyLoadedRulesetPin

func VerifyLoadedRulesetPin() error

VerifyLoadedRulesetPin checks the native engine's version and ruleset digest against this SDK's generated pin.

func Version

func Version() string

Version returns the rule-set version the engine in use reports, or "" when the native engine is not in use.

func WireIdentity

func WireIdentity() (version, hash string)

WireIdentity returns the engine identity a request may state: the rule-set version and the SHA-256 of the loaded engine file when the native engine is in use, and two empty strings otherwise. A request prepared by the built-in rules states no engine identity.

Types

type EngineError

type EngineError struct{ Msg string }

EngineError means the engine call failed; it does not mean the content was refused. The error propagates to the caller in standard mode.

func (*EngineError) Error

func (e *EngineError) Error() string

func (*EngineError) Format

func (e *EngineError) Format(s fmt.State, verb rune)

type ReducedCoverageError

type ReducedCoverageError struct {
	Msg string
	// contains filtered or unexported fields
}

ReducedCoverageError is returned when a caller explicitly selects strict handling for a reduced-coverage text request.

func (*ReducedCoverageError) Error

func (e *ReducedCoverageError) Error() string

func (*ReducedCoverageError) Format

func (e *ReducedCoverageError) Format(s fmt.State, verb rune)

func (*ReducedCoverageError) Is

func (e *ReducedCoverageError) Is(target error) bool

Is support, so `errors.Is(err, ErrReducedCoverage)` works for a caller that only wants the CLASS and not the text.

type TokeniseOptions

type TokeniseOptions struct {
	// Filename is the engine's `opts.filename` hint ("prompt.txt" for text).
	Filename string
	// Names are externally-detected PERSON spans folded into tokenisation.
	Names []string
	// SeedHex is the C21b cross-session continuity seed ("" = per-session).
	SeedHex string
	// Mode is the already-coerced surrogate mode ("balanced" | "max"). Empty is
	// NOT sent, and the engine then applies its own default (balanced) — but
	// cloakapi always sends an explicit, coerced value.
	Mode string
	// Bindings is the conversation ledger, round-tripped. NON-NIL (even empty)
	// means "the caller is running a conversation", and the engine then reports
	// continuity: "conversation". NIL means single-message.
	//
	// RE-IDENTIFICATION MATERIAL: this maps stand-ins back to real values. It is
	// CLIENT-SIDE ONLY — never egress it, never log it, never put it in a
	// receipt, exactly like the token map.
	Bindings map[string]any
	// HasBindings distinguishes "no conversation" from "a conversation whose
	// ledger is still empty". A nil Bindings map with HasBindings=true is sent
	// as `{}` and yields continuity: "conversation".
	HasBindings bool
	// StrictReducedCoverage refuses a text result when the native engine reports
	// that name detection is unavailable. The normal text path warns and continues.
	StrictReducedCoverage bool
}

TokeniseOptions are the mode-aware options for a tokenise call.

type TokeniseOutcome

type TokeniseOutcome struct {
	// Text is the tokenised text/markdown — the ONLY field that may egress.
	Text string
	// Replacements maps the FULL replacement string -> the original value. This
	// is the AUTHORITATIVE local detokenise table: in BALANCED the replacement is
	// not a token at all, so the hash-keyed Mappings CANNOT express it.
	Replacements map[string]string
	// Mappings is the legacy hash-keyed map (6-hex -> original). Kept for
	// compatibility; usable only in MAX.
	Mappings map[string]string
	// Mode is the mode the engine says it APPLIED ("balanced" | "max").
	Mode string
	// Continuity is the scope the engine says these bytes have
	// ("conversation" | "single-message").
	Continuity string
	// Bindings is the ledger, ADVANCED by this call. Feed it back into the next
	// call's TokeniseOptions.Bindings to keep stand-ins stable across turns.
	// CLIENT-SIDE ONLY — never egress.
	Bindings map[string]any
	// Categories are the cloud-token labels that fired (MAX only; BALANCED emits
	// no <<CLOAK:…>> markers to scan).
	Categories []string
	// Meta is the engine's honest record of what ran on-device.
	Meta map[string]any
}

TokeniseOutcome is everything the shared engine reported about ONE tokenise pass. Every field is populated from the engine's own JSON — nothing here is inferred by this binding.

func Tokenise

func Tokenise(data []byte, mime string, o TokeniseOptions) (TokeniseOutcome, error)

Tokenise is the MODE-AWARE entry point (spec §3) and the one every relay path uses. It passes `mode` + `bindings` straight to the shared engine and returns everything the engine reported — including the mode it ACTUALLY applied, so the caller can verify rather than assume.

Returns ErrEngineUnavailable if the library is absent, or *EngineError if the engine is present but refuses — in the latter case the caller MUST NOT then send the raw text.

func TokeniseTextMode

func TokeniseTextMode(text string, o TokeniseOptions) (TokeniseOutcome, error)

TokeniseTextMode is Tokenise for a plain-text prompt (fed as text/plain through the file pipeline, exactly like TokeniseText).

Source Files

  • degraded.go
  • degraded_cgo.go
  • engine_cgo.go
  • engine_common.go
  • gate.go

Jump to

Keyboard shortcuts

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