Skip to content

Starlark Code Mode, Built-In Read-Only Tools, and Go SDKs

Standard LLM tool loops waste turns and tokens fetching one resource at a time and stuffing full JSON payloads into conversation history. Faber’s Starlark Code Mode lets the model run one small, hermetic Starlark script (run_script) that calls multiple read-only tools in parallel, filters the results in memory, and returns only the distilled facts.

This guide also covers Faber’s built-in read-only OCI and HTTP fetch tools and how to embed the Apache-2.0 pkg/engine and pkg/trigger Go SDKs in your own applications.

Code Mode embeds a hermetic go.starlark.net interpreter inside the agent runner:

  • Hermetic by construction: load() is disabled, and scripts have zero filesystem, shell, or raw network access. Scripts can only call the authorized read-only tools bound into the runner.
  • Hard-denied mutations: Sandbox tools (sandbox_*), submit_result, run_script, and mutating Kubernetes or HTTP write tools are unconditionally excluded from Starlark bindings.
  • Strict per-script budgets: Every invocation is bounded by bytecode step count (maxSteps, default 100000), wall-clock timeout (timeout, default 15s), nested tool calls (maxToolCalls, default 25), serialized result() size (maxOutputBytes, default 32768), and batch() worker concurrency (maxBatchConcurrency, default 4, clamped at 8).

Enable spec.codeMode on a ToolProfile (or inline under MaintenancePolicy.spec.tools.codeMode):

apiVersion: faberops.dev/v1alpha1
kind: ToolProfile
metadata:
name: codemode-readonly
namespace: faber
spec:
codeMode:
enabled: true
hideWrappedTools: true
maxSteps: 100000
timeout: 15s
maxToolCalls: 25
maxOutputBytes: 32768
maxBatchConcurrency: 4

When hideWrappedTools is true (the default), individual wrapped read-only tools are removed from the top-level LLM tool schema list to save prompt tokens, while run_script, submit_result, and any sandbox tools stay directly callable.

Inside run_script, Faber exposes wrapped tools under clean namespaces:

  • k8s: k8s.list, k8s.get, k8s.logs, k8s.events
  • mcp.<server>: mcp.<server>.<tool> for each configured Streamable HTTP MCP server
  • oci: oci.list_tags, oci.resolve_digest
  • http: http.fetch
  • tools: tools.<name> for any custom read-only SDK tools

Three built-in helpers keep scripts short and fast:

  • help() or help(k8s.list): Returns compact parameter signatures and descriptions for bound tools so the model can discover exact argument names without bloating the system prompt.
  • batch([call(fn, key="val"), call(other_fn, key="val")]): Runs multiple read-only tool calls concurrently in a bounded Go worker pool and returns their results in the same order.
  • result(value): Sets the compact JSON value returned to the LLM turn (every script must call result(value)).

Example Starlark script executed by the model in a single turn:

pods = k8s.list(resource="pods", namespace="apps")
unready = [p["name"] for p in pods["items"] if not p["ready"]]
logs, tags = batch([
call(k8s.logs, namespace="apps", name=unready[0]),
call(oci.list_tags, repository="ghcr.io/my-org/checkout", semverOnly=True, maxTags=5),
])
errors = [line for line in logs.splitlines() if "ERROR" in line]
result({
"pod": unready[0],
"errorCount": len(errors),
"latestTag": tags["tags"][0] if tags["tags"] else "",
})

For parameter names that match a Starlark keyword (such as from or in), scripts can pass a single positional dict argument instead of keyword arguments, for example mcp.prom.query({"from": "5m"}).

Faber ships two operator-side, SSRF-guarded read-only tools configurable on ToolProfile or MaintenancePolicy.spec.tools and usable either directly or inside Code Mode.

Exposes two read-only Distribution Spec v2 tools without pulling image layers or blobs:

  • oci_list_tags (oci.list_tags in Code Mode): Lists repository tags with optional prefix, semverOnly sorting, and maxTags (default 50, hard cap 200).
  • oci_resolve_digest (oci.resolve_digest in Code Mode): Resolves a tag or reference via HEAD/GET manifest lookup and returns content digest, media type, and multi-arch platform metadata.

Guardrails:

  • allowedRegistries requires exact registry hostnames (for example ghcr.io or registry.k8s.io). Empty allowlists fail closed and wildcards (*, *.example.com) are rejected.
  • Optional authSecretRef supplies pull credentials from a same-namespace Secret.
  • Private, loopback, and link-local IP ranges are blocked at dial time.

Exposes http_fetch (http.fetch in Code Mode) for read-only GET lookups against documentation, release feeds, or vulnerability APIs (for example api.github.com, artifacthub.io, or api.osv.dev).

Guardrails:

  • allowedHosts requires exact hostnames. Empty lists fail closed and wildcards are rejected.
  • maxBytes defaults to 512 KiB (hard cap 2 MiB) and timeout defaults to 15s.
  • Supports If-None-Match (etag) conditional requests and returns compact JSON (statusCode, contentType, etag, truncated, body).
  • Environment HTTP proxies are ignored, private/loopback/link-local IPs are blocked at dial time, redirect hops (max 5) are re-validated against allowedHosts, and auth headers are never forwarded across host boundaries.

See config/samples/connector-observability.yaml and the CRD API Reference for configuring Connector resources.

Two public packages in this repository are licensed under Apache-2.0 so you can embed them in proprietary or open-source Go services without AGPL obligations:

  • github.com/faberops/faber/pkg/engine: Bounded ReAct agent runtime (Runner, LLMClient, StrictSchema, Governor, MCPClient, Sandbox, Starlark Code Mode, OCIToolkit, HTTPFetchToolkit). License boundary enforced mechanically by TestApacheSDKLicenseBoundary.
  • github.com/faberops/faber/pkg/trigger: Stdlib-only CloudEvents v1.0 emitter (dev.faberops.app.incident) with HMAC-SHA256 signing and automatic backoff retries. Zero external dependencies enforced by TestTriggerStdlibOnlyBoundary.

Embedding pkg/engine with Code Mode, OCI, and HTTP Fetch

Section titled “Embedding pkg/engine with Code Mode, OCI, and HTTP Fetch”
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
"github.com/faberops/faber/pkg/engine"
)
func main() {
llmClient, err := engine.NewLLMClient(engine.LLMClientConfig{
Protocol: engine.ProtocolOpenAI,
BaseURL: "https://api.openai.com/v1",
APIKey: os.Getenv("OPENAI_API_KEY"),
})
if err != nil {
panic(err)
}
ociKit, err := engine.NewOCIToolkit(engine.OCIConfig{
AllowedRegistries: []string{"ghcr.io"},
})
if err != nil {
panic(err)
}
httpKit, err := engine.NewHTTPFetchToolkit(engine.HTTPFetchConfig{
AllowedHosts: []string{"api.github.com"},
})
if err != nil {
panic(err)
}
outSchema, err := engine.NewStrictSchema([]byte(`{
"type": "object",
"required": ["latestTag", "digest", "summary"],
"properties": {
"latestTag": {"type": "string"},
"digest": {"type": "string"},
"summary": {"type": "string"}
}
}`))
if err != nil {
panic(err)
}
runner, err := engine.NewRunner(engine.RunnerConfig{
LLM: llmClient,
CodeMode: engine.DefaultCodeModeConfig(),
EventSink: engine.EventSinkFunc(func(_ context.Context, ev engine.Event) {
fmt.Println("event:", ev.Type)
}),
})
if err != nil {
panic(err)
}
tools := engine.ToolsFromOCI(ociKit)
for _, t := range engine.ToolsFromHTTPFetch(httpKit) {
tools = append(tools, t)
}
res, err := runner.Run(context.Background(), engine.RunRequest{
Model: "gpt-5-mini",
SystemPrompt: "Use run_script to check the latest ghcr.io/faberops/faber-controller tag and digest, then return strict JSON.",
UserMessage: "Check the newest release tag and digest.",
OutputSchema: outSchema,
Tools: tools,
Governor: engine.NewGovernor(engine.GovernorConfig{
MaxSteps: 6,
MaxCostUSD: 0.10,
WallTimeout: 2 * time.Minute,
}),
})
if err != nil {
panic(err)
}
fmt.Println(string(json.RawMessage(res.Output)))
}

Use pkg/trigger in any Go service to report application incidents directly to a Faber webhook trigger without pulling Kubernetes or controller libraries into your dependency graph. See the full trigger.NewClient and client.Emit example in Triggers and Zero-Cost Pre-Checks.

Run offline SDK and boundary tests locally with:

Terminal window
go test -v ./pkg/engine ./pkg/trigger