npm package: @intend-it/core
Description: Core compiler and AI integration for the Intend programming language
Latest version: 4.0.4

<div align="center">
  <h1>@intend-it/core</h1>
  <p><strong>AI-Powered Code Generator for the Intend Language</strong></p>
  <p>
    <a href="https://intend.fly.dev">Documentation</a> •
    <a href="https://www.npmjs.com/package/@intend-it/core"><img src="https://img.shields.io/npm/v/@intend-it/core.svg" alt="npm version"></a>
    <a href="https://www.npmjs.com/package/@intend-it/core"><img src="https://img.shields.io/npm/dm/@intend-it/core.svg" alt="npm downloads"></a>
    <a href="https://github.com/DRFR0ST/intend/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@intend-it/core.svg" alt="license"></a>
  </p>
</div>

---

## Overview

`@intend-it/core` is the heart of the Intend compiler. It takes parsed AST from `@intend-it/parser` and generates production-ready TypeScript code using AI (Google Gemini or Ollama).

**[Read the full documentation 📖](https://intend.fly.dev)**

### ✨ Key Features

- **🧠 AI Code Generation** - Transforms natural language steps into actual code
- **🌐 Global Context** - Define file-level rules using the `context` keyword
- **🔀 Hybrid Orchestration** - Mix AI steps with deterministic function calls
- **🔄 Self-Correction Loop** - Validates output and auto-fixes errors
- **⚡ Smart Caching (CAS)** - Content-addressable storage for instant rebuilds
- **🔌 Multi-Provider** - Supports Gemini and Ollama (local)
- **🛡️ Type-Safe Output** - Generates valid, compilable TypeScript

## Installation

```bash
npm install @intend-it/core @intend-it/parser
# or
bun add @intend-it/core @intend-it/parser
```

## Usage

### Basic Code Generation

```typescript
import { AICodeGenerator } from "@intend-it/core";
import { parseToAST } from "@intend-it/parser";

const source = `
export intent Add(a: number, b: number) -> number {
    step "Add the two numbers together" => const result
    ensure result is a number
}
`;

const { ast } = parseToAST(source);

const generator = new AICodeGenerator({
  provider: "gemini",
  geminiConfig: {
    apiKey: process.env.GEMINI_API_KEY!,
    model: "gemini-2.0-flash"
  }
});

const result = await generator.generate(ast);
console.log(result.code);
// export function Add(a: number, b: number): number {
//   const result = a + b;
//   if (typeof result !== 'number') throw new Error(...);
//   return result;
// }
```

### Using Ollama (Local AI)

```typescript
const generator = new AICodeGenerator({
  provider: "ollama",
  ollamaConfig: {
    model: "llama3",
    baseUrl: "http://localhost:11434",
    num_thread: 4 // Optional: limit CPU usage
  }
});
```

### Template Generation (No AI)

```typescript
import { generateTypeScript } from "@intend-it/core";

const result = generateTypeScript(ast);
// Generates template with // TODO comments
```

## Configuration Options

```typescript
interface AIGeneratorOptions {
  provider: "gemini" | "ollama";
  
  geminiConfig?: {
    apiKey: string;
    model?: string;        // Default: "gemini-2.0-flash"
    temperature?: number;  // Default: 0.2
  };
  
  ollamaConfig?: {
    model?: string;        // Default: "llama3"
    baseUrl?: string;      // Default: "http://localhost:11434"
    temperature?: number;
    num_thread?: number;   // CPU thread limit
  };
  
  maxAttempts?: number;    // Auto-correction retries (default: 5)
}
```

## 🔒 Build Determinism & Lockfiles

The core package includes a `LockfileManager` that ensures generated code is deterministic and reusable.

```typescript
import { LockfileManager, computeHash } from "@intend-it/core";

const lockManager = new LockfileManager("./intend.lock");

// Calculate hashes
const sourceHash = computeHash(intentSource);
const configHash = computeHash(JSON.stringify(config));

// Try to get from lockfile
const cachedCode = lockManager.getEntry(relativePath, sourceHash, configHash);

if (cachedCode) {
  return cachedCode; // Instant build!
}

// Generate new code and save to lockfile
const result = await generator.generate(ast);
lockManager.setEntry(relativePath, sourceHash, configHash, result.code, {
  model: "gemini-2.0-flash",
  provider: "gemini"
});
lockManager.save();
```

### Why a Lockfile?
- **Determinism**: Prevents minor AI fluctuations from changing your production code.
- **Performance**: Skips expensive LLM calls for unchanged intentions.
- **Auditability**: Changes to generated code appear in your git diffs, making it easy to review what the AI has changed.

## Architecture

```
┌─────────────────┐     ┌──────────────┐     ┌─────────────────┐
│  .intent file   │ ──▶ │    Parser    │ ──▶ │       AST       │
└─────────────────┘     └──────────────┘     └────────┬────────┘
                                                      │
                        ┌──────────────┐              ▼
                        │   AI Provider │ ◀── ┌─────────────────┐
                        │ (Gemini/Ollama)│    │  Prompt Builder │
                        └───────┬───────┘    └─────────────────┘
                                │
                                ▼
                        ┌──────────────┐     ┌─────────────────┐
                        │  Validator   │ ──▶ │  TypeScript.ts  │
                        │ (auto-retry) │     └─────────────────┘
                        └──────────────┘
```

## Related Packages

- [`@intend-it/parser`](https://www.npmjs.com/package/@intend-it/parser) - Lexer and parser
- [`@intend-it/cli`](https://www.npmjs.com/package/@intend-it/cli) - Command-line interface

## License

MIT © [Intend Team](https://github.com/DRFR0ST/intend)