codescripts

package
v0.75.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package codescripts resolves and lists server-side stored scripts for the code_execution tool (Spec 097).

A stored script is a file named `<name>.js` or `<name>.ts` in the `scripts/` directory next to the ACTIVE configuration file. Callers address it by base NAME — never by path — and this package is the single owner of what a name may be, how it maps to a file, and what a usable script file looks like.

Confinement is the name validator, not the filesystem walk: a token-valid name contains no separators and no dots, so joining it to the scripts directory cannot escape that directory by construction (FR-003 / SC-003). ValidateName therefore runs before any filesystem call. On top of that boundary sits a symlink/non-regular POLICY, made atomic where the platform allows it (Unix O_NOFOLLOW) and best-effort where it does not (Windows).

Nothing here caches: each Resolve performs one open and one bounded read, so an atomic replacement of a script file is visible to the very next invocation with nothing to invalidate (FR-009).

Index

Constants

View Source
const (
	// MaxNameLen is the longest permitted script name.
	MaxNameLen = 64

	// MaxSizeBytes bounds the daemon-side read of a script file. Inline code
	// has no such bound; stored scripts do, purely to bound the read.
	MaxSizeBytes = 256 * 1024

	// MaxErrorNames is how many available names a not-found error lists
	// (FR-004); the total count is reported alongside.
	MaxErrorNames = 20

	// DirName is the scripts directory's name, relative to the config file.
	DirName = "scripts"

	// LanguageJavaScript / LanguageTypeScript are the languages a script
	// extension can derive, matching the code_execution `language` parameter.
	LanguageJavaScript = "javascript"
	LanguageTypeScript = "typescript"
)
View Source
const (
	ReasonEmpty      = "empty"
	ReasonOversized  = "oversized"
	ReasonUnreadable = "unreadable"
	ReasonNonRegular = "non-regular"
)

Reasons a script file is present but unusable.

Variables

This section is empty.

Functions

func DeriveLanguage

func DeriveLanguage(name, ext, explicitLanguage string) (string, error)

DeriveLanguage maps a script extension to a code_execution language and rejects an explicit language that contradicts it. An empty explicit language always agrees.

func DirFor

func DirFor(configFilePath string) string

DirFor returns the scripts directory belonging to a config file path. An empty config path yields an empty directory (no authority, no scripts).

func Resolve

func Resolve(scriptsDir, name, explicitLanguage string) (source []byte, language string, err error)

Resolve reads the stored script `name` from scriptsDir and returns its source together with the language derived from its extension. This is the ADMINISTRATOR form: a not-found error carries the directory's listing (FR-004) and every other refusal names the host path it is about.

Order matters: the name is validated BEFORE any filesystem call (SC-003), then the directory decides which candidates exist (pre-105 behaviour, kept verbatim: a directory the administrator cannot list is a refusal, SC-005), then the surviving candidate is opened with the platform's no-follow idiom and read through a bounded reader. Exactly one open and one read per call — no cache, no re-read.

func ResolveScoped added in v0.68.0

func ResolveScoped(scriptsDir, name, explicitLanguage string) (source []byte, language string, err error)

ResolveScoped is Resolve for a scoped (agent-token) caller — Spec 105 FR-012. It opens and reads the script exactly as Resolve does, but decides its candidates by a constant-cost path probe instead of the directory listing, and every refusal it returns is already the non-disclosing form: a not-found error is built WITHOUT listing the directory — neither the discovery listing nor a directory read on the way to the miss; the two candidate names are probed and nothing else, so the refusal's cost does not grow with what is stored and does not depend on the name asked for (probeCandidates) — and the ambiguous / invalid forms carry the caller's own name and the reason but no host path and no raw OS error. Typed identities are the same, so the REST classifier does not tell the two callers apart. The probe is the scoped resolver's alone: the administrator path keeps its directory-based decision (SC-005), so a directory that is searchable but not listable still refuses administrators as it always did.

func SetIndexClockForTest added in v0.68.0

func SetIndexClockForTest(now func() time.Time) (restore func())

SetIndexClockForTest overrides the clock the settle check reads (round 9 MUST-FIX) and returns a func that restores it. A directory's on-disk change stamp cannot be forged from user space — it is exactly what makes the settle window a real guarantee — so a caller outside this package that needs a freshly written scripts directory treated as settled at once (an internal/server fixture, say) has no way to fake it by backdating a file; it must move the clock the settle check reads instead, as this package's own tests do internally. Test-only: production code never calls this, and callers outside this package must restore it (defer the returned func, or t.Cleanup) before any other test observes the override.

func ValidateName

func ValidateName(name string) error

ValidateName enforces the script-name token: 1-MaxNameLen characters of [A-Za-z0-9_-]. This is the confinement boundary and performs NO filesystem access — a valid name has no separators and no dots, so it cannot traverse.

func Warm added in v0.68.0

func Warm(scriptsDir string) error

Warm builds the stored-name index of scriptsDir on the caller's goroutine, so the first scoped request finds it ready. The server calls it when it learns its scripts directory; it is never called on a request's behalf. The listing is taken after Warm was called (a rebuild already in flight is waited for, then Warm lists again), so the index reflects the directory as it was at the call. A directory that cannot be opened or listed leaves a failed index (scoped callers are refused as unreadable until the directory changes) and the failure is returned for logging. On Windows there is no index of this shape (storedspellings_probe_windows.go keeps its own, round 13) and Warm is a no-op; darwin joined this index round 13, so Warm behaves for it exactly as it does for Linux/BSD.

Warm also keeps ONLY scriptsDir's index (round 9 SHOULD): the server calls Warm whenever the active scripts directory changes, so this is the point that knows which directory is current — every other directory's index is dropped (its rebuild context cancelled, round 11 SHOULD) rather than left to accumulate for as long as the process runs.

Warm's own rebuild is never cancelled by that pruning (round 11 SHOULD): cancellation exists to stop an ASYNC rebuild nobody is waiting for from outliving the index that scheduled it, not to let a concurrent caller's eviction of a DIFFERENT directory silently turn this synchronous call — which the caller is blocked on and whose error it trusts — into a no-op. scriptsDir's own index is never among the ones pruneOtherIndexesLocked drops here, so this is only a concern for a hypothetical concurrent Warm of a different directory; the rebuild call below simply does not consult ctx, so it always runs to completion and its result is always installed.

Types

type AmbiguousError

type AmbiguousError struct {
	Name  string
	Paths []string

	// Undisclosed marks the agent-token form: the message names the caller's
	// own script and the reason only, never a host path (Spec 105 FR-012).
	Undisclosed bool
}

AmbiguousError reports a name backed by both a .js and a .ts file.

The paths are host filesystem locations (they reveal the config directory), so the scoped form withholds them — see NonDisclosing().

func (*AmbiguousError) Error

func (e *AmbiguousError) Error() string

func (*AmbiguousError) NonDisclosing added in v0.68.0

func (e *AmbiguousError) NonDisclosing() *AmbiguousError

NonDisclosing returns a copy stripped of the host paths, for delivery to a scoped (agent-token) caller. The typed identity is preserved, so the REST surface still classifies it as SCRIPT_UNUSABLE.

type Entry

type Entry struct {
	Name   string   `json:"name"`
	Paths  []string `json:"paths"`
	Status Status   `json:"status"`
	Reason string   `json:"reason,omitempty"`
}

Entry is one listed script (FR-007). Paths holds the single source file, or both candidates when the name is ambiguous.

func List

func List(scriptsDir string) ([]Entry, error)

List enumerates the token-valid stored scripts in scriptsDir, alphabetically by name. An absent (or unset) directory is an empty list, not an error (FR-007). Statuses are advisory — Resolve re-checks at invocation time.

type InvalidError

type InvalidError struct {
	Name   string
	Path   string
	Reason string
	Detail string

	// Undisclosed marks the agent-token form: the message names the caller's
	// own script and the reason only — no path, no OS error (Spec 105 FR-012).
	Undisclosed bool
}

InvalidError reports a script file that exists but cannot be executed.

Path is a host filesystem location and Detail is frequently a raw OS error carrying another one, so the scoped form withholds both — see NonDisclosing().

func (*InvalidError) Error

func (e *InvalidError) Error() string

func (*InvalidError) NonDisclosing added in v0.68.0

func (e *InvalidError) NonDisclosing() *InvalidError

NonDisclosing returns a copy stripped of the host path and the raw detail, for delivery to a scoped (agent-token) caller. The typed identity and the reason are preserved, so the REST surface still classifies it as SCRIPT_UNUSABLE and the caller still learns what is wrong with its own script.

type InvalidNameError

type InvalidNameError struct {
	Name   string
	Reason string
}

InvalidNameError rejects a script name before any filesystem access.

func (*InvalidNameError) Error

func (e *InvalidNameError) Error() string

type LanguageMismatchError

type LanguageMismatchError struct {
	Name      string
	Extension string
	Requested string
	Derived   string

	// Undisclosed marks the agent-token form: the message names the caller's
	// own requested language (its own input, not host information) but
	// withholds the script's actual extension and derived language — host
	// filesystem facts a directory listing would show (Spec 105 FR-012).
	Undisclosed bool
}

LanguageMismatchError reports an explicit `language` that contradicts the script's extension (the extension is authoritative).

Extension and Derived are host filesystem facts about the script (its real extension is what a directory listing would show), so — like AmbiguousError and InvalidError — the scoped form withholds them: see NonDisclosing(). Every other refusal `resolve` can return (NotFoundError, AmbiguousError, InvalidError) already threads the `disclose` flag through to its own NonDisclosing() form; this type was the one omission, always returning the full administrator detail regardless of caller kind.

func (*LanguageMismatchError) Error

func (e *LanguageMismatchError) Error() string

func (*LanguageMismatchError) NonDisclosing added in v0.68.0

func (e *LanguageMismatchError) NonDisclosing() *LanguageMismatchError

NonDisclosing returns a copy stripped of the extension/derived language details, for delivery to a scoped (agent-token) caller. The typed identity is preserved, so the REST surface still classifies it as INVALID_LANGUAGE — same as AmbiguousError/InvalidError keeping their own distinct classification as SCRIPT_UNUSABLE rather than being folded into SCRIPT_NOT_FOUND.

type NotFoundError

type NotFoundError struct {
	Name      string
	Dir       string
	Available []string // first MaxErrorNames ok names, alphabetical
	Total     int      // total ok scripts in the directory

	// Undisclosed marks the agent-token form of the error: the listing is
	// withheld and the message is independent of the directory's contents,
	// so a failed call cannot serve as an oracle for what is stored.
	Undisclosed bool
}

NotFoundError reports a name with no script file behind it, carrying the available names so the caller can recover in one round trip (FR-004).

The enumeration is administrator-only (Spec 105 FR-012): a scoped caller receives the same error with Undisclosed set, whose text names neither the other scripts, their count nor the directory — see NonDisclosing().

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

func (*NotFoundError) NonDisclosing added in v0.68.0

func (e *NotFoundError) NonDisclosing() *NotFoundError

NonDisclosing returns a copy of the error stripped of everything that discloses the directory's contents — names, count and path — for delivery to a scoped (agent-token) caller. The typed identity is preserved, so the REST surface still classifies it as SCRIPT_NOT_FOUND.

type Status

type Status string

Status classifies a listed script.

const (
	StatusOK        Status = "ok"        // invocable
	StatusAmbiguous Status = "ambiguous" // both .js and .ts exist for this name
	StatusInvalid   Status = "invalid"   // present but not usable; see Reason
)

Jump to

Keyboard shortcuts

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