Documentation
¶
Overview ¶
Package parse reads the file formats of agent surfaces (json, jsonc, jsonl, toml, yaml, ini, dotenv, shell-history and ipynb) into a small tree that keeps the 1-based source line of every value, and selects string values from it with field selectors.
Parsers never panic and never run unbounded: nesting is capped at MaxDepth and the tree at MaxNodes. A malformed file gives ErrParse; the error carries no file content, so it is safe to turn into a warning.
Index ¶
- Constants
- Variables
- func NotebookRawLimit(textLimit int64) int64
- func Supported(format string) bool
- type Item
- type JSONLResult
- type Kind
- type Match
- type Node
- func Parse(format string, data []byte) ([]*Node, error)
- func ParseDotenv(data []byte) (*Node, error)
- func ParseDotenvLines(data []byte) (root *Node, skipped int, err error)
- func ParseINI(data []byte) (*Node, error)
- func ParseIPYNB(data []byte) (*Node, error)
- func ParseIPYNBReader(r io.Reader, maxText, maxRaw int64) (*Node, bool, error)
- func ParseJSON(data []byte) (*Node, error)
- func ParseJSONC(data []byte) (*Node, error)
- func ParseShellHistory(data []byte) (*Node, error)
- func ParseTOML(data []byte) (*Node, error)
- func ParseYAML(data []byte) ([]*Node, error)
- type Notebook
- type NotebookCell
- type Result
- type Selector
Constants ¶
const ( // MaxDepth is the deepest nesting of objects and arrays a parser accepts. MaxDepth = 64 // MaxNodes is the most tree nodes one file may produce. MaxNodes = 1 << 20 // MaxKeyBytes is the longest object key kept; longer keys are cut. MaxKeyBytes = 256 )
Limits that keep a hostile file from using unbounded time or memory.
const DefaultMaxLine = 10 << 20
DefaultMaxLine is the line limit used when ScanJSONL gets a limit of zero or less (10 MiB).
const MaxCommandBytes = 1 << 20
MaxCommandBytes is the longest shell command kept; a longer line, or a continued command that grows past it, is skipped.
const NotebookRawFactor = 8
NotebookRawFactor is how many times larger than the text limit a raw notebook may be. The text limit applies to the retained text (sources and text outputs); image and other binary payloads are never retained, so the raw file may be bigger.
Variables ¶
var ErrNotebookTooLarge = errors.New("notebook: raw size limit")
ErrNotebookTooLarge is returned when the raw notebook is larger than the raw limit.
var ErrParse = errors.New("surface parse: malformed file")
ErrParse is the error of every malformed or over-limit file. It never carries file content.
var ErrSelector = errors.New("surface parse: invalid field selector")
ErrSelector is returned for a selector that is not valid.
var ErrUnsupported = errors.New("surface parse: unsupported format")
ErrUnsupported is returned for a format with no parser in this binary.
Functions ¶
func NotebookRawLimit ¶
NotebookRawLimit returns the raw size limit of a notebook for the text limit.
Types ¶
type Item ¶
type Item struct {
// Key is the object key of a member of a Group; empty otherwise.
Key string
Value string
// Line is the 1-based source line of the value.
Line int
}
Item is one string value selected from a file.
type JSONLResult ¶
type JSONLResult struct {
// Malformed is the number of lines that were not valid JSON.
Malformed int
// TooLong is the number of lines longer than the line limit.
TooLong int
}
JSONLResult counts what ScanJSONL skipped.
func ScanJSONL ¶
ScanJSONL reads r line by line and parses each non-empty line as one JSON value. fn gets the 1-based file line of the record and its root; it returns false to stop. A line longer than maxLine bytes is skipped without being held in memory, and a line that is not valid JSON is skipped; both are counted in the result. Nothing but the current line is buffered. err is non-nil only when reading r fails.
type Match ¶
type Match struct {
// Field is the concrete field path, for example "permissions.allow[3]"; for a
// Group it is the path of the parent object ("mcpServers.github.env").
Field string
Group bool
Items []Item
}
Match is one selected unit: either a single string (an array element, a named key or a ** leaf) or a Group, the string members of one object reached by a trailing *.
type Node ¶
type Node struct {
Kind Kind
// Line is the 1-based line where the value starts.
Line int
// Str is the text of a KindString node.
Str string
// Keys holds the keys of a KindObject node, parallel to Kids (duplicates kept).
Keys []string
// Kids are the members of an object or the elements of an array.
Kids []*Node
}
Node is one value of a parsed file.
func Parse ¶
Parse parses data as format and returns the root of each document in it (one for every format but yaml). Formats with no parser here (jsonl, which is read with ScanJSONL) return ErrUnsupported.
func ParseDotenv ¶
ParseDotenv parses a dotenv file: KEY=value lines (optionally after "export "), # comments and blank lines. Values may be double quoted (with \n, \r, \t, \" and \\ escapes, and spanning lines), single quoted (literal, spanning lines) or bare (trimmed, ending at a " #" comment). The result is one object of strings. A line that is not a comment or an assignment (a bare KEY, an unterminated quote, text after a closing quote) is skipped, so the keys on the other lines are still read.
func ParseDotenvLines ¶
ParseDotenvLines is ParseDotenv that also returns how many lines it skipped.
func ParseINI ¶
ParseINI parses an INI file: [section] headers, key=value or key: value lines and ; or # comment lines. Keys before the first section sit at the top level; each section is an object. Values are the text after the separator, trimmed, with one pair of surrounding quotes removed. A line that is none of these is malformed.
func ParseIPYNB ¶
ParseIPYNB reads a Jupyter notebook (nbformat JSON) into one object
{cells: [ {source: [line, ...], outputs: [line, ...]}, ... ]}
where every array element is one text line with its line break stripped. The Line of a source element is its 1-based line in the cell's source; the Line of an outputs element is its 1-based line in the cell's outputs joined in order. The cell keeps its position in cells even when it is empty or malformed, so the index of a cell in the tree is its index in the notebook; a cell that is not an object is a KindOther placeholder and a field of the wrong type is skipped, never an error.
The text is read by ReadNotebook (see there for what a cell holds and what is skipped); outputs have ANSI escape sequences removed. A file that is not JSON, is not an object or has no "cells" array gives ErrParse. Nesting and size are capped like every other parser. A BOM is tolerated.
func ParseIPYNBReader ¶
ParseIPYNBReader is ParseIPYNB reading from r with the limits of ReadNotebook. The bool is true when the retained text hit maxText and the tree holds only what was read before.
func ParseJSON ¶
ParseJSON parses one JSON value from the token stream of encoding/json. Only strings are kept as values; numbers, booleans and null become KindOther nodes.
func ParseJSONC ¶
ParseJSONC parses JSON with // and /* */ comments and trailing commas. Comments are blanked out and newlines kept, so every value keeps its line.
func ParseShellHistory ¶
ParseShellHistory parses a shell history file of any dialect into one object with the array "commands"; every command is one string whose Line is the 1-based line it starts on. The grammar is per line and tolerant, so one reader serves every shell:
- fish entries: "- cmd: <text>" (\\ and \n unescaped); the "when:", "paths:" and path-list lines under an entry are skipped;
- zsh extended lines ": <timestamp>:<elapsed>;<command>" (prefix stripped);
- bash "#<digits>" timestamp lines are skipped;
- every other non-blank line is a command (bash, zsh plain, PowerShell);
- a line ending in an odd number of backslashes continues on the next line, and the lines join into one command that keeps the first line number.
Malformed lines (NUL bytes, over MaxCommandBytes, an empty command) are skipped, and the file never fails. Past MaxNodes the rest of the file is ignored.
func ParseTOML ¶
ParseTOML parses the TOML subset agent configs use: tables, arrays of tables, dotted keys, basic and literal strings (also multi-line), scalars (kept as their text), arrays and inline tables. Dates and numbers are not validated beyond their first character.
type Notebook ¶
type Notebook struct {
Cells []NotebookCell
// Truncated is set when the retained text reached its limit: the rest of the
// notebook was dropped and the cells hold what was read before that.
Truncated bool
}
Notebook is what ReadNotebook retained of a notebook.
func ReadNotebook ¶
ReadNotebook reads Jupyter notebook JSON (nbformat) from r with a streaming decoder. It keeps the text of every cell source and cell output and nothing else: "metadata", "attachments" and every data member that is not "text/plain" (images, audio, binary) are skipped without being retained. maxText bounds the retained text (the sum of all source and output text); when it is reached the rest is dropped and Truncated is set, with no error. maxRaw bounds the bytes read; more gives ErrNotebookTooLarge.
Cell source is a string or an array of strings (joined as written); a field of the wrong type is skipped. A file that is not JSON, is not an object, has no "cells" array, is truncated, nests deeper than MaxDepth or has more than MaxNodes cells gives ErrParse. A BOM is tolerated. Duplicate keys keep the last value, as encoding/json.
type NotebookCell ¶
NotebookCell is the text of one cell of a Jupyter notebook: its source as written, and its outputs (the "text" of an output, then its data["text/plain"], then its "traceback", each non-empty output starting on a new line) with ANSI escape sequences removed. Malformed is set for a cell that is not a JSON object; it keeps its place in the cell list so that an index plus one is the cell number of the notebook.
type Result ¶
type Result struct {
Roots []*Node
// Skipped counts the dotenv lines that were not KEY=value assignments and were left
// out. Other formats are strict and never skip.
Skipped int
}
Result is a parsed file: the root of each document in it and how many lines or entries a tolerant parser skipped.
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
Selector picks values from a Node tree: a.b names keys, [] after a name takes every element of that array, * takes every key of an object and ** as the last part takes every string at any depth below that point (the node itself when it is a string).
func ParseSelector ¶
ParseSelector parses a selector such as "permissions.allow[]" or "mcpServers.*.env.*".