Documentation
¶
Overview ¶
Package codemode runs model-written JavaScript programs that orchestrate other tools. The model calls one tool with a script; the script calls the other tools through a `tools` object, combines and filters their results, and returns a small answer. Intermediate tool results never enter the model's context.
The package is independent of the LLM framework. The host gives it a Catalog of tool specs and an Invoker that executes one nested call; the core tool in internal/core adapts the agent's tool set to these types.
Index ¶
- Constants
- type Call
- type CallStatus
- type Catalog
- func (c *Catalog) Describe(name string) (string, bool)
- func (c *Catalog) Entries() []Entry
- func (c *Catalog) Lookup(name string) (Entry, bool)
- func (c *Catalog) Namespaces() []string
- func (c *Catalog) RenderCatalog(budget int) (string, int)
- func (c *Catalog) Search(query, namespace string, limit int) []SearchHit
- func (c *Catalog) Suggest(name string) []string
- type Diagnostic
- type Entry
- type ErrorKind
- type Exposure
- type ExposureRule
- type InvokeResult
- type Invoker
- type Limits
- type Observer
- type Policy
- type Program
- type Result
- type SearchHit
- type Store
- type ToolSpec
Constants ¶
const ( DefaultTimeout = 30 * time.Second DefaultMaxToolCalls = 50 DefaultMaxOutputBytes = 100_000 DefaultMaxConcurrency = 8 DefaultMemoryLimit = 256 << 20 )
Default limits. Each one can be overridden in Limits.
const NamespaceSeparator = "__"
NamespaceSeparator separates an MCP server name from the tool name in a prefixed tool name ("github__list_issues"). The catalog exposes such a tool as tools.github.list_issues.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Call ¶
type Call struct {
// ID is a synthetic tool call ID: "<prefix>.<n>".
ID string `json:"id"`
// Name is the full tool name ("github__list_issues").
Name string `json:"name"`
// Path is the dotted script path ("github.list_issues").
Path string `json:"path"`
// Args is the JSON input.
Args string `json:"args,omitempty"`
// Status is the call state.
Status CallStatus `json:"status"`
// Duration is the wall time of the call.
Duration time.Duration `json:"duration_ns"`
// Error is the error text for failed calls.
Error string `json:"error,omitempty"`
}
Call records one nested tool call made by a script.
type CallStatus ¶
type CallStatus string
CallStatus is the state of one nested tool call.
const ( CallRunning CallStatus = "running" CallOK CallStatus = "ok" CallError CallStatus = "error" CallCancelled CallStatus = "cancelled" )
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
Catalog is the set of tools a script can see, organized as a tree.
func NewCatalog ¶
NewCatalog builds a catalog from specs. Tools with ExposureModelOnly are dropped: the script cannot call them. Specs keep their input order inside a namespace; namespaces are sorted.
func (*Catalog) Describe ¶
Describe returns the full signature, description and JSON schema of one tool.
func (*Catalog) Lookup ¶
Lookup finds an entry by full tool name or by its dotted path ("github.list_issues").
func (*Catalog) Namespaces ¶
Namespaces returns the sorted namespace names ("" is the root).
func (*Catalog) RenderCatalog ¶
RenderCatalog renders the model-facing tool list within budget bytes. Namespaces are visited round-robin so one large MCP server cannot crowd out the others. Tools with ExposureDeferred are never listed. Direct tools get a short signature (the model already has their schema); script-only tools get the full signature and a one-line description. The second return value is the number of callable tools left out.
type Diagnostic ¶
type Diagnostic struct {
Kind ErrorKind `json:"kind"`
Message string `json:"message"`
// Line and Column locate the error in the submitted code (1-based);
// zero when unknown.
Line int `json:"line,omitempty"`
Column int `json:"column,omitempty"`
Hint string `json:"hint,omitempty"`
}
Diagnostic describes why a run failed.
type Entry ¶
type Entry struct {
ToolSpec
// Namespace is the tree namespace ("" for root-level tools).
Namespace string
// Method is the property name inside the namespace.
Method string
}
Entry is a catalog entry: a ToolSpec plus its location in the tools tree.
func (Entry) Path ¶
Path returns the JavaScript expression that reaches the tool, e.g. `tools.read`, `tools.github.list_issues` or `tools["my-tool"]`.
func (Entry) ShortSignature ¶
ShortSignature renders the signature with parameter names only. It is used for tools the model already sees as direct tools, whose full schema is already in the request.
type ErrorKind ¶
type ErrorKind string
ErrorKind classifies a failed run.
const ( ErrParse ErrorKind = "ParseError" ErrUnknownTool ErrorKind = "UnknownTool" ErrInvalidToolInput ErrorKind = "InvalidToolInput" ErrToolFailure ErrorKind = "ToolFailure" ErrToolCallLimit ErrorKind = "ToolCallLimitExceeded" ErrTimeout ErrorKind = "TimeoutExceeded" ErrMemoryLimit ErrorKind = "MemoryLimitExceeded" ErrCancelled ErrorKind = "Cancelled" ErrUnsettled ErrorKind = "UnsettledPromise" ErrExecution ErrorKind = "ExecutionFailure" )
type Exposure ¶
type Exposure string
Exposure controls where a tool is visible when code mode is on.
const ( // ExposureDirect: the model sees the tool and can call it directly. A // script can also call it. This is the default. ExposureDirect Exposure = "direct" // ExposureCodeMode: the model does not see the tool as a direct tool. // Only a script can call it. The code mode catalog lists its full // signature. ExposureCodeMode Exposure = "codemode" // ExposureDeferred: like ExposureCodeMode, but the catalog does not // list the tool. A script finds it with searchTools(). ExposureDeferred Exposure = "deferred" // ExposureModelOnly: the model sees the tool, a script cannot call it. ExposureModelOnly Exposure = "model-only" )
func ParseExposure ¶
ParseExposure validates s and returns the matching Exposure.
func (Exposure) VisibleToModel ¶
VisibleToModel reports whether the model sees a tool with this exposure as a direct tool.
type ExposureRule ¶
ExposureRule maps a tool-name glob (path.Match syntax, e.g. "github__*") to an exposure.
func ParseRules ¶
func ParseRules(m map[string]string) ([]ExposureRule, error)
ParseRules converts a pattern → exposure map into ordered rules. Exact names sort before globs, and longer patterns before shorter ones, so the most specific rule wins regardless of map order.
type InvokeResult ¶
InvokeResult is the outcome of one nested tool call.
type Invoker ¶
type Invoker func(ctx context.Context, call Call) (InvokeResult, error)
Invoker executes one nested tool call. A returned error means the call could not run (not a tool-level failure, which uses IsError).
type Limits ¶
type Limits struct {
Timeout time.Duration
MaxToolCalls int
MaxOutputBytes int
MaxConcurrency int
MemoryLimit int64
}
Limits bounds one script run. Zero fields use the defaults above. A negative MemoryLimit disables the memory watchdog.
func (Limits) WithDefaults ¶
WithDefaults returns l with every zero field set to its default.
type Observer ¶
Observer receives live progress. All callbacks run on the script goroutine; they must not block for long.
type Policy ¶
type Policy struct {
Rules []ExposureRule
MCPDefault Exposure
}
Policy decides the exposure of each tool. Rules are evaluated in order; the first rule whose pattern matches wins. Tools that match no rule get MCPDefault when they are MCP tools (their name contains the namespace separator), else ExposureDirect.
type Program ¶
type Program struct {
Code string
Catalog *Catalog
Invoke Invoker
Limits Limits
// Store persists values across runs. Nil gives each run a fresh store.
Store *Store
Observer Observer
// CallIDPrefix prefixes nested call IDs. Usually the code mode tool
// call ID.
CallIDPrefix string
}
Program is one script run request.
type Result ¶
type Result struct {
OK bool `json:"ok"`
// Output is everything the script passed to text() followed by its
// return value.
Output string `json:"output,omitempty"`
Logs []string `json:"logs,omitempty"`
Calls []Call `json:"calls,omitempty"`
// Error is set when OK is false.
Error *Diagnostic `json:"error,omitempty"`
// CaptureTruncated reports that output or logs exceeded the capture
// cap and were cut.
CaptureTruncated bool `json:"capture_truncated,omitempty"`
WallTime time.Duration `json:"wall_time_ns"`
}
Result is the outcome of a run. Run never panics and never returns a Go error; failures are reported in Error.
type SearchHit ¶
type SearchHit struct {
Name string `json:"name"`
Path string `json:"path"`
Description string `json:"description"`
Signature string `json:"signature"`
}
SearchHit is one search result.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store keeps JSON values that scripts save with store() and read with load(). One Store lives as long as its code mode tool, so values survive across script runs in the same Kit instance. Values are copied in and out as JSON text, so scripts never share live objects.
func (*Store) Restore ¶
Restore replaces all entries with m (used to reload persisted values). Entries beyond the size limit are dropped.
type ToolSpec ¶
type ToolSpec struct {
// Name is the full tool name as the agent knows it, e.g. "read" or
// "github__list_issues".
Name string
// Description is the tool's model-facing description.
Description string
// Parameters is the JSON Schema "properties" map of the tool input.
Parameters map[string]any
// Required lists the required parameter names.
Required []string
// Exposure controls how the tool appears to the model and the script.
Exposure Exposure
}
ToolSpec describes one tool the script can call.