jinn

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: May 30, 2026 License: MIT Imports: 32 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.

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"
)

Error code constants for structured error reporting.

View Source
const (
	DefaultMaxLines = 2000
	DefaultMaxBytes = 50 * 1024 // 50KB
)

Default limits for tool output truncation, matching pi conventions.

Variables

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 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 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 list of tool names declared in Schema. This is the single source of truth — list_tools and other introspection callers derive their tool list from here rather than maintaining a parallel slice that drifts as tools are added or renamed.

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 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 string, 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 (*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]string, 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

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 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.

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 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.

Jump to

Keyboard shortcuts

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