taisce

package module
v0.0.0-...-dfbfaef Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 14 Imported by: ? 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.

README

Taisce for Go

Memory for agents built on the Microsoft Agent Framework for Go, backed by a Taisce deployment you run.

  • github.com/ensera-ai/taisce-go is the client over the deployment's v1 contract: observe, freshness, recall, context, citations, passage search, artifacts, erasure and export.
  • github.com/ensera-ai/taisce-go/agentframework is the adapter, on four of the framework's own seams:
    • ContextProvider recalls before a run and stores the turn after it;
    • Compaction replaces a long history with the deployment's context;
    • SessionStore keeps the framework's session where the memory formed from it already lives;
    • NewTextSearchProvider binds the deployment's passage search to the framework's text-search seam, for grounding without forming anything.
client, err := taisce.New("https://memory.example", os.Getenv("TAISCE_TOKEN"))
if err != nil {
	return err
}
memory, err := agentframework.NewContextProvider(agentframework.Config{
	Client: client, DataSubjectID: "alice", RunID: sessionID,
	OnError: func(stage string, err error) { log.Printf("taisce %s: %v", stage, err) },
})
if err != nil {
	return err
}
// model is your model provider's agent.ProviderConfig.
a := agent.New(model, agent.Config{ContextProviders: []agent.ContextProvider{memory}})

Give the agent process an agent key (taisce credential issue <name>), which can store and recall but cannot erase anybody.

What the provider does, and holds to

  • Memory arrives as exactly one user message, marked untrusted. Never a system message. The message is the line taisce-memory/v1 untrusted and a JSON document carrying the freshness watermark, what the recall did, and the recall's facts, reports and passages unchanged. It sits just before the person's latest message. Recall returning nothing injects nothing.
  • A recall failure is not fatal. The agent runs without memory rather than not at all, and OnError is how an operator still finds out.
  • A write failure is never silent. A failed store is returned from the run.
  • A failed turn is not a memory. The store runs only after a run that succeeded.
  • Only what people said becomes memory by default. The person's messages from the run's input and the assistant's final words are stored. History a history provider loaded is not, because it was stored when it happened. Nor are messages a provider added, tool calls, or a tool's answers.
  • A retried store is one observation, and a different turn is another. The idempotency key is the conformance suite's taisce-turn-key/2 derivation: every field is length-prefixed, so content cannot move a boundary between them. It is checked against the suite's published vectors and is the same bytes as every other adapter's.
  • Compaction is replacement, never a summary. When the loaded history is longer than AfterMessages, Compaction asks the deployment for the person's context and puts it, unchanged, in place of that history. A context that cannot be fetched leaves the history as it was.
  • A session belongs to a person, and lives where their memory does. The framework ships no durable session store, so every application invents one — and inventing it in the application's own database splits one person's data across two systems, which gives a deletion two places to sweep and only one that can produce a counted residual. SessionStore keeps the serialized session as an artifact under the subject: the deployment never reads it, expires it with that person's retention, and removes it with that person's erasure. Every call names the subject, and the deployment answers another person's session exactly as one that does not exist. A save carries the version it expects to replace, so two turns of one session cannot silently lose a write.
  • Passage search grounds without forming anything. NewTextSearchProvider recalls nothing and stores nothing: it searches what was actually said and hands it to the model under the same untrusted mark the memory message carries, because a passage is something somebody said. When the deployment says the index behind the answer is still building, the model is told so in the text it reads — a model handed an incomplete answer as though it were complete answers confidently from it.

Erasure and export

These are for your application's code, never the model's: nothing in agentframework offers them.

receipt, err := client.EraseSubject(ctx, "alice", "right to erasure")
var notClean *taisce.ErasureNotCleanError
switch {
case errors.As(err, &notClean): // rows still match; notClean.Receipt says which
case errors.Is(err, taisce.ErrForbidden): // this key may not erase: use the read_write key
case err != nil:
}
everything, err := client.ExportSubject(ctx, "bob") // sections of rows, and a count per section
  • EraseSubject and EraseSources are separate methods because the deployment refuses a request that names both a person and sources.
  • A receipt that is not clean is an error, *ErasureNotCleanError, and it carries the whole receipt. Code that ignores the receipt cannot tell a person their data is gone while rows still match.
  • ErrExportTooLarge means the person holds more rows than one export returns. The deployment refuses the export rather than returning part of it.

The address must be https

taisce.New refuses an address that is not https, unless its host is loopback (localhost, 127.0.0.0/8, ::1). The credential travels with every request. The client never follows a redirect.

How it is proved

The adapter conformance suite from the service repository runs against a live deployment, with this repository's driver:

go build -o driver ./conformance
TAISCE_TOKEN=… taisce conformance --api http://localhost:8080 --cases ../taisce/conformance/cases.json --driver ./driver
  • go test ./... holds what needs no deployment.
  • go test -tags live ./... runs erasure and export against a deployment. It needs TAISCE_API, TAISCE_TOKEN (read_write) and TAISCE_READER_TOKEN (read_only), and fails rather than skips without them.
  • The conformance workflow stands a deployment up and runs both.

Versions

Built against github.com/microsoft/agent-framework-go v0.3.0, which is pre-1.0: its seam may change in any minor release. Go 1.26 or later.

Documentation

Overview

Package taisce is the client for a Taisce memory deployment over its v1 contract, and the renderings every adapter shares: the memory message and the turn key.

It decides how a request is sent and how an answer is read, and nothing about any agent framework; the adapter in package agentframework is built on it. It must not decide what is remembered or how a recall is ranked: that is the deployment's, and a client that second-guessed it would be a second memory system with no proof behind it.

The credential is a bearer token bound to one project. It is sent to the one deployment the client was built for, never over plaintext to a host that is not loopback, never across a redirect, and never logged.

Index

Constants

View Source
const MaxErasureSources = 10000

MaxErasureSources is the most source observations one erasure may name. The deployment refuses more; refusing here says so before a request is spent on it.

View Source
const MemoryMessagePrefix = "taisce-memory/v1 untrusted"

MemoryMessagePrefix is the first line of every memory message an adapter injects. The conformance suite parses what follows it, so every adapter renders the same document under the same line.

View Source
const TurnKeyDerivation = "taisce-turn-key/2"

TurnKeyDerivation is the derivation TurnKey implements, and the first field it hashes, so a key from it never equals one from another derivation.

Variables

View Source
var (
	// ErrForbidden is a credential whose access does not cover the operation: a read-only key
	// changing memory, or an agent key erasing a person. Retrying with the same key cannot succeed.
	ErrForbidden = errors.New("taisce: the credential does not permit this operation")
	// ErrExportTooLarge is a subject holding more rows than one export returns. The deployment
	// refuses rather than truncates, because a partial export is a false answer to an access request.
	ErrExportTooLarge = errors.New("taisce: the export is larger than one response")
)
View Source
var ErrArtifactConflict = errors.New("taisce: the artifact changed since the version this write expected")

ErrArtifactConflict is a write whose expected version is not the stored one.

View Source
var ErrArtifactNotFound = errors.New("taisce: no such artifact for this subject")

ErrArtifactNotFound is an artifact this subject does not have.

A sentinel rather than a status, because "this person has not been here before" is the ordinary first turn of every conversation and a caller should not have to read HTTP codes to handle it. Another person's artifact answers the same way as one that does not exist, which is the check that makes one end user's state unreachable to another inside a project a single credential opens.

Functions

func IsMemoryText

func IsMemoryText(text string) bool

IsMemoryText reports whether a message's text is one an adapter injected, by its first line.

func RenderContextMessage

func RenderContextMessage(assembled AssembledContext) string

RenderContextMessage is the prefix line, then a JSON document with the watermark, the assembly's cost as the plan, and the context's segments and turns unchanged: what replaces a history is the deployment's answer and nothing an adapter wrote.

func RenderMemoryMessage

func RenderMemoryMessage(fresh Freshness, bundle RecallBundle) string

RenderMemoryMessage is the prefix line, then a JSON document with the watermark, the plan (what the recall did) and the recall's own arrays unchanged.

func TurnKey

func TurnKey(dataSubjectID, runID string, messages []Message) string

TurnKey is a turn's idempotency key: a version-5 UUID over SHA-256 of netstrings — length in UTF-8 bytes, a colon, the bytes, a comma — of the derivation, the subject, the run, and each message's role and content. A retried turn derives the same key and is stored once; a different turn derives another.

The lengths are the point. Fields joined by a separator let content holding the separator and a role name move a boundary, so two different turns hashed the same bytes and the deployment refused the second as a conflicting retry, for good. Go's len counts UTF-8 bytes already; another language's string length may not, which is why the vectors this is tested against include a character outside the Basic Multilingual Plane.

Types

type Artifact

type Artifact struct {
	ID                  string    `json:"id"`
	Version             string    `json:"version"`
	DataSubjectID       string    `json:"data_subject_id"`
	Kind                string    `json:"kind"`
	Name                string    `json:"name"`
	SourceObservationID string    `json:"source_observation_id"`
	Bytes               int       `json:"bytes"`
	AuthoredBy          string    `json:"authored_by"`
	CreatedAt           time.Time `json:"created_at"`
	UpdatedAt           time.Time `json:"updated_at"`
	ExpiresAt           time.Time `json:"expires_at"`
	Content             []byte    `json:"content"`
}

Artifact is a stored artifact and its bytes.

type ArtifactListing

type ArtifactListing struct {
	Artifacts []Artifact `json:"artifacts"`
	// Next carries the id to continue after, and is absent on the last page.
	Next *struct {
		ID string `json:"id"`
	} `json:"next"`
}

ArtifactListing is one page of a subject's artifacts, without their bytes.

type ArtifactPut

type ArtifactPut struct {
	// ID is the caller's name for it, unique within the project.
	ID string `json:"id"`
	// ExpectedVersion is the version this write expects to replace, and is how two writers of the
	// same artifact cannot silently lose one of their writes. Empty is not last-write-wins: the
	// deployment replays an identical write and refuses a changed one, so a second writer who did
	// not read first is told rather than obeyed.
	ExpectedVersion string `json:"expected_version,omitempty"`
	// DataSubjectID is whose artifact it is. Required by every caller here, because without it the
	// deployment cannot tell whose it is and one person's state is reachable to another.
	DataSubjectID string `json:"data_subject_id"`
	// Kind is an opaque label the deployment lists by, so an operator can see one kind of stored
	// object apart from another.
	Kind string `json:"kind"`
	// Name is a label within the kind.
	Name string `json:"name"`
	// Content is the bytes. They travel as base64 and the deployment stores them as given.
	Content []byte `json:"content"`
}

ArtifactPut is one artifact being written.

type ArtifactReceipt

type ArtifactReceipt struct {
	ID                  string    `json:"id"`
	Version             string    `json:"version"`
	DataSubjectID       string    `json:"data_subject_id"`
	Kind                string    `json:"kind"`
	Name                string    `json:"name"`
	SourceObservationID string    `json:"source_observation_id"`
	Bytes               int       `json:"bytes"`
	AuthoredBy          string    `json:"authored_by"`
	CreatedAt           time.Time `json:"created_at"`
	UpdatedAt           time.Time `json:"updated_at"`
	ExpiresAt           time.Time `json:"expires_at"`
	// Replayed says the deployment recognised this write as one it had already performed.
	Replayed bool `json:"replayed"`
}

ArtifactReceipt is what a write returned, including the version the next write should expect.

type ArtifactRef

type ArtifactRef struct {
	ID              string `json:"id"`
	DataSubjectID   string `json:"data_subject_id"`
	ExpectedVersion string `json:"expected_version,omitempty"`
}

ArtifactRef names one artifact, and whose it is.

type AssembledContext

type AssembledContext struct {
	Watermark  Freshness       `json:"watermark"`
	Segments   json.RawMessage `json:"segments"`
	Turns      json.RawMessage `json:"turns"`
	Characters int             `json:"characters"`
	Truncated  bool            `json:"truncated"`
}

AssembledContext is the newest turns verbatim and, over the rest, the segments the deployment wrote. Segments and turns are kept as sent, for the reason RecallBundle's arrays are.

type Client

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

Client speaks the v1 contract to one deployment with one credential. It is safe for concurrent use.

func New

func New(baseURL, token string, opts ...Option) (*Client, error)

New builds a client for the deployment at baseURL, authenticated by token.

An address that is not https is refused unless its host is loopback (localhost, 127.0.0.0/8, ::1). The token travels with every request and a project holds every end user's memory, so one mistyped scheme would hand the credential to anyone on the path. There is no switch to allow more: nothing has needed one, and a switch is what gets left on.

func (*Client) Context

func (c *Client) Context(ctx context.Context, req ContextRequest) (AssembledContext, error)

Context assembles one subject's history. No model call is made.

func (*Client) DeleteArtifact

func (c *Client) DeleteArtifact(ctx context.Context, ref ArtifactRef) error

DeleteArtifact removes one subject's artifact. An artifact that is not there is already removed, so that is not an error.

func (*Client) EraseSources

func (c *Client) EraseSources(ctx context.Context, sourceObservationIDs []string, reason string) (ErasureReceipt, error)

EraseSources erases what the named observations said and everything formed from them.

func (*Client) EraseSubject

func (c *Client) EraseSubject(ctx context.Context, dataSubjectID, reason string) (ErasureReceipt, error)

EraseSubject erases everything held for one person and returns the receipt.

It is a separate method from EraseSources because the deployment refuses a request naming both a person and sources: the receipt says what was asked, and it was one thing. Give it the read_write key your erasure path holds; an agent key is refused by design, with ErrForbidden.

func (*Client) ExportSources

func (c *Client) ExportSources(ctx context.Context, sourceObservationIDs []string) (Export, error)

ExportSources returns everything held from the named observations.

func (*Client) ExportSubject

func (c *Client) ExportSubject(ctx context.Context, dataSubjectID string) (Export, error)

ExportSubject returns everything held for one person, or ErrExportTooLarge rather than part of it.

func (*Client) Freshness

func (c *Client) Freshness(ctx context.Context) (Freshness, error)

Freshness reads the watermark.

func (*Client) GetArtifact

func (c *Client) GetArtifact(ctx context.Context, ref ArtifactRef) (Artifact, error)

GetArtifact reads one subject's artifact. It returns ErrArtifactNotFound when there is none.

func (*Client) ListArtifacts

func (c *Client) ListArtifacts(ctx context.Context, dataSubjectID, kind, namePrefix, after string, limit int) (ArtifactListing, error)

ListArtifacts lists one subject's artifacts of a kind, newest page first by the deployment's order. Bytes are not returned.

func (*Client) Observe

func (c *Client) Observe(ctx context.Context, req ObserveRequest) (ObserveReceipt, error)

Observe records a turn. A retry with the same key is folded into what is already held; the same key with a different turn is refused, with Code "idempotency_conflict", and is never stored.

func (*Client) PutArtifact

func (c *Client) PutArtifact(ctx context.Context, req ArtifactPut) (ArtifactReceipt, error)

PutArtifact writes one artifact under one subject.

func (*Client) Recall

func (c *Client) Recall(ctx context.Context, req RecallRequest) (RecallBundle, error)

Recall asks memory a question.

func (*Client) ResolveCitation

func (c *Client) ResolveCitation(ctx context.Context, factID string, limit int) (json.RawMessage, error)

ResolveCitation resolves a fact to the record and the words it stands on. The answer is returned as sent.

func (*Client) SearchPassages

func (c *Client) SearchPassages(ctx context.Context, req PassageRequest) (PassageResults, error)

SearchPassages returns the passages nearest a question.

type ContextRequest

type ContextRequest struct {
	DataSubjectID string `json:"data_subject_id"`
	MaxCharacters int    `json:"max_characters,omitempty"`
}

ContextRequest asks for one subject's history under a budget.

type ErasureNotCleanError

type ErasureNotCleanError struct {
	Receipt ErasureReceipt
}

ErasureNotCleanError is an erasure that completed with rows still matching what it named. It is returned as an error rather than as a receipt with Clean false, so that an application which never reads the receipt cannot tell a person their data is gone while it is not. The receipt is carried whole.

func (*ErasureNotCleanError) Error

func (e *ErasureNotCleanError) Error() string

type ErasureReceipt

type ErasureReceipt struct {
	RequestID            string         `json:"request_id"`
	Scope                string         `json:"scope"`
	DataSubjectID        string         `json:"data_subject_id"`
	SourceObservationIDs []string       `json:"source_observation_ids,omitempty"`
	CompletedAt          time.Time      `json:"completed_at"`
	Deleted              map[string]int `json:"deleted"`
	Residual             map[string]int `json:"residual"`
	Clean                bool           `json:"clean"`
}

ErasureReceipt is what an erasure did, as the deployment counted it. Residual is the product: a count of what still matches, taken after the delete in the same transaction. Clean is that every residual is zero.

type Error

type Error struct {
	Status  int
	Code    string
	Message string
}

Error is a refusal from the deployment, carrying the contract's own code. Branch on Code, or use errors.Is with ErrForbidden or ErrExportTooLarge.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

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

Is matches the sentinel a refusal stands for, by status and code together.

type Export

type Export struct {
	Scope                string                       `json:"scope"`
	DataSubjectID        string                       `json:"data_subject_id"`
	SourceObservationIDs []string                     `json:"source_observation_ids,omitempty"`
	Sections             map[string][]json.RawMessage `json:"sections"`
	Rows                 map[string]int               `json:"rows"`
}

Export is everything held for a person or a set of sources. Sections are raw rows keyed by what produced them, unshaped so that a column a migration added is in the export without anybody remembering to add it here; Rows counts each section, so an export can be compared with an erasure receipt without parsing either.

type Freshness

type Freshness struct {
	Scope  string `json:"scope"`
	Stored *int64 `json:"stored"`
	Formed *int64 `json:"formed"`
	Parked int    `json:"parked"`
}

Freshness is how far behind memory is. Stored and Formed are absent before the first turn is stored or formed, and absent is not zero.

type Message

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

Message is one message of a turn as it is observed: who said it, and what they said.

type ObserveReceipt

type ObserveReceipt struct {
	ID        string `json:"id"`
	Scope     string `json:"scope"`
	LogOffset int64  `json:"log_offset"`
}

ObserveReceipt is the observation as stored: durable when Observe returns; formation follows.

type ObserveRequest

type ObserveRequest struct {
	IdempotencyKey string    `json:"idempotency_key"`
	DataSubjectID  string    `json:"data_subject_id,omitempty"`
	Messages       []Message `json:"messages"`
	// OccurredAt is RFC 3339, or empty for the deployment's own clock.
	OccurredAt string `json:"occurred_at,omitempty"`
}

ObserveRequest records a turn.

type Option

type Option func(*Client)

Option configures a Client.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient replaces the HTTP client. The replacement is used as given: a caller who supplies one that follows redirects takes back the decision this package made not to.

type Passage

type Passage struct {
	ChunkID    string    `json:"chunk_id"`
	SourceID   string    `json:"source_id"`
	Ordinal    int       `json:"ordinal"`
	Role       string    `json:"role"`
	Preview    string    `json:"preview"`
	Similarity float64   `json:"similarity"`
	OccurredAt time.Time `json:"occurred_at"`
	// MessageBytes is the whole message's length, and PreviewComplete says whether the preview is
	// all of it — so a reader knows whether the sentence continues past what they were given.
	MessageBytes    int    `json:"message_bytes"`
	PreviewComplete bool   `json:"preview_complete"`
	PreviewByteEnd  int    `json:"preview_byte_end"`
	ContentDigest   string `json:"content_digest"`
}

Passage is one message reached by similarity. It is evidence and never a fact.

type PassageRequest

type PassageRequest struct {
	Question string `json:"question"`
	Limit    int    `json:"limit,omitempty"`
	// Candidates is how wide the deployment's own search goes before it keeps Limit of them.
	Candidates int `json:"candidates,omitempty"`
	// DataSubjectID narrows the search to one person's words. A passage is somebody's words, so a
	// search narrowed to one person must not quote anybody else.
	DataSubjectID string `json:"data_subject_id,omitempty"`
	// SourceRole is whose messages to search; the deployment's default is the person's own.
	SourceRole string `json:"source_role,omitempty"`
}

PassageRequest asks for the passages nearest a question. A zero control is the deployment's default, and the deployment bounds every one of them regardless.

type PassageResults

type PassageResults struct {
	GenerationID         string `json:"generation_id"`
	ThroughOffset        int64  `json:"through_offset"`
	CoveredThroughOffset int64  `json:"covered_through_offset"`
	BuildState           string `json:"build_state"`
	// Approximate says the index is still being built, so these are some of what was said and not
	// necessarily all of it. It is reported rather than smoothed over, because a model handed an
	// incomplete answer as though it were complete answers confidently from it.
	Approximate bool      `json:"approximate"`
	Passages    []Passage `json:"passages"`
}

PassageResults is what the search returned, and how complete the index behind it was.

type RecallBundle

type RecallBundle struct {
	Controls json.RawMessage `json:"controls"`
	Degraded json.RawMessage `json:"degraded"`
	Reach    json.RawMessage `json:"reach"`
	Facts    json.RawMessage `json:"facts"`
	Reports  json.RawMessage `json:"reports"`
	Passages json.RawMessage `json:"passages"`
}

RecallBundle is a recall's answer. Its arrays are kept as the deployment sent them: an adapter hands them to a model unchanged, and a client that decoded them would be the place a field added by the deployment went missing.

func (RecallBundle) Empty

func (b RecallBundle) Empty() bool

Empty reports whether the recall returned nothing at all: no facts, no reports, no passages.

type RecallRequest

type RecallRequest struct {
	Question      string   `json:"question"`
	DataSubjectID string   `json:"data_subject_id,omitempty"`
	MaxCharacters int      `json:"max_characters,omitempty"`
	SourceRoles   []string `json:"source_roles,omitempty"`
	AsOf          string   `json:"as_of,omitempty"`
	AsKnownAt     string   `json:"as_known_at,omitempty"`
}

RecallRequest asks memory a question. The zero value of every control means the deployment's default.

Directories

Path Synopsis
Package agentframework connects the Microsoft Agent Framework for Go to a Taisce deployment, on four of the framework's own seams: a context provider that recalls before a run and observes after it, a second that replaces a long history with the deployment's context, a store that keeps the framework's session where the memory formed from it already lives, and a binding of the deployment's passage search to the framework's text-search seam.
Package agentframework connects the Microsoft Agent Framework for Go to a Taisce deployment, on four of the framework's own seams: a context provider that recalls before a run and observes after it, a second that replaces a long history with the deployment's context, a store that keeps the framework's session where the memory formed from it already lives, and a binding of the deployment's passage search to the framework's text-search seam.
Command conformance is the adapter wrapped in the subprocess protocol the Taisce conformance suite speaks: one JSON instruction per line on stdin, one report per line on stdout.
Command conformance is the adapter wrapped in the subprocess protocol the Taisce conformance suite speaks: one JSON instruction per line on stdin, one report per line on stdout.

Jump to

Keyboard shortcuts

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