ai

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

haistack-ai (pkg/ai)

Policy-governed FHIR AI gateway for HAIStack. LLMs call typed, audited tools — not arbitrary FHIR server commands.

What it does

v1 centers on four generic tools that sit in front of the existing stack:

  • read_fhir_resource — read one resource through policy allow-lists
  • search_fhir_resources — search with allow-listed parameters and bounded paging
  • run_view — execute a registered ViewDefinition for structured context
  • write_fhir_resource — structured create/update with validation and optional approval

Convenience wrappers (get_patient_summary, get_upcoming_appointments, search_patient_by_phone) delegate to these generic operations and are pre-registered in Registry.

In short: given policy rules and typed tool input, produce safe structured context with citations and audit records.

Usage

Configure policy and executor:

policy := ai.NewAllowListPolicy()
policy.Read["Patient"] = ai.ReadTypePolicy{}
policy.Search["Patient"] = ai.SearchTypePolicy{
    AllowedParams: []string{"name"},
    AllowedFields: []string{"name", "gender"},
    MaxCount:      50,
}
policy.Views["patient_summary_view"] = ai.ViewTypePolicy{}
policy.Write["Patient"] = ai.WriteTypePolicy{
    CreateFields:   []string{"name", "gender"},
    UpdateFields:   []string{"name"},
    CreateApproval: true,
}

exec, err := ai.NewExecutor(ai.Config{
    Resources: resourceStore,
    Search:    searchSvc,
    Views:     viewExec,
    Core:      coreSvc,
    Policy:    policy,
    Audit:     &ai.AuditStoreAdapter{Store: auditStore},
    AuditRequired: true,
    RequireConversationID: true,
    Approval:  myApprovalHook,
    ApprovalStore: approvalStore,
})

Execute a generic read:

res, err := exec.ExecuteTool(ctx, ai.ToolRequest{
    ToolName: ai.ToolReadFhirResource,
    Actor:    "agent-1",
    Subject:  "patient/pat-1",
    Input: map[string]any{
        "resourceType": "Patient",
        "id":           "pat-1",
    },
})
// res.Data, res.Context, res.Citations, res.AuditMeta

Discover tools for a model:

reg := ai.NewRegistry()
for _, tool := range reg.AllToolDescriptors() {
    // tool.Name, tool.Description, tool.Generic, tool.InputKeys
}

Optional model routing (tools work without this):

exec, err := ai.NewExecutor(ai.Config{
    // ...
    ModelRouter: &ai.ModelRouter{
        Local: localAdapter,
        Cloud: cloudAdapter,
    },
})

resp, err := exec.InvokeModel(ctx, ai.ToolRequest{ModelHint: "cloud"}, prompt, res.Context)

Tool input reference

read_fhir_resource
Field Required Description
resourceType yes FHIR resource type
id yes Resource id
search_fhir_resources
Field Required Description
resourceType yes FHIR resource type
params no Map of search parameter name to string values
count no Page size; clamped by policy MaxCount
offset no Result offset
run_view
Field Required Description
viewName yes Registered view name
version no View version; defaults when unambiguous
parameters no Passed to view auth/audit
limit no Max rows returned
offset no Row offset
write_fhir_resource
Field Required Description
operation yes create or update
resourceType yes FHIR resource type
id update only Existing resource id
fields yes Approved top-level FHIR fields

Writes do not accept arbitrary FHIR JSON or PATCH documents.

Safety model

AllowListPolicy denies by default:

  • Unlisted resource types cannot be read, searched, or written
  • Unlisted views cannot be executed
  • Search requests containing any parameter not on the allow-list are denied
  • Search results expose only resourceType/id unless AllowedFields or AllowAllFields is configured
  • Write fields not on the allow-list are rejected
  • SearchTypePolicy.MaxCount bounds page size
  • _include and _revinclude directives require exact policy allow-list entries

Approval is policy-driven via WriteTypePolicy.CreateApproval / UpdateApproval. Pending writes use ApprovalStore tokens; approved tokens are verified and consumed before a write is committed. An approval hook that returns an approved result must also return a token backed by that store.

De-identification is policy-driven via ReadTypePolicy.Deidentify, SearchTypePolicy.Deidentify, and ViewTypePolicy.Deidentify. When any of these flags is enabled, an explicit Deidentifier must be configured; the executor will not silently use pass-through behavior.

Citations and audit

Citations attach provenance for model grounding:

  • Resource refs (Patient/pat-1) for reads and search matches
  • View name, version, and columns for run_view
  • Search parameter names for search_fhir_resources
  • Written resource ref and operation for write_fhir_resource

Audit records capture actor, subject, tool name, outcome, and request scope. Outcomes include success, denied, validation-failed, and approval-required.

Where it fits

Layer Role
ai Policy-governed tool harness (this package)
view Structured projections for run_view
search Parameterized lookup for search_fhir_resources
core Validated writes for write_fhir_resource
validate Structural validation on write path
auth AIPolicyAdapter implements PolicyEngine with principal/tenant decisions; optional decision audit via pkg/audit
audit Shared audit event library used by AI AuditStoreAdapter

MVP limits

  • Generic tools only; no raw FHIR server passthrough
  • Writes use structured field maps, not full resource JSON or PATCH
  • Search scope is allow-listed even when more registry params exist
  • In-memory tool registry; persistent tool catalogs are future work
  • Model invocation is optional and separate from tool execution
  • No prompt orchestration bundled into every flow

See doc.go for the full API, package boundaries, and integration points.

Documentation

Overview

Package ai implements haistack-ai, a policy-governed FHIR AI gateway for Health AI Stack.

Scope

v1 centers on four generic, policy-bounded tools rather than a large catalog of hard-coded domain tools:

  • read_fhir_resource
  • search_fhir_resources
  • run_view
  • write_fhir_resource

These are constrained, typed, audited operations in front of pkg/view, pkg/search, pkg/core, and pkg/validate — not raw FHIR server passthroughs. There is no arbitrary URL execution, no raw PATCH, and no "submit any FHIR JSON" write path in v1.

Optional convenience wrappers (get_patient_summary, get_upcoming_appointments, search_patient_by_phone) delegate to the generic core and are registered in Registry by default.

Public API

The package centers on:

  • PolicyEngine / AllowListPolicy: central allow-list and safety layer with CheckRead, CheckSearch, CheckView, and CheckWrite.
  • Registry: convenience wrappers and custom tool registration.
  • Executor: validates requests, enforces policy, invokes backing packages, builds citations, and emits audit records via ExecuteTool and InvokeModel.
  • GenericToolDescriptors / Registry.AllToolDescriptors: model-facing tool discovery metadata.
  • ContextFormatter: converts tool output into model-facing JSON context.
  • CitationBuilder: attaches provenance from resource refs, search params, view columns, and write metadata.
  • ModelRouter / Executor.InvokeModel: optional local/cloud model adapter selection; tool execution remains useful without any model configured.
  • ApprovalHook / ApprovalStore: human approval seam and token verification boundary for policy-gated writes.
  • Deidentifier: required output scrubbing seam whenever policy requests de-identification; pass-through must be explicitly opted into.

Tool input shapes

read_fhir_resource: resourceType, id

search_fhir_resources: resourceType, params, optional count and offset

run_view: viewName, optional version, parameters, limit, offset

write_fhir_resource: operation (create|update), resourceType, id (update only), fields (approved top-level FHIR fields only)

Typical usage

policy := ai.NewAllowListPolicy()
policy.Read["Patient"] = ai.ReadTypePolicy{}
policy.Search["Patient"] = ai.SearchTypePolicy{
    AllowedParams: []string{"name", "telecom"},
    AllowedFields: []string{"name", "gender"},
    MaxCount:      50,
}
policy.Views["patient_summary_view"] = ai.ViewTypePolicy{}
policy.Write["Patient"] = ai.WriteTypePolicy{
    CreateFields: []string{"name", "gender"},
    UpdateFields: []string{"name"},
}

exec, err := ai.NewExecutor(ai.Config{
    Resources: resourceStore,
    Search:    searchSvc,
    Views:     viewExec,
    Core:      coreSvc,
    Policy:    policy,
    Audit:     &ai.AuditStoreAdapter{Store: auditStore},
})

res, err := exec.ExecuteTool(ctx, ai.ToolRequest{
    ToolName: ai.ToolReadFhirResource,
    Actor:    "agent-1",
    Input: map[string]any{
        "resourceType": "Patient",
        "id":           "pat-1",
    },
})

Execution model

ExecuteTool resolves convenience wrappers through Registry, validates typed input, runs the matching PolicyEngine check, invokes the backing package, optionally de-identifies output, formats model context, builds citations, and writes audit records on success, denial, validation failure, and approval-required outcomes. InvokeModel audits invoke-model when a model adapter actually runs.

Write operations validate structured field input, may require approval through ApprovalHook when policy demands it, and commit through core.ResourceService only after policy and validation pass.

Authorization and audit

PolicyEngine is required. AllowListPolicy denies by default until explicit allow-list entries are configured. AuditLogger is optional for local/test use; implement both LogToolAccess (ExecuteTool) and LogModelInvoke (InvokeModel). Production deployments should set Config.AuditRequired so missing or failed audit persistence fails closed.

Integration points

  • haistack-view: run_view delegates to view.Executor for structured rows.
  • haistack-search: search_fhir_resources delegates to search.Service.
  • haistack-core: write_fhir_resource commits through core.ResourceService.
  • haistack-validate: optional Validator on the write path.
  • haistack-auth: auth.AIPolicyAdapter implements PolicyEngine with principal/tenant decisions and optional AIConstraints for field narrowing.
  • haistack-modules: future installers can register tools and views by name.

Index

Constants

View Source
const (
	WriteOperationCreate = "create"
	WriteOperationUpdate = "update"
)

Write operation constants for write_fhir_resource input.

View Source
const (
	ToolReadFhirResource    = "read_fhir_resource"
	ToolSearchFhirResources = "search_fhir_resources"
	ToolRunView             = "run_view"
	ToolWriteFhirResource   = "write_fhir_resource"
)

Tool name constants for the v1 generic operations.

View Source
const (
	ToolGetPatientSummary       = "get_patient_summary"
	ToolGetUpcomingAppointments = "get_upcoming_appointments"
	ToolSearchPatientByPhone    = "search_patient_by_phone"
)

Convenience tool names built on the generic core.

Variables

View Source
var (
	// ErrToolNotFound is returned when a tool name is not registered or recognized.
	ErrToolNotFound = errors.New("ai: tool not found")

	// ErrToolAlreadyRegistered is returned when registering a duplicate tool name.
	ErrToolAlreadyRegistered = errors.New("ai: tool already registered")

	// ErrInvalidInput is returned when tool input fails structural validation.
	ErrInvalidInput = errors.New("ai: invalid tool input")

	// ErrPolicyDenied is returned when the policy engine rejects an operation.
	ErrPolicyDenied = errors.New("ai: policy denied")

	// ErrUnauthorized is returned when authorization fails for a view execution.
	ErrUnauthorized = errors.New("ai: unauthorized")

	// ErrApprovalRequired is returned when a write requires human approval
	// before it can be committed.
	ErrApprovalRequired = errors.New("ai: approval required")

	// ErrValidationFailed is returned when a write fails structural validation.
	ErrValidationFailed = errors.New("ai: validation failed")

	// ErrMissingPolicy is returned when an Executor is configured without a
	// policy engine.
	ErrMissingPolicy = errors.New("ai: missing policy engine")

	// ErrMissingDependency is returned when a tool's backing service is not
	// configured on the Executor.
	ErrMissingDependency = errors.New("ai: missing backing dependency")

	// ErrMissingDeidentifier is returned when policy requires de-identification
	// but no scrubbing implementation is configured.
	ErrMissingDeidentifier = errors.New("ai: missing deidentifier")

	// ErrMissingAudit is returned when audit is required but not configured.
	ErrMissingAudit = errors.New("ai: missing audit logger")

	// ErrMissingConversationID is returned when deployment policy requires a
	// correlation ID but the request does not provide one.
	ErrMissingConversationID = errors.New("ai: missing conversation id")

	// ErrAuditFailed is returned when required audit persistence fails.
	ErrAuditFailed = errors.New("ai: audit persistence failed")

	// ErrApprovalTokenRequired is returned when an approval provider approves a
	// write without returning a verifiable token.
	ErrApprovalTokenRequired = errors.New("ai: approval token required")

	// ErrApprovalTokenInvalid is returned when an approval token cannot be
	// verified for the exact requested write.
	ErrApprovalTokenInvalid = errors.New("ai: invalid approval token")

	// ErrMissingApprovalStore is returned when a required approval cannot be
	// verified because no approval store is configured.
	ErrMissingApprovalStore = errors.New("ai: missing approval store")
)

Functions

func IsGeneric

func IsGeneric(name string) bool

IsGeneric reports whether name is a built-in generic tool.

func ValidateSearchParameterValues

func ValidateSearchParameterValues(cfg SearchTypePolicy, key string, values []string) error

ValidateSearchParameterValues validates value-sensitive search controls. Include directives are intentionally allow-listed by their exact target declaration rather than by the broad parameter name alone.

Types

type AllowListPolicy

type AllowListPolicy struct {
	Read   map[string]ReadTypePolicy
	Search map[string]SearchTypePolicy
	Views  map[string]ViewTypePolicy
	Write  map[string]WriteTypePolicy
}

AllowListPolicy is a v1 policy engine backed by explicit allow-lists. When a resource type or view is not listed, access is denied.

func NewAllowListPolicy

func NewAllowListPolicy() *AllowListPolicy

NewAllowListPolicy returns an empty allow-list policy. All operations are denied until entries are added.

func (*AllowListPolicy) CheckRead

CheckRead implements PolicyEngine.

func (*AllowListPolicy) CheckSearch

CheckSearch implements PolicyEngine. Every supplied parameter must be on the allow-list; silently dropping a parameter could broaden a clinical query.

func (*AllowListPolicy) CheckView

func (p *AllowListPolicy) CheckView(_ context.Context, req ViewPolicyRequest) error

CheckView implements PolicyEngine.

func (*AllowListPolicy) CheckViewDecision

func (p *AllowListPolicy) CheckViewDecision(req ViewPolicyRequest) (*ViewPolicyDecision, error)

CheckViewDecision returns the view policy decision for callers that need de-identification flags.

func (*AllowListPolicy) CheckWrite

CheckWrite implements PolicyEngine.

func (*AllowListPolicy) MaxSearchCount

func (p *AllowListPolicy) MaxSearchCount(resourceType string) (int, bool)

MaxSearchCount implements SearchCountPolicy.

func (*AllowListPolicy) MaxViewCount

func (p *AllowListPolicy) MaxViewCount(viewName, version string) (int, bool)

MaxViewCount implements ViewCountPolicy. A zero value means the executor's safe default is used.

type ApprovalHook

type ApprovalHook interface {
	RequestApproval(ctx context.Context, req ApprovalRequest) (*ApprovalResult, error)
}

ApprovalHook is the optional human approval seam for policy-gated writes.

type ApprovalHookFunc

type ApprovalHookFunc func(ctx context.Context, req ApprovalRequest) (*ApprovalResult, error)

ApprovalHookFunc adapts a function to the ApprovalHook interface.

func (ApprovalHookFunc) RequestApproval

func (f ApprovalHookFunc) RequestApproval(ctx context.Context, req ApprovalRequest) (*ApprovalResult, error)

RequestApproval implements ApprovalHook.

type ApprovalRequest

type ApprovalRequest struct {
	Actor        string
	Subject      string
	Operation    string
	ResourceType string
	ID           string
	Fields       map[string]any
	Preview      any
}

ApprovalRequest carries context for a write approval decision.

type ApprovalResult

type ApprovalResult struct {
	Approved bool
	Token    string
}

ApprovalResult is the outcome of an approval request.

type ApprovalStore

type ApprovalStore interface {
	CreatePending(ctx context.Context, req ApprovalRequest) (string, error)
	VerifyAndConsume(ctx context.Context, token string, req ApprovalRequest) error
}

ApprovalStore is the durable approval boundary. Implementations should persist pending requests and atomically verify-and-consume approved tokens.

type AuditLogger

type AuditLogger interface {
	LogToolAccess(ctx context.Context, rec AuditRecord) error
	LogModelInvoke(ctx context.Context, rec AuditRecord) error
}

AuditLogger is the pluggable audit seam.

LogToolAccess is invoked for ExecuteTool (success, denial, validation failure, approval-required). LogModelInvoke is invoked for InvokeModel. Custom implementations must implement both; do not assume every record arrives through LogToolAccess.

type AuditLoggerFunc

type AuditLoggerFunc func(ctx context.Context, rec AuditRecord) error

AuditLoggerFunc adapts a function to AuditLogger. Both tool and model records are delivered to the function; model records have Action set to audit.ActionInvokeModel first.

func (AuditLoggerFunc) LogModelInvoke

func (f AuditLoggerFunc) LogModelInvoke(ctx context.Context, rec AuditRecord) error

LogModelInvoke implements AuditLogger.

func (AuditLoggerFunc) LogToolAccess

func (f AuditLoggerFunc) LogToolAccess(ctx context.Context, rec AuditRecord) error

LogToolAccess implements AuditLogger.

type AuditMeta

type AuditMeta struct {
	ExecutedAt time.Time     `json:"executedAt"`
	Duration   time.Duration `json:"duration"`
	Outcome    string        `json:"outcome"`
}

AuditMeta captures execution-side metadata returned with tool results.

type AuditRecord

type AuditRecord struct {
	Action         string            `json:"action,omitempty"`
	ToolName       string            `json:"toolName"`
	Actor          string            `json:"actor"`
	Tenant         string            `json:"tenant,omitempty"`
	Subject        string            `json:"subject,omitempty"`
	Outcome        string            `json:"outcome"`
	Details        map[string]string `json:"details,omitempty"`
	ConversationID string            `json:"conversationId,omitempty"`
	Timestamp      time.Time         `json:"timestamp"`
}

AuditRecord captures one AI tool or model invocation for the audit seam.

func (AuditRecord) CanonicalAction

func (r AuditRecord) CanonicalAction() string

CanonicalAction is the pkg/audit action for this record. InvokeModel sets audit.ActionInvokeModel; ExecuteTool sets audit.ActionExecuteTool. Empty Action defaults to execute-tool.

type AuditStoreAdapter

type AuditStoreAdapter struct {
	Store store.AuditStore
	Now   func() time.Time
	NewID func() string
}

AuditStoreAdapter writes AI audit records through pkg/audit into a store.AuditStore. Action naming is owned by pkg/audit: ExecuteTool maps to execute-tool, and InvokeModel maps to invoke-model. Set NewID for deterministic event IDs (research provenance bundles); the default is a UUID.

func (*AuditStoreAdapter) LogModelInvoke

func (a *AuditStoreAdapter) LogModelInvoke(ctx context.Context, rec AuditRecord) error

LogModelInvoke converts an InvokeModel ai.AuditRecord to invoke-model.

func (*AuditStoreAdapter) LogToolAccess

func (a *AuditStoreAdapter) LogToolAccess(ctx context.Context, rec AuditRecord) error

LogToolAccess converts an ExecuteTool ai.AuditRecord to execute-tool.

type Citation

type Citation struct {
	Kind   string            `json:"kind"`
	Ref    string            `json:"ref,omitempty"`
	Detail map[string]string `json:"detail,omitempty"`
}

Citation attaches provenance to tool output for model grounding.

type CitationBuilder

type CitationBuilder struct{}

CitationBuilder constructs provenance citations from tool outputs.

func NewCitationBuilder

func NewCitationBuilder() *CitationBuilder

NewCitationBuilder returns a citation builder.

func (*CitationBuilder) ResourceRef

func (b *CitationBuilder) ResourceRef(resourceType, id string) Citation

ResourceRef builds a resource citation.

func (*CitationBuilder) SearchCitations

func (b *CitationBuilder) SearchCitations(resourceType string, params url.Values, resources []*types.ResourceEnvelope) []Citation

SearchCitations builds citations for search results and allowed parameters.

func (*CitationBuilder) SearchCitationsWithIncludes

func (b *CitationBuilder) SearchCitationsWithIncludes(resourceType string, params url.Values, resources, included []*types.ResourceEnvelope) []Citation

SearchCitationsWithIncludes builds citations for primary and authorized included resources. Parameter names are sorted for deterministic output and values are intentionally excluded.

func (*CitationBuilder) ViewCitations

func (b *CitationBuilder) ViewCitations(viewName, version, resourceType string, columns []string, rows []map[string]any) []Citation

ViewCitations builds citations for a view execution result.

func (*CitationBuilder) WriteCitation

func (b *CitationBuilder) WriteCitation(operation, resourceType, id string) Citation

WriteCitation builds a citation for a committed write.

type Config

type Config struct {
	Resources             store.ResourceStore
	Search                *search.Service
	Views                 *view.Executor
	Core                  *core.ResourceService
	Validator             validate.Engine
	Policy                PolicyEngine
	Registry              *Registry
	Audit                 AuditLogger
	AuditRequired         bool
	RequireConversationID bool
	Approval              ApprovalHook
	ApprovalStore         ApprovalStore
	Deidentify            Deidentifier
	ModelRouter           *ModelRouter
	Citations             *CitationBuilder
	Formatter             *ContextFormatter
	Now                   func() time.Time
}

Config configures an Executor. Policy is required; backing services are optional but required for their respective tools.

type ContextFormatter

type ContextFormatter struct{}

ContextFormatter converts tool output into model-facing context text.

func NewContextFormatter

func NewContextFormatter() *ContextFormatter

NewContextFormatter returns a context formatter.

func (*ContextFormatter) Format

func (f *ContextFormatter) Format(data any) (string, error)

Format serializes data as indented JSON for model consumption.

type Deidentifier

type Deidentifier interface {
	Deidentify(ctx context.Context, req DeidentifyRequest) (any, []string, error)
}

Deidentifier is the optional output scrubbing seam. The default implementation is a pass-through.

type DeidentifierFunc

type DeidentifierFunc func(ctx context.Context, req DeidentifyRequest) (any, []string, error)

DeidentifierFunc adapts a function to the Deidentifier interface.

func (DeidentifierFunc) Deidentify

func (f DeidentifierFunc) Deidentify(ctx context.Context, req DeidentifyRequest) (any, []string, error)

Deidentify implements Deidentifier.

type DeidentifyRequest

type DeidentifyRequest struct {
	ToolName     string
	ResourceType string
	ViewName     string
	ViewVersion  string
	Data         any
}

DeidentifyRequest carries output data to scrub before returning to a model.

type Executor

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

Executor validates requests, enforces policy, invokes backing packages, builds citations, and emits audit records.

func NewExecutor

func NewExecutor(cfg Config) (*Executor, error)

NewExecutor validates configuration and returns an Executor.

func (*Executor) ExecuteTool

func (e *Executor) ExecuteTool(ctx context.Context, req ToolRequest) (*ToolResult, error)

ExecuteTool validates a request, enforces policy, runs the backing operation, and returns structured output with citations and audit metadata.

func (*Executor) InvokeModel

func (e *Executor) InvokeModel(ctx context.Context, req ToolRequest, prompt, context string) (*ModelResponse, error)

InvokeModel routes an optional model invocation using the configured ModelRouter. Tool execution does not require a model adapter; this helper is for callers that want to combine tool output with model generation in the same session. When a model is actually invoked, the call is audited as audit.ActionInvokeModel via AuditLogger.LogModelInvoke, not LogToolAccess.

type MemoryApprovalStore

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

MemoryApprovalStore is a small stateful implementation for tests and local development. Production deployments should provide a durable implementation.

func NewMemoryApprovalStore

func NewMemoryApprovalStore() *MemoryApprovalStore

NewMemoryApprovalStore returns an empty approval store.

func (*MemoryApprovalStore) Approve

func (s *MemoryApprovalStore) Approve(token string) error

Approve marks a pending token approved. It is intended for tests/local use; durable systems should expose this transition through their approval service.

func (*MemoryApprovalStore) CreatePending

func (s *MemoryApprovalStore) CreatePending(_ context.Context, req ApprovalRequest) (string, error)

CreatePending stores a pending approval and returns its opaque token.

func (*MemoryApprovalStore) VerifyAndConsume

func (s *MemoryApprovalStore) VerifyAndConsume(_ context.Context, token string, req ApprovalRequest) error

VerifyAndConsume validates the token against the exact write request and prevents replay.

type ModelAdapter

type ModelAdapter interface {
	Name() string
	Invoke(ctx context.Context, req ModelRequest) (*ModelResponse, error)
}

ModelAdapter invokes a language model backend.

type ModelRequest

type ModelRequest struct {
	Hint    string
	Prompt  string
	Context string
	Tools   []string
}

ModelRequest carries a model invocation request. Tool execution does not require a model adapter; this seam is for optional local/cloud routing.

type ModelResponse

type ModelResponse struct {
	Adapter string
	Content string
}

ModelResponse is the outcome of a model invocation.

type ModelRouter

type ModelRouter struct {
	Local ModelAdapter
	Cloud ModelAdapter
}

ModelRouter selects a local or cloud model adapter based on a hint.

func (*ModelRouter) Invoke

func (r *ModelRouter) Invoke(ctx context.Context, req ModelRequest) (*ModelResponse, error)

Invoke routes and invokes a model when an adapter is configured.

func (*ModelRouter) Route

func (r *ModelRouter) Route(hint string) ModelAdapter

Route returns the adapter for hint. "cloud" selects Cloud when configured; everything else selects Local when configured, then Cloud as fallback.

type PassThroughDeidentifier

type PassThroughDeidentifier struct{}

PassThroughDeidentifier returns data unchanged with no redactions.

func (PassThroughDeidentifier) Deidentify

Deidentify implements Deidentifier.

type PolicyEngine

type PolicyEngine interface {
	CheckRead(ctx context.Context, req ReadPolicyRequest) (*ReadPolicyDecision, error)
	CheckSearch(ctx context.Context, req SearchPolicyRequest) (*SearchPolicyDecision, error)
	CheckView(ctx context.Context, req ViewPolicyRequest) error
	CheckWrite(ctx context.Context, req WritePolicyRequest) (*WritePolicyDecision, error)
}

PolicyEngine is the central allow-list and safety layer for AI tool operations.

type ReadInput

type ReadInput struct {
	ResourceType string
	ID           string
}

ReadInput is the typed input for read_fhir_resource.

type ReadPolicyDecision

type ReadPolicyDecision struct {
	Allowed       bool
	AllowedFields []string
	Deidentify    bool
}

ReadPolicyDecision is the outcome of a read policy check.

type ReadPolicyRequest

type ReadPolicyRequest struct {
	Actor        string
	Subject      string
	ResourceType string
	ID           string
}

ReadPolicyRequest carries read authorization context.

type ReadTypePolicy

type ReadTypePolicy struct {
	AllowedFields []string
	Deidentify    bool
}

ReadTypePolicy configures read access for one resource type.

type Registry

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

Registry stores named tools for runtime lookup. It is safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns a tool registry with built-in convenience wrappers pre-registered.

func (*Registry) AllToolDescriptors

func (r *Registry) AllToolDescriptors() []ToolDescriptor

AllToolDescriptors returns generic tools plus registered convenience wrappers.

func (*Registry) List

func (r *Registry) List() []*ToolSpec

List returns all registered tools.

func (*Registry) Register

func (r *Registry) Register(spec ToolSpec) error

Register adds a custom tool to the registry.

func (*Registry) Resolve

func (r *Registry) Resolve(name string) (*ToolSpec, error)

Resolve returns a registered tool by name. Returns ErrToolNotFound for unknown names and built-in generic tools (those are handled directly by the Executor).

type SearchCountPolicy

type SearchCountPolicy interface {
	MaxSearchCount(resourceType string) (int, bool)
}

SearchCountPolicy optionally exposes per-resource search count caps.

type SearchInput

type SearchInput struct {
	ResourceType string
	Params       map[string][]string
	Count        int
	Offset       int
}

SearchInput is the typed input for search_fhir_resources.

type SearchPolicyDecision

type SearchPolicyDecision struct {
	Allowed        bool
	Params         url.Values
	AllowedFields  []string
	AllowAllFields bool
	Deidentify     bool
}

SearchPolicyDecision is the outcome of a search policy check. Params may be narrowed by policy before execution.

type SearchPolicyRequest

type SearchPolicyRequest struct {
	Actor        string
	Subject      string
	ResourceType string
	Params       url.Values
}

SearchPolicyRequest carries search authorization context.

type SearchTypePolicy

type SearchTypePolicy struct {
	AllowedParams      []string
	AllowedFields      []string
	AllowAllFields     bool
	AllowedIncludes    []string
	AllowedRevIncludes []string
	MaxCount           int
	Deidentify         bool
}

SearchTypePolicy configures search access for one resource type.

type ToolDescriptor

type ToolDescriptor struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Generic     bool     `json:"generic"`
	Delegate    string   `json:"delegate,omitempty"`
	InputKeys   []string `json:"inputKeys,omitempty"`
}

ToolDescriptor describes one tool for model discovery and operator review.

func GenericToolDescriptors

func GenericToolDescriptors() []ToolDescriptor

GenericToolDescriptors returns metadata for the four built-in generic tools.

type ToolRequest

type ToolRequest struct {
	ToolName       string
	Actor          string
	TenantID       string
	Subject        string
	Input          map[string]any
	ConversationID string
	ModelHint      string
	ApprovalToken  string
}

ToolRequest carries runtime parameters for one tool invocation.

type ToolResult

type ToolResult struct {
	ToolName         string
	Data             any
	Context          string
	Citations        []Citation
	AuditMeta        AuditMeta
	ApprovalRequired bool
	ApprovalToken    string
	Redactions       []string
}

ToolResult is the structured output of a tool invocation.

type ToolSpec

type ToolSpec struct {
	Name        string
	Description string
	Delegate    string
	MapInput    func(input map[string]any) (map[string]any, error)
}

ToolSpec describes a registered tool. Generic tools are built into the Executor; the registry holds convenience wrappers and custom tools.

type ViewCountPolicy

type ViewCountPolicy interface {
	MaxViewCount(viewName, version string) (int, bool)
}

ViewCountPolicy optionally exposes a maximum row count for AI view calls.

type ViewDecisionPolicy

type ViewDecisionPolicy interface {
	CheckViewDecision(req ViewPolicyRequest) (*ViewPolicyDecision, error)
}

ViewDecisionPolicy optionally exposes structured view decisions to callers that need AI-layer de-identification hints.

type ViewDecisionPolicyContext

type ViewDecisionPolicyContext interface {
	CheckViewDecisionContext(ctx context.Context, req ViewPolicyRequest) (*ViewPolicyDecision, error)
}

ViewDecisionPolicyContext is the context-aware variant used by the executor when policy decisions depend on the actor or subject.

type ViewInput

type ViewInput struct {
	ViewName   string
	Version    string
	Parameters map[string]any
	Limit      int
	Offset     int
}

ViewInput is the typed input for run_view.

type ViewPolicyDecision

type ViewPolicyDecision struct {
	Allowed    bool
	Deidentify bool
	MaxCount   int
}

ViewPolicyDecision is the outcome of a view policy check.

type ViewPolicyRequest

type ViewPolicyRequest struct {
	Actor      string
	Subject    string
	ViewName   string
	Version    string
	Parameters map[string]any
	Limit      int
	Offset     int
}

ViewPolicyRequest carries view authorization context.

type ViewScopePolicy

type ViewScopePolicy interface {
	ApplyViewScope(ctx context.Context, req ViewPolicyRequest) (*ViewPolicyRequest, error)
}

ViewScopePolicy optionally narrows view parameters for a subject-scoped request. Implementations must ensure the registered view consumes the injected scope parameter before allowing execution.

type ViewTypePolicy

type ViewTypePolicy struct {
	Deidentify bool
	MaxCount   int
}

ViewTypePolicy configures view access for one view name or name|version key.

type WriteInput

type WriteInput struct {
	Operation    string
	ResourceType string
	ID           string
	Fields       map[string]any
}

WriteInput is the typed input for write_fhir_resource.

type WritePolicyDecision

type WritePolicyDecision struct {
	Allowed          bool
	AllowedFields    []string
	RequiresApproval bool
	Deidentify       bool
}

WritePolicyDecision is the outcome of a write policy check.

type WritePolicyRequest

type WritePolicyRequest struct {
	Actor        string
	Subject      string
	Operation    string
	ResourceType string
	ID           string
	Fields       map[string]any
}

WritePolicyRequest carries write authorization context.

type WriteTypePolicy

type WriteTypePolicy struct {
	CreateFields   []string
	UpdateFields   []string
	CreateApproval bool
	UpdateApproval bool
}

WriteTypePolicy configures write access for one resource type.

Jump to

Keyboard shortcuts

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