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
- Variables
- func CompactSchema() (string, error)
- func ExplainRisk(r RiskLevel, reason string) string
- func LeanSchema() (string, error)
- func ResolveVersion(ldVersion string) string
- func SchemaToolNames() ([]string, error)
- type Classification
- type CompressionMeta
- type Compressor
- type Condition
- type ContentBlock
- type DiffResult
- type Engine
- type ErrWithSuggestion
- type Memory
- type PlanEdge
- type PlanNode
- type PlanNodeResult
- type PlanOp
- type PlanOpResult
- type PlanRunResult
- type PlanStatsRecord
- type PlanTree
- type Request
- type Response
- type RiskLevel
- type RouteMatch
- type RouteRequest
- type RouteResponse
- type StopReason
- type Strategy
- type ToolCapabilities
- type ToolResult
- type TruncationResult
Constants ¶
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" 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" )
Error code constants for structured error reporting.
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.
const ( RouteDefaultMaxTools = 5 RouteMaxTools = 8 )
const DefaultMaxDepth = 8
DefaultMaxDepth mirrors predexec's DEFAULT_MAX_DEPTH.
Variables ¶
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.
var Schema string
Schema is the tool definitions in OpenAI function-calling format.
Functions ¶
func CompactSchema ¶ added in v0.8.10
CompactSchema returns Schema without insignificant JSON whitespace.
func ExplainRisk ¶ added in v0.6.0
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
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 ResolveVersion ¶
ResolveVersion returns a human-readable version string, preferring ldflags-injected version, then VCS revision, then module version.
func SchemaToolNames ¶ added in v0.8.14
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: flattened union on Kind (not oneOf/const-union — avoids JSON-schema provider-compat issues when embedded in schema.json).
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 ¶
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 (*Engine) Close ¶ added in v0.9.0
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.
type ErrWithSuggestion ¶ added in v0.6.0
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 PlanNodeResult ¶ added in v0.11.0
type PlanNodeResult struct {
NodeID string `json:"node_id"`
Depth int `json:"depth"`
Ops []PlanOpResult `json:"ops"`
}
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: exactly one of Shell / Tool is set. Mirrors Request{Tool,Args} (schema.go), not a flat {tool,...rest} shape.
type PlanOpResult ¶ added in v0.11.0
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"`
}
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 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 (*Request) UnmarshalJSON ¶ added in v0.11.0
UnmarshalJSON implements json.Unmarshaler for Request, repairing the common LLM misbehavior of double-encoding args as a JSON string.
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.
func ClassifyCommand ¶ added in v0.6.0
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.
type RouteMatch ¶ added in v0.10.0
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"`
IncludeMutating *bool `json:"include_mutating,omitempty"`
}
func DecodeRouteRequest ¶ added in v0.10.0
func DecodeRouteRequest(data []byte) (RouteRequest, error)
type RouteResponse ¶ added in v0.10.0
type RouteResponse struct {
Query string `json:"query"`
Matches []RouteMatch `json:"matches"`
Notes []string `json:"notes"`
}
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.
type StopReason ¶ added in v0.11.0
type StopReason string
const ( StopLeaf StopReason = "leaf" StopNoEdgeMatch StopReason = "no_edge_match" StopMaxDepth StopReason = "max_depth" StopMutationBlocked StopReason = "mutation_blocked" StopAborted StopReason = "aborted" StopError StopReason = "error" )
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"`
}
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.
Source Files
¶
- blob_codec.go
- command_risk.go
- command_risk_parse.go
- compress.go
- compress_buildoutput.go
- compress_gitlog.go
- compress_gitstatus.go
- compress_shell.go
- compress_testplain.go
- compress_testresult.go
- db.go
- detect.go
- diff.go
- diff_edit_fast.go
- edit_apply.go
- engine.go
- errors.go
- exitcode.go
- filelock.go
- history.go
- idempotency_store.go
- lsp_actions.go
- lsp_client.go
- lsp_go_symbols.go
- lsp_helpers.go
- lsp_protocol.go
- lsp_render.go
- memory_helpers.go
- memory_schema.go
- memory_scope.go
- memory_sqlite.go
- multi_edit_apply.go
- multi_edit_overlap.go
- mutating_registry.go
- normalize.go
- output.go
- output_transform.go
- partial_apply.go
- patch.go
- patch_apply.go
- plan_coerce.go
- plan_engine.go
- plan_types.go
- read_window.go
- router.go
- schema.go
- schema_compact.go
- search_parse.go
- search_replace_apply.go
- search_replace_collect.go
- search_run.go
- security.go
- shell_capture.go
- spill_registry.go
- stats.go
- tool_detect.go
- tool_diff.go
- tool_edit.go
- tool_find.go
- tool_list.go
- tool_lsp.go
- tool_lsp_go_diagnostics.go
- tool_memory.go
- tool_multi_edit.go
- tool_multi_read.go
- tool_patch.go
- tool_read.go
- tool_read_file.go
- tool_read_trunc.go
- tool_registry.go
- tool_run_plan.go
- tool_search.go
- tool_search_replace.go
- tool_shell.go
- tool_stat.go
- tool_undo.go
- tool_write.go
- tracker.go
- truncate_smart.go