jinn

package
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 27 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 provides state-token helpers for optimistic concurrency control over file edits.

Adapted from: https://github.com/frane/agented@9f88dae/internal/store/types.go What changed: extracted ComputeStateToken + HashContent as standalone functions;

replaced agented-specific format string with jinn-specific namespace;
removed all SQLite/edit-tree domain types.

Date: 2026-04-29

The pattern: every state of a file gets a deterministic fingerprint. Reads return it. Writes accept an optional "expect" token. If the file changed between read and write (by another process, another agent, or a concurrent tool call), the token won't match and the write rejects with the current content attached. One round trip on conflict, no "re-read before every write" ritual, no defensive re-reads.

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

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.

View Source
const Schema = `` /* 17371-byte string literal not displayed */

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

View Source
const StateTokenLen = 16

StateTokenLen is the number of hex characters in a state token.

Variables

This section is empty.

Functions

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 HashContent added in v0.7.0

func HashContent(content string) string

HashContent returns the hex SHA-256 of the given content. This is the building block for state tokens — a content hash that deterministically identifies a file's current state.

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 StateToken added in v0.7.0

func StateToken(absPath string, mtimeNs int64, contentHash string) string

StateToken computes a deterministic state token for a file. The token encodes (path, mtime_ns, content_hash) so that:

  • Same content + same mtime = same token (idempotent reads)
  • Content change = different token (detect concurrent edits)
  • Path change = different token (files are distinct)

Returns the first StateTokenLen hex characters of SHA-256.

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