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.
Starlark Multi-Tool Code Mode
Section titled “Starlark Multi-Tool Code Mode”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, default100000), wall-clock timeout (timeout, default15s), nested tool calls (maxToolCalls, default25), serializedresult()size (maxOutputBytes, default32768), andbatch()worker concurrency (maxBatchConcurrency, default4, clamped at8).
Enabling Code Mode on a ToolProfile
Section titled “Enabling Code Mode on a ToolProfile”Enable spec.codeMode on a ToolProfile (or inline under MaintenancePolicy.spec.tools.codeMode):
apiVersion: faberops.dev/v1alpha1kind: ToolProfilemetadata: name: codemode-readonly namespace: faberspec: codeMode: enabled: true hideWrappedTools: true maxSteps: 100000 timeout: 15s maxToolCalls: 25 maxOutputBytes: 32768 maxBatchConcurrency: 4When 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.
Built-In Starlark Namespaces and Helpers
Section titled “Built-In Starlark Namespaces and Helpers”Inside run_script, Faber exposes wrapped tools under clean namespaces:
k8s:k8s.list,k8s.get,k8s.logs,k8s.eventsmcp.<server>:mcp.<server>.<tool>for each configured Streamable HTTP MCP serveroci:oci.list_tags,oci.resolve_digesthttp:http.fetchtools:tools.<name>for any custom read-only SDK tools
Three built-in helpers keep scripts short and fast:
help()orhelp(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 callresult(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"}).
Read-Only OCI and HTTP Fetch Tools
Section titled “Read-Only OCI and HTTP Fetch Tools”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.
OCI Registry Inspection (spec.oci)
Section titled “OCI Registry Inspection (spec.oci)”Exposes two read-only Distribution Spec v2 tools without pulling image layers or blobs:
oci_list_tags(oci.list_tagsin Code Mode): Lists repository tags with optionalprefix,semverOnlysorting, andmaxTags(default50, hard cap200).oci_resolve_digest(oci.resolve_digestin Code Mode): Resolves a tag or reference viaHEAD/GETmanifest lookup and returns content digest, media type, and multi-arch platform metadata.
Guardrails:
allowedRegistriesrequires exact registry hostnames (for exampleghcr.ioorregistry.k8s.io). Empty allowlists fail closed and wildcards (*,*.example.com) are rejected.- Optional
authSecretRefsupplies pull credentials from a same-namespace Secret. - Private, loopback, and link-local IP ranges are blocked at dial time.
Allowlisted HTTP Fetch (spec.httpFetch)
Section titled “Allowlisted HTTP Fetch (spec.httpFetch)”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:
allowedHostsrequires exact hostnames. Empty lists fail closed and wildcards are rejected.maxBytesdefaults to512 KiB(hard cap2 MiB) andtimeoutdefaults to15s.- 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.
Embedding the Apache-2.0 Go SDKs
Section titled “Embedding the Apache-2.0 Go SDKs”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 byTestApacheSDKLicenseBoundary.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 byTestTriggerStdlibOnlyBoundary.
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)))}Embedding pkg/trigger
Section titled “Embedding pkg/trigger”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:
go test -v ./pkg/engine ./pkg/trigger