codemode

package
v0.8.4-beta Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package codemode provides isolated JavaScript orchestration and authorized tool discovery.

Index

Constants

View Source
const MaxConcurrentToolCalls = 8

MaxConcurrentToolCalls bounds active children in both the VM and runner registry.

View Source
const MaxHostResponseBytes = 2 << 20

MaxHostResponseBytes bounds a serialized host response before it enters the VM. Tool executors can apply this limit before recording their final child summary.

View Source
const MaxScriptBytes = 128 << 10

MaxScriptBytes bounds the submitted async function body, before wrapping.

View Source
const RuntimeDeclaration = `` /* 1352-byte string literal not displayed */

RuntimeDeclaration is the TypeScript contract of the code-execution VM. The code_execute description embeds it verbatim and Describe declares each tool against these types, so the model reads the shared types exactly once.

Variables

This section is empty.

Functions

func Signature

func Signature(definition Definition) string

Signature renders input fields and, when the tool declares an output schema, a ToolReply<T> return type. Oversized signatures shed input types first, then output detail, and input field names last, since a call needs them. Any abbreviation adds a catalog.describe hint.

func Summary

func Summary(definition Definition) string

Summary returns a tool's one-line summary: its explicit Short, or else the first sentence of its description, on one line and capped in length.

func ToolIndex

func ToolIndex(definitions []Definition) string

ToolIndex renders every callable tool for the code_execute description. Built-in tools (no group) come first with signatures and summaries, then each group in name order. Every tool is named; within the byte budget, groups take turns upgrading their cheapest remaining tool to a full line (signature and summary), so each group is represented before any group is complete. If even the names do not fit, the largest groups are reduced to a count. Built-in tools are never reduced. The output is deterministic for prompt caching.

func ValidateOutputData

func ValidateOutputData(schema map[string]any, data json.RawMessage) error

ValidateOutputData checks an already-serialized, effective tool payload. Null is always permitted because result hooks can remove structured data. Schemas describe only data, not the reply envelope or presentation metadata.

Types

type Catalog

type Catalog struct {
	// contains filtered or unexported fields
}

Catalog is an immutable, in-memory snapshot safe for concurrent discovery. Authorization is supplied by its caller, never inferred from discovery requests.

func NewCatalog

func NewCatalog(definitions []Definition) *Catalog

NewCatalog snapshots authorized definitions. Duplicate names retain the first definition. Schemas must contain JSON values; unsupported non-JSON schemas degrade to unknown.

func (*Catalog) Describe

func (c *Catalog) Describe(name string) (Description, error)

Describe returns only an exact authorized name, with defensive schema copies. Its declaration uses the shared types in RuntimeDeclaration, which the code_execute description already carries, so they are not repeated here.

func (*Catalog) List

func (c *Catalog) List(options CatalogOptions) (Page, error)

List enumerates every authorized tool in stable registered-name order.

func (*Catalog) OutputSchema

func (c *Catalog) OutputSchema(name string) map[string]any

OutputSchema returns a defensive copy of a tool's output schema, or nil when the tool is unknown or declares none, without building its declaration.

func (*Catalog) Search

func (c *Catalog) Search(query string, options CatalogOptions) (Page, error)

Search ranks partial lexical matches using field-weighted BM25, exact names first. It does not pad results with unrelated tools or expose scores as probabilities.

type CatalogOptions

type CatalogOptions struct {
	Group  string `json:"group,omitempty"`
	Limit  int    `json:"limit,omitempty"`
	Cursor string `json:"cursor,omitempty"`
}

CatalogOptions controls exact group filtering and bounded pagination.

type Definition

type Definition struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Group       string `json:"group,omitempty"`
	// Short is an explicit one-line summary. Without one, listings use the
	// first sentence of Description.
	Short        string         `json:"short,omitempty"`
	InputSchema  map[string]any `json:"inputSchema"`
	OutputSchema map[string]any `json:"outputSchema,omitempty"`
}

Definition describes one already-authorized tool. Names are exact registered names.

type Description

type Description struct {
	Definition
	Declaration string `json:"declaration"`
}

Description contains the original schemas and a conservative TypeScript declaration.

type Error

type Error struct {
	Kind    string          `json:"kind"`
	Message string          `json:"message"`
	Tool    string          `json:"tool,omitempty"`
	CallID  string          `json:"callId,omitempty"`
	Outcome string          `json:"outcome,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
}

Error is a serializable runtime or host-operation failure.

func (*Error) Error

func (e *Error) Error() string

Error implements error. Tool failures name the tool, failure kind, and outcome, so callers that read only the message can tell what failed and whether it ran. Message itself remains the unmodified host or script text.

type Handler

type Handler func(context.Context, Request) (any, error)

Handler executes an authorized tool or reads the invocation's catalog. It must honor cancellation and may be called concurrently. An error that implements json.Marshaler supplies the fields of the guest's serializable Error.

type OutputItem

type OutputItem struct {
	Type       string          `json:"type"`
	Value      json.RawMessage `json:"value,omitempty"`
	ArtifactID string          `json:"artifactId,omitempty"`
	Detail     string          `json:"detail,omitempty"`
}

OutputItem is a selected JSON value, image, or artifact reference. Type is "json", "image", or "artifact", set by the host operation rather than inferred from an emitted JSON value. Value is used only for JSON; ArtifactID is used only for media, with optional Detail "original" for images.

type OutputValidationError

type OutputValidationError struct {
	Details []string
	// contains filtered or unexported fields
}

OutputValidationError reports an invalid output schema or mismatched data. Its message is safe to show scripts. Details are for host logs only: the compiler's diagnosis of a schema, or the instance and keyword locations of a mismatch, never instance values.

func (*OutputValidationError) Error

func (e *OutputValidationError) Error() string

type Page

type Page struct {
	Tools      []ToolSummary `json:"tools"`
	NextCursor string        `json:"nextCursor,omitempty"`
}

Page contains a bounded list of tools and an opaque continuation cursor.

type Request

type Request struct {
	Operation string          `json:"operation"`
	Name      string          `json:"name,omitempty"`
	Input     json.RawMessage `json:"input,omitempty"`
	Query     string          `json:"query,omitempty"`
	Options   json.RawMessage `json:"options,omitempty"`
}

Request is a host operation submitted by an isolated JavaScript invocation. Run identity, tool-call authority, and permissions belong to the host, not JS.

type Result

type Result struct {
	Outputs []OutputItem `json:"outputs"`
}

Result contains only explicitly emitted values and the async body's return value. Execute preserves previously emitted outputs when the invocation fails.

func Execute

func Execute(ctx context.Context, code string, handler Handler) (Result, error)

Execute runs an async JavaScript function body in a fresh QuickJS/WASM VM. It grants no ambient filesystem, network, environment, or module-loading access. Host callbacks are bounded and cancel with ctx; Execute does not wait for a callback that ignores cancellation, and such a callback can never access the VM. Media emissions require authority and are rejected; use ExecuteWithOutputValidator to authorize them.

func ExecuteWithOutputValidator

func ExecuteWithOutputValidator(ctx context.Context, code string, handler Handler, validator func(OutputItem) error) (Result, error)

ExecuteWithOutputValidator runs code with optional authorization of each output. The validator runs synchronously on the VM owner after structural and budget validation and before append. It must perform only local, nonblocking checks; it must not resolve artifacts, execute tools, or re-enter the VM. A nil validator permits JSON but rejects media. Errors are immediately catchable by emit callers.

type ToolSummary

type ToolSummary struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Group       string `json:"group,omitempty"`
}

ToolSummary is a compact discovery result; full schemas require Describe.

Jump to

Keyboard shortcuts

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