agentdecl

package
v1.1.0 Latest Latest
Warning

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

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

Documentation

Overview

Package agentdecl reads agent declarations — Markdown with a YAML frontmatter header — and renders each as the task chain and human-in-the-loop policy that run it.

Index

Constants

View Source
const (
	MacroRoundsUsed         = "{{rounds_used}}"
	MacroRecoveryRoundsUsed = "{{recovery_rounds_used}}"
	MacroMainRounds         = "{{main_rounds}}"
	MacroRecoveryRounds     = "{{recovery_rounds}}"
)

Loop macros a declaration may use. Both the round count and the budget are known only to the emitter, so a prompt cannot state either literally without going stale.

View Source
const (
	AxisFilesRead      = "files.read"
	AxisFilesWrite     = "files.write"
	AxisShell          = "shell"
	AxisNetworkRead    = "network.read"
	AxisNetworkWrite   = "network.write"
	AxisMissionsFire   = "missions.fire"
	AxisMissionsAnswer = "missions.answer"
)

Axis names. An axis left unset emits no rule at all: it falls through to default_action rather than being implicitly "approve".

View Source
const AgentFilename = "agent.md"

AgentFilename is the declaration at a tree node. A directory holding one is a node; a directory holding subdirectories as well is a router over them.

View Source
const ChainSchemaURL = "https://contenox.com/schema/task-chain.schema.json"

ChainSchemaURL is stamped on emitted chains so an editor completes and validates them the way it does the shipped ones.

View Source
const ConfigFilename = "agents.toml"

ConfigFilename is the operator-editable overlay read from each root.

View Source
const EnvelopeSection = "envelopes"

EnvelopeSection is the agents.toml table an operator writes policy in.

View Source
const FailureFilename = "failure.md"

FailureFilename is the optional terminal prompt at a tree's root: what the chain says when every branch has given up.

View Source
const FieldMCPServers = "mcpServers"

FieldMCPServers is Claude Code's own key. A list of names is a grant against servers the operator registered; a map is a set of definitions the agent brings with it.

View Source
const FieldRemoteTools = "remoteTools"

FieldRemoteTools has no counterpart in any source dialect; it is contenox's own.

View Source
const GeneratedDirName = ".generated"

GeneratedDirName holds transpiled chains. Everything in it is derived and is replaced whenever its source changes; the declaration is what an operator edits.

View Source
const NativeSourceDir = "agents"

NativeSourceDir is where agents are authored inside a contenox directory, as Markdown with YAML frontmatter rather than chain JSON.

View Source
const PolicySchemaURL = "https://contenox.com/schema/hitl-policy-v1.schema.json"

PolicySchemaURL is stamped on emitted policies so an editor completes and validates them the way it does the shipped presets.

View Source
const PreseedStateFilename = ".preseed-state.json"

PreseedStateFilename records the shipped bytes each seeded declaration came from. It sits beside the compiled chains: a copy whose bytes still match what this file recorded writing is ours to refresh, and anything else is the operator's.

View Source
const RecoveryFilename = "recovery.md"

RecoveryFilename is the optional second attempt beside a leaf's agent.md.

View Source
const RoleSubagent = RoleMission

RoleSubagent is what the source formats call RoleMission.

View Source
const SkillDirName = "skills"

SkillDirName is where procedures live inside a contenox directory, beside the agents that use them.

View Source
const SkillsMacro = "{{skills}}"

SkillsMacro is what a declaration writes to pull the inventory in. It expands when the chain is generated, not per request.

View Source
const SyncStateFilename = ".sync-state.json"

SyncStateFilename maps each source to what it produced, so a pass can skip unchanged sources and retire chains whose source is gone.

View Source
const ToolsInheritAll = "*"

ToolsInheritAll is the declaration token for "every connected toolset", matching the chain allowlist's own "*": every connected toolset with no exceptions. "!name" is how a declaration drops one of them.

View Source
const TreeDialect = DialectClaudeCode

TreeDialect is the dialect a tree's declarations are read as.

Variables

View Source
var ErrNoEnvelope = errors.New("agentdecl: no such envelope")

ErrNoEnvelope reports a name the envelopes table does not carry. Separate from a malformed envelope so a caller can fall back rather than fail.

View Source
var ForeignSourceDirs = []string{
	path.Join(".claude", "agents"),
	path.Join(".agents", "agents"),
}

ForeignSourceDirs are where other tools keep the same files, relative to a workspace root.

View Source
var Preseeded = []struct {
	// RelPath is relative to the contenox directory.
	RelPath string
	// Source is the file in this package that ships the content.
	Source  string
	Content func() string
}{
	{ConfigFilename, "agents.toml", func() string { return string(shippedConfig) }},
	{path.Join(NativeSourceDir, "README.md"), "preseed/README.md", func() string { return preseedReadme }},
	{path.Join(NativeSourceDir, "reviewer.md"), "preseed/reviewer.md", func() string { return preseedReviewer }},
	{path.Join(NativeSourceDir, "researcher.md"), "preseed/researcher.md", func() string { return preseedResearcher }},
	{path.Join(NativeSourceDir, "run.md"), "preseed/run.md", func() string { return preseedRun }},
	{path.Join(NativeSourceDir, "chat.md"), "preseed/chat.md", func() string { return preseedChat }},
}

Preseeded are the files that establish the authoring convention.

View Source
var ReservedNames = map[string]bool{
	"agent-planner": true,
}

ReservedNames are the shipped agents a declaration may not take the id of. The workspace directory is the first root chainagents scans, so a declaration claiming one would shadow the shipped agent rather than error.

Functions

func ChainFileFor added in v1.1.0

func ChainFileFor(chainID string) string

ChainFileFor is the one filename rule a compiled declaration's chain follows. The chain-agent- prefix is load-bearing: chainagents reads the BASENAME to decide what is an agent template, so a host that loads the chain back must name it the way the compiler did.

func EmitChain

func EmitChain(ir *AgentIR, cfg Config) (*taskengine.TaskChainDefinition, error)

EmitChain renders one agent as a task chain, so a declared agent rides the same tool loop and retry behaviour as a native one. It emits one loop; see EmitTree for a directory of declarations that becomes a router over several.

func EmitPolicy

func EmitPolicy(ir *AgentIR, cfg Config) (*hitlservice.Policy, error)

EmitPolicy widens the agent's single permission setting into the rules that govern it. Rules are first-match-wins, so unconditional denies precede every grant, and an unnamed tool falls to DefaultAction.

func EmitTree added in v0.40.6

func EmitTree(root *AgentTree, cfg Config) (*taskengine.TaskChainDefinition, error)

EmitTree renders a tree as one task chain: a router per branching node, the five-task loop per leaf, and a single terminal they all fall back to.

func EnvelopeName added in v1.0.0

func EnvelopeName(s string) (string, bool)

EnvelopeName resolves what an operator may write for one envelope — its bare name or the filename it transpiles to — to the bare name.

func EnvelopePolicyFile added in v1.0.0

func EnvelopePolicyFile(name string) string

EnvelopePolicyFile is the filename an envelope transpiles to. sync.go derives a declared agent's policy filename the same way, so the two families share one namespace and a collision is an error rather than an overwrite.

func PolicyFileFor added in v1.0.0

func PolicyFileFor(stem string) string

PolicyFileFor is the one filename rule both policy families follow.

func RenderEnvelopePolicy added in v1.0.0

func RenderEnvelopePolicy(cfg Config, name, source string) ([]byte, error)

RenderEnvelopePolicy transpiles one named envelope into the policy document the loader reads, annotated with where it came from so the file explains itself to whoever finds it.

func RenderSkillInventory

func RenderSkillInventory(skills []Skill) string

RenderSkillInventory is what {{skills}} becomes: one line per procedure, with the path to read. The index, not the bodies.

func SyncEnvelopePolicy added in v1.0.0

func SyncEnvelopePolicy(ctx context.Context, cfg Config, name string, generatedDir Root, source string) (string, bool, error)

SyncEnvelopePolicy writes one rendered envelope into the generated root, reporting whether the file changed. The directory is derived, so an unchanged render is left alone rather than rewritten.

func ToolPatternRef added in v1.0.0

func ToolPatternRef(pattern string) (tools, tool string, err error)

ToolPatternRef maps one tool pattern onto the (tools, tool) pair a rule carries. A bare toolset is that toolset's wildcard.

func ToolSets

func ToolSets(connected []string) []string

ToolSets returns the distinct toolset names covering the given connected tools, which is the vocabulary execute_config.tools takes.

Types

type AgentIR

type AgentIR struct {
	Source       Source `json:"source"`
	Name         string `json:"name"`
	Description  string `json:"description"`
	SystemPrompt string `json:"system_prompt"`
	Model        Model  `json:"model"`
	Tools        Tools  `json:"tools"`
	// MCPServers are names of servers the operator already registered — a
	// grant, not a definition. DeclaredMCP and DeclaredRemote are definitions
	// the agent brought itself, registered scoped to it.
	MCPServers     []string             `json:"mcp_servers,omitempty"`
	DeclaredMCP    []DeclaredMCPServer  `json:"declared_mcp,omitempty"`
	DeclaredRemote []DeclaredRemoteTool `json:"declared_remote,omitempty"`
	Role           Role                 `json:"role"`
	Posture        Posture              `json:"posture"`
	// Think maps onto execute_config.think; the source and contenox
	// vocabularies for reasoning effort coincide.
	Think string `json:"think,omitempty"`
	// DefaultBranch names the child a ROUTER falls back to. Meaningful only on
	// a directory that has children; see AgentTree.
	DefaultBranch string     `json:"default_branch,omitempty"`
	Temperature   *float32   `json:"temperature,omitempty"`
	Budgets       Budgets    `json:"budgets"`
	Unmapped      []Unmapped `json:"unmapped,omitempty"`
}

AgentIR is one parsed agent in the shape both emitters consume.

func Parse

func Parse(path string, data []byte, cfg Config) (*AgentIR, error)

Parse detects the dialect and delegates. Callers that already know the dialect should call its parser directly.

func ParseAntigravity

func ParseAntigravity(path string, data []byte, cfg Config) (*AgentIR, error)

ParseAntigravity parses an Antigravity agent definition. Its name comes from the enclosing directory when the frontmatter omits it, since the format fixes the filename at agent.md.

func ParseAs

func ParseAs(dialect Dialect, path string, data []byte, cfg Config) (*AgentIR, error)

ParseAs parses with the dialect stated rather than detected.

func ParseClaudeCode

func ParseClaudeCode(path string, data []byte, cfg Config) (*AgentIR, error)

ParseClaudeCode parses a .claude/agents definition. Frontmatter keys it does not recognize are reported through AgentIR.Unmapped rather than rejected, so a newer Claude Code release does not break the importer.

func (*AgentIR) AddUnmapped

func (ir *AgentIR) AddUnmapped(field, value, reason string)

AddUnmapped records a source field that will not be carried.

func (*AgentIR) DeclaredToolsetNames

func (ir *AgentIR) DeclaredToolsetNames(agentID string) []string

DeclaredToolsetNames are the registered names of the sources this agent brought, in declaration order. It is the single place that contract is expressed.

func (*AgentIR) RunsAsSubagent

func (ir *AgentIR) RunsAsSubagent() bool

RunsAsSubagent reports whether the declaration asked to be entered as a mission unit, which decides the turn budget and attention block it gets.

func (*AgentIR) ScopedName

func (ir *AgentIR) ScopedName(scopeWithDialect bool) string

ScopedName is the emitted chain id, which chainagents also uses as the registry name. Scoping by dialect stops two products' identically named agents from resolving to one row.

type AgentTree added in v0.40.6

type AgentTree struct {
	// Name is the directory's name, and for a child also the branch label the
	// router matches on.
	Name string
	// Agent is this node's declaration: a leaf's agent, or a router's classifier.
	Agent *AgentIR
	// Recovery is the leaf's second attempt, or nil. Always nil on a router.
	Recovery *AgentIR
	// Children are the branches, sorted by name so emission is deterministic.
	Children []*AgentTree
	// Default names the child a router falls back to when the classifier answers
	// something unmapped.
	Default string
	// Failure is the tree's terminal prompt, read from failure.md at the root.
	Failure *AgentIR
}

AgentTree is a directory of declarations: one agent, or a router over the agents beneath it.

func LoadTree added in v0.40.6

func LoadTree(ctx context.Context, dir Root, cfg Config) (*AgentTree, error)

LoadTree reads a directory as an agent tree. A directory qualifies when it holds an agent.md; subdirectories that hold one become branches.

func (*AgentTree) IsRouter added in v0.40.6

func (t *AgentTree) IsRouter() bool

IsRouter reports whether this node branches.

func (*AgentTree) Labels added in v0.40.6

func (t *AgentTree) Labels() []string

Labels returns the branch labels this router accepts, in emission order.

func (*AgentTree) MergedIR added in v0.40.6

func (t *AgentTree) MergedIR() *AgentIR

MergedIR is the tree seen as one agent, for what is decided per chain rather than per task. Tools are the union of every leaf's, the posture the broadest, and the hash covers every node.

type AttentionDefaults

type AttentionDefaults struct {
	AllowAgentAnswers   bool `toml:"allow_agent_answers"`
	MaxAgentAnswers     int  `toml:"max_agent_answers"`
	AllowAgentApprovals bool `toml:"allow_agent_approvals"`
	MaxAgentApprovals   int  `toml:"max_agent_approvals"`
}

AttentionDefaults say who besides a human may resolve a mission-role agent's asks. Both grants default off: an imported declaration states what an agent should do, never who may answer for it.

type AxisGrant added in v1.0.0

type AxisGrant struct {
	Grant string
	// DenyPaths and ApprovePaths refine the two files axes.
	DenyPaths    []string
	ApprovePaths []string
	// Blacklist, Substitution, PrefixAllowlist and AskAlways refine shell.
	Blacklist       []string
	Substitution    string
	PrefixAllowlist []string
	AskAlways       []string
	// DenyHosts refines the two network axes.
	DenyHosts []string
	// Timeout zero emits no rule deadline, leaving the ask on the operator's approval ceiling; a negative Timeout is hitlservice.WaitIndefinite, which emits no deadline at all; OnTimeout "" is its deny.
	Timeout   time.Duration
	OnTimeout string
}

AxisGrant is one grant an operator wrote — a capability axis, a tools pattern, or default_action: an action, plus the refinements that grant's position accepts. `shell = "approve"` is sugar for `shell = { grant = "approve" }`; both forms decode here, so the two can never diverge.

type Budgets

type Budgets struct {
	MaxTurns *int `json:"max_turns,omitempty"`
}

Budgets are execution bounds the source expressed. They bound what an agent may spend, so they land in the policy rather than the chain.

type ChainDefaults

type ChainDefaults struct {
	TokenLimit int64  `toml:"token_limit"`
	MaxTokens  string `toml:"max_tokens"`
	Think      string `toml:"think"`
	// MainRounds and RecoveryRounds bound the two-stage tool loop.
	MainRounds     int `toml:"main_rounds"`
	RecoveryRounds int `toml:"recovery_rounds"`
	RetryOnFailure int `toml:"retry_on_failure"`
	// Shift slides the context window on overflow instead of failing the task.
	Shift bool `toml:"shift"`
	// RetryPolicy wraps every model call of an emitted chain: transient
	// provider failures are retried with backoff instead of failing the task.
	RetryPolicy *llmretry.RetryPolicy `toml:"retry_policy"`
}

ChainDefaults are the execution bounds no declaration states.

type ComputeDefaults

type ComputeDefaults struct {
	MaxToolCalls int    `toml:"max_tool_calls"`
	MaxTokens    int    `toml:"max_tokens"`
	OnExhausted  string `toml:"on_exhausted"`
	// MaxTurns is the drive loop's own budget; it applies to a mission-role
	// agent only, since a primary agent's turns are the operator's prompts.
	MaxTurns         int      `toml:"max_turns"`
	ModelAllowlist   []string `toml:"model_allowlist"`
	BackendAllowlist []string `toml:"backend_allowlist"`
}

ComputeDefaults bound what one run may spend.

type Config

type Config struct {
	Version       int                          `toml:"version"`
	Chain         ChainDefaults                `toml:"chain"`
	Routing       RoutingDefaults              `toml:"routing"`
	ToolsPolicies map[string]map[string]string `toml:"tools_policies"`
	Policy        PolicyDefaults               `toml:"policy"`
	Naming        NamingDefaults               `toml:"naming"`
	// Tools maps a name a declaration may use onto a connected tool,
	// "toolset.tool". Models maps a declaration's model name onto
	// "provider:model".
	Tools  map[string]string `toml:"tools"`
	Models map[string]string `toml:"models"`
	// Envelopes holds [envelopes.<name>] sections, each transpiling to one HITL
	// policy. Held raw for the same reason Agents is: an axis omitted must stay
	// omitted through the overlay merge, and a typed struct could not tell
	// `shell = "deny"` from an absent key.
	Envelopes map[string]map[string]any `toml:"envelopes"`
	// Agents holds per-agent overlays keyed by the agent's id. Held raw so For
	// can replay it through the same decode the roots use; a typed struct could
	// not tell `retry_on_failure = 0` from an absent key.
	Agents map[string]map[string]any `toml:"agents"`
}

Config is agents.toml: everything an agent declaration cannot state, plus the names its tools and models resolve to.

func Load

func Load(ctx context.Context, roots ...Root) (Config, error)

Load returns the shipped defaults with each root's overlay applied in order, weakest first. A root without the file is skipped; an unreadable or malformed one is an error.

func Shipped

func Shipped() (Config, error)

Shipped returns the configuration compiled into the binary, without operator overlays.

func (Config) EnvelopeNames added in v1.0.0

func (cfg Config) EnvelopeNames() []string

EnvelopeNames lists the declared envelopes, sorted.

func (Config) For

func (cfg Config) For(agent string) (Config, error)

For resolves the configuration one agent runs under: the root-wide values with that agent's [agents.<id>] overlay applied. A key the overlay omits keeps what it inherited, including zero values and false.

func (Config) MapModel

func (c Config) MapModel(name string) (provider, id string, ok bool)

MapModel resolves a declaration's model name to a provider and id. An unrecognized name yields ok false, which leaves routing templated.

func (Config) MapTools

func (c Config) MapTools(names []string) ([]string, []Unmapped, error)

MapTools resolves declaration tool names to connected tools, preserving order and dropping duplicates. An unresolved name is dropped and reported; only a list where nothing resolves is an error.

func (Config) ParseEnvelope added in v1.0.0

func (cfg Config) ParseEnvelope(name string) (Envelope, error)

ParseEnvelope decodes one declared envelope without resolving its extends.

func (Config) PostureEnvelope added in v1.0.0

func (cfg Config) PostureEnvelope(p Posture) (Envelope, error)

PostureEnvelope resolves one posture to the envelope that expresses it. The envelopes table is authoritative; a configuration that still writes [policy.postures] directly is adapted onto the same axes, so both reach the emitter through one vocabulary.

func (Config) ResolveEnvelope added in v1.0.0

func (cfg Config) ResolveEnvelope(name string) (Envelope, error)

ResolveEnvelope returns the envelope with its extends chain applied, parent first. A missing parent, a cycle, and a chain deeper than maxEnvelopeChainDepth are all errors naming the offender.

func (Config) UnknownAgents

func (cfg Config) UnknownAgents(known map[string]bool) []string

UnknownAgents reports overlay sections naming an agent that does not exist. A mistyped id is otherwise a silent no-op, which reads as the knob having no effect rather than as a typo.

func (Config) Validate

func (cfg Config) Validate() error

Validate reports defaults that would emit a chain that cannot run.

type DeclaredMCPServer

type DeclaredMCPServer struct {
	// Declared is the name written in the declaration. The registered name is
	// derived from it and the agent id, so it is scoped rather than global.
	Declared  string            `json:"declared"`
	Transport string            `json:"transport"`
	Command   string            `json:"command,omitempty"`
	Args      []string          `json:"args,omitempty"`
	URL       string            `json:"url,omitempty"`
	Headers   map[string]string `json:"headers,omitempty"`
	// AuthEnvKey names an environment variable holding the token. A literal
	// token is refused: a declaration is a file that gets committed.
	AuthEnvKey string `json:"auth_env_key,omitempty"`
	AuthType   string `json:"auth_type,omitempty"`
}

DeclaredMCPServer is an MCP server an agent brought with it, rather than one the operator registered. Fields mirror runtimetypes.MCPServer; the row is built in the surface layer, which is the only place with a database.

type DeclaredRemoteTool

type DeclaredRemoteTool struct {
	Declared    string            `json:"declared"`
	EndpointURL string            `json:"endpoint_url"`
	SpecURL     string            `json:"spec_url,omitempty"`
	TimeoutMs   int               `json:"timeout_ms,omitempty"`
	Headers     map[string]string `json:"headers,omitempty"`
}

DeclaredRemoteTool is an OpenAPI service an agent brought with it. Every operation in the spec becomes a callable tool, exactly as with `contenox tools add`.

type Dialect

type Dialect string

Dialect names a source format.

const (
	DialectClaudeCode  Dialect = "claude-code"
	DialectAntigravity Dialect = "antigravity"
	DialectCopilot     Dialect = "copilot"
	DialectOpenCode    Dialect = "opencode"
	DialectCursor      Dialect = "cursor"
)

func DetectDialect

func DetectDialect(path string, data []byte) (Dialect, error)

DetectDialect establishes which product a file was written for, strongest signal first: the nearest ancestor agents directory, then the filename shape, then a frontmatter key unique to one dialect. It refuses rather than guess.

type Envelope added in v1.0.0

type Envelope struct {
	Name            string
	Extends         string
	Description     string
	DefaultAction   AxisGrant
	Axes            map[string]AxisGrant
	Tools           map[string]AxisGrant
	Compute         map[string]any
	Attention       map[string]any
	TrustedBinaries map[string]any
	AlwaysDeny      []StandingRule
	AlwaysAllow     []StandingRule
}

Envelope is one [envelopes.<name>] section, parsed but not yet layered onto its parent. Compute, Attention and TrustedBinaries stay raw so extends can merge them per leaf key; a typed struct could not tell an absent bound from a zero one.

type ErrAmbiguousDialect

type ErrAmbiguousDialect struct{ Path string }

ErrAmbiguousDialect reports a file whose source product could not be established. Guessing would apply the wrong tool vocabulary and silently mis-map, so detection refuses instead.

func (*ErrAmbiguousDialect) Error

func (e *ErrAmbiguousDialect) Error() string

type ErrMissingField

type ErrMissingField struct {
	Path  string
	Field string
}

ErrMissingField reports a required field the source omitted.

func (*ErrMissingField) Error

func (e *ErrMissingField) Error() string

type ErrNoFrontmatter

type ErrNoFrontmatter struct{ Path string }

ErrNoFrontmatter reports a source file that is not an agent definition.

func (*ErrNoFrontmatter) Error

func (e *ErrNoFrontmatter) Error() string

type ErrUnknownTool

type ErrUnknownTool struct {
	Tools []string
}

ErrUnknownTool reports declaration tool names that resolve to nothing connected. It names every unresolved entry rather than the first.

func (*ErrUnknownTool) Error

func (e *ErrUnknownTool) Error() string

type ErrUnsafePosture

type ErrUnsafePosture struct {
	Name    string
	Dialect Dialect
}

ErrUnsafePosture reports a source asking for permission prompts to be skipped entirely.

func (*ErrUnsafePosture) Error

func (e *ErrUnsafePosture) Error() string

type Model

type Model struct {
	Raw      string `json:"raw"`
	Provider string `json:"provider,omitempty"`
	ID       string `json:"id,omitempty"`
}

Model is the requested model. Raw survives mapping so a later import can remap it without re-reading the source.

type NamingDefaults

type NamingDefaults struct {
	ScopeWithDialect bool `toml:"scope_with_dialect"`
}

NamingDefaults control emitted identity.

type PolicyDefaults

type PolicyDefaults struct {
	DefaultAction string          `toml:"default_action"`
	Compute       ComputeDefaults `toml:"compute"`
	// Attention is emitted only for a mission-role agent; a primary agent has
	// nobody to escalate to.
	Attention  AttentionDefaults `toml:"attention"`
	AlwaysDeny []StandingRule    `toml:"always_deny"`
	// AlwaysAllow grants tools the postures do not name — typically a tool the
	// operator connected. Emitted after AlwaysDeny, so it can never widen past
	// a credential deny.
	AlwaysAllow []StandingRule           `toml:"always_allow"`
	Postures    map[string]PostureGrants `toml:"postures"`
}

PolicyDefaults describe the emitted human-in-the-loop policy.

type Posture

type Posture string

Posture is the normalized permission intent, ordered most to least restrictive.

const (
	PostureReadOnly  Posture = "read_only"
	PostureAskAlways Posture = "ask_always"
	PostureAutoEdit  Posture = "auto_edit"
	// PostureUnsafe is a source asking for permission prompts to be skipped
	// entirely. Emitting it requires explicit operator consent.
	PostureUnsafe Posture = "unsafe"
)

func ParsePosture added in v1.0.0

func ParsePosture(raw string) (Posture, error)

ParsePosture reads contenox's own posture vocabulary, which is the name of the envelope a declaration runs under. "unsafe" is refused here rather than at emit time so the declaration naming it fails with the same message an operator gets from a foreign dialect asking for the same thing.

type PostureGrants

type PostureGrants struct {
	LocalFSRead  string `toml:"local_fs_read"`
	LocalFSWrite string `toml:"local_fs_write"`
	LocalShell   string `toml:"local_shell"`
}

PostureGrants is how one permission setting widens into rules.

type PreseedResult added in v1.1.0

type PreseedResult struct {
	// Created are paths written because the directory held nothing there.
	Created []string
	// Updated are paths replaced with shipped content. Only a copy recognised as
	// ours is refreshed — the bytes this mechanism recorded writing, or a version
	// a release shipped, which is what keeps an operator's edit from being
	// overwritten by a later release.
	Updated []string
	// Edited are paths this mechanism wrote and the operator then changed. Left
	// alone and still recorded, so one restored to its shipped bytes is
	// refreshable again.
	Edited []string
	// Unrecorded are paths that differ from every shipped version and carry no
	// record: a declaration the operator authored. Reported the first time they
	// are seen, then kept without further notice, because nothing about them
	// changes until the operator edits them again.
	Unrecorded []string
}

PreseedResult is what one seeding pass did with the shipped declarations.

func Preseed

func Preseed(ctx context.Context, contenoxDir Root) (PreseedResult, error)

Preseed writes the authoring convention into the root, leaving the operator's own files alone, and refreshes a shipped copy a later release changed. The defaults file is written verbatim so its comments survive: they are what makes the knobs tunable.

type PreseedSource added in v1.1.0

type PreseedSource struct {
	Rel    string
	Source string
}

PreseedSource is one shipped declaration: where seeding writes it under a contenox directory, and the file in this package that holds the content.

func PreseedSources added in v1.1.0

func PreseedSources() ([]PreseedSource, error)

PreseedSources reports every shipped declaration and its source file. The blessed-hash table is generated from those files' history, so the mapping has to be the one seeding reads.

type Role

type Role string

Role is how the source expects the agent to be entered.

const (
	RolePrimary Role = "primary"
	RoleMission Role = "mission"
	RoleBoth    Role = "both"
)

type Root added in v1.1.0

type Root struct {
	// Key names the root, and the files under it, in reports and sync state.
	Key string
	// FS is the handle over Key. A call that takes a Root refuses a nil one.
	FS vfs.Files
	// Local marks a root whose Key is an operating-system path, so a path under
	// it is spelled with the host's separator. A stored root spells them with
	// slashes.
	Local bool
}

Root is one place declarations and their generated output live: an open vfs.Files handle, the path that names it in reports, and whether that path is an operating-system one.

The handle is what lets a declaration compile from a directory on disk and from a tenant's tree in a store through one code path. Key is what a human reads in a refusal and what the sync state keys a source by, so it has to stay stable across passes: a key that changes retires and rewrites every chain it names.

func LocalRoot added in v1.1.0

func LocalRoot(dir string) (Root, error)

LocalRoot opens a directory on disk as a Root. The directory need not exist: a root is a name, and the first read is what decides whether it holds anything. It permits the runtime to manage its own declarations inside the control plane; the returned handle must never be exposed as an agent file tool.

Key is the RESOLVED directory, not the string the caller passed. The sync state keys every source by the path it was read from, so a Key that changed spelling — a symlinked checkout, a relative path — would retire every chain the previous pass compiled, and chain discovery disables an agent whose chain file has vanished.

func (Root) Base added in v1.1.0

func (r Root) Base() string

Base is the root's own name, which is what an agent tree takes its name from.

func (Root) Child added in v1.1.0

func (r Root) Child(rel string) (Root, error)

Child returns the root of a directory inside this one. The directory need not exist.

func (Root) Path added in v1.1.0

func (r Root) Path(rel string) string

Path names a path inside the root the way this root's Key spells paths: with the host's separator under a directory on disk, with slashes under a store.

type RoutingDefaults

type RoutingDefaults struct {
	Model    string `toml:"model"`
	Provider string `toml:"provider"`
	// PinModel emits the source's own model instead of the templates, when the
	// registry could resolve it.
	PinModel bool `toml:"pin_model"`
	// RouterModel and RouterProvider run a tree's classifier nodes. Empty falls
	// back to Model/Provider.
	RouterModel    string `toml:"router_model"`
	RouterProvider string `toml:"router_provider"`
	// AltModel and AltProvider run the recovery and terminal nodes: a second
	// attempt and a failure summary do not need the model the first attempt
	// used. Empty falls back to Model/Provider.
	AltModel    string `toml:"alt_model"`
	AltProvider string `toml:"alt_provider"`
}

RoutingDefaults hold model routing, as templates unless the operator pins them.

type Skill

type Skill struct {
	Name        string
	Description string
	Path        string
}

Skill is one procedure: how to orchestrate several tools for a repeated job. The runtime does not load or execute it; the agent reads it with its file tool.

func DiscoverSkills

func DiscoverSkills(ctx context.Context, contenoxDirs []Root, workspaceRoot string) []Skill

DiscoverSkills reads every skill under the given contenox roots, nearest root first, in either the flat `timesheet.md` or the `timesheet/SKILL.md` layout. A nearer skill shadows one of the same name further out, and one outside workspaceRoot is left out because the agent could not address it.

type Source

type Source struct {
	Dialect Dialect `json:"dialect"`
	// SpecDate is the documented spec version the dialect parser targets.
	SpecDate string `json:"spec_date"`
	Path     string `json:"path"`
	SHA256   string `json:"sha256"`
}

Source is the provenance of one parsed agent. SHA256 covers the source file verbatim; a re-import compares against it to tell an unchanged source from an edited one.

type SourceDir

type SourceDir struct {
	Root
	Native bool
}

SourceDir is one directory of declarations. A native directory keeps the names its files declare; a foreign directory's are scoped by the product they came from.

func DiscoverSourceDirs

func DiscoverSourceDirs(ctx context.Context, contenoxDirs []Root, workspaceRoots []Root) []SourceDir

DiscoverSourceDirs returns the agent directories that exist, native ones first so a workspace's own declarations precede those of other tools.

type StandingRule

type StandingRule struct {
	Tools     string `toml:"tools"`
	Tool      string `toml:"tool"`
	WhenKey   string `toml:"when_key"`
	WhenOp    string `toml:"when_op"`
	WhenValue string `toml:"when_value"`
}

StandingRule is a rule emitted under every posture, which a declaration can neither request nor waive.

type SyncOption

type SyncOption func(*syncOptions)

SyncOption tunes one pass. Variadic so a caller that has nothing to add — every test, and any caller predating a later option — stays unchanged.

func WithSkills

func WithSkills(skills []Skill) SyncOption

WithSkills supplies the procedures {{skills}} expands to. Omitted, the macro expands to "No skills are available." rather than being left in the prompt as a literal the model would have to interpret.

type SyncResult

type SyncResult struct {
	Source   string
	Name     string
	Dialect  Dialect
	Action   WriteAction
	Reason   string
	Unmapped []Unmapped
	// MCP and Remote are the tool sources this declaration brought with it, for
	// the caller to register scoped to Name. Returned rather than registered
	// here because registration needs a database this package does not have.
	MCP    []DeclaredMCPServer
	Remote []DeclaredRemoteTool
}

SyncResult is what one pass did with one source file.

func Sync

func Sync(ctx context.Context, sourceDirs []SourceDir, generated Root, cfg Config, opts ...SyncOption) ([]SyncResult, error)

Sync transpiles every declaration under sourceDirs into generated and retires chains whose source is gone. An unreadable or unmappable source is reported and skipped rather than failing the pass.

type Tools

type Tools struct {
	Allow   []string `json:"allow,omitempty"`
	Deny    []string `json:"deny,omitempty"`
	Inherit bool     `json:"inherit,omitempty"`
}

Tools is the resolved grant in canonical contenox names ("local_fs.read_file"). Inherit is set when the declaration named no tools at all, which the format reads as every tool rather than none.

type TranspiledEnvelope added in v1.0.0

type TranspiledEnvelope struct {
	Policy *hitlservice.Policy
	// Notes are informational: intent the envelope stated that nothing in this
	// build serves yet. They are not defects.
	Notes []string
}

TranspiledEnvelope is one envelope compiled to the policy the engine loads, plus what the compilation could not carry.

func TranspileEnvelope added in v1.0.0

func TranspileEnvelope(env Envelope) (TranspiledEnvelope, error)

TranspileEnvelope compiles an envelope into a HITL policy. Rules are first-match-wins, so the emission order below IS the semantics: unconditional denies lead, conditional refinements precede the grants they carve out of, and an axis nobody set falls through to default_action.

type Unmapped

type Unmapped struct {
	Field  string `json:"field"`
	Value  string `json:"value,omitempty"`
	Reason string `json:"reason"`
}

Unmapped is one thing the source stated that contenox will not carry.

type WriteAction

type WriteAction string

WriteAction is what one pass did with one declaration.

const (
	ActionCreated   WriteAction = "created"
	ActionUpdated   WriteAction = "updated"
	ActionUnchanged WriteAction = "unchanged"
	ActionRefused   WriteAction = "refused"
	// ActionIgnored is configuration that named something that does not exist.
	// Not a refusal: nothing was rejected, a knob simply had nothing to act on.
	ActionIgnored WriteAction = "ignored"
)

Jump to

Keyboard shortcuts

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