ai

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 29 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 six 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
  • create_fhir_resource — structured create with field maps, validation, and optional approval
  • update_fhir_resource — updates via patch-path patches only (FHIR Patch path syntax such as name[0].family; not FHIRPath .where() expressions)
  • execute_fhir_bundle — FHIR transaction or batch bundles (POST/PUT; batch allows GET); deprecated alias execute_fhir_transaction

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.

Agent harness (Phase A)

For upstream apps that only configure model URL + system prompt, use Harness.Chat on top of the same Executor. See HARNESS.md for the full discussion→implementation checklist, production guardrails (HarnessExecutorGuardrails), phased rollout, and OpenAICompatibleAdapter.

Runnable demos: go run ./examples/ai-harness, ./examples/ai-harness-chat-approval, ./examples/ai-harness-host-approval.

h, _ := ai.NewHarness(ai.HarnessConfig{
    Executor: exec, Model: chatModel, Actor: "agent-1",
    ToolContextFormat: ai.ToolContextMarkdown,
    EnableProposeWriteHelper: true,
})
res, _ := h.Chat(ctx, "Find patient Jane")
// Multi-turn: call h.Chat again on the same instance to retain session history.

What it does not do

  • Expose raw FHIR REST or arbitrary SQL to models
  • Own OAuth or long-term conversation storage (in-memory session only in v1 harness)
  • Replace pkg/auth — use AIPolicyAdapter or AllowListPolicy for decisions
  • Guarantee model output safety beyond tool boundaries and policy

How it fits in the ecosystem

  LLM / agent orchestrator
            |
            v
     ai.Executor.ExecuteTool / InvokeModel
            |
    +-------+-------+-------+-------+
    |       |       |       |       |
    v       v       v       v       v
 Policy  core   search  view   validate
    |                       |
    v                       v
 pkg/auth              pkg/fhirpath (via view)
 (AIPolicyAdapter)          |
                            v
                      structured rows + citations
                            |
                            v
                      pkg/audit (AuditStoreAdapter)
Direction Package Relationship
Upstream core Validated writes for create_fhir_resource / update_fhir_resource
Upstream search Parameterized lookup for search_fhir_resources
Upstream view run_view executes registered ViewDefinitions
Upstream validate Structural checks on write field maps
Peer auth AIPolicyAdapter implements PolicyEngine
Peer audit Tool/model events via AuditStoreAdapter
Downstream testkit/aitest Harness for executor tests (test-only)

When to use it

  • Building an agent that needs FHIR context with enforceable allow-lists
  • Exposing tool descriptors to models (Registry.AllToolDescriptors)
  • Requiring human approval before sensitive writes
  • De-identifying reads/search/view rows when policy flags demand it
  • Auditing every tool invocation with actor, subject, and outcome

Usage modes

1. Allow-list policy (tests and prototypes)

Configure AllowListPolicy maps directly when you do not need principal/tenant auth yet:

policy := ai.NewAllowListPolicy()
policy.Read["Patient"] = ai.ReadTypePolicy{}
policy.Search["Patient"] = ai.SearchTypePolicy{
    AllowedParams: []string{"name"},
    MaxCount:      50,
}
exec, err := ai.NewExecutor(ai.Config{
    Resources: resourceStore,
    Search:    searchSvc,
    Views:     viewExec,
    Core:      coreSvc,
    Policy:    policy,
})
2. Auth-backed policy (AIPolicyAdapter)

Use when decisions must match human users, roles, and tenant policy DSL:

exec, err := ai.NewExecutor(ai.Config{
    Policy: &auth.AIPolicyAdapter{
        Engine: authEngine,
        TenantID: "tenant-a",
        Resolve: resolveActor,
        Constraints: aiConstraints,
    },
    Audit: &ai.AuditStoreAdapter{Store: auditStore},
    AuditRequired: true,
})
3. Approval-gated writes

Enable CreateApproval / UpdateApproval on write policies and wire Approval + ApprovalStore:

exec, err := ai.NewExecutor(ai.Config{
    Policy:        policyWithApproval,
    Approval:      myApprovalHook,
    ApprovalStore: tokenStore,
    RequireConversationID: true,
})
res, err := exec.ExecuteTool(ctx, ai.ToolRequest{
    ToolName: ai.ToolCreateFhirResource,
    Input: map[string]any{
        "resourceType": "Patient",
        "fields": map[string]any{"name": []any{map[string]any{"family": "Smith"}}},
    },
})
// res may indicate approval-required with a pending token
4. De-identified context

Set Deidentify: true on read/search/view policies. Omit Deidentify on Config to use the built-in shared FHIRDeidentifier, or construct one explicitly:

deid, err := ai.NewFHIRDeidentifier(ai.DefaultPHICatalog())
if err != nil {
    return err
}
exec, err := ai.NewExecutor(ai.Config{
    Policy:     deidPolicy,
    Deidentify: deid,
})

Executor uses a shared FHIRDeidentifier (PHIModeStandard, EvalModeKeywordsOnly) when Config.Deidentify is nil, warms path indexes for common resource types at startup, and passes ProfileCatalog when set. Override with PHIMode, EvalMode, or a custom Deidentifier.

FHIRDeidentifier applies (on read_fhir_resource, search_fhir_resources, and run_view only; other tool names return ErrUnsupportedDeidentifyTool — use a custom Deidentifier for bespoke tools):

  • FHIRPath expression text expanded to JSON segment paths at index build (no runtime FHIRPath evaluation against live values during scrubbing)
  • StructureDefinition-driven paths when ProfileCatalog / Executor.ProfileCatalog is set (base type SD plus meta.profile URLs on each resource instance)
  • Keyword-style FHIRPath strings (for example text.\div``) that do not map to a single catalog segment
  • PHICatalog path suffixes and passive element names at any depth
  • meta.security labels (v3 confidentiality and HL7 security-labels by default)

When policy uses a narrow AllowedFields projection, the executor temporarily merges meta.security and meta.profile from the full resource for scrub decisions, then removes meta from model output if it was not allow-listed.

Customize PHICatalog, PHIStructureRules, or implement Deidentifier for site-specific rules.

snapshot, _ := manager.RebuildSnapshot(ctx)
exec, _ := ai.NewExecutor(ai.Config{
    Policy:         policy,
    ProfileCatalog: validate.NewRegistryProfileCatalog(snapshot),
})

The executor refuses to silently skip de-identification when policy requires it.

5. Model routing (optional)

Tools work without a router; add ModelRouter when some prompts should hit local vs cloud adapters:

exec, err := ai.NewExecutor(ai.Config{
    ModelRouter: &ai.ModelRouter{Local: localLLM, Cloud: cloudLLM},
})
resp, err := exec.InvokeModel(ctx, ai.ToolRequest{ModelHint: "cloud"}, prompt, toolResult.Context)
6. Registry-only discovery

Enumerate descriptors without constructing a full executor:

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

Examples

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

Search with bounded paging:

res, err := exec.ExecuteTool(ctx, ai.ToolRequest{
    ToolName: ai.ToolSearchFhirResources,
    Actor:    "agent-1",
    Input: map[string]any{
        "resourceType": "Patient",
        "params":       map[string]any{"name": "Jane"},
        "count":        25,
    },
})

Run a view for structured rows:

res, err := exec.ExecuteTool(ctx, ai.ToolRequest{
    ToolName: ai.ToolRunView,
    Actor:    "agent-1",
    Input: map[string]any{
        "viewName": "patient_summary_view",
        "limit":    10,
    },
})

Convenience wrapper:

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

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
create_fhir_resource
Field Required Description
resourceType yes FHIR resource type
id no Optional client-assigned id
fields yes Approved top-level FHIR fields
update_fhir_resource
Field Required Description
resourceType yes FHIR resource type
id yes Existing resource id
patches yes Map of patch path → value (same path rules as FHIR Patch, not FHIRPath functions)

Creates and updates use structured fields / patches (not raw PATCH documents). Patch keys cannot set resourceType or id (use tool arguments for those).

execute_fhir_bundle
Field Required Description
bundleType no transaction (default, all-or-nothing) or batch (per-entry success/failure)
entries yes Array of {method, resourceType, id?, fields?, patches?, fullUrl?}
  • POST — same shape as create (fields required).
  • PUT — same shape as update (id and patches required).
  • GET — batch only: resourceType + id (read through policy).
  • DELETE — not exposed on the AI bundle tool in v1 (future).

The tool name execute_fhir_transaction is a deprecated alias for the same operation.

When AIAttribution is enabled the executor appends Provenance POSTs for clinical writes (in addition to any Provenance entries in the bundle). Harness CommitWrite / CommitWritePlan always commit via execute_fhir_bundle (bundleType=transaction). Direct executor calls (outside harness) still use create/update unless AtomicProvenance or this bundle tool is used. With bundleType=batch, entries are independent.

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; for updates an UpdateFields parent path allows descendant patch paths (e.g. name allows name[0].family)
  • 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 create/update tools

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 create/update FHIR tools
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

Testing

go test ./pkg/ai/... -count=1

Use pkg/testkit/aitest for executor harnesses with optional search, views, and approval fakes.

Limits

  • Generic tools only; no raw FHIR server passthrough
  • Writes default to structured field maps and patch paths (primary v1 shape)
  • 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

Documentation

Overview

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

Scope

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

  • read_fhir_resource
  • search_fhir_resources
  • run_view
  • create_fhir_resource
  • update_fhir_resource
  • execute_fhir_bundle (alias: execute_fhir_transaction)

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 already de-identified tool output into model-facing JSON context (Executor runs Deidentify on structured Data first when policy requires it, so the formatter does not perform a separate PHI scrub pass).
  • 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.
  • Harness / ChatModel / OpenAICompatibleAdapter: optional agent layer that runs a tool-calling conversation loop on top of ExecuteTool (see HARNESS.md).
  • MarkdownContextBuilder / ToolContextMarkdown: markdown summaries for tool rows.
  • ResourceWriteDraft / CommitWrite: structured create/update proposals (any type).
  • PatientCreateDraft: convenience wrapper for Patient create (deprecated path).
  • HarnessExecutorGuardrails / BlockDirectWriteTools / AutoConversationID: production agent wiring.
  • ModelAdapterChatModel: bridge legacy ModelAdapter stubs to Harness.Chat.
  • ToolCallProtocol / ParsePromptToolCalls: native and prompt-JSON tool loops.
  • SessionService integration: LoadAgentSession, append-only events, session state.
  • ApprovalHook / ApprovalStore: human approval seam and token verification boundary for policy-gated writes.
  • Deidentifier / FHIRDeidentifier / PHICatalog / ProfileCatalog: Executor defaults to FHIRDeidentifier when Config.Deidentify is nil; override with any Deidentifier. FHIRDeidentifier handles read_fhir_resource, search_fhir_resources, and run_view only (other ToolName values return ErrUnsupportedDeidentifyTool). It derives segment paths from PHICatalog, StructureDefinitions (base type and meta.profile), and FHIRPath expression text (not runtime FHIRPath evaluation), scrubs JSON in one pass (including nested contained and Bundle entries), and applies meta.security strict mode when policy sets Deidentify. Narrow AllowedFields projections still merge meta.security and meta.profile from the full resource for scrubbing, then drop meta from output when not allow-listed. Output is for model-facing tool context, not for persisting de-identified FHIR resources.

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

create_fhir_resource: resourceType, optional id, fields (approved top-level FHIR fields)

update_fhir_resource: resourceType, id, patches (FHIR Patch path keys → values; not full FHIRPath expressions with functions)

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[0].family"},
}

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 structured tool output (before ContextFormatter), 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: create/update FHIR tools commit 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 (
	AIASTCodeSystem = "http://terminology.hl7.org/CodeSystem/v3-ObservationValue"
	AIASTCode       = "AIAST"
	AIASTDisplay    = "Artificial Intelligence asserted"
	// AIAgentContextExtensionURL stores harness/agent correlation on meta.extension (does not replace clinical meta.source).
	AIAgentContextExtensionURL = "urn:haistack:fhir:StructureDefinition:ai-agent-context"
)

HL7 AI Transparency on FHIR: AIAST in Resource.meta.security when AI influenced the resource. https://build.fhir.org/ig/HL7/aitransparency-ig/en/requirements.html

View Source
const (
	ChatRoleSystem    = "system"
	ChatRoleUser      = "user"
	ChatRoleAssistant = "assistant"
	ChatRoleTool      = "tool"
)

Chat roles follow common OpenAI-compatible chat APIs.

View Source
const (
	TiktokenCl100kBase = "cl100k_base" // GPT-4 / GPT-3.5
	TiktokenO200kBase  = "o200k_base"  // GPT-4o family
)

TiktokenEncoding names common OpenAI-compatible encodings (see tiktoken-go).

View Source
const (
	WriteOperationCreate = "create"
	WriteOperationUpdate = "update"
	// WriteOperationRead is a batch-bundle GET entry (read through policy); not a FHIR write.
	WriteOperationRead = "read"
)

Write operation constants for harness drafts and policy.

View Source
const (
	ToolReadFhirResource    = "read_fhir_resource"
	ToolSearchFhirResources = "search_fhir_resources"
	ToolRunView             = "run_view"
	ToolCreateFhirResource  = "create_fhir_resource"
	ToolUpdateFhirResource  = "update_fhir_resource"
	// ToolExecuteFhirBundle runs FHIR transaction or batch bundles (see bundleType).
	ToolExecuteFhirBundle = "execute_fhir_bundle"
	// ToolExecuteFhirTransaction is a deprecated alias of ToolExecuteFhirBundle.
	ToolExecuteFhirTransaction = "execute_fhir_transaction"
)

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.

View Source
const DefaultFHIRGroundingSystemPrompt = `` /* 866-byte string literal not displayed */

DefaultFHIRGroundingSystemPrompt instructs models to stay on the executor tool path.

View Source
const DefaultHarnessAppName = "haistack-harness"

DefaultHarnessAppName is the default SessionService app_name when HarnessConfig.AppName is empty.

View Source
const DefaultMaxToolRounds = 8

DefaultMaxToolRounds bounds the model ↔ tool loop in Harness.Chat.

View Source
const DefaultRedactedValue = "[redacted]"

DefaultRedactedValue is the placeholder written when a PHI field is removed.

View Source
const NarrativeDivFHIRPath = "text.`div`"

NarrativeDivFHIRPath is the compiled FHIRPath expression for Narrative.div.

View Source
const NarrativeDivSegmentPath = "text.div"

NarrativeDivSegmentPath is the JSON segment path for Narrative.div (segment redaction).

View Source
const PolicyApprovalPauseAnswer = "" /* 148-byte string literal not displayed */

PolicyApprovalPauseAnswer is the assistant text when Chat ends on policy approval-required.

View Source
const ToolProposePatientCreate = "propose_patient_create"

ToolProposePatientCreate is deprecated: use ToolProposeWriteResource.

View Source
const ToolProposeWritePlan = "propose_write_plan"

ToolProposeWritePlan is a harness-only tool for multi-step write proposals.

View Source
const ToolProposeWriteResource = "propose_write_resource"

ToolProposeWriteResource is a harness-only tool. It returns create/update tool input without committing; use Harness.CommitWrite to execute through Executor policy.

View Source
const V3ConfidentialityCodeSystem = "http://terminology.hl7.org/CodeSystem/v3-ConfidentialityCode"

V3ConfidentialityCodeSystem is the HL7 v3 confidentiality code system used on Resource.meta.security.

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 a nil FHIRDeidentifier is used or
	// de-identification is invoked without a configured implementation. Executor
	// defaults Config.Deidentify to DefaultDeidentifier when unset.
	ErrMissingDeidentifier = errors.New("ai: missing deidentifier")

	// ErrUnsupportedDeidentifyTool is returned when FHIRDeidentifier receives a
	// ToolName it does not handle. Custom tools must use DeidentifierFunc or
	// PassThroughDeidentifier explicitly.
	ErrUnsupportedDeidentifyTool = errors.New("ai: unsupported tool for FHIR de-identification")

	// 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")

	// ErrUngroundedAnswer is returned when strict grounding checks fail (missing tool evidence or uncited refs).
	ErrUngroundedAnswer = errors.New("ai: ungrounded answer")

	// ErrCommitNotConfirmed is returned when host confirmation is required but not granted for CommitWrite.
	ErrCommitNotConfirmed = errors.New("ai: commit write not confirmed")
)
View Source
var DefaultWarmResourceTypes = []string{
	"Patient", "Observation", "Encounter", "Appointment", "Practitioner", "Condition",
}

DefaultWarmResourceTypes are pre-warmed on Executor startup when profiles are configured.

Functions

func AnalyzeAnswerGrounding added in v0.2.1

func AnalyzeAnswerGrounding(answer string, citations []Citation) []string

AnalyzeAnswerGrounding returns warnings when answer text cites resources not backed by citations.

func AnalyzeClinicalValueGrounding added in v0.2.1

func AnalyzeClinicalValueGrounding(answer string, toolSummaries []HarnessToolResult) []string

AnalyzeClinicalValueGrounding flags numeric clinical quantities in the answer that do not appear in tool JSON evidence.

func AnalyzeSearchParamGrounding added in v0.2.1

func AnalyzeSearchParamGrounding(answer string, records []toolCallRecord) []string

AnalyzeSearchParamGrounding warns when the answer cites FHIR search parameter names not used in search tool calls this turn.

func AppendGroundingSystemPrompt added in v0.2.1

func AppendGroundingSystemPrompt(systemPrompt string, cfg GroundingConfig) string

AppendGroundingSystemPrompt merges host system prompt with FHIR grounding instructions.

func AppendPromptJSONToolInstructions added in v0.2.1

func AppendPromptJSONToolInstructions(systemPrompt string, tools []ChatTool) string

AppendPromptJSONToolInstructions extends a system prompt with tool-calling format guidance.

func EstimateChatMessagesTokens added in v0.2.1

func EstimateChatMessagesTokens(messages []ChatMessage) int

EstimateChatMessagesTokens is a coarse token estimate (~utf-8 bytes/4 plus per-message overhead). Prefer NewTiktokenContextCounter for OpenAI-compatible models when accuracy matters.

func EventsForModelContext added in v0.2.1

func EventsForModelContext(events []store.SessionEvent) (checkpointSummary string, active []store.SessionEvent)

EventsForModelContext splits append-only history into the latest checkpoint summary and active tail events.

func ExpandFHIRPathExpressions added in v0.2.1

func ExpandFHIRPathExpressions(paths []string) (segment []string, compile []string)

ExpandFHIRPathExpressions adds compile-friendly variants for keyword segments.

func FormatHarnessExecutorGuardrails added in v0.2.1

func FormatHarnessExecutorGuardrails(cfg Config) string

FormatHarnessExecutorGuardrails renders guardrail notes as bullet lines (empty when OK).

func HarnessExecutorGuardrails added in v0.2.1

func HarnessExecutorGuardrails(cfg Config) []string

HarnessExecutorGuardrails returns production wiring reminders for Executor used behind Harness. Policy and de-identification rules remain application-specific; this helper only checks cross-cutting agent safety seams discussed for the harness layer.

func HarnessGroundingGuardrails added in v0.2.1

func HarnessGroundingGuardrails(hcfg HarnessConfig) []string

HarnessGroundingGuardrails returns wiring notes for FHIR grounding behind Harness.

func IsGeneric

func IsGeneric(name string) bool

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

func IsWriteTool added in v0.2.1

func IsWriteTool(name string) bool

IsWriteTool reports whether name is a FHIR write tool (create, update, or transaction).

func NewCompactionSessionEvent added in v0.2.1

func NewCompactionSessionEvent(summary string, coveredCount int, lastCoveredEventID, basisTailEventID string, activeTokensEstimate int) store.SessionEvent

NewCompactionSessionEvent records a checkpoint summarizing prior active events (append-only).

func NewModelSessionEvent added in v0.2.1

func NewModelSessionEvent(content string, toolCalls []ChatToolCall) store.SessionEvent

NewModelSessionEvent records an assistant turn (optional tool calls).

func NewToolSessionEvent added in v0.2.1

func NewToolSessionEvent(toolCallID, content string) store.SessionEvent

NewToolSessionEvent records a tool result message.

func NewUserSessionEvent added in v0.2.1

func NewUserSessionEvent(content string) store.SessionEvent

NewUserSessionEvent records a user turn.

func NormalizeFHIRPathForCompile added in v0.2.1

func NormalizeFHIRPathForCompile(dotPath string) string

NormalizeFHIRPathForCompile converts a dot-separated element path (for example text.div) into a FHIRPath source string (for example text.`div`).

func ParseToolArguments added in v0.2.1

func ParseToolArguments(arguments string) (map[string]any, error)

ParseToolArguments decodes a tool call arguments JSON object into a map.

func PreflightSearchPolicy added in v0.2.1

func PreflightSearchPolicy(ctx context.Context, policy PolicyEngine, req ToolRequest, input map[string]any) error

PreflightSearchPolicy validates search tool input against policy before execution (stricter harness path).

func SearchParamsFromToolInput added in v0.2.1

func SearchParamsFromToolInput(input map[string]any) map[string]bool

SearchParamsFromToolInput extracts normalized search parameter base names from tool input.

func SegmentPathFromFHIRPathExpr added in v0.2.1

func SegmentPathFromFHIRPathExpr(expr string) string

SegmentPathFromFHIRPathExpr returns a dot path for JSON segment redaction when the expression is a simple property path (possibly with backticks).

func SensitiveFHIRPathsFromStructureDefinition added in v0.2.1

func SensitiveFHIRPathsFromStructureDefinition(sd *validate.StructureDefinition, rules PHIStructureRules, _ *PHICatalog) []string

SensitiveFHIRPathsFromStructureDefinition derives FHIRPath expressions from one StructureDefinition only. Catalog paths are added once in the path index build.

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.

func WarmPathIndex added in v0.2.1

func WarmPathIndex(ctx context.Context, d *FHIRDeidentifier, resourceTypes ...string) error

WarmPathIndex pre-builds path bundles for resource types.

Types

type AIAttributionConfig added in v0.2.1

type AIAttributionConfig struct {
	// Enabled applies meta.security (AIAST) and optional Provenance on successful writes.
	Enabled bool
	// CreateProvenance records a Provenance resource targeting the written resource (default true when Enabled).
	CreateProvenance *bool
	// AgentDisplay is used for Provenance.agent[].who.display when set.
	AgentDisplay string
	// ModelID is stored in Provenance.entity or agent extension when set.
	ModelID string
	// ProvenanceBestEffort when true (default), a Provenance create failure does not fail the clinical write.
	// Ignored when AtomicProvenance is true (write + Provenance use ProcessTransactionBundle).
	ProvenanceBestEffort *bool
	// AtomicProvenance when true, clinical writes with CreateProvenance use a transaction bundle
	// (resource + Provenance). execute_fhir_transaction is always atomic.
	AtomicProvenance *bool
}

AIAttributionConfig stamps AI transparency metadata on executor writes and optionally records Provenance.

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 ChatMessage added in v0.2.1

type ChatMessage struct {
	Role       string
	Content    string
	ToolCallID string
	ToolCalls  []ChatToolCall
}

ChatMessage is one turn in a conversational model session.

func ChatMessagesFromSessionEvents added in v0.2.1

func ChatMessagesFromSessionEvents(events []store.SessionEvent) []ChatMessage

ChatMessagesFromSessionEvents rebuilds model context from append-only history, using the latest compaction checkpoint plus events after it.

type ChatModel added in v0.2.1

type ChatModel interface {
	Name() string
	Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error)
}

ChatModel performs multi-message completions with optional tool definitions. Implementations include OpenAICompatibleAdapter and test fakes.

type ChatOptions added in v0.2.1

type ChatOptions struct {
	UserMessage  string
	InvocationID string
}

ChatOptions configures one user turn. InvocationID enables idempotent retries when SessionService is set.

type ChatRequest added in v0.2.1

type ChatRequest struct {
	Messages     []ChatMessage
	Tools        []ChatTool
	SystemPrompt string
	Hint         string
}

ChatRequest is input to a conversational model backend.

type ChatResponse added in v0.2.1

type ChatResponse struct {
	Adapter    string
	Content    string
	ToolCalls  []ChatToolCall
	StopReason string
}

ChatResponse is the outcome of one model completion.

type ChatResult added in v0.2.1

type ChatResult struct {
	InvocationID      string
	Answer            string
	Messages          []ChatMessage
	ToolResults       []HarnessToolResult
	Citations         []Citation
	PendingApprovals  []HarnessPendingApproval
	GroundingWarnings []string
}

ChatResult is the outcome of one Harness.Chat user turn.

type ChatTool added in v0.2.1

type ChatTool struct {
	Name        string
	Description string
	Parameters  map[string]any
}

ChatTool describes one callable tool for the model (JSON-schema parameters).

func ChatToolsFromDescriptors added in v0.2.1

func ChatToolsFromDescriptors(descriptors []ToolDescriptor) []ChatTool

ChatToolsFromDescriptors builds OpenAI-style function tools from registry metadata.

type ChatToolCall added in v0.2.1

type ChatToolCall struct {
	ID        string
	Name      string
	Arguments string
}

ChatToolCall is a model-requested tool invocation (function-style).

func ParsePromptToolCalls added in v0.2.1

func ParsePromptToolCalls(content string, allowed []ChatTool) ([]ChatToolCall, error)

ParsePromptToolCalls extracts tool invocations from assistant text.

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.

func MergeHarnessCitations added in v0.2.1

func MergeHarnessCitations(existing []Citation, results []HarnessToolResult) []Citation

MergeHarnessCitations appends unique citations from tool results (stable order).

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 CommitWriteOptions added in v0.2.1

type CommitWriteOptions struct {
	// SkipHostConfirm bypasses RequireCommitConfirmation (tests and trusted automation only).
	SkipHostConfirm bool
	// ApprovalToken resumes a policy-gated commit (same bundle input as the pending approval).
	// Host UI confirmation is not invoked again when ApprovalToken is set.
	ApprovalToken string
}

CommitWriteOptions configures host confirmation for CommitWrite.

type CompactionMetricEvent added in v0.2.1

type CompactionMetricEvent struct {
	Kind               CompactionMetricKind
	ActiveTokens       int
	MaxContextTokens   int
	EventsSummarized   int
	TokensAfterCompact int
	Err                error
}

CompactionMetricEvent is emitted when compaction is evaluated or runs.

type CompactionMetricKind added in v0.2.1

type CompactionMetricKind string

CompactionMetricKind classifies a compaction metrics observation.

const (
	CompactionMetricCheck        CompactionMetricKind = "check"
	CompactionMetricSkippedUnder CompactionMetricKind = "skipped_under_limit"
	CompactionMetricCompacted    CompactionMetricKind = "compacted"
	CompactionMetricFailed       CompactionMetricKind = "failed"
)

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
	// ProfileCatalog enables StructureDefinition-driven FHIRPath PHI rules on the
	// default FHIRDeidentifier when Deidentify is nil.
	ProfileCatalog validate.ProfileCatalog
	// PHIMode / EvalMode tune default FHIRDeidentifier performance vs coverage.
	PHIMode  PHIMode
	EvalMode EvalMode
	// SharedFHIRDeidentifier reuses a process-wide FHIRDeidentifier (default true).
	SharedFHIRDeidentifier *bool
	ModelRouter            *ModelRouter
	Citations              *CitationBuilder
	Formatter              *ContextFormatter
	Now                    func() time.Time
	// AIAttribution stamps AIAST meta.security and optional Provenance on AI-mediated writes.
	AIAttribution AIAttributionConfig
	// RequireValidatorOnWrites rejects writes when Validator is nil (production guardrail).
	RequireValidatorOnWrites bool
}

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 ContextTokenCounter added in v0.2.1

type ContextTokenCounter func(messages []ChatMessage) int

ContextTokenCounter estimates token usage for a model message list (for compaction thresholds).

func NewTiktokenContextCounter added in v0.2.1

func NewTiktokenContextCounter(encoding string) (ContextTokenCounter, error)

NewTiktokenContextCounter returns a ContextTokenCounter backed by tiktoken. Use encoding names such as TiktokenCl100kBase or TiktokenO200kBase for OpenAI-compatible models.

type CreateInput added in v0.2.1

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

CreateInput is the typed input for create_fhir_resource.

type Deidentifier

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

Deidentifier is the optional output scrubbing seam. FHIRDeidentifier handles read_fhir_resource, search_fhir_resources, and run_view only; other tool names return ErrUnsupportedDeidentifyTool unless you use PassThroughDeidentifier or a custom DeidentifierFunc. Executor wires FHIRDeidentifier by default.

func DefaultDeidentifier added in v0.2.1

func DefaultDeidentifier() (Deidentifier, error)

DefaultDeidentifier returns the standard FHIR de-identifier used when Executor Config.Deidentify is nil. Pass a custom Deidentifier to override.

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 EvalMode added in v0.2.1

type EvalMode string

EvalMode controls which FHIRPath expression strings augment segment redaction. Scrubbing does not evaluate FHIRPath against live values (only path segments derived from expression text). Search tool output skips label augmentation unless EvalModeAlways is set (see effectiveEvalMode).

const (
	// EvalModeNever uses segment and catalog paths only (no label augmentation).
	EvalModeNever EvalMode = "never"
	// EvalModeKeywordsOnly adds segment paths from expressions without an indexed
	// equivalent (e.g. text.`div`).
	EvalModeKeywordsOnly EvalMode = "keywords-only"
	// EvalModeAlways adds segment paths from every compileable expression string,
	// including on search tool output.
	EvalModeAlways EvalMode = "always"
)

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.

func (*Executor) Policy added in v0.2.1

func (e *Executor) Policy() PolicyEngine

Policy returns the configured policy engine (for harness preflight checks).

func (*Executor) ToolDescriptors added in v0.2.1

func (e *Executor) ToolDescriptors() []ToolDescriptor

ToolDescriptors returns model-facing metadata for tools on this executor.

type FHIRDeidentifier added in v0.2.1

type FHIRDeidentifier struct {
	Redacted string
	// contains filtered or unexported fields
}

FHIRDeidentifier implements Deidentifier using compiled FHIRPath expressions, StructureDefinition sensitivity (types, extensions, mustSupport/isSummary), PHICatalog paths, passive element detection, and meta.security labels.

func NewFHIRDeidentifier added in v0.2.1

func NewFHIRDeidentifier(catalog *PHICatalog) (*FHIRDeidentifier, error)

NewFHIRDeidentifier returns a de-identifier backed by catalog. When catalog is nil, DefaultPHICatalog is used. Use NewFHIRDeidentifierWithConfig for StructureDefinition-backed paths.

func NewFHIRDeidentifierWithConfig added in v0.2.1

func NewFHIRDeidentifierWithConfig(cfg FHIRDeidentifierConfig) (*FHIRDeidentifier, error)

NewFHIRDeidentifierWithConfig constructs a FHIR de-identifier.

func SharedFHIRDeidentifier added in v0.2.1

func SharedFHIRDeidentifier(cfg FHIRDeidentifierConfig) (*FHIRDeidentifier, error)

SharedFHIRDeidentifier returns a process-wide FHIRDeidentifier for equivalent configuration. Use when multiple Executors should share warm path caches.

func (*FHIRDeidentifier) Deidentify added in v0.2.1

func (d *FHIRDeidentifier) Deidentify(ctx context.Context, req DeidentifyRequest) (any, []string, error)

Deidentify implements Deidentifier.

type FHIRDeidentifierConfig added in v0.2.1

type FHIRDeidentifierConfig struct {
	Catalog  *PHICatalog
	Profiles validate.ProfileCatalog // optional StructureDefinition-driven paths
	Rules    *PHIStructureRules
	Engine   fhirpath.Engine // optional; default engine compiles catalog paths
	Redacted string
	// Mode controls StructureDefinition path breadth (default PHIModeStandard).
	Mode PHIMode
	// EvalMode controls which FHIRPath expression strings add segment paths at
	// scrub time (default EvalModeKeywordsOnly). FHIRPath is not evaluated
	// against resource values during scrubbing.
	EvalMode EvalMode
	// UseShared reuses a process-wide de-identifier instance for identical config.
	UseShared bool
}

FHIRDeidentifierConfig configures the built-in FHIR de-identifier.

type GroundingConfig added in v0.2.1

type GroundingConfig struct {
	Mode GroundingMode
	// AppendFHIRInstructions adds default grounding text to the model system prompt (default true when Mode != off).
	AppendFHIRInstructions bool
	// RequireToolEvidenceOnDataQuestions requires a successful read/search/view tool with citations before answering data-style questions (strict).
	RequireToolEvidenceOnDataQuestions bool
	// RejectUncitedResourceRefs fails the turn when the answer mentions Resource/id literals not present in citations (strict).
	RejectUncitedResourceRefs bool
	// RejectUncitedClinicalValues fails when the answer states clinical numbers/units not present in tool JSON (strict).
	RejectUncitedClinicalValues bool
	// ValidateSearchParamsInAnswer warns when the answer cites search parameters not used in search tool calls.
	ValidateSearchParamsInAnswer bool
	// PreflightSearchPolicy runs policy.CheckSearch before search_fhir_resources executes (strict default).
	PreflightSearchPolicy bool
}

GroundingConfig tunes grounding for natural-language ↔ FHIR workflows.

type GroundingMode added in v0.2.1

type GroundingMode string

GroundingMode controls harness anti-hallucination behavior for FHIR-backed answers.

const (
	// GroundingOff disables harness grounding prompts and post-checks (executor policy still applies).
	GroundingOff GroundingMode = "off"
	// GroundingStandard adds instructions and records warnings on the ChatResult.
	GroundingStandard GroundingMode = "standard"
	// GroundingStrict rejects answers that lack tool evidence or cite unknown resource refs.
	GroundingStrict GroundingMode = "strict"
)

type Harness added in v0.2.1

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

Harness orchestrates conversation turns: model completions, tool execution via Executor, and session history (persisted via SessionService when configured). It does not replace policy, audit, or FHIR validation on the executor path.

func NewHarness added in v0.2.1

func NewHarness(cfg HarnessConfig) (*Harness, error)

NewHarness validates configuration and returns a harness with an empty session.

func NewHarnessWithSession added in v0.2.1

func NewHarnessWithSession(cfg HarnessConfig, session Session) (*Harness, error)

NewHarnessWithSession binds a conversation id before Chat. With SessionService, transcript and state are always loaded from the store (preloaded Messages/State are ignored).

func (*Harness) ActiveEventsAfterCheckpoint added in v0.2.1

func (h *Harness) ActiveEventsAfterCheckpoint(ctx context.Context) ([]store.SessionEvent, error)

ActiveEventsAfterCheckpoint loads tail events after the latest compaction via SessionService.

func (*Harness) Chat added in v0.2.1

func (h *Harness) Chat(ctx context.Context, userMessage string) (*ChatResult, error)

Chat handles one user message: model completion, optional tool calls through Executor, and a final natural-language answer when the model stops requesting tools.

func (*Harness) ChatWithOptions added in v0.2.1

func (h *Harness) ChatWithOptions(ctx context.Context, opts ChatOptions) (*ChatResult, error)

ChatWithOptions runs one user turn with an optional invocation id for idempotent retries.

func (*Harness) CommitPatientCreate added in v0.2.1

func (h *Harness) CommitPatientCreate(ctx context.Context, draft PatientCreateDraft) (*ToolResult, error)

CommitPatientCreate is deprecated: use CommitWrite with ResourceWriteDraft.

func (*Harness) CommitPatientCreateFromSession added in v0.2.1

func (h *Harness) CommitPatientCreateFromSession(ctx context.Context) (*ToolResult, error)

CommitPatientCreateFromSession is deprecated: use CommitWriteFromSession.

func (*Harness) CommitWrite added in v0.2.1

func (h *Harness) CommitWrite(ctx context.Context, draft ResourceWriteDraft) (*ToolResult, error)

CommitWrite executes one write draft as a transaction bundle (host adds Provenance when configured).

func (*Harness) CommitWriteFromSession added in v0.2.1

func (h *Harness) CommitWriteFromSession(ctx context.Context) (*ToolResult, error)

CommitWriteFromSession extracts a write_resource (or legacy patient_create) block and commits.

func (*Harness) CommitWriteFromSessionWithOptions added in v0.2.1

func (h *Harness) CommitWriteFromSessionWithOptions(ctx context.Context, opts CommitWriteOptions) (*ToolResult, error)

CommitWriteFromSessionWithOptions commits a session draft after optional host confirmation.

func (*Harness) CommitWritePlan added in v0.2.1

func (h *Harness) CommitWritePlan(ctx context.Context, plan ResourceWritePlan) (*ToolResult, error)

CommitWritePlan commits multiple drafts in one atomic transaction (host adds Provenance when configured).

func (*Harness) CommitWritePlanFromSession added in v0.2.1

func (h *Harness) CommitWritePlanFromSession(ctx context.Context) (*ToolResult, error)

CommitWritePlanFromSession extracts a write_plan block and commits via transaction bundle.

func (*Harness) CommitWritePlanFromSessionWithOptions added in v0.2.1

func (h *Harness) CommitWritePlanFromSessionWithOptions(ctx context.Context, opts CommitWriteOptions) (*ToolResult, error)

CommitWritePlanFromSessionWithOptions commits a session write_plan after optional host confirmation.

func (*Harness) CommitWritePlanWithOptions added in v0.2.1

func (h *Harness) CommitWritePlanWithOptions(ctx context.Context, plan ResourceWritePlan, opts CommitWriteOptions) (*ToolResult, error)

CommitWritePlanWithOptions runs host confirmation then execute_fhir_bundle for the plan.

func (*Harness) CommitWriteWithOptions added in v0.2.1

func (h *Harness) CommitWriteWithOptions(ctx context.Context, draft ResourceWriteDraft, opts CommitWriteOptions) (*ToolResult, error)

CommitWriteWithOptions commits one draft via CommitWritePlan (transaction bundle).

func (*Harness) CompactionMetrics added in v0.2.1

func (h *Harness) CompactionMetrics() SessionCompactionMetrics

func (*Harness) CreateAgentSession added in v0.2.1

func (h *Harness) CreateAgentSession(ctx context.Context, sessionID string) error

CreateAgentSession creates a new persisted session and binds it to the harness.

func (*Harness) ExecuteHarnessTool added in v0.2.1

func (h *Harness) ExecuteHarnessTool(ctx context.Context, req ToolRequest) (*ToolResult, error)

ExecuteHarnessTool runs a single executor tool with harness actor/subject/conversation defaults. Use this to resume approval-gated writes with ApprovalToken after Chat surfaces PendingApprovals.

func (*Harness) ExecuteHarnessToolWithOptions added in v0.2.1

func (h *Harness) ExecuteHarnessToolWithOptions(ctx context.Context, req ToolRequest, commitOpts CommitWriteOptions) (*ToolResult, error)

ExecuteHarnessToolWithOptions runs a harness tool with optional commit confirmation for writes.

func (*Harness) LoadAgentSession added in v0.2.1

func (h *Harness) LoadAgentSession(ctx context.Context, sessionID string) error

LoadAgentSession loads session metadata, state, and events into the harness.

func (*Harness) LoadFullEventLog added in v0.2.1

func (h *Harness) LoadFullEventLog(ctx context.Context) ([]store.SessionEvent, error)

LoadFullEventLog loads the complete append-only event history (including pre-checkpoint events).

func (*Harness) PersistedEvents added in v0.2.1

func (h *Harness) PersistedEvents() []store.SessionEvent

PersistedEvents returns the full append-only event log (including events before compaction checkpoints).

func (*Harness) Session added in v0.2.1

func (h *Harness) Session() Session

Session returns the loaded session view (from SessionService after load/Chat, or ephemeral test history).

func (*Harness) SetConversationID added in v0.2.1

func (h *Harness) SetConversationID(id string)

SetConversationID sets the correlation id used on executor tool requests.

type HarnessConfig added in v0.2.1

type HarnessConfig struct {
	Executor     *Executor
	Model        ChatModel
	SystemPrompt string
	Actor        string
	TenantID     string
	Subject      string
	// ModelHint is passed to ChatModel backends that support routing (e.g. local vs cloud).
	ModelHint string
	// MaxToolRounds limits model completion rounds that include tool calls (default 8).
	MaxToolRounds int
	// ToolContextFormat selects JSON (default) or markdown summaries for tool messages.
	ToolContextFormat ToolContextFormat
	// EnableProposeWriteHelper exposes propose_write_resource in the harness tool list.
	EnableProposeWriteHelper bool
	// EnablePatientCreateHelper is deprecated: use EnableProposeWriteHelper (kept for compatibility).
	EnablePatientCreateHelper bool
	// BlockDirectWriteTools removes create/update FHIR write tools from the model tool list so commits
	// go through structured helpers (e.g. CommitWrite) instead of free-form tool args.
	BlockDirectWriteTools bool
	// AutoConversationID assigns a UUID when Chat runs without SetConversationID (useful with RequireConversationID).
	AutoConversationID bool
	// ToolCallProtocol selects native function tools, prompt JSON in text, or both (default native).
	ToolCallProtocol ToolCallProtocol
	// SessionService persists ADK-style sessions (events + state).
	SessionService store.SessionService
	// AppName scopes sessions (ADK app_name); defaults to DefaultHarnessAppName.
	AppName string
	// SessionCompaction optionally summarizes older events into append-only checkpoint events.
	SessionCompaction SessionCompactionConfig
	// Grounding reduces hallucination via prompts, citation checks, and optional strict enforcement.
	Grounding GroundingConfig
	// RequireCommitConfirmation requires CommitWritePlanConfirm before CommitWrite / CommitWritePlan.
	RequireCommitConfirmation bool
	// CommitWritePlanConfirm is invoked before any commit (single- or multi-entry plans).
	CommitWritePlanConfirm func(ctx context.Context, plan ResourceWritePlan) error
	// EnableProposeWritePlanHelper exposes propose_write_plan in the harness tool list.
	EnableProposeWritePlanHelper bool
}

HarnessConfig wires an upstream app to Executor-backed tools through a ChatModel.

type HarnessPendingApproval added in v0.2.1

type HarnessPendingApproval struct {
	ToolName string
	Token    string
	Preview  any
	// Input is the executor tool input to replay with ApprovalToken (often execute_fhir_bundle after harness normalization).
	Input map[string]any
}

HarnessPendingApproval captures approval-required writes surfaced during Chat.

type HarnessToolResult added in v0.2.1

type HarnessToolResult struct {
	ToolName string
	Input    map[string]any
	Result   *ToolResult
	Err      error
}

HarnessToolResult summarizes one tool invocation performed during Chat.

type MarkdownContextBuilder added in v0.2.1

type MarkdownContextBuilder struct{}

MarkdownContextBuilder formats executor tool data as markdown summaries.

func NewMarkdownContextBuilder added in v0.2.1

func NewMarkdownContextBuilder() *MarkdownContextBuilder

NewMarkdownContextBuilder returns a markdown context builder.

func (*MarkdownContextBuilder) FormatToolResult added in v0.2.1

func (b *MarkdownContextBuilder) FormatToolResult(toolName string, data any, citations []Citation) (string, error)

FormatToolResult renders tool output for model consumption.

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 ModelAdapterChatModel added in v0.2.1

type ModelAdapterChatModel struct {
	Adapter ModelAdapter
	Hint    string
}

ModelAdapterChatModel wraps a legacy ModelAdapter as a ChatModel for Harness. The adapter receives a flattened transcript and does not emit tool calls; use OpenAICompatibleAdapter (or another native ChatModel) for tool-calling loops.

func NewModelAdapterChatModel added in v0.2.1

func NewModelAdapterChatModel(adapter ModelAdapter, hint string) (*ModelAdapterChatModel, error)

NewModelAdapterChatModel returns a ChatModel backed by ModelAdapter.Invoke.

func (*ModelAdapterChatModel) Chat added in v0.2.1

Chat implements ChatModel by delegating to ModelAdapter.Invoke.

func (*ModelAdapterChatModel) Name added in v0.2.1

func (m *ModelAdapterChatModel) Name() string

Name implements ChatModel.

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 OpenAICompatibleAdapter added in v0.2.1

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

OpenAICompatibleAdapter calls a remote chat completions endpoint with tools support.

func NewOpenAICompatibleAdapter added in v0.2.1

func NewOpenAICompatibleAdapter(cfg OpenAICompatibleConfig) (*OpenAICompatibleAdapter, error)

NewOpenAICompatibleAdapter validates config and returns an adapter.

func (*OpenAICompatibleAdapter) Chat added in v0.2.1

Chat posts one chat completion request.

func (*OpenAICompatibleAdapter) Invoke added in v0.2.1

Invoke implements ModelAdapter using a single user turn (legacy Executor.InvokeModel seam).

func (*OpenAICompatibleAdapter) Name added in v0.2.1

func (a *OpenAICompatibleAdapter) Name() string

Name implements ModelAdapter and ChatModel.

type OpenAICompatibleConfig added in v0.2.1

type OpenAICompatibleConfig struct {
	BaseURL    string
	APIKey     string
	Model      string
	HTTPClient *http.Client
	Name       string
}

OpenAICompatibleConfig configures an HTTP client for chat/completions-style APIs (OpenAI, Azure OpenAI, vLLM, Ollama OpenAI shim, etc.).

type PHICatalog added in v0.2.1

type PHICatalog struct {
	// ResourceElements lists top-level elements whose entire subtree is redacted.
	// Prefer GlobalPathSuffixes and ResourcePathSuffixes for precise control.
	ResourceElements map[string][]string
	// GlobalElements are top-level subtrees redacted on every resource type.
	GlobalElements []string
	// GlobalPathSuffixes match element paths at any depth (dot notation), for
	// example "telecom.value", "name.family", "identifier.value", "text.div".
	GlobalPathSuffixes []string
	// ResourcePathSuffixes adds type-specific deep path suffixes.
	ResourcePathSuffixes map[string][]string
	// PassiveSensitiveKeys overrides default leaf element names redacted at any
	// depth (family, given, value, div, ...).
	PassiveSensitiveKeys map[string]bool
	// StrictConfidentialityCodes are v3-ConfidentialityCode values that trigger
	// aggressive redaction for the whole resource (default R and V).
	StrictConfidentialityCodes []string
	// StrictSecurityLabels maps Code.system to codes that trigger strict mode.
	StrictSecurityLabels map[string][]string
	// StrictAllowPathSuffixes are paths still returned when strict mode is active
	// (for example coded status fields).
	StrictAllowPathSuffixes []string
	// ViewColumnNames lists exact column names (case-insensitive) redacted in
	// run_view row maps.
	ViewColumnNames []string
	// ViewColumnSubstrings match when contained in a column name (case-insensitive).
	ViewColumnSubstrings []string
}

PHICatalog drives FHIR de-identification: deep FHIR path suffixes, passive element-name detection at any depth, meta.security confidentiality labels, and view column rules. Copy DefaultPHICatalog and extend fields for local profiles, or replace Executor.Config.Deidentify with a custom Deidentifier.

func DefaultPHICatalog added in v0.2.1

func DefaultPHICatalog() *PHICatalog

DefaultPHICatalog returns the built-in PHI profile for FHIR R4 tool output.

func (*PHICatalog) ElementsForResource added in v0.2.1

func (c *PHICatalog) ElementsForResource(resourceType string) []string

ElementsForResource returns top-level element names to redact for resourceType, including GlobalElements.

func (*PHICatalog) ViewColumnIsPHI added in v0.2.1

func (c *PHICatalog) ViewColumnIsPHI(column string) bool

ViewColumnIsPHI reports whether a view column name should be redacted.

type PHIMode added in v0.2.1

type PHIMode string

PHIMode controls how aggressively StructureDefinition elements become paths.

const (
	// PHIModeCatalog uses PHICatalog paths only (no SD-derived paths).
	PHIModeCatalog PHIMode = "catalog"
	// PHIModeStandard uses catalog plus SD complex types and gated primitives.
	PHIModeStandard PHIMode = "standard"
	// PHIModeFull uses catalog plus all SD-sensitive elements (including every string leaf).
	PHIModeFull PHIMode = "full"
)

type PHIStructureRules added in v0.2.1

type PHIStructureRules struct {
	// SensitiveTypeCodes marks complex or primitive types that imply redaction.
	SensitiveTypeCodes map[string]bool
	// SensitiveExtensionURLs marks elementdefinition extensions that force redaction.
	SensitiveExtensionURLs map[string]bool
	// SensitiveExtensionSubstrings match extension URLs (case-insensitive contains).
	SensitiveExtensionSubstrings []string
	// RedactMustSupportPrimitives redacts mustSupport elements with string-like types.
	RedactMustSupportPrimitives bool
	// RedactIsSummaryPrimitives redacts isSummary elements with string-like types.
	RedactIsSummaryPrimitives bool
}

PHIStructureRules controls how StructureDefinition elements become FHIRPath redaction expressions.

func DefaultPHIStructureRules added in v0.2.1

func DefaultPHIStructureRules() PHIStructureRules

DefaultPHIStructureRules returns built-in StructureDefinition sensitivity rules.

func StructureRulesForMode added in v0.2.1

func StructureRulesForMode(mode PHIMode, base PHIStructureRules) PHIStructureRules

StructureRulesForMode returns PHIStructureRules for the given mode.

type PassThroughDeidentifier

type PassThroughDeidentifier struct{}

PassThroughDeidentifier returns data unchanged with no redactions.

func (PassThroughDeidentifier) Deidentify

Deidentify implements Deidentifier.

type PatientCreateDraft added in v0.2.1

type PatientCreateDraft struct {
	Family    string
	Given     []string
	Gender    string
	BirthDate string
	Phone     string
}

PatientCreateDraft is a convenience wrapper for Patient create proposals. Prefer ResourceWriteDraft for generic create/update flows.

func ExtractPatientCreateDraft added in v0.2.1

func ExtractPatientCreateDraft(messages []ChatMessage) (PatientCreateDraft, bool)

ExtractPatientCreateDraft scans assistant messages for a fenced ```patient_create block.

func ParsePatientCreateDraftJSON added in v0.2.1

func ParsePatientCreateDraftJSON(raw string) (PatientCreateDraft, error)

ParsePatientCreateDraftJSON decodes a JSON object from model or app output.

func PatientCreateDraftFromMap added in v0.2.1

func PatientCreateDraftFromMap(input map[string]any) (PatientCreateDraft, error)

PatientCreateDraftFromMap parses harness tool arguments or JSON objects.

func (PatientCreateDraft) ToCreateFhirResourceInput added in v0.2.1

func (d PatientCreateDraft) ToCreateFhirResourceInput() (map[string]any, error)

ToCreateFhirResourceInput returns create_fhir_resource tool input only (no execution).

func (PatientCreateDraft) ToResourceWriteDraft added in v0.2.1

func (d PatientCreateDraft) ToResourceWriteDraft() (ResourceWriteDraft, error)

ToResourceWriteDraft converts the patient-specific draft to a generic write draft.

func (PatientCreateDraft) Validate added in v0.2.1

func (d PatientCreateDraft) Validate() error

Validate checks required demographics for a Patient create proposal.

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 PromptToolInvocation added in v0.2.1

type PromptToolInvocation struct {
	Tool      string         `json:"tool"`
	ToolName  string         `json:"toolName"`
	Input     map[string]any `json:"input"`
	Arguments map[string]any `json:"arguments"`
}

PromptToolInvocation is one JSON tool call embedded in model text.

type ProvenanceRecordResult added in v0.2.1

type ProvenanceRecordResult struct {
	Err     error
	Warning string
}

ProvenanceRecordResult captures best-effort provenance side effects after a write.

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 ResourceWriteDraft added in v0.2.1

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

ResourceWriteDraft is a structured create/update proposal, not arbitrary full Resource JSON. Create uses top-level fields; update uses FHIRPath patches only.

func ExtractResourceWriteDraft added in v0.2.1

func ExtractResourceWriteDraft(messages []ChatMessage) (ResourceWriteDraft, bool)

ExtractResourceWriteDraft scans assistant messages for a fenced ```write_resource block. Legacy ```patient_create blocks are converted to Patient create drafts.

func ParseResourceWriteDraftJSON added in v0.2.1

func ParseResourceWriteDraftJSON(raw string) (ResourceWriteDraft, error)

ParseResourceWriteDraftJSON decodes a JSON object from model or app output.

func ResourceWriteDraftFromMap added in v0.2.1

func ResourceWriteDraftFromMap(input map[string]any) (ResourceWriteDraft, error)

ResourceWriteDraftFromMap parses harness tool arguments or JSON objects.

func (ResourceWriteDraft) ToExecutorToolInput added in v0.2.1

func (d ResourceWriteDraft) ToExecutorToolInput() (string, map[string]any, error)

ToExecutorToolInput returns the create_fhir_resource or update_fhir_resource tool input (no execution).

func (ResourceWriteDraft) Validate added in v0.2.1

func (d ResourceWriteDraft) Validate() error

Validate checks the draft matches executor write tool rules at the harness layer.

type ResourceWritePlan added in v0.2.1

type ResourceWritePlan struct {
	// BundleType is transaction (default) or batch. Batch is required when Entries include reads.
	BundleType string
	Entries    []ResourceWriteDraft
}

ResourceWritePlan is an ordered list of bundle steps (writes and optional batch reads). When AI attribution is enabled the executor may also append Provenance for clinical writes.

func ExtractResourceWritePlan added in v0.2.1

func ExtractResourceWritePlan(messages []ChatMessage) (ResourceWritePlan, bool)

ExtractResourceWritePlan scans assistant messages for a ```write_plan block.

func ParseResourceWritePlanJSON added in v0.2.1

func ParseResourceWritePlanJSON(raw string) (ResourceWritePlan, error)

ParseResourceWritePlanJSON decodes a JSON plan from model or app output.

func ResourceWritePlanFromMap added in v0.2.1

func ResourceWritePlanFromMap(input map[string]any) (ResourceWritePlan, error)

ResourceWritePlanFromMap parses harness tool arguments.

func ResourceWritePlanFromTransactionInput added in v0.2.1

func ResourceWritePlanFromTransactionInput(input map[string]any) (ResourceWritePlan, error)

ResourceWritePlanFromTransactionInput converts execute_fhir_bundle input to a plan.

func (ResourceWritePlan) ToTransactionInput added in v0.2.1

func (p ResourceWritePlan) ToTransactionInput() (map[string]any, error)

ToTransactionInput builds execute_fhir_bundle input for commit execution.

func (ResourceWritePlan) Validate added in v0.2.1

func (p ResourceWritePlan) Validate() error

Validate checks each entry and bundle shape.

func (ResourceWritePlan) ValidateForCommit added in v0.2.1

func (p ResourceWritePlan) ValidateForCommit() error

ValidateForCommit checks Validate and requires at least one create/update (reads alone are confirm-only).

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 Session added in v0.2.1

type Session struct {
	ConversationID string
	Messages       []ChatMessage
	State          map[string]any
}

Session is the harness view of a stored agent session after load (or ephemeral test mode). ConversationID is set before Chat; Messages and State come from SessionService when configured.

func SessionFromAgentSession added in v0.2.1

func SessionFromAgentSession(rec *store.AgentSession) Session

SessionFromAgentSession maps a stored session into harness memory (events → chat messages).

type SessionCompactionConfig added in v0.2.1

type SessionCompactionConfig struct {
	// MaxContextTokens triggers compaction when active model context exceeds this estimate (0 = disabled).
	MaxContextTokens int
	// TokenCounter estimates tokens for the active message list (default EstimateChatMessagesTokens).
	TokenCounter ContextTokenCounter
	// Summarizer overrides the default ChatModel summarization (optional).
	Summarizer SessionCompactionSummarizer
	// OnMetric receives compaction telemetry (optional).
	OnMetric func(CompactionMetricEvent)
	// RetainRecentEvents keeps this many newest events after the checkpoint uncompacted (default 12).
	RetainRecentEvents int
	// MinEventsToCompact requires at least this many active events before compacting (default 16).
	MinEventsToCompact int
	// CompactHeadroomTokens compacts when active tokens exceed MaxContextTokens minus this buffer (default 2048).
	CompactHeadroomTokens int
}

SessionCompactionConfig controls append-only context compaction via checkpoint events.

type SessionCompactionMetrics added in v0.2.1

type SessionCompactionMetrics struct {
	Checks            uint64
	SkippedUnderLimit uint64
	Compactions       uint64
	Failures          uint64
	LastActiveTokens  int
	LastTokensAfter   int
}

SessionCompactionMetrics is cumulative compaction telemetry for one harness instance.

type SessionCompactionSummarizeInput added in v0.2.1

type SessionCompactionSummarizeInput struct {
	PriorCheckpointSummary string
	Events                 []store.SessionEvent
}

SessionCompactionSummarizeInput is passed to a custom compaction summarizer.

type SessionCompactionSummarizer added in v0.2.1

type SessionCompactionSummarizer func(ctx context.Context, in SessionCompactionSummarizeInput) (string, error)

SessionCompactionSummarizer compresses a segment of session events into checkpoint text.

type ToolCallProtocol added in v0.2.1

type ToolCallProtocol string

ToolCallProtocol selects how the harness interprets model tool requests.

const (
	// ToolCallProtocolNative uses provider-native tool_calls only (OpenAI function tools).
	ToolCallProtocolNative ToolCallProtocol = "native"
	// ToolCallProtocolPromptJSON parses tool JSON from assistant message text.
	ToolCallProtocolPromptJSON ToolCallProtocol = "prompt_json"
	// ToolCallProtocolBoth accepts native tool_calls first, then prompt JSON fallback.
	ToolCallProtocolBoth ToolCallProtocol = "both"
)

type ToolContextFormat added in v0.2.1

type ToolContextFormat string

ToolContextFormat selects how tool results are returned to the model in Harness.Chat.

const (
	// ToolContextJSON uses executor ContextFormatter output (indented JSON).
	ToolContextJSON ToolContextFormat = "json"
	// ToolContextMarkdown renders read/search/view rows as markdown for models.
	ToolContextMarkdown ToolContextFormat = "markdown"
)

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 FilterToolDescriptorsForHarness added in v0.2.1

func FilterToolDescriptorsForHarness(descriptors []ToolDescriptor, blockDirectWrites bool) []ToolDescriptor

FilterToolDescriptorsForHarness optionally removes direct write tools from the model tool list.

func GenericToolDescriptors

func GenericToolDescriptors() []ToolDescriptor

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

func ProposePatientCreateToolDescriptor added in v0.2.1

func ProposePatientCreateToolDescriptor() ToolDescriptor

ProposePatientCreateToolDescriptor is deprecated: use ProposeWriteResourceToolDescriptor.

func ProposeWritePlanToolDescriptor added in v0.2.1

func ProposeWritePlanToolDescriptor() ToolDescriptor

ProposeWritePlanToolDescriptor returns harness-only tool metadata.

func ProposeWriteResourceToolDescriptor added in v0.2.1

func ProposeWriteResourceToolDescriptor() ToolDescriptor

ProposeWriteResourceToolDescriptor returns harness-only tool metadata.

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 UpdateInput added in v0.2.1

type UpdateInput struct {
	ResourceType string
	ID           string
	Patches      map[string]any
}

UpdateInput is the typed input for update_fhir_resource.

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 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.

CreateFields lists allowed top-level field names (and dotted top-level paths for create). UpdateFields lists allowed patch keys for update_fhir_resource. A listed parent path also allows descendants (e.g. "name" allows name[0].family). Do not list resourceType or id.

Jump to

Keyboard shortcuts

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