interop

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 39 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.

README

Go cross-language adapter

This is a synthetic local test harness, not a production agent integration. The launch descriptor is adapter.json; run its commands from the SDK root:

go run ./cmd/interop server --config /absolute/server-config.json
go run ./cmd/interop client --config /absolute/client-config.json

The configuration, readiness, control endpoints, and reports follow ../agent-hooks-protocol/interop/CONTRACT.md. Both transports carry the complete canonical JSON-RPC envelope (hooks/intercept, not a second wrapper). Stdio capability discovery uses hooks/capabilities; HTTP uses GET /capabilities. Stdio discovery requires params.protocolVersion: "draft" and returns the canonical result.protocolVersion plus result.manifest envelope, validated by both generated codecs and canonical schemas. HTTP discovery returns the capabilities object. No legacy method aliases are accepted. Stdio requests and responses are compacted into exactly one physical JSON line, including when source fixtures use multiline pretty-printed JSON.

Public SDK path and deliberate bypasses

Ordinary client fixtures use named public client boundaries with fixture-owned connections injected through http.RoundTripper. Ordinary server callbacks mount server.NewHandler directly for HTTP and use server.ServeStdio for stdio. Explicit negative-response fixtures bypass output validation, preserving their wire envelopes (including intentionally wrong IDs). Ordinary lifecycle sends and notifications also use the public client; lifecycle HTTP and scheduled stdio frames use the public server handler. Only explicit raw emission and sending against an already-stopped native prefix bypass ordinary client dispatch. The synthetic Apply evaluator still owns native permission and actual execution policy; the public SDK composes protocol effects but does not execute tools.

Validation and application

  • Generated Go codecs plus live canonical JSON Schema draft 2020-12 validation with format assertions. Schemas default to ../agent-hooks-protocol/schema/draft relative to SDK cwd. Set schemaDir in config or AHP_SCHEMA_DIR to use another absolute checkout location.
  • Request/event and response correlation checks; unknown/unadvertised effects, unsupported modification operations, exhausted continuation allowances, and unadvertised injection delivery reject the whole response.
  • Synthetic tool input supports modify(input) replace and shallow merge, with literal null and whole nested value replacement. task, when initially present, must be a positive integer before execution. A host-schema refusal retains accepted input/messages and reports executed: false and hostInputRejected: true; it is not an invalid-response rejection.
  • Input modifications precede result binding. Changed input invalidates previous candidates and stale allow decisions. Deny wins over ask and allow; ask remains pending; return does not bypass either. Messages and injections accumulate only after successful staging. Stop wins over continue; multiple continues consume one allowance and retain ordered instructions.
  • executed describes the synthetic pending tool decision. This harness does not run shell commands, obtain native interactive approval, or invoke a real model. ask records an unresolved approval requirement and prevents execution/result selection. Injection records represent admitted current/next-turn context; no external scheduler is started. Only input modification is advertised.

Authentication and isolation

HTTP none, bearer, OAuth client credentials, mTLS, and signed workload assertions are implemented. OAuth calls the configured token endpoint; it does not synthesize an access token. OAuth/workload verification pins HS256 and verifies signature, issuer, audience, purpose, issuance, not-before (if supplied), and expiry. auth.clock supports the shared fixed test clock; omitted clock uses wall time. Signing keys and certificates must be supplied explicitly in server config. mTLS verifies both peers against the supplied CA and requires a client certificate. All are local public TEST ONLY identities, not production federation support. Auth checks precede receipt recording and also protect discovery. Reports never contain auth configuration; receipts may retain canonical messages, never transport credentials.

This adapter does not implement OAuth protected-resource or authorization-server discovery.

Stdio uses process trust; combining HTTP auth with it reports inapplicable. Unknown HTTP auth reports unsupported, never passed. Failed transport/discovery or invalid request cannot satisfy a negative-response scenario. Validated normal server replies and deliberately malformed negative fixture replies are distinct.

Reads are bounded to 4 MiB, HTTP exchanges to 15 seconds, per-scenario stdio calls and server barriers to 20 seconds, and the CLI client to three minutes. Explicit POST /release releases named scenario barriers. Clients kill and reap spawned stdio servers; Unix uses a dedicated process group to include go run children. Non-Unix cleanup currently kills the direct child only. Unix/macOS is the tested launch environment. HTTP server lifetime is controlled through /shutdown or SIGTERM; the controller must enforce an overall server watchdog.

Tests

go test ./... -count=1
go test -race ./... -count=1
go vet ./...

Tests cover generated/canonical rejection, atomic staging/no input mutation, central scenario application, actual HTTP exchanges under every supported auth mode, bad credentials/untrusted mTLS rejection without receipts, real OAuth token acquisition, JWT claim/signature rejection, actual stdio subprocess exchange and cleanup. Transport tests include all central scenarios when the shared file is present, plus SDK-local smoke cases. Without the sibling central file, transport smoke tests still run and the central application test explicitly skips. Tests require the sibling canonical schemas and public test-only certificate fixtures. No shared scenarios are edited here.

Catalogue extension

The lifecycle commands support suite: "catalogue" for authenticated Execution observations, source-local lineage rejection and registration enforcement against real discovery. See CATALOGUE.md for the wire and test contracts.

Coordinated draft validation

Tests accept AHP_INTEROP_FIXTURE_ROOT (the canonical checkout's interop directory) and AHP_SCHEMA_DIR (its schema/draft directory). For example, from this SDK worktree:

AHP_INTEROP_FIXTURE_ROOT="$PWD/../canonical-inline-messages/interop" \
AHP_SCHEMA_DIR="$PWD/../canonical-inline-messages/schema/draft" \
go test ./interop -timeout 120s

Compaction instructions and summaries are ordered inline text-part arrays. Elicitation request/result objects are JSON serialized into inline text parts; these exchanges do not resolve references or upload text. Compaction snapshots are detached values, not a reference-to-byte cache. Binary upload receiver storage remains separate from client runtime content.

Documentation

Overview

Package interop implements the synthetic cross-language pending-boundary adapter.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Client

func Client(ctx context.Context, c Config) error

func DispatchObservations

func DispatchObservations(event Object, subscriptions []Object, called map[string]bool, prepare func(Object, Object) (Object, error), notify func(Object) error)

DispatchObservations delivers an already-settled boundary to explicit observers and remaining uncalled matching intercept subscriptions. prepare must apply the subscription's existing permissions/selections and confirm selected uploads. Each worker is best effort: no wait, response effects, or decision reopening.

func LifecycleClient

func LifecycleClient(ctx context.Context, c LifecycleConfig) error

func LifecycleServer

func LifecycleServer(parent context.Context, c LifecycleConfig) error

func Load

func Load(path string, v any) error

func Server

func Server(ctx context.Context, c Config) error

func ValidateElicitationAnswer

func ValidateElicitationAnswer(request, answer Object, validate func(string, any) error) error

ValidateElicitationAnswer validates submitted values; schema defaults remain annotations and are neither applied nor checked against the declared type.

func ValidateElicitationCorrelation

func ValidateElicitationCorrelation(request, result Object) error

ValidateElicitationCorrelation must run before body resolution or effects.

Types

type Auth

type Auth struct {
	Mode          string  `json:"mode"`
	Token         string  `json:"token"`
	TokenEndpoint string  `json:"tokenEndpoint"`
	ClientID      string  `json:"clientId"`
	ClientSecret  string  `json:"clientSecret"`
	Assertion     string  `json:"assertion"`
	SigningKey    string  `json:"signingKey"`
	Issuer        string  `json:"issuer"`
	Audience      string  `json:"audience"`
	Purpose       string  `json:"purpose"`
	Clock         float64 `json:"clock"`
	CAFile        string  `json:"caFile"`
	CertFile      string  `json:"certFile"`
	KeyFile       string  `json:"keyFile"`
}

type CompactionHook

type CompactionHook struct {
	Supplier      string
	FailurePolicy string
	Run           func(Object) ([]Object, error)
}

CompactionHook is a serial host-owned subscription. Run receives a detached snapshot. A failed response never commits any of its staged effects.

type Config

type Config struct {
	Transport     string   `json:"transport"`
	Endpoint      string   `json:"endpoint"`
	ReadinessFile string   `json:"readinessFile"`
	ScenarioFile  string   `json:"scenarioFile"`
	ReportFile    string   `json:"reportFile"`
	ServerCommand []string `json:"serverCommand"`
	ServerCwd     string   `json:"serverCwd"`
	ServerConfig  string   `json:"serverConfig"`
	SchemaDir     string   `json:"schemaDir"`
	Auth          Auth     `json:"auth"`
}

type LifecycleConfig

type LifecycleConfig struct {
	Config
	Suite      string        `json:"suite"`
	Upload     UploadBinding `json:"upload"`
	UploadAuth struct {
		Token         string   `json:"token"`
		Subscriptions []string `json:"subscriptions"`
	} `json:"uploadAuth"`
	Uploads           map[string]UploadBinding     `json:"uploads"`
	ContentSelections map[string]map[string]string `json:"contentSelections"`
	ControlEndpoint   string                       `json:"controlEndpoint"`
	ChildPidFile      string                       `json:"childPidFile"`
}

type Object

type Object = map[string]any

func Apply

func Apply(request, response Object) (Object, error)

Apply stages a whole response in private memory, committing no partial state on structural, capability, or flow-admission failure. Host input validation runs after protocol acceptance and can refuse execution without rejection.

func ApplyElicitationEffects

func ApplyElicitationEffects(request, result Object, resolve func(Object) ([]byte, error), validate func(string, any) error, principal string, effects []any) (Object, error)

ApplyElicitationEffects stages a complete list without mutating inputs or uploads. A nil result means a before-request return/deny boundary. Callers publish only the returned validated state, after uploading its complete JSON.

func Capabilities

func Capabilities() Object

func CompactionCapabilities

func CompactionCapabilities(boundary string, observeOnly bool) (Object, error)

CompactionCapabilities advertises only enforceable text replacement.

func ProjectContent

func ProjectContent(event Object, selection map[string]string, bodyAllowed bool) (Object, error)

ProjectContent never grants access. BodyAllowed must come from receiver or host policy, not from event fields or a subscriber's requested selection.

func PublicBoundary

func PublicBoundary(ctx context.Context, request Object, exchange func(context.Context, string, []byte) ([]byte, error), settings ...PublicBoundaryOptions) (Object, bool, error)

PublicBoundary runs a fixture occurrence through the public client. The exchange retains host transport/auth and test-controller scheduling, not acceptance.

func ReadSelectedElicitation

func ReadSelectedElicitation(meta Object, stage string, resolve func(Object) ([]byte, error), validate func(string, any) error) (Object, error)

ReadSelectedElicitation never resolves metadata/omit; selected gaps fail closed.

func ReceiveBoundary

func ReceiveBoundary(ctx context.Context, request Object, callback func(Object) (Object, error)) (Object, error)

ReceiveBoundary runs a fixture callback behind the public server's canonical admission and response acceptance. Authentication and host effects stay with the adapter. The in-memory HTTP exchange also serves owned stdio fixtures.

func RunCompaction

func RunCompaction(instructions, itemID string, before, after []CompactionHook, generate func(string) (string, error), observeOnly bool) (Object, error)

RunCompaction runs the before pipeline, generation/substitution, then after controls. Only applied=true permits downstream use. Returned bodies are inline text parts; no upload or reference cache is needed. Observe-only after callbacks run on detached goroutines after settlement; their results, errors and panics cannot change settlement or delay downstream use.

func RunCompactionParts added in v0.3.0

func RunCompactionParts(instructions []any, itemID string, before, after []CompactionHook, generate func(string) (string, error), observeOnly bool) (Object, error)

RunCompactionParts retains the ordered canonical instruction parts, including their identities. Generation consumes their effective text in part order.

func ToolCapabilities

func ToolCapabilities() Object

func UploadContent

func UploadContent(ctx context.Context, binding UploadBinding, body []byte) (Object, int, error)

UploadContent sends arbitrary octets to the exact configured endpoint. The returned reference is usable only after validating synchronous 201 confirmation.

func ValidateElicitationExchange

func ValidateElicitationExchange(request, result Object, resolve func(Object) ([]byte, error), validate func(string, any) error, principal string) (Object, error)

ValidateElicitationExchange binds complete uploaded MCP objects to normalized metadata without applying effects or checking effect grants. Resolve and validate are host-owned. Principal MUST come from the authenticated transport, never event.source or elicitation.server.

func ValidateElicitationMode

func ValidateElicitationMode(mode string, capabilities Object, origin string) (Object, error)

type PublicBoundaryOptions

type PublicBoundaryOptions struct {
	Content          hooks.ContentOptions
	ContentSelection Object
	Upload           Object
	UploadClient     *http.Client
	InterceptOptions []hooks.InterceptOption
	Accepted         func(*hooks.Result)
}

PublicBoundaryOptions supplies host-owned content and pinned boundary context. Upload credentials remain separate from the event exchange.

type Result

type Result struct {
	ID             string `json:"id"`
	Status         string `json:"status"`
	Actual         Object `json:"actual"`
	Error          string `json:"error,omitempty"`
	SDKAccepted    *bool  `json:"sdkAccepted,omitempty"`
	HostAccepted   *bool  `json:"hostAccepted,omitempty"`
	RejectionLayer string `json:"rejectionLayer,omitempty"`
}

type Scenario

type Scenario struct {
	ID           string          `json:"id"`
	Request      json.RawMessage `json:"request"`
	Response     json.RawMessage `json:"response"`
	Expected     Object          `json:"expected"`
	HostExpected Object          `json:"hostExpected"`
	Tags         []string        `json:"tags"`
	ExpectError  bool            `json:"expectError"`
	Barrier      string          `json:"barrier"`
}

type TaskLineage

type TaskLineage struct {
	RequireKnownParents bool
	// contains filtered or unexported fields
}

TaskLineage tracks source-local identity, not task execution lifetime. A subscriber can receive a child first. Producers may require known parents.

func (*TaskLineage) Accept

func (l *TaskLineage) Accept(event Object) error

Accept follows canonical envelope validation. Rejected edges leave no state.

type UploadAuth

type UploadAuth struct {
	Type     string `json:"type"`
	TokenEnv string `json:"tokenEnv"`
}

type UploadBinding

type UploadBinding struct {
	Endpoint  string      `json:"endpoint"`
	TimeoutMs int         `json:"timeoutMs"`
	MaxBytes  *int64      `json:"maxBytes"`
	Auth      *UploadAuth `json:"auth,omitempty"`
}

UploadBinding is independent of event authentication and transport.

type Validator

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

func NewValidator

func NewValidator(dir string) (*Validator, error)

func (*Validator) Validate

func (v *Validator) Validate(kind string, b []byte) (Object, error)

Jump to

Keyboard shortcuts

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