--- layout: default title: "INTHON - Developer Guide & Technical Specifications" description: "A complete step-by-step developer guide and comprehensive language specification to master the INTHON programming language." ---

Official Developer Guide & Specification

Welcome to the complete language reference and learning portal for the INTHON programming language layer.

INTHON (Intelligent + Python) is a domain-specific language layer designed for AI-native workflows. By representing agent execution intent as structured, deterministic code rather than unstructured natural language or verbose JSON/XML, INTHON reduces token footprint, validates schemas statically, and guarantees absolute sandbox safety.

This guide serves as both a step-by-step learning course and a technical manual, detailing language mechanics, compiler behavior, scoping rules, and safety boundaries.

The Learning Path

Follow these modules in sequence to master INTHON:

1. Getting Started & Tooling

Prerequisites, environment setup, CLI reference, and compiling standalone Windows installer binaries.

2. Scoping, Operators & Closures

Variable scoping, typing details, mathematical operators, lexical closures, and implicit return pipelines.

3. Agents, Tools & Policies

Creating agent blocks, configuring goals, static tool validation, and capability policy constraints.

4. PyBridge Sandbox & Security

Module allowlists, custom import hook interception, and secure proxy wrapper mechanics.

5. Advanced Primitives & Resiliency

Human-in-the-loop approval gates, semantic memory stores, and exponential backoff retry math.

Why Learn INTHON?

Traditional agent architectures rely on Large Language Models (LLMs) outputting fragile JSON schemas or raw code blocks to trigger actions. These approaches lead to:

  1. Token Bloat: Verbose JSON syntax consumes excessive tokens, increasing prompt costs.
  2. Side-Effect Risks: Running raw python/shell code exposes the host filesystem and network to compromises.
  3. Audit Hardness: Non-deterministic agent loops cannot be easily replayed or restricted.

INTHON solves these issues by introducing an optimized domain grammar, capability sandboxing, and deterministic JSON trace logging.

Part 1: Getting Started & Tooling

Set up your local environment, run your first program, and explore CLI compiler commands.

1. Prerequisites

Ensure your local host has Python version 3.11 or higher and the `pip` package manager installed. Verify your environment:

python --version

2. Setup & Installation

Clone the INTHON repository and install it in editable/developer mode to make the CLI available system-wide:

# Clone the repository
git clone https://github.com/harvatechs/inthon.git
cd inthon

# Set up virtual environment
python -m venv .venv
# On Windows:
.venv\Scripts\activate
# On Unix/macOS:
source .venv/bin/activate

# Install with development dependencies
pip install -e .[dev,data,ml]

Verify that the command line tool is registered on the system PATH:

inthon --help

3. Your First Program: hello.inth

Create a file named hello.inth in your text editor:

// hello.inth
// INTHON supports single-line comments using double-slashes

fn greet(name: str) -> str {
    return "Hello, " + name + "!"
}

let message = greet("INTHON Developer")
message

4. Executing code

Use the CLI to run the program via the AST-walking interpreter:

inthon run hello.inth

Output:

Hello, INTHON Developer!

5. CLI Tooling Reference

Command Usage Description
run inthon run <file.inth> Executes the file in the sandboxed runtime. Supports cost caps and trace exports.
check inthon check <file.inth> Lints and statically verifies type safety and tool references without executing.
fmt inthon fmt <file.inth> --write Formats spacing, brackets, and newlines. --write updates the file.
ast inthon ast <file.inth> Prints the parsed Abstract Syntax Tree output as a structured JSON object.
ir inthon ir <file.inth> Prints the lowered Intermediate Representation tree serialized as JSON.

Specifying Execution Budgets

You can override default interpreter cost limits directly from the CLI:

inthon run hello.inth --max-cost 0.50 --trace-out trace_log.json

Part 2: Scoping, Operators & Closures

Deep-dive into INTHON scoping rules, data types, operators precedence, and call frame stacks.

1. Block Scoping (let and const)

INTHON implements strict block scoping. Variables declared within a block {} are invisible outside of it.

Variable Scope Lifespans

  • Mutable Scope (let): Can be declared with or without type annotations. Value bindings can be changed.
  • Immutable Scope (const): Must be bound at declaration time. Value bindings are read-only; attempts to assign a new value to a constant trigger compile-time checking failures.
let x = 10
const y: float = 3.14

if x > 5 {
    let z = "inner scope"
    x = x + 1 // OK: reassigning let variable
    // y = 2.71 // ERROR: Cannot reassign const variable 'y'
}
// z // ERROR: Variable 'z' is undefined in this scope

2. Complete Operators Reference

INTHON v0.1 evaluates operators using left-to-right precedence. Brackets are recommended to enforce specific mathematical precedence.

Mathematical Operators

  • + (Addition / String Concatenation): Adds numbers or merges text.
  • - (Subtraction): Subtracts numbers.
  • * (Multiplication): Multiplies numbers.
  • / (Division): Divides floats.

Comparison & Logical Operators

  • == (Equality), != (Inequality).
  • <, >, <=, >=: Relational comparisons.
  • && (Logical AND), || (Logical OR), ! (Logical NOT).

3. Collections & Custom Types

INTHON lists and dicts are dynamic and strictly checked. Typing annotations are declared using brackets: list[T] and dict[K, V].

let items: list[str] = ["gpt-4o", "gemini-3.5"]
let data: dict[str, float] = {"latency": 45.2, "cost": 0.001}

Use standard index notation to query and modify values:

let first_item = items[0]
data["cost"] = 0.002

4. Functions & Closures

Functions are declared with fn, parameter names, type signatures, and an optional return type.

Activation Call Frames

When a function is called, the VM spawns a new frame containing the parameters. Variables in the outer lexical scope remain accessible to nested helper functions, forming closures.

Implicit Return Pipeline

If the last statement in a function body is an expression (not terminated by a semicolon or keyword), the VM automatically pops it from the evaluation stack and returns it as the function's output.

fn multiplier(factor: int) -> fn(int) -> int {
    fn inner(x: int) -> int {
        x * factor // Implicit return of evaluation
    }
    return inner
}

let double = multiplier(2)
let result = double(10) // Returns 20

Part 3: Agents, Tools & Policies

Learn how to declare structured agent containers, import capabilities, and apply sandbox constraints.

1. Structured Agent Container

The agent block maps an execution lifecycle. It encapsulates a goals directive, boundary interfaces, sandboxing policies, and the tool workflow code.

SVG Diagram: Policy Guard Enforcement

Agent Execution Plan Instructions Policy Guard Validate Cost & Quotas Protected OS / Host Approved Action

2. Declaring and Importing Tools

Tools are external service bindings registered on the host machine. To invoke them, you must import them at the file header using use tool:

use tool web.search
use tool file.write

This imports the structural parameter schema of the tool. The semantic analyzer uses these schemas to verify argument counts, types, and names prior to compilation, ensuring the LLM cannot emit malformed API structures.

3. Complete Policy Reference

The policy block contains the execution boundaries. If code attempts to cross these limits, the runtime raises a PolicyViolationError.

Key Type Default Description
allow_network bool false Controls outbound API calls from tool and PyBridge calls.
max_tool_calls int 0 Integer cap on total tool calls allowed per session.
max_cost_usd float 0.00 Financial cap on cumulative LLM token cost.
allow_memory_persist bool false Controls SQLite episodic database inserts.
allow_fs bool false Controls local disk read and write privileges.

Agent Implementation Example

use tool web.search

agent Researcher {
    goal "Find room-temperature superconductor papers on arxiv"
    inputs {
        count: int
    }
    outputs {
        papers: list[dict]
    }
    policy {
        allow_network: true
        max_tool_calls: 3
        max_cost_usd: 0.05
    }
    plan {
        let results = web.search("superconductor", limit: count)
        return results
    }
}

Part 4: PyBridge Sandbox & Security

Import standard Python libraries safely. Leverage NumPy and Pandas under strict capability validation checks.

1. The Import Hook Filter (sys.meta_path)

To enforce absolute sandbox safety, PyBridge intercepts module requests before loading them onto the Python process. It injects a custom meta-importer hook inside sys.meta_path. When the script parses use py.numpy, the hook performs strict name validations.

SVG Diagram: PyBridge Sandbox Interception Flow

use py.subprocess Malicious Request sys.meta_path Hook Blocked: NOT Allowed PyBridgeError InthonPyObject Proxy Safe Attribute Wrapper use py.numpy (Allowed)

2. Permitted vs Blocked Packages

Pre-approved libraries contain no filesystem writes or system access wrappers:

  • Approved: numpy, pandas, math, json, datetime, collections.
  • Blocked: os, sys, subprocess, ctypes, socket, shutil.

If you need to permit a new library, add it to the allowlist in inthon/pybridge/allowlist.py.

3. Attribute Level Protection (InthonPyObject)

Even if a module is allowed, standard library functions can sometimes be exploited. PyBridge wraps all returned packages inside a proxy object called InthonPyObject.

This proxy class overrides the Python attribute resolution dunder methods (__getattribute__, __setattr__). If code attempts to access private properties (e.g. np.__dict__) or traverse namespaces to access system commands (e.g. np.__config__.__builtins__['eval']), the proxy raises a SecurityViolation exception and terminates execution.

Part 5: Advanced Primitives & Resiliency

Master human verification gateways, relational memory storage, and automatic retry algorithms.

1. Human-in-the-Loop Approval Gates (approve)

For critical side-effects, INTHON enforces human intervention. The compiler registers the target action and suspends the thread execution, emitting a structured request event:

approve subscription_charge before stripe.charge(amount: 49.00)

SVG Diagram: HITL Execution Suspend Flow

Execute Plan Interpreter Thread Halt & Emit Hook Approval Prompted Approved: Resume Exec Denied: Abort Transaction

2. Episodic Memory Primitives (SQLite Backed)

Semantic variables can be persisted across sessions using the remember and recall primitives:

remember "Superconductors display zero electrical resistance" in session
let val = recall "electrical resistance" from session

Storage Architecture

Under the hood, memory spaces are backed by a local SQLite relational store. The database computes embeddings of the textual statement using cosine similarity metric indexes to fetch the most semantically relevant fact matches on demand.

3. Resilient Retries & Backoff Mathematics

External APIs often fail due to network instability. INTHON includes structured retry loops with automatic backoff options:

retry 3 with backoff exponential {
    let raw = web.search("AI")
    guard raw.status == 200
} catch err {
    return "Failed: " + err.message
}

Exponential Backoff Formula

The time interval (in seconds) between retry attempts is computed by the interpreter using the following formula:

\(t_{\text{backoff}} = \text{base} \times 2^{\text{attempt}} \pm \text{jitter}\)

Where base defaults to 1.0 second, attempt represents the zero-indexed retry number, and jitter is a random offset variable to prevent request synchronization bottlenecks on the host server.