codemode

package
v0.143.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 16 Imported by: 0

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

View Source
const (
	DefaultTimeout        = 30 * time.Second
	DefaultMaxToolCalls   = 50
	DefaultMaxOutputBytes = 100_000
	DefaultMaxConcurrency = 8
	DefaultMemoryLimit    = 256 << 20
)

Default limits. Each one can be overridden in Limits.

View Source
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

func NewCatalog(specs []ToolSpec) *Catalog

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

func (c *Catalog) Describe(name string) (string, bool)

Describe returns the full signature, description and JSON schema of one tool.

func (*Catalog) Entries

func (c *Catalog) Entries() []Entry

Entries returns all entries.

func (*Catalog) Lookup

func (c *Catalog) Lookup(name string) (Entry, bool)

Lookup finds an entry by full tool name or by its dotted path ("github.list_issues").

func (*Catalog) Namespaces

func (c *Catalog) Namespaces() []string

Namespaces returns the sorted namespace names ("" is the root).

func (*Catalog) RenderCatalog

func (c *Catalog) RenderCatalog(budget int) (string, int)

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.

func (*Catalog) Search

func (c *Catalog) Search(query, namespace string, limit int) []SearchHit

Search returns the entries that best match query. Each query word that occurs in the tool name scores 3, in the description 1. An empty query matches every tool. namespace, when not empty, limits the search to one namespace.

func (*Catalog) Suggest

func (c *Catalog) Suggest(name string) []string

Suggest returns up to three tool paths whose name resembles name. It is used for "unknown tool" errors.

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

func (e Entry) Path() string

Path returns the JavaScript expression that reaches the tool, e.g. `tools.read`, `tools.github.list_issues` or `tools["my-tool"]`.

func (Entry) ShortSignature

func (e Entry) ShortSignature() string

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.

func (Entry) Signature

func (e Entry) Signature() string

Signature renders a TypeScript-like signature for the tool.

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

func ParseExposure(s string) (Exposure, error)

ParseExposure validates s and returns the matching Exposure.

func (Exposure) VisibleToModel

func (e Exposure) VisibleToModel() bool

VisibleToModel reports whether the model sees a tool with this exposure as a direct tool.

type ExposureRule

type ExposureRule struct {
	Pattern  string
	Exposure Exposure
}

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

type InvokeResult struct {
	Text    string
	IsError bool
	// Stop ends the script successfully without running promise continuations.
	// JavaScript cannot catch this stop or run catch/finally handlers for it.
	Stop bool
}

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

func (l Limits) WithDefaults() Limits

WithDefaults returns l with every zero field set to its default.

type Observer

type Observer struct {
	OnCallStart func(Call)
	OnCallEnd   func(Call)
	OnLog       func(line string)
}

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.

func (Policy) Resolve

func (p Policy) Resolve(name string) Exposure

Resolve returns the exposure of the named tool. Matching ignores case, because configuration loaders may lowercase map keys.

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"`
	// Stopped reports a successful early stop requested by a nested tool.
	Stopped bool `json:"stopped,omitempty"`
	// 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.

func Run

func Run(ctx context.Context, p Program) Result

Run executes p and returns its result.

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 NewStore

func NewStore() *Store

NewStore returns an empty store with the default size limit.

func (*Store) Delete

func (s *Store) Delete(key string)

Delete removes key.

func (*Store) Get

func (s *Store) Get(key string) (string, bool)

Get returns the JSON text stored under key.

func (*Store) Restore

func (s *Store) Restore(m map[string]string)

Restore replaces all entries with m (used to reload persisted values). Entries beyond the size limit are dropped.

func (*Store) Set

func (s *Store) Set(key, jsonText string) error

Set stores JSON text under key. It fails when the store would exceed its size limit.

func (*Store) Snapshot

func (s *Store) Snapshot() map[string]string

Snapshot returns a copy of all entries.

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.

Jump to

Keyboard shortcuts

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