Documentation
¶
Overview ¶
Package compose wires a workload bundle plus its specialist specs into a runnable root agent. It is the shared core behind the two entry points that construct dispatch shapes: cmd/mast (flag-driven) and the top-level mast convenience package (programmatic). Both MUST go through BuildRoot so the dispatch semantics — planner override, graph vs. coordinator, per-mode toolset offering — cannot drift between the binary and the library.
This is runtime glue, not public API (docs/library-api-design.md marks internal/ packages churnable); library consumers reach it via the root mast package or compose the pkg/ subsystems directly.
Index ¶
- Constants
- func ApprovedChangeSet(logger *slog.Logger) graph.ChangeSetLookup
- func Backend(provider, modelName string) string
- func BuildClassRoot(class string, llm model.LLM, pauseRecorder planner.PauseRecorder) (adkagent.Agent, error)
- func BuildModel(ctx context.Context, provider, name string, bt workload.BuiltinTools) (model.LLM, error)
- func BuildRoot(ctx context.Context, cfg RootConfig) (adkagent.Agent, []tool.Tool, error)
- func BuiltinToolsSummary(m model.LLM) string
- func CheckCapabilitySplit(b workload.Bundle, specs []specialists.Spec, pred effects.Predicate, ...) error
- func CheckMCPServerNames(b workload.Bundle, specs []specialists.Spec) error
- func CheckMonitorCollectSurface(b workload.Bundle, specs []specialists.Spec) error
- func CheckPlannerWriteSurface(b workload.Bundle, specs []specialists.Spec) error
- func CheckRoster(b workload.Bundle, specs []specialists.Spec, dispatch Dispatch) error
- func IsOfflineFake(name string) bool
- func MeterLimits(provider, modelName string) budget.Limits
- func MeterScopes(specs []specialists.Spec, provider, rootModelName string) map[string]budget.Limits
- func MutationPredicate(b workload.Bundle, logger *slog.Logger) effects.Predicate
- func NewModelResolver(ctx context.Context, provider, rootName string, root model.LLM, ...) specialists.ModelResolver
- func NewTierResolver(ctx context.Context, provider, rootName string, root model.LLM, ...) specialists.TierResolver
- func RatePer1K(provider, modelName string) float64
- func SpecModelName(spec specialists.Spec, provider, rootModelName string) string
- func TierModelName(provider, rootModelName, tier string) (string, error)
- func WriteGate(cfg WriteGateConfig) (*plugin.Plugin, error)
- type BuiltinToolsReporter
- type Dispatch
- type RootConfig
- type SubRunIntentStore
- func (s SubRunIntentStore) CompleteSubRunIntents(ctx context.Context, sessionID string, callIDs []string) error
- func (s SubRunIntentStore) Dangling(ctx context.Context, sessionID string) []effects.DanglingIntent
- func (s SubRunIntentStore) RecordSubRunIntents(ctx context.Context, sessionID, specialist string, ...) error
- type WriteGateConfig
Constants ¶
const ( // ProviderGemini serves gemini-* models through whichever backend // genai detects from the environment. ProviderGemini = "gemini" // ProviderVertex serves gemini-* models against Vertex AI, named // outright rather than inferred from GOOGLE_GENAI_USE_VERTEXAI. ProviderVertex = "vertex" )
Provider aliases for the Gemini family. The Anthropic pair lives in pkg/providers/anthropic (ProviderName / VertexProviderName); these two have no provider package of their own because both backends are the same genai client under different configuration.
The names match pkg/taskclass.Providers(), which has carried a "vertex" family since the port — the tier table could always resolve against it, there was just no way to ask for it. They also match core-agent's config.ProviderVertex, which is where the pattern comes from.
const DefaultVertexLocation = "global"
DefaultVertexLocation is the location a Vertex client falls back to when neither GOOGLE_CLOUD_LOCATION nor GOOGLE_CLOUD_REGION is set. It is genai's own default for the backend, restated here only so that the value mast passes is explicit and loggable rather than filled in somewhere inside the SDK.
Variables ¶
This section is empty.
Functions ¶
func ApprovedChangeSet ¶ added in v0.4.0
func ApprovedChangeSet(logger *slog.Logger) graph.ChangeSetLookup
ApprovedChangeSet reads back what the write gate recorded when a specialist's finding proposed an executable change (v0.4 W7.0), for pkg/graph's diagnoser→executor routing predicate.
This function is the seam between the two packages. pkg/graph cannot read the record itself — pkg/approval's own tests import pkg/graph, so the import can only go one way — and internal/compose is the one place that already imports both.
A read failure is "nothing was proposed", not an error: the state key is absent for every finding that proposed nothing, which is most of them. What it must never do is guess. Returning true on a value it could not decode would route an unreadable proposal to a specialist that changes clusters.
func Backend ¶ added in v0.6.0
Backend resolves the --provider alias and the environment to the backend that will serve modelName: one of anthropic.ProviderName, anthropic.VertexProviderName, ProviderGemini, or ProviderVertex.
It returns "" — meaning "price this by bare model id" — for an offline fake, for a model in neither family, and for a claude-* model whose backend cannot be resolved from the environment. That last case is not silently wrong: BuildModel is about to fail on the same condition with a message naming the missing variables, so the run never reaches a point where the quoted price could matter.
This is the key half of pricing.LookupFor. The alias alone is not the answer: --provider="" with GOOGLE_GENAI_USE_VERTEXAI set runs Gemini on Vertex, and --provider="" with only a Vertex project set runs Claude on Vertex. Keying a price on the flag rather than on the resolved backend would get both of those wrong.
func BuildClassRoot ¶
func BuildClassRoot(class string, llm model.LLM, pauseRecorder planner.PauseRecorder) (adkagent.Agent, error)
BuildClassRoot constructs the runnable root agent for one public task class — the shape behind cmd/mast's one-shot path (`mast --task=<class> "<prompt>"`). The class → mode mapping is pkg/taskclass's (docs/orchestration-design.md "Public task classes"):
- chat → a Chat-mode coordinator (pkg/agent.NewCoordinator).
- debug / implement / research / review → a Task-mode agent, wrapped in a one-node workflow root because ADK v2.1.0's runner only accepts Chat-mode LlmAgent roots directly (same idiom as pkg/planner.NewRoot).
- orchestrate → the planner-enabled root (pkg/planner.NewRoot) with an empty specialist roster — the planner scaffold runs and reports honestly that no specialists are declared; a roster needs a workload bundle, which is serve-mode territory in v0.1.
Instruction precedence (pkg/taskclass modes.go): the class profile's per-class default is passed explicitly, so it beats the generic per-mode fallback; classes without per-class text (chat) fall through to pkg/agent's mode default via the constructor's own empty-Instruction rule. pauseRecorder enables the planner classes' pause_session tool when the caller has a durable store (nil otherwise — an in-memory pause would die with the process).
func BuildModel ¶
func BuildModel(ctx context.Context, provider, name string, bt workload.BuiltinTools) (model.LLM, error)
BuildModel constructs the model.LLM for the given provider alias and model name. The provider alias is only consulted where the model id alone is ambiguous (claude-* serves against api.anthropic.com or Vertex); everything else dispatches on the name.
- "echo": fake in-process echo model (no credentials required).
- "toolactor": request-driven offline fake that drives registered tool calls deterministically (pkg/agent/toolactor.go); the v0.2 UAT harness uses it to exercise the crash/drain/abort legs against a real blocking MCP tool. No credentials required.
- "scripted": JSONL recorded-turn replay via pkg/providers/mock; the recording path comes from MAST_SCRIPT, and MAST_SCRIPT_STRICT=1 enables strict Contents matching.
- "gemini-*": ADK's Gemini model wrapped in pkg/providers/gemini's builtin-tool layer. `--provider=vertex` names the Vertex backend outright; with no alias it stays genai's env-driven selection. See geminiClientConfig.
- "claude-*": pkg/providers/anthropic; see anthropicProvider for backend selection.
bt gates the provider's server-side built-in tools. Its zero value is mast's baseline — every one of them off, whichever backend resolves — so a caller with no bundle to read (a one-shot, a library embed, an eval rig) gets the safe posture by construction. See builtintools.go for why mast does not inherit the vendor's own default.
func BuildRoot ¶
BuildRoot builds the roster and assembles the dispatch shape. Every shape is refused up front if the roster's read/write split does not hold — see CheckCapabilitySplit.
- bundle.Planner.Enabled → the supervisor-body planner root (pkg/planner); Dispatch is ignored.
- DispatchGraph → the workflow graph (pkg/graph); errors without a SingleTurn classifier.
- DispatchFanout → the concurrent-analysts fan-out shape (pkg/graph.BuildFanout); errors without a graph.SynthesisName specialist, or if any analyst can reach a mutating tool.
- DispatchBounded → the one-call shape (bounded.go); errors unless the roster is exactly one SingleTurn specialist declaring an output_schema.
- DispatchCoordinator → the SubAgents coordinator (pkg/router).
- DispatchAuto/empty → the bundle's own `dispatch:` when it names one (see Dispatch.Resolve); otherwise fanout when the roster has a synthesis specialist, graph when it has both a SingleTurn classifier and a graph.FallbackName specialist, else coordinator.
The second return is the non-MCP tools this call wired onto the root, for an operator catalog to report (#137). It is what compose itself registered and nothing more: the planner's control-plane vocabulary under planner dispatch, and empty under every other shape. Tools ADK installs on its own — finish_task, a coordinator's per-sub-agent delegation tools — are not in it, because compose never sees them and there is no accessor for a built agent's tools (#51 / adk-go#1229). A caller with no catalog to feed discards it.
func BuiltinToolsSummary ¶ added in v0.8.0
BuiltinToolsSummary renders a constructed model's effective server-side built-in set for an operator-facing log line: the comma-joined neutral names, or "none" when the backend has the concept and everything is off.
Returns "" — not "none" — for a backend with no server-side built-in concept at all, so a caller can omit the field rather than assert an absence that means nothing there.
Read off the constructed model rather than off the bundle, and that is the point rather than a detail. YAML decoding does not reject unknown keys, so `builtin_tols: {web_search: true}` is discarded in silence; a line derived from the same struct that was discarded would agree with the typo. This one answers the question an operator actually has — what will the model send — from the far side of the constructor.
func CheckCapabilitySplit ¶ added in v0.3.0
func CheckCapabilitySplit(b workload.Bundle, specs []specialists.Spec, pred effects.Predicate, logger *slog.Logger) error
CheckCapabilitySplit is W2.4: a specialist may only reach a mutating tool if it says so.
The rule is one line — a roster's write surface must be declared, per specialist, in a field rather than in a prompt — and the reason is that the alternative was load-bearing until now. The shipped gke-triage diagnosers held `patch_resource` and were restrained by the sentence "Do NOT mutate anything on your own initiative", which is a suggestion to a language model, not a control. Declaring `capability: change_executor` is not an approval either: every mutating call still goes to the write gate. What it buys is that adding a write tool to a diagnoser now fails the roster at startup, naming the specialist and the tool, instead of quietly widening what an incident can do to a cluster.
Three cases count as reaching a mutating tool, and only the first is the obvious one (this mirrors pkg/graph's fan-out branch check, which found the other two):
- the specialist names a tool the predicate does not classify read-only;
- it names an MCP server with no tools: list, which grants it every tool on that server, present and future;
- it declares no tools.mcp key at all while the workload declares a tool catalog, which grants it the whole catalog.
Under mast's default-deny-unknown predicate an un-enumerated grant is a grant of mutating tools whether or not any exist today, so cases 2 and 3 are refusals rather than warnings. The cost is real — a roster has to classify its read tools by name in tool_catalog.tools — and it is the intended cost: the alternative is trusting a tool's name.
Case 3 turns on presence, not length: `mcp: []` is the documented deny-all spelling and passes, because a specialist that reaches no MCP tool at all reaches no mutating one. That is the spelling for a pure-reasoning specialist — a synthesis node, a summarizer — in a workload that does have a catalog.
SingleTurn specialists are exempt. They are built without toolsets (see BuildRoot), so a classifier cannot reach a tool of any class, and requiring it to enumerate an allowlist it will never use would be ceremony.
The boundary worth knowing: this checks *declarations*. A library embed that passes Toolsets directly and composes its own Specs can hand a read-only specialist a mutating tool without saying so, and nothing here will see it — enumerating a live toolset means connecting to every MCP server at construction. The write gate is the runtime backstop for that path: an undeclared mutating call still parks.
func CheckMCPServerNames ¶ added in v0.7.0
func CheckMCPServerNames(b workload.Bundle, specs []specialists.Spec) error
CheckMCPServerNames refuses a roster whose specialist names an MCP server the workload does not have (#278).
The allowlist is applied by dropping what does not match (pkg/specialists.filterToolsets iterates the *offered* toolsets and looks each one up in the specialist's map), so an entry that matches no toolset is never consulted and never reported. `server: loggging` reads like a granted capability and grants nothing. The specialist starts clean, runs, and cannot do the thing its own prompt tells it to do — the first symptom being a model behaving oddly, at incident time, three tool calls into a diagnosis.
This is the same class of mistake as a `model:` whose credentials do not resolve, a `tier:` the provider cannot answer, or a malformed `output_schema`, all of which already fail the roster at startup with the name in the message. It was the one that passed.
Why only the server half is refused here ¶
The set of servers a specialist may name is `tool_catalog.mcp`, already loaded and already validated against mcp.json (cmd/mast/main.go). Checking a name against it costs nothing and reaches no network. The *tool* half of the same allowlist cannot be checked here: it needs a live `tools/list`, which is why mast's toolsets are lazy — connecting to every server at startup to validate a name would make a bundle un-loadable whenever a server is down. That half is reported as a warning the first time a toolset lists, by pkg/specialists (see allowlist.go).
Why a bundle with no catalog is exempt ¶
`tool_catalog.mcp` is the authoritative list of what a workload wired. A bundle that declares none has not said what exists, so nothing here can tell a typo from a server this deployment does not happen to carry. A library embed that hands compose its own toolsets is in the same position. Both fall through to the runtime warning.
func CheckMonitorCollectSurface ¶ added in v0.5.0
func CheckMonitorCollectSurface(b workload.Bundle, specs []specialists.Spec) error
CheckMonitorCollectSurface keeps the collection leg out of the model's hands (v0.5 W4.2).
What the exception is ¶
A tool named in `monitor.collect` is run by mast on its own behalf, at the top of a scheduled cycle, before the model is woken. It is not gated, and it is not gated on purpose: a run-to-run finding diff declares itself mutating because it advances persisted state, and under the default `hitl.on_mutation: require_approval` a model that held it would park the cycle for a human every single fire.
Why the exception needs a fence ¶
Every other narrow exception in mast is bounded by the direction it runs in. The precondition read (v0.4 W7) is bounded by classification — internal/compose refuses to start if the declared read is mutating, so the exception can only ever widen towards *safer* calls. This one inverts that: it permits a mutating call precisely because it is mast's own. Classification cannot fence it, so reachability does.
The rule is that a collect tool must be reachable by NOBODY else. A tool that mast runs ungated at the top of the cycle and that a specialist can also call mid-turn is the worst of both: the audited answer to "was this write approved?" becomes "it depends which door it came through", and "there is no ack tool the model can call" stops being a structural fact and becomes a convention someone has to remember when they next edit a roster.
The ack tool is fenced by the same rule (v0.5 W4.6) ¶
monitor.ack names the tool an operator's acknowledgement is forwarded to, and it is checked here alongside the collection calls because the fence is one rule, not two. It matters more for this one. A collect tool the model could also reach would let the model gather facts ungated; an ack tool it could reach would let it SUPPRESS ITS OWN ALERTS — and the producer's triage-status write is typically not permission-gated on its side, so mast's ingress authn is the only thing in front of it (docs/orchestration-design.md, "Ack routing").
This is what makes "acks enter through the operator ingress, never through the tool loop" a property of the build rather than a rule in a prompt. An agent that cannot see the tool cannot be talked into calling it.
Three ways a roster reaches a tool, and all three are refused ¶
The first is the obvious one; the other two are the un-enumerated grants CheckCapabilitySplit found, and they matter more here because CheckCapabilitySplit *exempts* a declared change executor from them. A `capability: change_executor` specialist with `mcp: [{server: k8s}]` and no tools list holds every tool on that server — including the diff — and nothing before this check would say so.
- the specialist names a collect tool outright, on an MCP server or among its built-ins;
- it names an MCP server with no `tools:` list, which grants it every tool on that server, present and future;
- it declares no `tools.mcp` key at all while the workload declares a tool catalog, which grants it the whole catalog.
Cases 2 and 3 are refused whether or not the collect tool happens to live on that server today, because mast cannot tell without connecting to it — and "refuse rather than guess" is the property this seam inherits from the read it generalizes.
SingleTurn specialists are exempt, as they are in CheckCapabilitySplit and for the same reason: BuildRoot builds them without toolsets, so they cannot reach a tool of any class. That exemption is what lets the clearest demonstration of the whole idea exist — a `dispatch: bounded` monitoring workload whose model holds no tools at all and still gets the transitions.
The boundary worth knowing is the one CheckCapabilitySplit names: this checks *declarations*. A library embed that composes its own Specs and passes Toolsets directly can hand a specialist a collect tool without saying so, and nothing here will see it. Unlike the write gate, there is no runtime backstop for that path, because the whole point of the collection leg is that it is ungated — an embed that wants the property has to declare the roster it is claiming.
func CheckPlannerWriteSurface ¶ added in v0.5.0
func CheckPlannerWriteSurface(b workload.Bundle, specs []specialists.Spec) error
CheckPlannerWriteSurface refuses a planner roster that holds a change executor while the bundle asks for the mutation to be gated (#235).
The hole ¶
The write gate and the effect outbox are runner plugins, and `invoke_specialist` runs its specialist on a runner it constructs itself — with none. So a mutating call made inside a planner dispatch does not park, does not dry-run, and leaves no durable intent record, on a bundle whose `hitl.on_mutation` asked for all three. Every other dispatch shape runs on the outer runner and is gated normally; `examples/workloads/gke-triage` is two commented lines away from the combination, which is how close a supported configuration sits to it.
Measured rather than reasoned about: an outer BeforeToolCallback over this shape sees invoke_specialist and finish_task, and never the mutating call the specialist executed between them.
Why refuse rather than warn ¶
Same argument as CheckNameCollisions one file over, and the same argument the read/write split makes: a fail-open hole in the write path is refused at startup, not run carefully. A warning would be a line in a log nobody is tailing on a deployment nobody is watching, which is the posture this whole product is built against — and the operator who wrote `require_approval` would go on believing they had it. The refusal is also cheap to escape: the same roster runs under `coordinator` or `graph`, where the gate reaches it.
Why on_mutation: apply is exempt ¶
The refusal is scoped to the promise that is actually broken. Under `apply` the gate was never going to stop the call, so nothing about the dispatch changes what executes. The recording gap that used to remain there is closed as of v0.6 W9.3: the observer seam writes each dispatched mutating intent and completion to the outer session's companion ops row, and the outbox folds them into its dangling scan (pkg/effects/subrun.go). What `apply` gives up is the stop, not the record.
Why this check is permanent ¶
It was written as containment, with a promise to come out when #235 settled a boundary. That promise is withdrawn (2026-08-31): the gate cannot cross this seam, and no wiring makes it.
A park is not a suspended turn. RequestConfirmation writes the question into the SESSION EVENT LOG and the callback then returns normally with an "awaiting approval" result; the resume matches that log and re-enters at the ROOT (pkg/approval/dispatchseam_test.go). A dispatch sub-session is in-memory, dies with the tool call, and nothing re-enters a dispatch mid-flight — so an approval has nowhere to come back to. Coordinator and graph dispatch are gated at full per-call fidelity precisely BECAUSE they share the log, which is why the escape hatch below is a real answer and not a consolation.
Gating invoke_specialist itself was the other candidate and is worse than refusing. Its arguments are a specialist name and a prose string, so the operator would approve an intention: no typed arguments to review, nothing to edit, no per-change-set grant to bind, N mutations collapsed into one park, and a Decision record naming the dispatch rather than the change. Lead row L7 exists to distinguish mast from "a static list of tool names to interrupt on; the arguments are whatever the model produces on resume" — that is a description of boundary gating.
The other half of #235 — the outbox record — was a recording problem rather than an approval one and did not inherit the obstacle: recording is one-directional, and SubRunSink sees a mutating FunctionCall before the tool body runs (pkg/planner/outboxseam_test.go). It shipped in v0.6, and closing it did not delete this check: a record of what a dispatch did is not a chance to say no before it does it.
func CheckRoster ¶ added in v0.4.0
CheckRoster answers "could this roster ever be this shape?" from the bundle and the specs alone — no model, no provider, no toolsets.
It exists because BuildRoot is not the first thing a daemon does. The binary wires the workload's MCP servers first, and wiring one is a real side effect: a process spawned, or an OAuth token fetched. A roster the shape can never build should not cost either, and in an environment without credentials it costs worse than that — the operator gets "initial Google OAuth token fetch: 403" as the reason mast would not start, when the actual reason is that they pointed `--dispatch=bounded` at a fourteen-specialist roster. The token fetch was never going to make that roster buildable.
Static checks only, and deliberately a subset of BuildRoot's: the dispatch enum and the bounded roster contract. CheckCapabilitySplit is just as static but stays where it is, because it logs the audited mutation-class overrides as it goes and those lines are worth exactly one appearance in a startup log.
BuildRoot re-runs both checks rather than trusting a caller to have called this first — every refusal here is a pure function of its arguments, so running it twice costs nothing and skipping it would make the library path weaker than the binary's.
func IsOfflineFake ¶ added in v0.3.0
IsOfflineFake reports whether name is one of mast's offline test doubles.
func MeterLimits ¶ added in v0.7.0
MeterLimits is the session-level price half of a budget.Limits: the pricer that costs each call exactly, the (backend, model) pair it is keyed by, and the flat rate behind all of it. Callers add the bundle's ceilings.
It exists because there were two of these — cmd/mast's meterPool and the library's limits() — and both wrote `budget.Limits{RatePer1K: compose.RatePer1K(provider, name)}` from memory. Pricing is meant to be derived in exactly one place so the daemon and mast.RunWorkload cannot bill the same run differently; the flat rate was, and the catalog now is.
The provider alias is passed for the reason RatePer1K takes it: the backend is what the pair-keyed lookup needs, Backend is the one place that resolves it, and no caller should be re-deriving it.
Offline fakes get no pricer, for the same reason MeterScopes does not price them: echo/scripted/toolactor produce no billable tokens, so a real per-model rate would report money that provably was not spent. They keep RatePer1K's inflated fake rate, which is what lets a smoke test trip a small cap, and they never touch Meter.Unpriced.
func MeterScopes ¶ added in v0.3.0
MeterScopes derives the per-specialist budget scopes for a roster: the ceilings a spec declares (`max_turns`, `max_cost_usd`) plus, when it declares a `model:` override or a `tier:`, that model's price. Specialists that declare neither get no scope — they are metered into the session totals and nothing else, which is what an un-tiered, un-capped roster wants.
The price follows SpecModelName, so a `tier:` is priced at the model the tier resolved to and not at the root's rate; that is why the provider the run was started with is a parameter here.
max_wallclock_seconds is deliberately absent: it is a node-level knob (pkg/graph maps it onto workflow.NodeConfig.Timeout), not something a usage meter can see.
Pricing collapses under an offline fake, on the same condition NewModelResolver collapses the models themselves: if the root model is echo/scripted/toolactor then every override resolved back to it, so every token was produced by the fake and pricing a specialist at its declared tier would report a cost that provably did not happen. The consequence is worth stating plainly — per-model cost attribution cannot be demonstrated end-to-end in a credential-free test tier, because the condition that makes the tier credential-free is exactly the condition that collapses the tiers. The derivation is unit- testable here; the end-to-end claim needs real models.
func MutationPredicate ¶ added in v0.3.0
MutationPredicate builds the tool mutation classifier for a bundle: mast's default-deny-unknown stance, narrowed by the workload's audited tool_catalog.tools overrides.
The conversion exists because pkg/effects deliberately does not import pkg/workload (that would drag the YAML loader into every library embed that only wants the guard), so somebody who imports both has to bridge the two ToolPolicy types. compose imports both.
func NewModelResolver ¶ added in v0.3.0
func NewModelResolver(ctx context.Context, provider, rootName string, root model.LLM, bt workload.BuiltinTools, logger *slog.Logger) specialists.ModelResolver
NewModelResolver returns the specialists.ModelResolver that binds a specialist's `model:` override to a concrete model.LLM. Resolution goes through BuildModel, so an override is dispatched exactly like a --model value: by model id, with provider only disambiguating the Anthropic backend.
Two rules shape it, and both are load-bearing:
Cross-provider overrides are allowed (specialists-design open Q#4, resolved 2026-08-12). BuildModel already dispatches on the model id, so a gemini-* specialist under a claude-* parent needs no new machinery; refusing it would mean inventing a provider-family classifier as a second source of truth beside BuildModel's own dispatch. The price is that credentials for every distinct provider in the roster must resolve, and they must resolve at construction — which is where the error lands, not mid-incident on first call.
When the root model is an offline fake, every override collapses back to it. A bundle that declares real model tiers must still run under `--model=echo` / `scripted` / `toolactor`, or tiering a bundle would silently break the offline S/U/E test tiers (docs/v0.3-plan.md §2) and scripts/demo-spike2.sh — the whole process is a test double, and there is nothing to tier.
Resolution is memoized per model id: eight analysts on one tier share one provider client.
bt is the workload's server-side built-in gate, and it applies to an override exactly as it applies to the root. That is the property worth naming: a bundle that turned web search off cannot have it handed back by a specialist that declares a different model. There is no per-specialist axis to merge — see builtintools.go for why the inheritance trap upstream guards against cannot occur under a default-off baseline.
func NewTierResolver ¶ added in v0.4.0
func NewTierResolver(ctx context.Context, provider, rootName string, root model.LLM, resolve specialists.ModelResolver, logger *slog.Logger) specialists.TierResolver
NewTierResolver builds the specialists.TierResolver mast ships. It resolves through resolve — the memoized ModelResolver — rather than calling BuildModel itself, so a roster of twelve small-tier diagnosers shares the one client the tier maps to.
Offline fakes collapse before the mapping is attempted, not after: under `--model=echo` there is no provider family to derive and nothing to tier, and a tiered bundle must still run in the credential-free S/U/E test tiers. Same rule NewModelResolver applies to `model:` overrides, for the same reason.
func RatePer1K ¶
RatePer1K derives pkg/budget's flat USD-per-1K-total-tokens rate for a model as served under a given --provider alias (budget.Limits.RatePer1K).
The price is looked up for the (backend, model) pair, not the model id: Backend resolves the alias and the environment to the backend that will actually bill the tokens, and pricing.LookupFor prices that pair, falling back to the bare id when no backend-qualified row exists. Passing the alias rather than the resolved backend is deliberate — every caller has the alias, none of them should be re-deriving the backend, and Backend is shared with the code that builds the client so the two cannot drift.
Gemini and Claude rates come from pkg/pricing's builtin catalog (longest-prefix lookup, so dated/suffixed IDs land). The catalog prices input and output tokens separately, but the budget meter only sees UsageMetadata.TotalTokenCount, so the flat rate is the plain average of the two per-MTok rates scaled to per-1K — a deliberate v0.1 approximation that overcharges input-heavy sessions and undercharges output-heavy ones rather than complicating the budget API. Gemini IDs the catalog doesn't know keep the old flat spike rate so cost metering never silently drops to zero.
The echo fake keeps its inflated rate: offline smoke tests (scripts/demo-spike2.sh scenario 3) trip small caps with it. The scripted replay and toolactor share it — all offline test doubles.
func SpecModelName ¶ added in v0.4.0
func SpecModelName(spec specialists.Spec, provider, rootModelName string) string
SpecModelName is the model id a spec will actually run on, or "" when it inherits the parent's. It exists so the two places that need that answer — building the agent and pricing its tokens — derive it the same way. They did not, at first: MeterScopes priced off `s.Model` alone, which would have billed every tiered specialist at the root model's rate while the audit log showed the tiered one.
Errors are swallowed to "" on purpose: the callers that price cannot act on them, and BuildRoot has already refused the roster by the time anything is metered.
func TierModelName ¶ added in v0.4.0
TierModelName maps a `tier:` declaration to a concrete model id for the running provider. It is the whole of tier resolution; everything else in this file is plumbing around it.
An unmappable tier is an error, not a fall-through to the root model. A roster that declares tiers and silently runs every specialist on the parent's model is the exact fiction W1.1 removed for `model:`.
func WriteGate ¶ added in v0.3.0
func WriteGate(cfg WriteGateConfig) (*plugin.Plugin, error)
WriteGate builds the pre-call write gate for a workload (docs/v0.3-plan.md W2.1/W2.2; docs/orchestration-design.md hitl_policy.on_mutation).
It returns (nil, nil) when there is no bundle. The gate's whole mechanism is parking a call until an operator answers, and the default place an operator's answer arrives is the daemon's resume path against a durable session. A library embed that constructs its own runner with no workload has neither, so defaulting it on there would park mutating calls in a process with no way to un-park them — a hang, not a safety property. Such an embed opts in by passing a bundle (or by registering pkg/approval's plugin itself).
With a bundle, the policy is hitl.on_mutation, whose default is require_approval: a workload that says nothing about mutation gets gated. Registration order matters and is settled — the effects outbox runs first, so a call whose result is being replayed from the log is never re-approved (resolved-decision row 144).
Types ¶
type BuiltinToolsReporter ¶ added in v0.8.0
type BuiltinToolsReporter interface {
BuiltinToolNames() []string
}
BuiltinToolsReporter is the optional extension a backend implements when it injects the provider's own server-side tools into every request. It reports the effective set under the provider-neutral names the bundle uses.
Owned here, at the consumer, rather than in a provider package: pkg/providers/gemini and pkg/providers/anthropic satisfy it structurally and import nothing to do so, and the two backends stay unable to see each other. Backends with no such concept (echo, scripted, toolactor) simply do not implement it.
type Dispatch ¶
type Dispatch string
Dispatch selects the root shape BuildRoot assembles.
const ( // DispatchCoordinator is the spike-1 SubAgents pattern: a // Chat-mode coordinator with the roster as SubAgents (pkg/router). DispatchCoordinator Dispatch = "coordinator" // DispatchGraph is the spike-2 workflow-graph LLM-as-router shape // (pkg/graph). Requires a SingleTurn classifier in the roster. DispatchGraph Dispatch = "graph" // DispatchFanout is the W3 fan-out shape (pkg/graph.BuildFanout): // the roster's Task specialists run concurrently as read-only // analysts and a graph.SynthesisName specialist merges what they // return. Requires that specialist, and refuses to build an analyst // that can mutate. DispatchFanout Dispatch = "fanout" // DispatchBounded is the W4.3 one-call shape (see bounded.go): a // roster of exactly one SingleTurn specialist that declares an // output_schema, run as a single workflow node. No router, no tool // loop, no second specialist to choose between — so a cycle costs // one model call, and that is a number rather than a hope. DispatchBounded Dispatch = "bounded" // DispatchAuto picks the shape from the roster: fanout when a // graph.SynthesisName specialist is present, graph when a // SingleTurn classifier and a graph.FallbackName Task specialist // are both present (the pair graph dispatch needs), coordinator // otherwise. This is the library default — programmatic callers // declare a roster, not a flag. // // It never picks bounded; see RosterShape. DispatchAuto Dispatch = "auto" )
func RosterShape ¶ added in v0.3.0
func RosterShape(specs []specialists.Spec) Dispatch
RosterShape reads the dispatch shape out of a roster: fan-out when it has a synthesis merger, graph when it has both a SingleTurn classifier and a graph.FallbackName Task specialist, coordinator otherwise.
Exported because BuildRoot is not the only caller that has to know the shape — cmd/mast's boot-time auto-resume pass runs only under coordinator dispatch, and a second copy of this rule living there is a copy that drifts. It reads specs rather than built agents so a caller can ask before paying for construction.
Why bounded is never inferred ¶
A roster of one SingleTurn specialist that declares an output_schema is exactly the bounded shape's roster, and it falls through to coordinator here on purpose. Every other shape this function infers is one a roster cannot have arrived at by accident — you do not add a `_synthesis` specialist without meaning fan-out. A one-specialist roster is what every workload looks like on its first day, and inferring bounded from it would silently take the coordinator away from bundles that have been running on it since v0.1: the coordinator answers in its own voice, the bounded shape returns the specialist's JSON report, and no error is raised on the way. `dispatch: bounded` is therefore a declaration, never a deduction — the same reasoning that keeps cmd/mast's terminal default at coordinator rather than auto (see resolveDispatch).
func (Dispatch) Resolve ¶ added in v0.3.0
Resolve returns the dispatch shape to build, given the caller's choice and the bundle's own declaration.
A shape is a property of the roster — fan-out needs read-only analysts and a synthesis specialist, graph needs a SingleTurn classifier and a `_fallback` — so a bundle that declares one is stating a fact about itself, not a preference. It therefore wins over an unspecified caller, and loses to a caller that named a shape explicitly (an operator overriding one run).
type RootConfig ¶
type RootConfig struct {
// Bundle is the workload definition (naming, roster order,
// planner/HITL policy).
Bundle workload.Bundle
// Specs is the loaded specialist roster. Specs with an empty Mode
// build as Task-mode (the same default pkg/specialists applies).
Specs []specialists.Spec
// Model is the root model: the one the coordinator/planner runs on
// and the default for every specialist that declares no `model:`
// override.
Model model.LLM
// ModelName and Provider are the strings Model was built from (the
// --model / --provider values). They are what per-specialist
// `model:` overrides resolve against — see NewModelResolver.
//
// Leaving ModelName empty is legal (a library caller may hand over
// a model.LLM it constructed itself); overrides then resolve on
// their own model id, with provider selection falling back to the
// env-driven detection in BuildModel.
ModelName string
Provider string
// Toolsets are offered to Task-mode specialists (and filtered
// through each spec's allowlist by specialists.Build). SingleTurn
// classifiers never receive toolsets — they run one shot with no
// tool loop.
Toolsets []tool.Toolset
// SpecialistTools are mast built-ins handed to every Task-mode
// specialist alongside Toolsets. Today that is retrieve_raw, the
// MCP digest wrap's escape hatch (#221).
//
// They are tools rather than a toolset on purpose. A toolset is
// matched to a `tools.mcp: - server:` allowlist entry by name and
// dropped when there is no match, which is right for an MCP server
// — reach the operator did not grant — and wrong for this: a
// roster that enumerates its tools, the posture mast recommends,
// would be the one that silently lost the escape hatch for the
// digests it is still being served. Nothing here grants new reach;
// retrieve_raw returns bytes the specialist was already sent.
SpecialistTools []tool.Tool
// Dispatch selects the root shape. Empty means DispatchAuto.
Dispatch Dispatch
// Logger, when non-nil, receives the same construction-time notes
// cmd/mast has always logged (e.g. planner overriding dispatch).
Logger *slog.Logger
// PauseRecorder enables the planner's pause_session tool (v0.2
// plane-A self-pause) by giving it a durable record sink —
// *transcript.Store, or the daemon's scheduler-aware wrapper. Nil
// (no durable store) leaves the tool unregistered.
PauseRecorder planner.PauseRecorder
// SubRunObserver folds the events of a planner dispatch's private
// sub-runner back into the caller's accounting (#226). A host that
// meters, records metrics or watches for loops on the root runner's
// event stream MUST set this, or a planner-dispatched specialist's
// spend reaches none of them. Only the planner shape has the seam;
// coordinator, graph and fan-out dispatch funnel sub-agent events up
// the root stream already.
SubRunObserver planner.SubRunObserver
}
RootConfig carries everything BuildRoot needs to turn a loaded bundle + specs into a root agent. Bundle and Specs use the existing pkg/workload and pkg/specialists vocabulary — file-loaded and programmatic values are indistinguishable here by design (docs/library-api-design.md, "Embeddable config vs. file-loaded config").
type SubRunIntentStore ¶ added in v0.6.0
type SubRunIntentStore struct {
Store *transcript.Store
UserID string
}
SubRunIntentStore joins the two halves of the v0.6 W9.3 seam (#235): pkg/effects decides what counts as a mutating call and when to record it, pkg/transcript owns the ops row it lands on, and neither imports the other — effects is the one package in mast's graph with no mast dependencies, and keeping it that way is what lets a slim embed pull the outbox in without the operator surface.
It also binds the user ID. The store can resolve one by scanning the app's session list, but that scan would sit in front of every dispatched mutating call; a host that already knows its user ID should say so.
func (SubRunIntentStore) CompleteSubRunIntents ¶ added in v0.6.0
func (s SubRunIntentStore) CompleteSubRunIntents(ctx context.Context, sessionID string, callIDs []string) error
CompleteSubRunIntents implements effects.IntentStore.
func (SubRunIntentStore) Dangling ¶ added in v0.6.0
func (s SubRunIntentStore) Dangling(ctx context.Context, sessionID string) []effects.DanglingIntent
Dangling reads the session's recorded-but-unpaired dispatched mutations back in the outbox's own vocabulary. It is the function to hand to effects.Config.ExternalDangling and to fold into a DanglingScan with WithExternal.
EventIndex is -1 rather than 0: these calls are not in the session's event log at all, and the auto-resume repair path groups by that index (see effects.MutatingCalls).
func (SubRunIntentStore) RecordSubRunIntents ¶ added in v0.6.0
func (s SubRunIntentStore) RecordSubRunIntents(ctx context.Context, sessionID, specialist string, intents []effects.DanglingIntent) error
RecordSubRunIntents implements effects.IntentStore.
type WriteGateConfig ¶ added in v0.3.0
type WriteGateConfig struct {
// Bundle is the loaded workload, or nil when there is none.
Bundle *workload.Bundle
// Predicate classifies tools. Optional: WriteGate derives one from
// the bundle when it is nil. Pass the one the effects outbox is
// using so the two plugins agree about what a mutation is —
// disagreement means either a call that is recorded but ungated or
// one that is gated but unrecorded.
Predicate effects.Predicate
// Gate decides policy for a parked call. Optional: WriteGate builds
// a default gate when the policy needs one and this is nil.
Gate *permissions.Gate
// Specs is the loaded roster, used to work out which tools a change
// executor in it can actually run. Optional: without it the
// producer contract still checks that a proposed change names a
// real tool with valid arguments, it just cannot narrow that to one
// specialist's allowlist.
Specs []specialists.Spec
// ToolSchemas resolves a wired tool's declared input schema by
// name, for the producer contract (v0.4 W7.0). It answers two
// questions at once: whether this daemon holds a tool by that name
// at all, and what arguments it takes.
//
// Optional, and its absence is fail-closed rather than fail-open:
// with a bundle and no resolver, a specialist that proposes a
// change gets it refused, because nothing here can tell an
// executable call from an invented one. A roster whose report
// schema has no proposed_change field is unaffected either way.
ToolSchemas func(toolName string) (*jsonschema.Schema, error)
// ToolRead runs a read-only tool on mast's own behalf and returns
// its result, for change-set freshness preconditions (v0.4 W7).
// It is mast reading the cluster, not the agent: the call is not in
// the model's transcript and its result is not shown to the model,
// because its only consumer is the comparison between what the
// world looked like when an operator approved a change set and what
// it looks like now.
//
// Optional, and fail-closed in the same direction as ToolSchemas: a
// tool that declares a precondition and a deployment that cannot
// run reads simply mints no grant, so its calls park one at a time.
ToolRead func(ctx adkagent.Context, toolName string, args map[string]any) (map[string]any, error)
Logger *slog.Logger
}
WriteGateConfig configures WriteGate.