jinn

package
v0.14.1 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 42 Imported by: 0

Documentation

Overview

Package jinn provides a blob codec for compressing undo history snapshots.

Adapted from: https://github.com/frane/agented@9f88dae/internal/store/blob/blob.go What changed: extracted as standalone codec with no dependencies on agented internals;

kept the gzip+raw adaptive strategy with tag-prefix encoding;
added fsync-free API (callers handle durability).

Date: 2026-04-29

The pattern: blob storage with adaptive compression. Small payloads are stored raw (compression overhead exceeds savings). Larger payloads get gzip. A 1-byte tag prefix makes decoding unambiguous. If gzip makes it larger (already- compressed data), fall back to raw. This gives good compression for text edits while avoiding the double-compression penalty on binary content.

Package jinn is a sandboxed tool executor bound to a working directory.

File naming: tool_<name>.go = a tool handler plus its direct support; bare <domain>.go = generic infrastructure/helpers shared across tools. A few support files (read_window.go, search_parse.go, search_run.go) keep bare names despite being tool-specific — renaming would be churn.

Index

Constants

View Source
const (
	ErrCodePathOutsideSandbox = "path_outside_sandbox"
	ErrCodeFileNotFound       = "file_not_found"
	ErrCodePermissionDenied   = "permission_denied"
	ErrCodeEditNotUnique      = "edit_not_unique"
	ErrCodeEditNoChange       = "edit_no_change"
	ErrCodeEditNotFound       = "edit_not_found"
	ErrCodeEditOverlap        = "edit_overlap"
	ErrCodeOldTextEmpty       = "old_text_empty"
	ErrCodeTimeout            = "timeout"
	ErrCodeLspUnavailable     = "lsp_unavailable"
	ErrCodeBinaryFile         = "binary_file"
	ErrCodeFileTooLarge       = "file_too_large"
	ErrCodeInvalidRegex       = "invalid_regex"
	ErrCodeStaleFile          = "stale_file"
	ErrCodeCommandBlocked     = "command_blocked"
	ErrCodeInvalidArgs        = "invalid_args"
	ErrCodeCanceled           = "canceled"
	ErrCodeConflict           = "conflict"
	ErrCodePlanInvalid        = "plan_invalid"
	ErrCodePlanCoerceFailed   = "plan_coerce_failed"
	ErrCodeResourceLimit      = "resource_limit"
)

Error code constants for structured error reporting.

View Source
const (
	DefaultMaxLines        = 2000
	DefaultMaxBytes        = 50 * 1024  // 50KB
	PlanTranscriptMaxBytes = 200 * 1024 // aggregate transcript cap for run_plan, oldest-node-first trim
)

Default limits for tool output truncation, matching pi conventions.

View Source
const (
	// RouteDefaultMaxTools is the unambiguous adaptive result limit.
	RouteDefaultMaxTools = 1
	// RouteMaxTools bounds the number of recommendations returned by a route request.
	RouteMaxTools = 8
)
View Source
const DefaultMaxDepth = 8

DefaultMaxDepth mirrors predexec's DEFAULT_MAX_DEPTH.

Variables

View Source
var HighConfidenceKinds = map[string]bool{
	"exitCode": true, "fileExists": true, "jsonPath": true,
	"numeric": true, "always": true,
}

HighConfidenceKinds — "always" IS high-confidence (unconditional edges are unambiguous); only "match" (fuzzy regex) is low-confidence.

View Source
var Schema string

Schema is the tool definitions in OpenAI function-calling format.

Functions

func CompactSchema added in v0.8.10

func CompactSchema() (string, error)

CompactSchema returns Schema without insignificant JSON whitespace.

func ErrorDetails added in v0.14.0

func ErrorDetails(err error) (code, suggestion string)

ErrorDetails extracts the stable code and corrective suggestion from err.

func ExplainRisk added in v0.6.0

func ExplainRisk(r RiskLevel, reason string) string

ExplainRisk returns a one-line formatted explanation for the user, e.g. "dangerous: rm with force flags — irreversible".

func LeanSchema added in v0.8.10

func LeanSchema() (string, error)

LeanSchema returns a prompt-facing schema that keeps tool descriptions but removes nested parameter descriptions. Parameter names, types, defaults, enums, oneOf branches, and required fields remain intact.

func LeanSchemaForMode added in v0.12.0

func LeanSchemaForMode(mode ShellMode) (string, error)

LeanSchemaForMode returns the prompt-facing schema for an execution policy.

func NetworkToolNames added in v0.13.0

func NetworkToolNames() []string

NetworkToolNames returns the stable, non-mutating open-world tool allowlist.

func ReadOnlyToolNames added in v0.13.0

func ReadOnlyToolNames() []string

ReadOnlyToolNames returns the canonical tool allowlist for callers that need to expose a strictly read-only execution surface. The returned slice is a defensive copy and follows the stable catalog order.

func ResolveVersion

func ResolveVersion(ldVersion string) string

ResolveVersion returns a human-readable version string, preferring ldflags-injected version, then VCS revision, then module version.

func SchemaToolNames added in v0.8.14

func SchemaToolNames() ([]string, error)

SchemaToolNames returns the ordered tool names declared by the embedded wire schema. The runtime registry validates exact parity with this declaration.

Types

type Classification added in v0.6.0

type Classification string

Classification describes how a shell exit code should be interpreted by the calling LLM. Expected-nonzero exits are semantic signals, not failures.

const (
	// ClassSuccess means exit 0 — command completed normally.
	ClassSuccess Classification = "success"
	// ClassExpectedNonzero means a non-zero exit that is a semantic signal
	// (e.g., grep exit 1 = no matches). The LLM should NOT retry.
	ClassExpectedNonzero Classification = "expected_nonzero"
	// ClassError means an unexpected non-zero exit indicating failure.
	ClassError Classification = "error"
	// ClassTimeout means the command exceeded its time limit (exit 124).
	ClassTimeout Classification = "timeout"
	// ClassSignal means the process was killed by a signal.
	ClassSignal Classification = "signal"
)

type CompressionMeta added in v0.8.4

type CompressionMeta struct {
	Strategies  []string `json:"strategies,omitempty"`
	OriginalLen int      `json:"original_len,omitempty"`
	FinalLen    int      `json:"final_len,omitempty"`
}

CompressionMeta carries metadata about what compression was applied.

type Compressor added in v0.8.4

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

Compressor applies a chain of strategies to tool output.

func NewCompressor added in v0.8.4

func NewCompressor() *Compressor

NewCompressor creates a Compressor with the default strategy chain.

func (*Compressor) Compress added in v0.8.4

func (c *Compressor) Compress(output string, tool string) (result string, meta CompressionMeta)

Compress applies all applicable strategies to the output. It returns the compressed text and metadata about what was applied. If compression panics, the original output is returned (fail-open).

type Condition added in v0.11.0

type Condition struct {
	Kind    string `json:"kind"` // exitCode|fileExists|jsonPath|numeric|match|always
	Op      string `json:"op,omitempty"`
	Value   any    `json:"value,omitempty"`
	Path    string `json:"path,omitempty"`
	Extract string `json:"extract,omitempty"`
	Regex   string `json:"regex,omitempty"`
	Stream  string `json:"stream,omitempty"` // match only: stdout|stderr
	Negate  bool   `json:"negate,omitempty"`
}

Condition is a flattened Kind union in Go. The wire schema validates its six forms with oneOf while this type stays straightforward to coerce.

type ContentBlock added in v0.6.2

type ContentBlock struct {
	Type     string `json:"type"`               // "text" or "image"
	Text     string `json:"text,omitempty"`     // for type="text"
	Data     string `json:"data,omitempty"`     // base64-encoded, for type="image"
	MimeType string `json:"mimeType,omitempty"` // e.g. "image/png", for type="image"
}

ContentBlock represents a typed piece of content in a tool response (text or image).

type DiffResult added in v0.6.2

type DiffResult struct {
	Diff             string `json:"diff"`
	FirstChangedLine int    `json:"firstChangedLine,omitempty"`
}

DiffResult holds structured diff output.

type Engine

type Engine struct {
	LSPTimeoutSec int // per-query LSP timeout; 0 uses default (10s)
	// contains filtered or unexported fields
}

Engine is a sandboxed tool executor bound to a working directory.

func New

func New(workDir, version string) *Engine

New creates an Engine rooted at the given working directory. The workDir is resolved via EvalSymlinks so that path boundary checks work correctly on platforms where temp dirs are symlinks (e.g., macOS).

func NewWithConfig added in v0.12.0

func NewWithConfig(workDir string, config EngineConfig) (*Engine, error)

NewWithConfig creates an Engine with explicit process and mutation policy.

func (*Engine) Close added in v0.9.0

func (e *Engine) Close() error

Close releases the engine's resources, closing the lazily-opened memory DB if it was ever opened. Safe to call when memDB is nil.

func (*Engine) Dispatch

func (e *Engine) Dispatch(ctx context.Context, tool string, args map[string]interface{}) (*ToolResult, map[string]any, error)

Dispatch routes a tool call to the appropriate handler and returns structured metadata alongside the result. Meta keys:

  • "risk": pre-execution risk level set by run_shell ("safe", "caution", "dangerous")
  • "classification": exit-code class set by run_shell ("success", "expected_nonzero", "error", "timeout", "signal")

Tools that don't set meta return a nil map. Callers should treat nil as empty.

func (*Engine) ShellMode added in v0.12.0

func (e *Engine) ShellMode() ShellMode

ShellMode reports the engine's configured shell execution policy.

type EngineConfig added in v0.12.0

type EngineConfig struct {
	Version   string
	ShellMode ShellMode
	// Web is the explicit configuration for opt-in network tools. It is
	// intentionally supplied by the process entry point, which owns env reads.
	Web webfetch.Config
	// UnsafeAllowMutationWithoutPreconditions is an explicit compatibility
	// escape hatch for trusted embedders and tests. Production callers should
	// leave it false so every mutation supplies a current assertion.
	UnsafeAllowMutationWithoutPreconditions bool
}

EngineConfig is the explicit security policy for an Engine.

type ErrWithSuggestion added in v0.6.0

type ErrWithSuggestion struct {
	Err        error
	Suggestion string
	Code       string
}

ErrWithSuggestion wraps an error with a user-facing suggestion and an optional machine-readable error code.

func (*ErrWithSuggestion) Error added in v0.6.0

func (e *ErrWithSuggestion) Error() string

func (*ErrWithSuggestion) Unwrap added in v0.6.0

func (e *ErrWithSuggestion) Unwrap() error

type Memory added in v0.9.2

type Memory struct {
	ID        int64     `json:"id"`
	Scope     string    `json:"scope"`
	ScopeID   string    `json:"scope_id,omitempty"`
	Key       string    `json:"key"`
	Value     string    `json:"value"`
	ValueType string    `json:"value_type"`
	Kind      string    `json:"kind"`
	Pinned    bool      `json:"pinned"`
	ExpiresAt time.Time `json:"expires_at,omitempty"`
	UpdatedAt time.Time `json:"updated_at"`
	CreatedAt time.Time `json:"created_at"`
}

Memory is a memory-table row.

type NextCall added in v0.14.0

type NextCall struct {
	Tool      string         `json:"tool"`
	Arguments map[string]any `json:"arguments"`
}

NextCall is an exact, machine-readable follow-up invocation.

type PlanEdge added in v0.11.0

type PlanEdge struct {
	When Condition `json:"when"`
	To   string    `json:"to"`
}

PlanEdge selects the next plan node when its condition matches.

type PlanNode added in v0.11.0

type PlanNode struct {
	ID       string     `json:"id"`
	Commands []PlanOp   `json:"commands"`
	Parallel bool       `json:"parallel,omitempty"`
	Mutates  bool       `json:"mutates,omitempty"`
	Force    bool       `json:"force,omitempty"` // node-level dangerous-mutation gate, Phase 2 only
	Edges    []PlanEdge `json:"edges,omitempty"`
}

PlanNode is a plan execution step and its outgoing conditional edges.

type PlanNodeResult added in v0.11.0

type PlanNodeResult struct {
	NodeID string         `json:"node_id"`
	Depth  int            `json:"depth"`
	Ops    []PlanOpResult `json:"ops"`
}

PlanNodeResult records one node and its operation outcomes.

type PlanOp added in v0.11.0

type PlanOp struct {
	Shell string         `json:"shell,omitempty"`
	Tool  string         `json:"tool,omitempty"`
	Args  map[string]any `json:"args,omitempty"`
}

PlanOp has exactly one of Shell or Tool set. It mirrors Request{Tool,Args} (schema.go), not a flat {tool,...rest} shape.

type PlanOpResult added in v0.11.0

type PlanOpResult struct {
	OK             bool   `json:"ok"`
	Result         string `json:"result,omitempty"`
	Stdout         string `json:"stdout,omitempty"`
	Stderr         string `json:"stderr,omitempty"`
	Error          string `json:"error,omitempty"`
	Classification string `json:"classification,omitempty"`
	Risk           string `json:"risk,omitempty"`
	ExitCode       int    `json:"exit_code,omitempty"` // shell exit code, or nonzero for failed/blocked tool ops
}

PlanOpResult records the outcome of one command or tool operation.

type PlanRunResult added in v0.11.0

type PlanRunResult struct {
	Transcript     []PlanNodeResult `json:"transcript"`
	PathTaken      []string         `json:"path_taken"`
	DepthReached   int              `json:"depth_reached"`
	StoppedReason  StopReason       `json:"stopped_reason"`
	EdgesEvaluated int              `json:"edges_evaluated"`
	EdgesMatched   int              `json:"edges_matched"`
	// contains filtered or unexported fields
}

PlanRunResult rides in ToolResult.Meta["plan_run"].

type PlanStatsRecord added in v0.11.0

type PlanStatsRecord struct {
	V              int    `json:"v"`
	Ts             string `json:"ts"`
	StoppedReason  string `json:"stopped_reason"`
	DepthReached   int    `json:"depth_reached"`
	Nodes          int    `json:"nodes"`
	Ops            int    `json:"ops"`
	EdgesEvaluated int    `json:"edges_evaluated"`
	EdgesMatched   int    `json:"edges_matched"`
	RequestsSaved  int    `json:"requests_saved"`
}

PlanStatsRecord is a single row in the run_plan stats JSONL log.

type PlanTree added in v0.11.0

type PlanTree struct {
	Root     string     `json:"root"`
	Nodes    []PlanNode `json:"nodes"`
	Cwd      string     `json:"cwd,omitempty"`       // existing directory within the Engine sandbox; empty keeps Engine workDir
	MaxDepth int        `json:"max_depth,omitempty"` // 0 => DefaultMaxDepth at the outermost plan; nested 0 inherits, positive values can only lower the inherited ceiling
	Force    bool       `json:"force,omitempty"`     // plan-level dangerous-mutation gate, Phase 2 only
}

PlanTree is the condition-gated execution graph accepted by run_plan.

type Request

type Request struct {
	Tool      string                 `json:"tool"`
	Args      map[string]interface{} `json:"args"`
	Client    string                 `json:"client,omitempty"`
	Compress  bool                   `json:"compress,omitempty"`
	RequestID string                 `json:"request_id,omitempty"`
}

Request is the one-shot tool invocation envelope.

func DecodeOneRequest added in v0.12.0

func DecodeOneRequest(reader io.Reader, maxBytes int64) (Request, error)

DecodeOneRequest accepts exactly one bounded JSON object and rejects duplicate keys before ordinary struct decoding can collapse them.

func (*Request) UnmarshalJSON added in v0.11.0

func (r *Request) UnmarshalJSON(data []byte) error

UnmarshalJSON strictly decodes the request envelope. Compatibility coercion is intentionally rejected at this trust boundary.

type Response

type Response struct {
	OK             bool           `json:"ok"`
	Result         string         `json:"result,omitempty"`  // legacy text result (backwards compat)
	Content        []ContentBlock `json:"content,omitempty"` // structured content blocks (images, etc.)
	Meta           map[string]any `json:"meta,omitempty"`    // structured metadata (truncation, etc.)
	Error          string         `json:"error,omitempty"`
	Suggestion     string         `json:"suggestion,omitempty"`
	Classification string         `json:"classification,omitempty"` // exit-code class: "success", "expected_nonzero", "error", "timeout", "signal"
	Risk           string         `json:"risk,omitempty"`           // pre-execution risk: "safe", "caution", "dangerous" — only set by run_shell
	ErrorCode      string         `json:"error_code,omitempty"`
	RequestID      string         `json:"request_id,omitempty"`
}

Response is the one-shot tool result envelope.

type RiskLevel added in v0.6.0

type RiskLevel int

RiskLevel describes how dangerous a shell command is to execute.

const (
	// RiskSafe — read-only, no side effects visible outside stdout.
	RiskSafe RiskLevel = iota
	// RiskCaution — modifies state, but generally recoverable.
	RiskCaution
	// RiskDangerous — destructive or irreversible.
	RiskDangerous
)

func ClassifyCommand added in v0.6.0

func ClassifyCommand(cmdline string) (RiskLevel, string)

ClassifyCommand parses cmdline (a bash-style command string) and returns the highest risk level it can detect plus a human reason.

Conservative: unknown verbs default to RiskCaution, not RiskSafe. Pipelines (cmd1 | cmd2) return the MAX risk of any component. Heredocs and subshells are treated as opaque — RiskCaution minimum unless the content contains dangerous verbs.

func (RiskLevel) String added in v0.6.0

func (r RiskLevel) String() string

String returns the lowercase label used in user-visible output.

type RouteCallTemplate added in v0.14.0

type RouteCallTemplate struct {
	Tool      string         `json:"tool"`
	Arguments map[string]any `json:"arguments"`
	Replace   []string       `json:"replace,omitempty"`
}

RouteCallTemplate is the smallest argument skeleton for one recommendation.

type RouteMatch added in v0.10.0

type RouteMatch struct {
	Name        string             `json:"name"`
	Description string             `json:"description"`
	Reason      string             `json:"reason"`
	Mutating    bool               `json:"mutating"`
	Risk        string             `json:"risk"`
	Features    []string           `json:"features,omitempty"`
	Schema      any                `json:"schema,omitempty"`
	Signature   string             `json:"signature,omitempty"`
	Call        *RouteCallTemplate `json:"call,omitempty"`
}

RouteMatch describes one recommended tool.

type RouteRequest added in v0.10.0

type RouteRequest struct {
	Need             string `json:"need"`
	MaxTools         int    `json:"max_tools,omitempty"`
	IncludeSchema    bool   `json:"include_schema,omitempty"`
	IncludeSignature bool   `json:"include_signature,omitempty"`
	IncludeCall      bool   `json:"include_call,omitempty"`
	IncludeMutating  *bool  `json:"include_mutating,omitempty"`
	IncludeNetwork   *bool  `json:"include_network,omitempty"`
}

RouteRequest describes the desired routing result.

func DecodeRouteRequest added in v0.10.0

func DecodeRouteRequest(data []byte) (RouteRequest, error)

DecodeRouteRequest decodes one JSON route request with its default policy.

type RouteResponse added in v0.10.0

type RouteResponse struct {
	RouteID     string       `json:"route_id,omitempty"`
	Query       string       `json:"query"`
	Confidence  string       `json:"confidence"`
	ScoreMargin *int         `json:"score_margin,omitempty"`
	Adaptive    bool         `json:"adaptive"`
	Matches     []RouteMatch `json:"matches"`
	Notes       []string     `json:"notes"`
}

RouteResponse contains the deterministic recommendations for a route request.

func RouteTools added in v0.10.0

func RouteTools(req RouteRequest) (RouteResponse, error)

RouteTools recommends existing jinn tools for a natural-language need. It never dispatches or executes a tool.

func RouteToolsForMode added in v0.12.0

func RouteToolsForMode(req RouteRequest, mode ShellMode) (RouteResponse, error)

RouteToolsForMode applies the engine shell policy to recommendations and embedded schemas using an explicit execution mode.

type ShellMode added in v0.12.0

type ShellMode string

ShellMode controls whether and how commands may execute.

const (
	// ShellModeDisabled forbids shell execution.
	ShellModeDisabled ShellMode = "disabled"
	// ShellModeSandboxed runs shell commands inside the platform sandbox.
	ShellModeSandboxed ShellMode = "sandboxed"
	// ShellModeUnsafe permits direct host shell execution.
	ShellModeUnsafe ShellMode = "unsafe"
)

func ParseShellMode added in v0.12.0

func ParseShellMode(value string) (ShellMode, error)

ParseShellMode validates a shell-mode flag value.

type StopReason added in v0.11.0

type StopReason string

StopReason identifies why a plan execution ended.

const (
	// StopLeaf indicates that the current node had no outgoing edges.
	StopLeaf StopReason = "leaf"
	// StopNoEdgeMatch indicates no outgoing condition matched.
	StopNoEdgeMatch StopReason = "no_edge_match"
	// StopMaxDepth indicates the configured depth limit was reached.
	StopMaxDepth StopReason = "max_depth"
	// StopMutationBlocked indicates a mutation did not pass its safety gate.
	StopMutationBlocked StopReason = "mutation_blocked"
	// StopAborted indicates context cancellation ended the plan.
	StopAborted StopReason = "aborted"
	// StopError indicates an execution or validation failure ended the plan.
	StopError StopReason = "error"
	// StopResourceLimit indicates an operation or transcript budget was exhausted.
	StopResourceLimit StopReason = "resource_limit"
)

type Strategy added in v0.8.4

type Strategy interface {
	// Name returns a unique identifier for this strategy (used in metadata).
	Name() string
	// AppliesTo returns true if this strategy should run on the given output.
	// The tool name is provided so strategies can be tool-specific.
	AppliesTo(output string, tool string) bool
	// Compress applies the strategy to the output and returns the compressed version.
	// Must be deterministic: same input always produces same output.
	// Must be lossless for signal: never drop error messages, test failures, or diff hunks.
	Compress(output string) string
}

Strategy is a compression strategy that can be applied to tool output.

type ToolCapabilities added in v0.8.1

type ToolCapabilities struct {
	JinnVersion string              `json:"jinn_version"`
	Tools       []string            `json:"tools"`
	Features    map[string][]string `json:"features"`
	Schema      any                 `json:"schema,omitempty"`
}

ToolCapabilities describes the features available in this jinn version. Returned by the list_tools tool so callers can adapt behavior to what the current build supports (e.g. dry_run, fuzzy_indent, etc.).

type ToolResult added in v0.6.2

type ToolResult struct {
	Text    string         // human/LLM-readable text result
	Content []ContentBlock // structured content blocks (images, etc.)
	Meta    map[string]any // structured metadata for callers (truncation, etc.)
}

ToolResult is the structured output of a tool handler. Text results populate Text (and Content is nil). Image results populate Content with typed blocks (and Text is empty). Meta carries optional structured metadata (e.g. truncation info for read_file).

type TruncationResult added in v0.6.2

type TruncationResult struct {
	Truncated   bool   `json:"truncated"`
	TruncatedBy string `json:"truncatedBy,omitempty"` // "lines", "bytes", or ""
	TotalLines  int    `json:"totalLines"`
	TotalBytes  int    `json:"totalBytes"`
	OutputLines int    `json:"outputLines"`
	OutputBytes int    `json:"outputBytes"`
	MaxLines    int    `json:"maxLines"`
	MaxBytes    int    `json:"maxBytes"`
}

TruncationResult describes how output was truncated, mirroring pi's truncateHead/truncateTail result structure.

Jump to

Keyboard shortcuts

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