cloakapi

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: 34 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 cloakapi is the official Go client for the CloakAPI privacy gateway.

CloakAPI tokenises PII in outbound prompts before they leave your machine, routes the anonymised request through the gateway to an AI provider, and de-tokenises the response on the way back.

Quick start:

client := cloakapi.NewClient("cloak_abc123", &cloakapi.Config{
    Review: func(request cloakapi.EgressRequest) bool { return reviewRequest(request) },
})
resp, err := client.Messages.Create(context.Background(), cloakapi.MessagesRequest{
    Model:    "claude-sonnet-4-6",
    Messages: []cloakapi.Message{{Role: "user", Content: "Hello!"}},
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(resp.FirstText())

Index

Constants

View Source
const (
	TierBalanced = "balanced"
	TierMax      = "max"

	// TierContinuity is a RETIRED CHOICE, kept only so existing source keeps
	// compiling. It is NOT in PrivacyTiers, and NormaliseTier migrates it to
	// TierBalanced.
	//
	// Deprecated: use TierBalanced. continuity is always-on in both tiers.
	TierContinuity = "continuity"
)

The Level-1 tiers CloakAPI exposes. There is NO plaintext off tier — off/plaintext is refused LOUD at client construction (Level-1-only).

TASK #24 / DECISION 11: continuity IS RETIRED AS A CHOICE. There are EXACTLY TWO tiers, forever: balanced (default) and max. Until 2026-08-10 PrivacyTiers advertised continuity as a third selectable posture, which the two-mode contract forbids. The continuity BEHAVIOUR (the same real value keeps the same stand-in for the whole conversation) is ALWAYS ON in BOTH tiers and is never named or offered — offering it as a toggle would only ever be offering a defect. Matches sdk/php/src/Tier.php and sdk/typescript/src/client.ts, which retired it 2026-07-29.

View Source
const (
	// WarningReducedCoverage: detection ran with less than the full engine.
	WarningReducedCoverage = "reduced_coverage"
	// WarningUncheckedContent: part of the text could not be checked or a
	// detected value could not be replaced. The text is sent as written.
	WarningUncheckedContent = "unchecked_content"
)

Codes of a SendWarning.

View Source
const (
	ReasonUnverifiedScript = "unverified_script"
	ReasonValueNotReplaced = "value_not_replaced"
	// ReasonDetectionLimit: the text is longer or denser than the built-in rules
	// examine in one pass, so part of it was not checked.
	ReasonDetectionLimit = "detection_limit"
)

Reasons of an unchecked_content warning. The reasons of reduced_coverage are the engine.Reason* constants.

View Source
const (
	// StateOK: the full engine checked the text.
	StateOK = "ok"
	// StateDegraded: at least one warning applies.
	StateDegraded = "degraded"
)

Review states.

View Source
const DefaultSurrogateMode = SurrogateModeBalanced

DefaultSurrogateMode is the mode used whenever a caller does not choose one. Never "no protection".

View Source
const EndUserPseudonymPrefix = "cloak_eu_"

EndUserPseudonymPrefix marks a DERIVED end-user ref. Identical to the gateway's StableEndUserPseudonym::PREFIX and the TypeScript SDK's END_USER_PSEUDONYM_PREFIX, so all three emit one vocabulary.

View Source
const ModeSharedNote = "Either way, the same detail always maps to the same replacement for the " +
	"whole conversation, and the real values are restored in the reply on your device."

ModeSharedNote is shown ONCE, under both modes. Never uses the word "continuity".

Variables

View Source
var (
	ErrReviewRequired = errors.New("cloakapi: request requires explicit review approval; no request was sent")
	ErrReviewRejected = errors.New("cloakapi: request review was not approved; no request was sent")
)
View Source
var CLKDisclosureText = mustLockDisclosure("clk.txt", clkDisclosureRaw, clkSHA256)

CLKDisclosureText is the byte-locked disclosure for the clk (browser WASM / gateway) lane, CONVERSATION-scoped. len 3054 runes, sha256 e7684324….

View Source
var CLKDisclosureTextMessageScoped = mustDeriveDisclosure(
	"clk_message.txt", clkMessageDisclosureRaw, clkMessageSHA256, CLKDisclosureText)

CLKDisclosureTextMessageScoped is the clk disclosure with the continuity claim NARROWED to this message. sha256 770b44de….

View Source
var CloakAngleDisclosureText = mustLockDisclosure("cloak_angle.txt", cloakAngleDisclosureRaw, cloakAngleSHA256)

CloakAngleDisclosureText is the byte-locked disclosure for the cloak-angle (FFI / portal / extension / proxy) lane — the format THIS SDK's <<CLOAK:TYPE:ID>> tokens use — CONVERSATION-scoped. len 4212 runes, sha256 fd4ace75….

View Source
var CloakAngleDisclosureTextMessageScoped = mustDeriveDisclosure(
	"cloak_angle_message.txt", cloakAngleMessageDisclosureRaw, cloakAngleMessageSHA256, CloakAngleDisclosureText)

CloakAngleDisclosureTextMessageScoped is the cloak-angle disclosure with the continuity claim NARROWED to this message. sha256 a7bfc5e2….

View Source
var ContinuitySentence = map[SurrogateContinuity]string{
	ContinuityConversation:  "They are stable within this conversation.",
	ContinuitySingleMessage: "They are stable within this message.",
}

ContinuitySentence is the one sentence that differs between the two scopes. Byte-identical to the TS reference's CONTINUITY_SENTENCE map.

View Source
var LegacySurrogateModeAliases = map[string]SurrogateMode{
	"continuity": SurrogateModeBalanced,
	"off":        SurrogateModeBalanced,
	"plaintext":  SurrogateModeBalanced,
	"none":       SurrogateModeBalanced,
	"disabled":   SurrogateModeBalanced,
	"realistic":  SurrogateModeBalanced,
	"token":      SurrogateModeMax,
	"opaque":     SurrogateModeMax,
	"strict":     SurrogateModeMax,
}

LegacySurrogateModeAliases are mode values that once existed and may still be sitting in a consumer's config, a saved profile, or an old API request. Every one of them resolves to a PROTECTED mode — never to plaintext.

"continuity"  → balanced (its behaviour is now unconditional in both modes)
"off"         → balanced (there has never been, and will never be, a
"plaintext"   →           plaintext posture; the gateway is Level-1-only)
"none"        →
"disabled"    →
"realistic"   → balanced
"token"       → max      (the internal name the client-tier benchmark used)
"opaque"      → max
"strict"      → max
View Source
var ModeCopy = map[SurrogateMode]SurrogateModeCopy{
	SurrogateModeBalanced: {
		Label: "Balanced",
		Short: "Realistic stand-ins — John Mellows becomes Henry Caulinger.",
		Tradeoff: "The model cannot tell the stand-ins are fake, so it may reason about them as if " +
			"they were real — drawing conclusions from a substituted name, or treating a substituted " +
			"address as a genuine place.",
	},
	SurrogateModeMax: {
		Label: "Max",
		Short: "Opaque placeholders — John Mellows becomes <<CLOAK:PERSON:1>>.",
		Tradeoff: "The model can see the value is hidden, so it may write awkwardly around the " +
			"placeholder, ask you for the real value, or decline to continue.",
	},
}

ModeCopy is the verbatim trade-off copy from the binding spec §1.

View Source
var PrivacyTiers = []string{TierBalanced, TierMax}

PrivacyTiers are the valid Level-1 privacy tiers (no plaintext relay).

View Source
var SurrogateContinuities = []SurrogateContinuity{ContinuityConversation, ContinuitySingleMessage}

SurrogateContinuities is the canonical list of continuity scopes.

View Source
var SurrogateModes = []SurrogateMode{SurrogateModeBalanced, SurrogateModeMax}

SurrogateModes is the canonical list — also the picker order (safest, least-disruptive default first).

Functions

func Canonicalise

func Canonicalise(v any) ([]byte, error)

Canonicalise produces RFC-8785 JCS-canonical UTF-8 bytes from a decoded-JSON value (map[string]any / []any / json.Number / string / bool / nil).

func DisclosureText

func DisclosureText(format MarkerFormat, continuity SurrogateContinuity) string

DisclosureText returns the byte-locked disclosure text for a marker format and a continuity SCOPE.

LOCK #2 (spec §2b): `continuity` is a REQUIRED POSITIONAL PARAMETER, not an option with a default. This function renders nothing itself and runs no engine — it cannot observe how stable the accompanying bytes actually are — so a default here would mean "when in doubt, make the STRONGEST claim". Omitting the argument is a compile error (`not enough arguments in call`); passing the zero value SurrogateContinuity("") NARROWS to single-message rather than widening (CoerceSurrogateContinuity), so no accident can ever produce the conversation claim.

Pass result.SurrogateMode().Continuity() straight off the tokenise result that produced those bytes.

Format defaults to clk to match the cross-language withDisclosure contract; callers on the FFI <<CLOAK:…>> lane should pass MarkerCloakAngle.

func EndUserHeaderValue

func EndUserHeaderValue(raw, secret string) string

EndUserHeaderValue is the single place that decides what X-Cloak-End-User carries. EXPORTED so a builder can derive the same token their own systems must join against — mirrors the TypeScript SDK, which exports pseudonymiseEndUser/looksLikeEndUserPii for the same reason. ⛔ KOMITÉ-ORDRE 10 §Q45 (sak 181) — TOKENISE, NEVER REFUSE.

The four relay call sites (chat, messages and two streaming paths) used to call sanitizeEndUser DIRECTLY, which returned "" for anything not already opaque-shaped: a SILENT DROP, client-side, with the builder none the wiser — they see a 200 and believe their attribution works. Worse, the opaque charset [A-Za-z0-9._:-] only stops values containing "@", so an SSN, a phone number, a payment card, an IBAN and an ABA routing number all passed it and went RAW onto the wire.

Now, exactly as the TypeScript SDK does: a shape-valid, non-PII-shaped token is sent EXACTLY as supplied (the builder's own id — every join against their own systems keeps working); anything else — PII-shaped or malformed — is TOKENISED here, before the value touches the network.

The call is NEVER refused. Only an absent/empty value returns "", because there is nothing to attribute.

func IsSurrogateContinuity

func IsSurrogateContinuity(c SurrogateContinuity) bool

IsSurrogateContinuity reports whether c is one of the two real scopes. The zero value SurrogateContinuity("") is NOT one of them — that is the whole point (see CoerceSurrogateContinuity for the total variant).

func IsSurrogateMode

func IsSurrogateMode(raw any) bool

IsSurrogateMode reports whether raw is one of the two real modes. It accepts `any` so a value read off a wire/config can be tested without a type assertion at every call site.

func IsTokenisationSuspended

func IsTokenisationSuspended(err error) bool

IsTokenisationSuspended returns true when the error indicates break-glass mode is active for the tenant (HTTP 503, code = tokenisation_suspended).

func LooksLikeEndUserPii

func LooksLikeEndUserPii(value string) bool

LooksLikeEndUserPii is the ADR-0015 / §Q45 structured-PII SHAPE check over a single end-user identifier, run CLIENT-SIDE, BEFORE the value is put on the wire. Family-for-family identical to the TypeScript SDK's looksLikeEndUserPii and the gateway's UsageAttributionGuard::looksLikePii (card / IBAN / ABA / national-id / phone / BIC), plus EMAIL — which the server-side guard documents as out of scope because "@" cannot survive the opaque charset. True on the wire; not here, where the SDK still sees the value.

func NormaliseTier

func NormaliseTier(t string) string

NormaliseTier maps any accepted tier literal onto one of PrivacyTiers. Retired literals migrate; unknown literals come back unchanged so the caller's own validation still rejects them.

func PseudonymiseEndUser

func PseudonymiseEndUser(raw, secret string) string

PseudonymiseEndUser derives the opaque token that REPLACES a PII-shaped (or malformed) end-user id before it is sent. HMAC-SHA256 under a caller-held secret, 128 bits of hex, "cloak_eu_"-prefixed — byte-identical to the TypeScript SDK's pseudonymiseEndUser and the gateway's StableEndUserPseudonym, so one end user reads as one vocabulary on every side of the wire.

⛔ HMAC, not a hash: sha256(email) is stable AND reversible with a wordlist. The secret is the caller's own API key, which CloakAPI does not hold in plaintext, so the derived token is not reversible by us either. Rotating the key rotates the pseudonym; set Config.EndUserSecret to pin it.

func ReceiptHash

func ReceiptHash(receipt any) (string, error)

ReceiptHash returns the lowercase hex SHA-256 of the JCS-canonical receipt (including sig).

func SignDeviceReceipt

func SignDeviceReceipt(opts SignReceiptOptions) (map[string]any, error)

SignDeviceReceipt signs a CONTENT-FREE v3 device receipt ON-DEVICE (ECDSA P-256 + JCS). The receipt is self-contained and OFFLINE-verifiable by VerifyDeviceReceipt (the public key is embedded in the signed bytes). It attests to HASHES + COUNTS + LABELS only — never any text.

FAIL-CLOSED: returns *DeviceReceiptError if key generation or signing fails — treat that as "no receipt, do not claim proof".

func Version

func Version() string

Version returns the SDK package semver, so a consumer can prove AT RUNTIME which artifact it is actually running. It is the exact string sent in the User-Agent and X-CloakAPI-SDK headers.

Types

type APIError

type APIError struct {
	StatusCode int      `json:"-"`
	Message    string   `json:"-"`
	Code       string   `json:"-"`
	Type       string   `json:"-"`
	RetryAfter *float64 `json:"-"`
}

APIError is returned when the CloakAPI gateway responds with a 4xx or 5xx status code.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Format

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

type Approved

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

Approved is a Prepared request the application has approved.

type ChainVerifyResult

type ChainVerifyResult struct {
	ChainOK         bool
	EntriesVerified int
	// BreakIndex is the 0-based index of the first inconsistent entry, or -1 when
	// the chain is intact.
	BreakIndex int
}

ChainVerifyResult is the outcome of a local receipt-chain integrity walk.

func VerifyChainLinks(entries []map[string]any) ChainVerifyResult

VerifyChainLinks walks an ordered receipt-chain export and verifies structural integrity WITHOUT any network call:

  • entries[i].prev_hash == entries[i-1].canonical_sha256 for i > 0
  • entries[i].seq == i (dense, monotonic from 0)

entries are the decoded chain-export entries (map[string]any each).

type ChatChoice

type ChatChoice struct {
	Index        int         `json:"index"`
	Message      ChatMessage `json:"message"`
	FinishReason string      `json:"finish_reason"`
}

ChatChoice is one choice in a chat completion response.

type ChatCompletionsRequest

type ChatCompletionsRequest struct {
	Model       string        `json:"model"`
	Messages    []ChatMessage `json:"messages"`
	MaxTokens   int           `json:"max_tokens,omitempty"`
	Temperature float64       `json:"temperature,omitempty"`
	Stream      bool          `json:"stream,omitempty"`

	// EndUser is an OPTIONAL opaque pseudonymous end-user id (ADR-0015). Sent as
	// the X-Cloak-End-User header, NEVER in the body (json:"-"). Pass your OWN
	// opaque token — never real PII; the gateway drops PII-shaped values.
	EndUser string `json:"-"`
}

ChatCompletionsRequest is the POST body for /api/v1/chat/completions.

func WithDisclosureChat

WithDisclosureChat is WithDisclosure for an OpenAI-format ChatCompletionsRequest: it prepends the format-correct disclosure as a leading system message (idempotent, fail-safe). OpenAI bodies carry the system prompt as a messages[] entry (no separate System field). LOCK #2 applies here too — see WithDisclosure.

type ChatCompletionsResponse

type ChatCompletionsResponse struct {
	ID      string       `json:"id"`
	Object  string       `json:"object"`
	Created int64        `json:"created"`
	Model   string       `json:"model"`
	Choices []ChatChoice `json:"choices"`
	Usage   struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`

	// Coverage is the detection that ran on the request this reply answers.
	// Set by the SDK; not part of the gateway's JSON.
	Coverage Coverage `json:"-"`
	// Warnings are the notices that applied to that request. Set by the SDK.
	Warnings []SendWarning `json:"-"`
}

ChatCompletionsResponse is the response shape from /api/v1/chat/completions.

func (*ChatCompletionsResponse) FirstContent

func (r *ChatCompletionsResponse) FirstContent() string

FirstContent returns the content of the first choice message, or an empty string if no choices are present.

type ChatMessage

type ChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

ChatMessage is a single turn in an OpenAI-format conversation.

type ChatResource

type ChatResource struct {
	Completions *CompletionsResource
	// contains filtered or unexported fields
}

ChatResource wraps the /api/v1/chat/completions endpoint (OpenAI format).

type Client

type Client struct {

	// Resource namespaces — same layout as Python / TypeScript SDKs.
	Messages    *MessagesResource
	Chat        *ChatResource
	Models      *ModelsResource
	Tokens      *TokensResource
	Receipts    *ReceiptsResource
	Reconstruct *ReconstructResource
	// contains filtered or unexported fields
}

Client is the CloakAPI SDK entry point. Create one per application lifetime. Client is safe for concurrent use by multiple goroutines.

func NewClient

func NewClient(apiKey string, cfg *Config) *Client

NewClient creates a new CloakAPI client.

apiKey may be empty to fall back to the CLOAKAPI_API_KEY environment variable.
cfg may be nil to use all defaults.

func (*Client) Approve

func (c *Client) Approve(prepared *Prepared) *Approved

Approve records the application's approval of prepared. It does not send. A nil prepared, or one from another client, gives an Approved that Send refuses with ErrReviewRequired.

func (Client) GoString

func (c Client) GoString() string

GoString keeps %#v safe as well as the default fmt string formats.

func (*Client) Posture

func (c *Client) Posture() PrivacyPosture

Posture returns this client's privacy posture (reads the process engine identity). Honest + content-free — safe to render in a status badge. Reports all available Level-1 tiers; the client's selected tier is c.Tier().

func (Client) String

func (c Client) String() string

String returns a safe debug representation of the client. The API key is deliberately omitted so formatting a client cannot expose credentials.

func (*Client) SurrogateMode

func (c *Client) SurrogateMode() SurrogateMode

SurrogateMode returns the substitution style this client sends to the shared engine as opts.mode ("balanced" | "max"). Never empty.

func (*Client) Tier

func (c *Client) Tier() string

Tier returns the client's active Level-1 privacy tier (the value sent as X-CloakAPI-Privacy-Tier on every relay).

func (*Client) Tokenise

func (c *Client) Tokenise(text string) (TokeniseResult, error)

Tokenise tokenises a single string on-device and returns the locked TokeniseResult. The replacement→original pairs are merged into this client's session detokenise table, and the conversation ledger is advanced, so the same real value keeps the same stand-in on every later turn (in BOTH modes).

func (*Client) TokenizeFile

func (c *Client) TokenizeFile(data []byte, opts FileOptions) (FileResult, error)

TokenizeFile tokenises a FILE or IMAGE ENTIRELY on-device and returns the tokenised text plus the local token map (already merged into this client's session map so a subsequent reply auto-detokenises).

Images (PNG/JPEG/WebP/GIF/BMP/TIFF) are OCR'd on-device; PDF/DOCX/XLSX/PPTX/ CSV/HTML/… are extracted and tokenised — the engine's one file-pipeline decides by MIME (no client-side allowlist blocks image types). The RAW bytes NEVER leave this machine: only FileResult.Text (tokenised Markdown) is meant to egress, and you relay it through the normal messages/chat path, e.g.:

res, err := client.TokenizeFile(imgBytes, cloakapi.FileOptions{Mime: "image/png"})
if err != nil { return err } // FAIL-CLOSED: nothing was sent
// Construct client with Config.Review to inspect and approve the exact body.
reply, err := client.Messages.Create(ctx, cloakapi.MessagesRequest{
    Model:    "claude-sonnet-4-6",
    Messages: []cloakapi.Message{{Role: "user", Content: res.Text}},
})
// reply is auto-detokenised via the session map TokenizeFile merged in.

FAIL-CLOSED: if the client-side engine (libcloak_engine) is unavailable this returns an error and NEVER sends the raw file/image — the core product invariant (the gateway must never receive raw file bytes). It also returns an error if the engine refuses a file (encrypted/unsupported/undecodable). In EVERY error case, nothing has egressed.

type CompletionsResource

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

CompletionsResource handles POST /api/v1/chat/completions.

func (*CompletionsResource) Create

Create sends a POST /api/v1/chat/completions request after the client's Review callback approves the exact serialized body. The reply carries the Coverage that ran and the Warnings that applied.

func (*CompletionsResource) CreateStream

func (cr *CompletionsResource) CreateStream(ctx context.Context, req ChatCompletionsRequest, handler StreamHandler) error

CreateStream sends a STREAMING POST /api/v1/chat/completions (OpenAI) and invokes handler for each on-device-detokenised event after the Review callback approves the exact request body.

func (*CompletionsResource) Prepare

Prepare is the first step of the step form for chat completions. See MessagesResource.Prepare.

func (*CompletionsResource) Send

Send is the last step of the step form for chat completions. See MessagesResource.Send.

type Config

type Config struct {
	// BaseURL overrides the default gateway URL (https://api.cloakapi.io).
	BaseURL string
	// Timeout overrides the default HTTP timeout (120 s).
	Timeout time.Duration
	// MaxRetries overrides the default retry count (3).
	MaxRetries int
	// HTTPClient allows injecting a custom *http.Client (e.g., for tests).
	HTTPClient *http.Client
	// Review approves one fully prepared request. It receives the exact outgoing
	// body (EgressRequest.Body) and how it was checked (EgressRequest.Info: state,
	// coverage, warnings). Show the body, then return true only after approval.
	// A nil Review, or one that returns false, means nothing is sent
	// (ErrReviewRequired / ErrReviewRejected). A server-side program that has
	// its own controls may approve without showing anything:
	//
	//	Review: func(cloakapi.EgressRequest) bool { return true }
	//
	// The step form (Messages.Prepare, Client.Approve, Messages.Send) does the
	// same without a callback.
	Review func(EgressRequest) bool
	// StrictReducedCoverage refuses text tokenisation when only the rules-based
	// lane is available. The default warns and continues with detected values.
	StrictReducedCoverage bool
	// Tokenize is DEPRECATED and ignored: client-side Level-1 PII tokenisation is
	// now ALWAYS ON (DECISIONS.md — Level-1-only, no plaintext relay). The
	// fail-closed gateway rejects any non-pre-tokenised relay, so raw-by-default
	// is neither offered nor sendable. Retained only for source compatibility.
	Tokenize bool
	// Routing enables §12b/P4a CLIENT-SIDE arbitrage routing. When set, the SDK
	// classifies the prompt + picks provider/model ON THIS MACHINE (the gateway
	// never inspects content), declares the choice via X-CloakAPI-Routing: client,
	// and consumes the §52d versioned catalogue for dead-model safety. Nil keeps
	// the classic behaviour (the gateway relays the declared model, no
	// classification). DefaultProvider is used as the declared provider.
	Routing *routing.Options
	// DefaultProvider is the provider declared to the gateway when routing is off
	// (or as the passthrough baseline). Empty = "anthropic".
	DefaultProvider string
	// AppID is the ADR-0015 ecosystem attribution app/site slug sent as
	// X-Cloak-App-Id on every relay call. Empty falls back to the CLOAK_APP_ID
	// env var; an invalid/empty value omits the header (builder-account-level
	// attribution). Slug shape: ≤64 [a-z0-9._-] (lower-cased).
	AppID string
	// EndUserSecret is the §Q45 HMAC secret for client-side end-user
	// tokenisation. Empty uses the API key, which means ROTATING THE KEY ROTATES
	// THE PSEUDONYM; set this to pin one end user to one token across rotations.
	// Must hold the SAME value in the other SDKs for a cross-language join to
	// line up.
	EndUserSecret string
	// Tier is the Level-1 privacy tier declared to the gateway as
	// X-CloakAPI-Privacy-Tier on every relay: "balanced" (default) | "max".
	// continuity is RETIRED AS A CHOICE (DECISION 11): it is always-on in BOTH
	// tiers and never named. A legacy stored "continuity" is still ACCEPTED and
	// migrates to "balanced" via NormaliseTier. There is NO plaintext tier — "off"/"plaintext" (or any other value)
	// PANICS at construction (Level-1-only, fail-closed), mirroring the TS SDK.
	Tier string
	// SurrogateMode selects the SUBSTITUTION STYLE (DECISIONS.md Decision 11):
	// "balanced" (realistic stand-ins — DEFAULT) or "max" (opaque
	// <<CLOAK:TYPE:ID>> placeholders). It is passed to the SHARED FFI engine as
	// opts.mode; this SDK ports no surrogate generator.
	//
	// A MODE SELECTS STYLE ONLY — it NEVER gates whether tokenisation happens.
	// Both modes run the identical detectors on the identical spans and differ
	// only in the replacement string written into each already-detected span.
	//
	// An unrecognised literal here is a BUG IN LIVE CODE and PANICS at
	// construction (same discipline as Tier / BaseURL). Values that came out of
	// storage should be passed through CoerceSurrogateMode first, which migrates
	// every legacy value ("continuity", "off", "plaintext", …) to a PROTECTED
	// mode. Empty = balanced.
	SurrogateMode string
	// SeedHex is the C21b continuity seed threaded to the engine for cross-session
	// STABLE stand-ins (same original → same surrogate id across sessions). Empty =
	// per-session ids. Forward-safe: an engine that predates the key ignores it.
	SeedHex string
	// Disclose, when true, auto-injects the byte-locked cloak-disclosure (C7) as a
	// leading system message on every relay BEFORE the pretokenised MAC (so it is
	// client-authored + MAC-covered). Idempotent + fail-safe. Defaults to the
	// cloak-angle format (the <<CLOAK:…>> lane this SDK emits); override with
	// DisclosureFormat.
	Disclose bool
	// DisclosureFormat selects the disclosure marker format when Disclose is on
	// (MarkerCLK | MarkerCloakAngle). Empty defaults to MarkerCloakAngle.
	DisclosureFormat MarkerFormat
}

Config holds optional client configuration.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

ContentBlock is a single block in the Anthropic response content array.

type Coverage

type Coverage string

Coverage says which detection ran on the text of one request.

const (
	// CoverageFull: the on-device engine with its name model.
	CoverageFull Coverage = "full"
	// CoverageRulesAndNames: the engine's rules and its built-in name list.
	CoverageRulesAndNames Coverage = "rules_and_names"
	// CoverageRulesOnly: structured rules (emails, phone numbers, cards, IDs,
	// addresses, keys). Names are usually not detected.
	CoverageRulesOnly Coverage = "rules_only"
)

type DeviceKeyPair

type DeviceKeyPair struct {
	Private *ecdsa.PrivateKey
}

DeviceKeyPair is an ECDSA P-256 key pair for device-receipt signing. Its public point is embedded in each receipt, so a receipt self-verifies via its own key.

func GenerateDeviceKeyPair

func GenerateDeviceKeyPair() (*DeviceKeyPair, error)

GenerateDeviceKeyPair generates a fresh ECDSA P-256 key pair. Exposed so a caller can persist a stable device identity across receipts; by default SignDeviceReceipt mints an ephemeral key per receipt.

func (*DeviceKeyPair) PublicPointHex

func (kp *DeviceKeyPair) PublicPointHex() string

PublicPointHex returns the uncompressed public point (0x04‖X‖Y, 130 hex).

type DeviceReceiptError

type DeviceReceiptError struct{ Msg string }

DeviceReceiptError is the fail-closed signal from the on-device receipt signer: crypto unavailable or signing failed. The caller MUST treat it as "no receipt, do not claim proof".

func (*DeviceReceiptError) Error

func (e *DeviceReceiptError) Error() string

func (*DeviceReceiptError) Format

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

type DisclosureOptions

type DisclosureOptions struct {
	// Format is the disclosure marker format to inject. Defaults to clk (the
	// cross-language contract default) when empty.
	Format MarkerFormat
	// DetectFrom, when non-empty, auto-selects the format from a tokenised sample
	// (overrides Format when a marker is detected).
	DetectFrom string
}

DisclosureOptions configures WithDisclosure.

type EgressRequest

type EgressRequest struct {
	Method  string
	URL     string
	Headers http.Header
	// Body is the exact outgoing body: the text to show the reviewer.
	Body []byte
	// Info says how Body was checked: State (ok or degraded), Coverage, and the
	// Warnings that apply. A warning never stops the request.
	Info ReviewInfo
}

EgressRequest is the exact HTTP request snapshot presented for approval. Body and Headers are copies; mutating them does not change the request sent.

func (EgressRequest) Text

func (r EgressRequest) Text() string

Text returns the exact outgoing body as a string.

type ErrSurrogateModeUnavailable

type ErrSurrogateModeUnavailable struct {
	Requested SurrogateMode
	Available SurrogateMode
	Reason    string
}

ErrSurrogateModeUnavailable is returned when the caller EXPLICITLY selected a surrogate mode that the available tokeniser cannot apply — e.g. balanced was requested but only the pure-regex fallback exists, which can only emit opaque tokens. Failing loud here is the point: silently downgrading and then REPORTING the requested mode is the defect this whole task eliminates.

func (*ErrSurrogateModeUnavailable) Error

func (*ErrSurrogateModeUnavailable) Format

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

type FileOptions

type FileOptions struct {
	// Mime is a best-effort content-type hint (e.g. "image/png",
	// "application/pdf", "application/vnd.openxmlformats-officedocument.
	// wordprocessingml.document"). Empty / "application/octet-stream" defers to
	// Filename's extension and then a magic-byte sniff.
	Mime string
	// Filename sharpens type resolution — DOCX/XLSX/PPTX share ZIP magic, so the
	// extension disambiguates them.
	Filename string
	// Names are externally-detected PERSON spans folded into tokenisation on top
	// of the engine's built-in name list / optional on-device NER.
	Names []string
}

FileOptions configures Client.TokenizeFile. Provide at least one of Mime or Filename so the engine can resolve the document type (it also falls back to a magic-byte sniff). Names lets you fold in externally-known PERSON spans.

type FileResult

type FileResult struct {
	// Text is the tokenised Markdown — the ONLY field meant to leave the machine.
	// Feed it into Messages.Create / Chat.Completions.Create as normal message
	// content; it rides the SAME pre-tokenised-MAC + engine-identity relay path
	// as text. The gateway only ever sees the stand-ins: realistic values in the
	// default balanced mode, opaque <<CLOAK:…>> placeholders in max mode.
	Text string
	// TokenMap is a snapshot of the client's session token map AFTER this file's
	// token↔original pairs were merged in (full-token -> original), so a later
	// reply auto-detokenises. It is LOCAL — never send it anywhere.
	TokenMap map[string]string
	// Categories are the labels of the <<CLOAK:LABEL:…>> placeholders in Text
	// (sorted, de-duped), e.g. ["CONTACT_EM","CONTACT_PH","PERSON"]. Only max
	// mode writes such placeholders; in the default balanced mode Text holds
	// realistic stand-ins and this list is empty.
	Categories []string
	// Meta is the engine's file-pipeline metadata — an honest record of what ran
	// on-device: mime, extractor, pii_count, needs_ocr, chars, engine_version.
	Meta map[string]any
	// contains filtered or unexported fields
}

FileResult is the outcome of Client.TokenizeFile.

func (FileResult) SurrogateMode

func (r FileResult) SurrogateMode() SurrogateModeReport

SurrogateMode is what the tokenise pass that produced this result ACTUALLY did — the mode applied and the scope over which the stand-ins are stable. Feed .Continuity() straight into WithDisclosure.

func (FileResult) Validate

func (r FileResult) Validate() error

Validate rejects a FileResult that carries no surrogate-mode report.

type MarkerFormat

type MarkerFormat string

MarkerFormat selects which byte-locked disclosure text is used.

const (
	// MarkerCLK is the browser-WASM / gateway [CLK-…] lane (the default, matching
	// the cross-language withDisclosure contract).
	MarkerCLK MarkerFormat = "clk"
	// MarkerCloakAngle is the FFI <<CLOAK:TYPE:ID>> lane this SDK's engine emits.
	MarkerCloakAngle MarkerFormat = "cloak-angle"
)

func DetectMarkerFormat

func DetectMarkerFormat(sample string) MarkerFormat

DetectMarkerFormat best-effort detects which marker format a tokenised sample uses: <<CLOAK:...>> or [TOKEN_...] → cloak-angle; [CLK-TAG-...] → clk; no marker → "" (empty).

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message is a single turn in an Anthropic-format conversation. There is no tool-call argument object and no tool name field: Content is a string, so tool names and tool-argument keys are not rewritten here.

type MessagesRequest

type MessagesRequest struct {
	Model     string            `json:"model"`
	Messages  []Message         `json:"messages"`
	MaxTokens int               `json:"max_tokens,omitempty"`
	System    string            `json:"system,omitempty"`
	Stream    bool              `json:"stream,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`

	// EndUser is an OPTIONAL opaque pseudonymous end-user id (ADR-0015). Sent as
	// the X-Cloak-End-User header, NEVER in the body (json:"-"). Pass your OWN
	// opaque token — never real PII; the gateway drops PII-shaped values.
	EndUser string `json:"-"`
}

MessagesRequest is the POST body for /api/v1/messages.

func WithDisclosure

func WithDisclosure(req MessagesRequest, continuity SurrogateContinuity, opts *DisclosureOptions) MessagesRequest

WithDisclosure prepends the format-correct cloak-disclosure as a leading system message onto an Anthropic-format MessagesRequest.

  • IDEMPOTENT — never doubles an existing disclosure (checks messages[0] and a string System field).
  • FAIL-SAFE — never panics; returns a request with the disclosure applied, leaving the input request untouched (returns a shallow copy).

For a request with a non-empty string System, the disclosure is merged onto the FRONT of System (message count unchanged); otherwise a leading system message is prepended to Messages. Applied BEFORE the pretokenised MAC so the disclosure is client-authored and MAC-covered (C6 step 2) — the relay path does this automatically when Disclose is enabled. LOCK #2 (spec §2b) — `continuity` is a REQUIRED POSITIONAL PARAMETER. This function takes ALREADY-TOKENISED bytes and prepends a disclosure that makes a CLAIM ABOUT THEM ("the stand-ins you are about to see are stable within …"). It runs no engine and cannot observe how stable they actually are, so an optional parameter would mean "defaults to the strongest claim". Pass result.SurrogateMode().Continuity().

type MessagesResource

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

MessagesResource wraps the /api/v1/messages endpoint (Anthropic format).

func (*MessagesResource) Create

Create sends a POST /api/v1/messages request.

Personal data in message content is replaced on this device before sending and restored in the returned response. The client's Review callback must approve the exact serialized request body before the MAC or relay request. The reply carries the Coverage that ran and the Warnings that applied.

func (*MessagesResource) CreateStream

func (mr *MessagesResource) CreateStream(ctx context.Context, req MessagesRequest, handler StreamHandler) error

CreateStream sends a STREAMING POST /api/v1/messages (Anthropic) and invokes handler for each on-device-detokenised event. Outbound content is tokenised first (engine-first, fail-closed) exactly like the non-streaming path. The client's Review callback must approve the exact request body before transport.

func (*MessagesResource) Prepare

func (mr *MessagesResource) Prepare(ctx context.Context, req MessagesRequest) (*Prepared, error)

Prepare is the first step of the step form: it replaces personal data in req on this device and returns the exact outgoing body with its coverage and warnings. Nothing is sent. Show Prepared.Text() to whoever approves, call Client.Approve, then Send.

func (*MessagesResource) Send

func (mr *MessagesResource) Send(ctx context.Context, approved *Approved) (*MessagesResponse, error)

Send is the last step of the step form: it sends a request that was prepared by Prepare and approved by Client.Approve, byte for byte, and returns the reply with the original values restored. Anything else is ErrReviewRequired.

type MessagesResponse

type MessagesResponse struct {
	ID      string         `json:"id"`
	Type    string         `json:"type"`
	Role    string         `json:"role"`
	Content []ContentBlock `json:"content"`
	Model   string         `json:"model"`
	Usage   struct {
		InputTokens  int `json:"input_tokens"`
		OutputTokens int `json:"output_tokens"`
	} `json:"usage"`

	// Coverage is the detection that ran on the request this reply answers.
	// Set by the SDK; not part of the gateway's JSON.
	Coverage Coverage `json:"-"`
	// Warnings are the notices that applied to that request (reduced coverage,
	// content that could not be checked). Set by the SDK.
	Warnings []SendWarning `json:"-"`
}

MessagesResponse is the response shape from /api/v1/messages.

func (*MessagesResponse) FirstText

func (r *MessagesResponse) FirstText() string

FirstText returns the text of the first text content block, or an empty string if no text block is present.

type ModelInfo

type ModelInfo struct {
	ID      string         `json:"id"`
	Object  string         `json:"object"`
	OwnedBy string         `json:"owned_by"`
	Created int64          `json:"created"`
	Raw     map[string]any `json:"-"`
}

ModelInfo is one entry in the live model catalogue (OpenAI /models shape). Extra provider-specific fields are preserved in Raw.

type ModelsResource

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

ModelsResource is the live model-discovery surface (C11) — GET /api/v1/models. Distinct from the client-side routing catalogue (C19, cloakapi/routing): this is the gateway's authoritative, live list of models the tenant may relay to.

TS reference: src/resources/models.ts:9. Python reference: sdk/python/cloakapi/resources/models.py.

func (*ModelsResource) List

func (r *ModelsResource) List(ctx context.Context) ([]ModelInfo, error)

List returns the LIVE model catalogue the gateway exposes.

func (*ModelsResource) Retrieve

func (r *ModelsResource) Retrieve(ctx context.Context, modelID string) (*ModelInfo, error)

Retrieve finds one model by id in the live catalogue, or returns nil when absent (no error).

type PostureOptions

type PostureOptions struct {
	// Identity is an explicit {version, hash}; when nil the process engine
	// identity is read (the only branch that may touch the engine).
	Version     string
	Hash        string
	HasIdentity bool

	EnhancedGazetteer bool
	ModelTierLoaded   bool
	MarkerFormat      MarkerFormat
	Tiers             []string
}

PostureOptions tunes PrivacyPostureOf without touching the engine.

type Prepared

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

Prepared is one request after on-device replacement and before sending.

func (*Prepared) Coverage

func (p *Prepared) Coverage() Coverage

Coverage is the detection that ran on this request.

func (*Prepared) Info

func (p *Prepared) Info() ReviewInfo

Info is State, Coverage and Warnings in one value: the same ReviewInfo the Config.Review callback receives.

func (*Prepared) State

func (p *Prepared) State() string

State is StateOK, or StateDegraded when a warning applies.

func (*Prepared) Text

func (p *Prepared) Text() string

Text is the exact outgoing request body. This is what to show the reviewer.

func (*Prepared) Warnings

func (p *Prepared) Warnings() []SendWarning

Warnings lists what the reviewer should know before approving.

type PretokenisedMacError

type PretokenisedMacError struct {
	// Err is the underlying cause (an *APIError from the /mac endpoint, a
	// transport error, or a sentinel for a missing `mac` field).
	Err error `json:"-"`
}

PretokenisedMacError is returned when the SDK could not obtain the per-body pre-tokenised passthrough MAC from POST /api/v1/pretokenised/mac (network error, non-2xx, or a missing/empty `mac` field). Under the Level-1-only strict gateway the relay is fail-loud: without a valid X-Cloak-Client-MAC the gateway would reject the call, so the SDK refuses to relay rather than send raw/unproven — there is deliberately NO no-MAC fallback. Mirrors the Python PretokenisedMacError / TypeScript `pretokenised_mac_unavailable`.

func (*PretokenisedMacError) Error

func (e *PretokenisedMacError) Error() string

func (*PretokenisedMacError) Format

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

func (*PretokenisedMacError) Unwrap

func (e *PretokenisedMacError) Unwrap() error

Unwrap deliberately returns a content-free sentinel. MAC failures may carry request or upstream text in their underlying error, and exposing that error would let callers leak it through errors.Unwrap or errors.Is/As traversal.

type PrivacyPosture

type PrivacyPosture struct {
	// EngineVersion is the ruleset semver (X-Cloak-Engine-Version).
	EngineVersion string
	// EngineHash is the SHA-256 of the engine binary that ran
	// (X-Cloak-Engine-Hash provenance); "" when only the pure-regex fallback ran.
	EngineHash string
	// Genuine is true when a real engine binary ran (non-empty hash).
	Genuine bool
	// FailClosed means there is no plaintext relay path. Text may continue on the
	// rules-only lane with an explicit warning; file/image tokenisation still
	// errors when the native engine is absent.
	FailClosed bool
	// Tiers are the privacy tiers available (Level-1 only).
	Tiers []string
	// Detectors are the detector layers active, most-fundamental first.
	Detectors []string
	// ModelTierLoaded reports whether a heavy on-device transformer NER model is
	// loaded.
	ModelTierLoaded bool
	// MarkerFormat is the marker format this engine produces (drives
	// auto-disclosure) — cloak-angle for the FFI lane.
	MarkerFormat MarkerFormat
}

PrivacyPosture is the privacy posture of a CloakAPI integration. Content-free, honest.

func PrivacyPostureOf

func PrivacyPostureOf(opts PostureOptions) PrivacyPosture

PrivacyPostureOf builds the privacy posture from an engine identity. When opts.HasIdentity is false it reads the process engine identity via engine.Identity() (the only branch that touches the engine).

type ReceiptListParams

type ReceiptListParams struct {
	Page     int
	PerPage  int
	Provider string
	ChainID  string
	Surface  string
}

ReceiptListParams filters the unified receipt ledger.

type ReceiptsResource

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

ReceiptsResource is the receipts verifiable-trust surface (C10).

func (*ReceiptsResource) ChainExport

func (r *ReceiptsResource) ChainExport(ctx context.Context, chainID string) (map[string]any, error)

ChainExport returns the ordered, gateway-signed manifest of the caller's receipt chain.

func (*ReceiptsResource) ChainVerify

func (r *ReceiptsResource) ChainVerify(ctx context.Context, chainID string) (ChainVerifyResult, error)

ChainVerify exports the chain and verifies its integrity LOCALLY (prev_hash links + dense seq) with no trust in the server (C9 chain walk).

func (*ReceiptsResource) Get

func (r *ReceiptsResource) Get(ctx context.Context, jti string) (map[string]any, error)

Get fetches a receipt record by JTI from the authenticated, key-scoped ledger.

func (*ReceiptsResource) List

func (r *ReceiptsResource) List(ctx context.Context, params ReceiptListParams) (map[string]any, error)

List returns the unified, per-user receipt ledger across every surface (chat / api / extension / desktop-local).

func (*ReceiptsResource) UnsafeRawCountersign

func (r *ReceiptsResource) UnsafeRawCountersign(ctx context.Context, payload map[string]any) (map[string]any, error)

UnsafeRawCountersign submits arbitrary caller-provided payload data. It is retained for compatibility with custom receipt formats. Callers must ensure the value is content-free before invoking this method.

func (*ReceiptsResource) UnsafeRawVerify

func (r *ReceiptsResource) UnsafeRawVerify(ctx context.Context, receipt any) (map[string]any, error)

UnsafeRawVerify submits arbitrary caller-provided receipt data to the gateway. It is retained for compatibility with custom receipt formats. Callers must ensure the value is content-free before invoking this method.

func (*ReceiptsResource) VerifyOffline

func (r *ReceiptsResource) VerifyOffline(receipt any, publicKeyHex string) VerifyResult

VerifyOffline verifies a receipt fully offline (no network) against a pinned P-256 public key (uncompressed-point hex). Pure C9 — no gateway trust.

type ReconstructParams

type ReconstructParams struct {
	// ResponseText is the (still-tokenised) model reply to detokenise + rebuild.
	ResponseText string
	// AliasMap maps placeholder → original (the real PII). Accepts a flat
	// token→original map; it is applied locally and NEVER egresses.
	AliasMap map[string]string
	// TargetFormat is one of txt/md/markdown/html/csv/json/yaml/yml/xml.
	TargetFormat string
}

ReconstructParams configures ReconstructResource.Create.

type ReconstructResource

type ReconstructResource struct{}

ReconstructResource is the local reconstruction surface (C13).

func (*ReconstructResource) Create

Create reconstructs ResponseText into TargetFormat FULLY ON-DEVICE. The alias map is applied locally (detokenisation); nothing is sent to the gateway. Text/structured formats only — binary/office formats fail closed.

type ReconstructResult

type ReconstructResult struct {
	Content     []byte
	ContentType string
	Filename    string
	// ReceiptHeaders is always empty: reconstruction is local, so there is no
	// gateway round-trip and thus no server receipt headers. Kept for shape parity.
	ReceiptHeaders map[string]string
}

ReconstructResult is a reconstructed file, built fully on-device.

type ReconstructionNotSupportedError

type ReconstructionNotSupportedError struct {
	Format string `json:"-"`
}

ReconstructionNotSupportedError is returned (fail-closed) when a binary/office target format is requested. Reconstruction is fully local; it never falls back to a gateway round-trip, so no alias map / PII ever egresses.

func (*ReconstructionNotSupportedError) Error

func (*ReconstructionNotSupportedError) GoString

func (*ReconstructionNotSupportedError) String

type ReviewInfo

type ReviewInfo struct {
	// State is StateOK or StateDegraded.
	State string
	// Coverage is the detection that ran.
	Coverage Coverage
	// Warnings lists what the reviewer should know before approving.
	Warnings []SendWarning
}

ReviewInfo tells the reviewer how the text they are looking at was checked.

type SendWarning

type SendWarning struct {
	Code    string
	Reason  string
	Message string
}

SendWarning is a notice about one request. It never stops the request. Message is plain English and repeats nothing from the request.

type SignReceiptOptions

type SignReceiptOptions struct {
	EntityCount     int
	FileEntityCount int
	Categories      []string
	OutputHash      string
	EngineVersion   string
	EngineHash      string
	// ExtraClaims are merged into the v3-attestation object (advanced).
	ExtraClaims map[string]any
	// KeyPair, when nil, mints an ephemeral P-256 key for this receipt.
	KeyPair *DeviceKeyPair
	// JTI / IAT override the auto-generated uuid / unix-now (for reproducible tests).
	JTI string
	IAT int64
}

SignReceiptOptions configures SignDeviceReceipt. All fields are optional; a receipt is produced even when nothing was found (a "checked, nothing found" signed proof), matching the zero-entity branch. Empty EngineVersion / EngineHash / OutputHash are emitted as JSON null (mirrors the Python None default) — this does not affect self-verification (verify re-canonicalises the same bytes).

type StreamEvent

type StreamEvent struct {
	// Event is the SSE event name (Anthropic sets it; OpenAI leaves it "message").
	Event string
	// Data is the parsed JSON payload. Error payloads are reduced to the fixed
	// type field so upstream response content is not exposed.
	Data map[string]any
	// Text is the DETOKENISED text delta carried by this event (already restored
	// on-device, boundary-safe). Empty for non-text events.
	Text string
}

StreamEvent is one decoded SSE event.

type StreamHandler

type StreamHandler func(StreamEvent) error

StreamHandler receives each decoded + on-device-detokenised StreamEvent. A non-nil return stops the stream (and is returned by CreateStream).

type SurrogateContinuity

type SurrogateContinuity string

SurrogateContinuity is the scope over which the same real value maps to the same stand-in.

const (
	// ContinuityConversation — a bindings ledger was supplied, so the same value
	// keeps the same stand-in across turns (in BOTH modes).
	ContinuityConversation SurrogateContinuity = "conversation"
	// ContinuitySingleMessage — no ledger, so the stand-ins are only stable
	// WITHIN this message.
	ContinuitySingleMessage SurrogateContinuity = "single-message"
)

func CoerceSurrogateContinuity

func CoerceSurrogateContinuity(raw any) SurrogateContinuity

CoerceSurrogateContinuity is the TOTAL migration for a continuity value read off the engine/wire. It NARROWS: anything that is not literally "conversation" becomes "single-message", so an unrecognised value can never widen the claim made to the model.

type SurrogateMode

type SurrogateMode string

SurrogateMode is one of the two substitution styles. It is a defined string type so a bare string cannot be passed where a mode is expected; values are only ever produced by the constants below, CoerceSurrogateMode, or ResolveSurrogateMode.

const (
	// SurrogateModeBalanced substitutes realistic stand-ins. DEFAULT.
	SurrogateModeBalanced SurrogateMode = "balanced"
	// SurrogateModeMax substitutes opaque <<CLOAK:TYPE:ID>> placeholders.
	SurrogateModeMax SurrogateMode = "max"
)

func CoerceSurrogateMode

func CoerceSurrogateMode(raw any) SurrogateMode

CoerceSurrogateMode is the TOTAL migration for a STORED / TRANSPORTED mode value. It maps ANY input — a current mode, a retired one, nil, a number, a struct — onto a real, PROTECTED mode.

It is structurally impossible for this to return a value outside SurrogateModes: the only returns other than DefaultSurrogateMode are guarded by a membership test against SurrogateModes itself, and the alias table's value type is SurrogateMode.

func ResolveSurrogateMode

func ResolveSurrogateMode(raw any) (SurrogateMode, error)

ResolveSurrogateMode resolves an EXPLICIT call-site mode argument.

  • nil / "" → DefaultSurrogateMode (the caller did not choose)
  • a real mode → itself
  • anything else → a *SurrogateModeError

Use CoerceSurrogateMode for values that came out of storage or off a wire.

type SurrogateModeCopy

type SurrogateModeCopy struct {
	Label    string
	Short    string
	Tradeoff string
}

SurrogateModeCopy is the user-facing copy for one mode. Each mode states a REAL cost — neither is marketed over the other, because the honest answer is that both trade something. Surfaces MUST show the trade-off at the point of choice.

The word "continuity" appears nowhere: the always-on behaviour is described plainly in ModeSharedNote instead, once, under both options.

type SurrogateModeError

type SurrogateModeError struct{}

SurrogateModeError is returned when an EXPLICIT call-site mode argument is not a real mode. Go twin of the TS SurrogateModeError.

func (*SurrogateModeError) Code

func (e *SurrogateModeError) Code() string

Code is the stable machine-readable error code (mirrors the TS `code` field).

func (*SurrogateModeError) Error

func (e *SurrogateModeError) Error() string

func (*SurrogateModeError) Format

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

type SurrogateModeReport

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

SurrogateModeReport is what a tokenise pass ACTUALLY did — a REQUIRED field on every tokenise result.

Deliberately NOT a plain struct of exported fields. The precedent is nerDegraded: computed honestly, transported, parsed, and then never read by anything — which is how raw PII egressed while the extension recorded outcomeReason: "tokenised". An optional signal is a signal that gets dropped.

In TypeScript/Java the equivalent lock is "required interface field / record component", which breaks a hand-written fake at COMPILE time. Go has no such thing: `SurrogateModeReport{}` would compile and carry two empty strings. The hole is closed by making both fields UNEXPORTED, so the only way for code outside this package to obtain a populated report is NewSurrogateModeReport(mode, continuity) — both arguments REQUIRED and positional (omitting one is `not enough arguments in call`, a compile error), both validated (passing a zero value is a construction error).

func NewSurrogateModeReport

func NewSurrogateModeReport(mode SurrogateMode, continuity SurrogateContinuity) (SurrogateModeReport, error)

NewSurrogateModeReport is the ONLY constructor for a SurrogateModeReport. Both arguments are required; either zero value is rejected.

func (SurrogateModeReport) Continuity

Continuity is the scope over which the stand-ins in this result are stable. The disclosure text is selected from this — see DisclosureText — so the claim made to the model is only ever the claim the bytes can support.

func (SurrogateModeReport) IsZero

func (r SurrogateModeReport) IsZero() bool

IsZero reports whether this is the unset zero value (never produced by NewSurrogateModeReport).

func (SurrogateModeReport) Mode

Mode is the mode the tokenise pass actually applied.

func (SurrogateModeReport) String

func (r SurrogateModeReport) String() string

func (SurrogateModeReport) Validate

func (r SurrogateModeReport) Validate() error

Validate returns an error for the zero value or any partially-set report. Every path in this SDK that reads a report calls it, so an unset report fails LOUD instead of silently becoming "balanced/conversation".

type TokenCountMessage

type TokenCountMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

TokenCountMessage is a role/content pair for token counting.

type TokenCountParams

type TokenCountParams struct {
	Provider     string              `json:"provider"`
	Model        string              `json:"model"`
	Messages     []TokenCountMessage `json:"messages"`
	AllProviders bool                `json:"all_providers"`
}

TokenCountParams is the POST body for /api/v1/tokens/count.

type TokeniseResult

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

TokeniseResult is the outcome of ONE on-device tokenise pass.

LOCK #1 (spec §2a) — SurrogateMode is a REQUIRED result field. In TypeScript and Java that is enforced by the type system (a required interface field / record component), so a hand-written fake result fails to COMPILE. Go has no required struct field: `TokeniseResult{Text: "…"}` would compile and silently carry the zero SurrogateModeReport, which is precisely the `nerDegraded` failure — a signal computed honestly, transported, and then dropped.

THE ZERO-VALUE HOLE IS CLOSED THREE WAYS, and the first one IS a compile error:

  1. EVERY field is unexported. Code outside package cloakapi therefore cannot write a composite literal that populates ANY field — `TokeniseResult{Text: "x"}` is `unknown field Text`, and the only way to obtain a usable value is NewTokeniseResult(text, replacements, report), whose report argument is REQUIRED and POSITIONAL (omit it and the compiler says "not enough arguments in call").
  2. NewTokeniseResult VALIDATES the report and refuses the zero value, so even inside this package a mode cannot be forgotten.
  3. Validate() is called on every consuming path (relay, disclosure), so a zero-value TokeniseResult that somehow reached one fails LOUD instead of being read as "balanced/conversation".

func NewTokeniseResult

func NewTokeniseResult(text string, replacements map[string]string, report SurrogateModeReport) (TokeniseResult, error)

NewTokeniseResult is the ONLY constructor for a TokeniseResult. `report` is a required positional argument and the zero value is rejected.

func (TokeniseResult) Categories

func (r TokeniseResult) Categories() []string

Categories are the CLOAK token labels that fired (MAX only — BALANCED emits no <<CLOAK:…>> markers to scan).

func (TokeniseResult) Coverage

func (r TokeniseResult) Coverage() Coverage

Coverage is the detection that ran for this text: full, rules_and_names or rules_only.

func (TokeniseResult) Degraded

func (r TokeniseResult) Degraded() bool

Degraded reports whether this result came from the pure-regex fallback rather than the shared engine. A degraded pass can only produce opaque tokens, so its SurrogateMode() reports max — the mode it ACTUALLY applied, never the mode the caller asked for.

func (TokeniseResult) Meta

func (r TokeniseResult) Meta() map[string]any

Meta is the honest record of what ran on-device. A reduced-coverage warning is neutral caller-facing text without detector or rule identifiers.

func (TokeniseResult) Replacements

func (r TokeniseResult) Replacements() map[string]string

Replacements maps the FULL replacement string -> the original value: the AUTHORITATIVE local detokenise table for these bytes. LOCAL ONLY — never send it anywhere.

func (TokeniseResult) SurrogateMode

func (r TokeniseResult) SurrogateMode() SurrogateModeReport

SurrogateMode is what this pass ACTUALLY did. Always populated on a result produced by this SDK.

func (TokeniseResult) Text

func (r TokeniseResult) Text() string

Text is the tokenised text — the ONLY field that may egress.

func (TokeniseResult) Validate

func (r TokeniseResult) Validate() error

Validate rejects the zero value. Every consuming path calls it.

func (TokeniseResult) Warnings

func (r TokeniseResult) Warnings() []SendWarning

Warnings lists what a reviewer should know about this result: reduced coverage and the reason for it, or content that could not be checked. Empty when the full engine ran.

type TokensResource

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

TokensResource is the token-counting surface (C12). Count is retained for source compatibility but is unavailable until the SDK has a local counting implementation; it never sends prompt text to the gateway.

N9hh, 2026-08-04 — the old doc comment read (kept verbatim, R2):

NOTE: this is a SERVER-SIDE estimate — the gateway sees the message text for
counting (a server-side convenience). It is documented explicitly so callers
choose the trade-off knowingly; for a fully client-side count use the bundled
engine. Pass ALREADY-TOKENISED messages if you do not want raw text counted
server-side.

That last sentence put the privacy guarantee on the CALLER — "pass already- tokenised messages if you do not want raw text counted". A default that leaks unless the caller knows to opt out is not a trade-off, it is a trap. Sixth of eight ports to be corrected.

TS reference: src/resources/tokens.ts:11. Python reference: sdk/python/cloakapi/resources/tokens.py.

func (*TokensResource) Count

func (r *TokensResource) Count(ctx context.Context, params TokenCountParams) (map[string]any, error)

Count returns an unavailable error without making a network request.

type VerifyResult

type VerifyResult struct {
	OK             bool
	Kind           string
	Reason         string
	WitnessChecked bool `json:"witness_checked"`
}

VerifyResult is the outcome of an offline receipt verification. Kind ∈ pass | unverified-witness | desktop-only-pass | fail.

func VerifyDeviceReceipt

func VerifyDeviceReceipt(receipt any, publicKeyHex string) VerifyResult

VerifyDeviceReceipt is the C8/C9 canonical name for the device-receipt verifier. A v3 device receipt carries neither egress_attestation nor countersignature, so this returns kind="pass" for a valid one (matching the golden fixture's verify_expected.kind == "pass").

func VerifyReceipt

func VerifyReceipt(receipt any, publicKeyHex string) VerifyResult

VerifyReceipt verifies a signed receipt against a hex-encoded uncompressed P-256 public key. Signature: raw r‖s (64 bytes) base64url. Signed bytes: JCS-canonical receipt with the "sig" field removed. OFFLINE — no gateway.

Source Files

  • attribution.go
  • chat.go
  • client.go
  • disclosure.go
  • errors.go
  • field_guard.go
  • file.go
  • http.go
  • messages.go
  • models.go
  • posture.go
  • prepared.go
  • receipt.go
  • receipts_rest.go
  • reconstruct.go
  • relay.go
  • route.go
  • streaming.go
  • surrogatemode.go
  • tokenize.go
  • tokens.go
  • warnings.go

Directories

Path Synopsis
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.
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.
Package pii provides Level-1 regex-based PII detection and tokenisation for the CloakAPI Go SDK.
Package pii provides Level-1 regex-based PII detection and tokenisation for the CloakAPI Go SDK.
Package routing is the Go client-side arbitrage router (§12b P4a + §52d).
Package routing is the Go client-side arbitrage router (§12b P4a + §52d).

Jump to

Keyboard shortcuts

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