# Kyronix Documentation

> Official documentation for the Kyronix Agentic Runtime Platform.
> Website: https://kyronix.harshitnakrani.me
> Dashboard: https://kyronix.harshitnakrani.me/dashboard

---

## Table of Contents

1. [What is Kyronix?](#what-is-kyronix)
2. [Getting Started](#getting-started)
3. [Core Concepts](#core-concepts)
4. [Built-in Agents](#built-in-agents)
5. [Custom Agents Guide](#custom-agents-guide)
6. [Runtime SDK](#runtime-sdk)
7. [Executor SDK](#executor-sdk)
8. [API & KML Reference](#api-kml-reference)

---

# What is Kyronix?

Kyronix is a **serverless agentic runtime platform** that bridges the gap between your application and Large Language Models. It provides a complete, scalable infrastructure for building, orchestrating, and executing AI agents seamlessly across your stack.

## The Problem It Solves

Building agentic infrastructure from scratch is complex and time-consuming. Developers often find themselves wrestling with:

- Tool orchestration and schema validation
- State and memory management
- Multi-step planning algorithms
- Custom agent definition and tool schema generation
- Managing execution sandboxes and permissions
- Streaming partial tool execution states back to the client

**Kyronix solves this.** We believe developers should focus on building great products, not boilerplate AI infrastructure. Kyronix handles the heavy lifting of planning, tools, context compilation, memory, streaming, and state management out of the box.

## How It Works

The Kyronix architecture is split into a cloud-based intelligence layer and a local execution layer. This ensures that sensitive operations (like filesystem access or local terminal execution) run safely on your own client, while the complex planning and context management happens on Kyronix Cloud.

```mermaid
graph LR
    subgraph ClientAppGroup["Client App"]
      UI["User Interface"] --> Frontend
      Frontend --> Executer["Kyronix Executer SDK"]
      Executer --> Tools[("Local & Custom Tools")]
    end

    subgraph BackendServerGroup["Backend Server"]
      Server["Your Backend"]
      Runtime["Kyronix Runtime SDK"]
      Server --> Runtime
    end

    subgraph KyronixPlatformGroup["Kyronix Platform"]
      Cloud["Kyronix Cloud API"]
      Planner["AI Planner & Memory"]
      CustomAgents["Custom Agent Registry"]
    end

    Frontend -->|"Prompt"| Server
    Runtime -->|"API Request"| Cloud
    Cloud -->|"Fetch Schema"| CustomAgents
    Cloud -->|"Context Compilation"| Planner
    Planner -->|"KML Response"| Cloud
    Cloud -->|"Streams KML"| Runtime
    Runtime -->|"Forwards KML"| Frontend
    Frontend -->|"Feeds KML"| Executer
```

1. **Your App** sends a user prompt to your **Backend**.
2. The Backend uses the `@kyronixai/runtime` SDK to communicate with **Kyronix Cloud** (invoking built-in agents like `coding` or custom agents created in your dashboard via `runCustomAgent`).
3. Kyronix compiles context, loads custom tool definitions, plans the execution, and returns a **KML (Kyronix Markup Language)** response.
4. Your Backend forwards the KML to the **Frontend/Client**.
5. The Client uses the `@kyronixai/executer` SDK to parse the KML and securely execute tools (filesystem, terminal, git, HTTP, browser, or custom tool handlers) locally.

## Key Capabilities

- **Custom Agents**: Define custom AI agents in the Kyronix Dashboard with specialized tool names, descriptions, and dynamic parameter lists.
- **Intelligent Planning**: Advanced multi-step reasoning capabilities designed to handle complex coding and research tasks.
- **Context Compilation**: Automatic injection of relevant system context, project structure, and file contents.
- **Memory Management**: Built-in conversational memory and session persistence.
- **Tool Orchestration**: A rich suite of pre-built tools (filesystem, terminal, git, browser, HTTP) plus custom tool execution.
- **Streaming**: Native support for streaming thoughts, plans, and tool execution states in real-time.
- **State Management**: Robust state tracking for multi-agent workflows.

## Supported Agent Types

Kyronix provides specialized agent instances optimized for specific domains:

- `coding` - Software engineering, debugging, and architecture
- `research` - Deep dive web research and synthesis
- `database` - SQL generation and database querying
- `sales` - Lead qualification and outreach
- **Custom Agents** - User-defined domain personas created in the Kyronix Dashboard with custom parameters

## Pricing & Free Tier

Start building immediately. We offer a generous free tier for all developers:
**Get 100 free credits upon signup** by authenticating via GitHub. 

> Ready to build? Head over to the [Getting Started](/docs/getting-started) guide.

---

# Getting Started 🚀

This guide will walk you through setting up a complete Kyronix integration, from acquiring your API keys to running your first agent execution over the recommended **WebSocket Tunnel** flow.

---

## 1. Authentication

Kyronix uses GitHub OAuth for seamless developer onboarding:

1. Navigate to the Kyronix Platform at [https://kyronix.harshitnakrani.me/api/auth](https://kyronix.harshitnakrani.me/api/auth)
2. Sign in using your GitHub account.
3. Upon successful login, you'll be redirected to your developer dashboard.

---

## 2. API Keys, Projects & Custom Agents

Once in the [Dashboard](/dashboard):
1. Create a new **Project** (or select an existing one).
2. Navigate to **Project Settings** to generate an **API Key** (`kyr_...`). Keep this secure for your backend server.
3. Navigate to **My Agents** to optionally create **Custom Agents** with dynamic tool parameter schemas. Copy the generated **Agent ID**.

---

## 3. Backend & WebSocket Tunnel Setup (`@kyronixai/runtime`)

Your application backend initializes `@kyronixai/runtime` with a WebSocket connection (`ws`) to dispatch KML plans directly over the recommended bi-directional tunnel (`executeKmlOverWs`).

First, install the required dependencies:

```bash
pnpm add @kyronixai/runtime ws dotenv
pnpm add -D @types/ws @types/node
```

Create a `.env` file in your project root:

```env
KYRONIX_API_KEY=kyr_your_api_key_here
KYRONIX_PROJECT_ID=your_project_id_here
```

Create your server implementation (`server.ts`):

```typescript
// server.ts
import express from 'express';
import { Kyronix } from '@kyronixai/runtime';
import WebSocket from 'ws';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
app.use(express.json());

// 1. Establish WebSocket client connection
const ws = new WebSocket('ws://localhost:8080/ws');

// 2. Initialize Kyronix Runtime Client with WebSocket instance
const kyronix = new Kyronix({
  apiKey: process.env.KYRONIX_API_KEY!,
  projectId: process.env.KYRONIX_PROJECT_ID!,
  ws
});

// Endpoint to execute agent instructions over WebSocket tunnel
app.post('/api/run', async (req, res) => {
  const { prompt, agent = 'coding' } = req.body;
  
  try {
    console.log('1. Dispatching prompt to Kyronix Cloud...');
    const runResponse = await kyronix.run({
      agent,
      input: prompt,
    });   

    console.log('2. Dispatching KML plan over WebSocket tunnel...');
    // Execute KML payload directly over WebSocket tunnel to connected local executer
    const executionResults = await kyronix.executeKmlOverWs(runResponse.response);

    res.json({
      success: true,
      executionResults,
      creditsRemaining: runResponse.creditsRemaining
    });
  } catch (error: any) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => console.log('Kyronix Backend running on port 3000'));
```

---

## 4. Client Setup (`@kyronixai/executer`)

The client SDK (`@kyronixai/executer`) runs on the user's machine or container sandbox. Instantiating with `wsUrl` connects it to the WebSocket relay server to execute KML requests automatically.

Install the executer SDK:

```bash
pnpm add @kyronixai/executer
```

Create your client daemon implementation (`client.ts`):

```typescript
// client.ts
import { KyronixExecuter } from '@kyronixai/executer';

// 1. Instantiating with wsUrl automatically connects to WebSocket relay and registers listeners
const executor = new KyronixExecuter({
  wsUrl: 'ws://localhost:8080/ws'
});

console.log('Local executor connected and listening for remote KML requests over WebSocket...');

// 2. Function to trigger backend run request
async function triggerAgentRun() {
  const prompt = "Create a React component called Button in src/components/Button.tsx";

  console.log('Sending run request to backend...');
  const res = await fetch('http://localhost:3000/api/run', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ prompt })
  });

  const data = await res.json();
  console.log('Agent execution complete:', data);
}

// Trigger run
triggerAgentRun().catch(console.error);
```

---

## 5. Run the Recommended Example

1. Start your local executor daemon: `npx ts-node client.ts`
2. Start your backend server: `npx ts-node server.ts`

You've successfully integrated Kyronix! The agent receives your prompt, generates KML plans in the cloud, streams the plan over WebSockets, and your local executor executes the tools directly on your filesystem.

---

# Core Concepts

Understanding the core concepts of the Kyronix architecture is crucial for building robust, agent-driven applications.

## Sessions

A **Session** represents a persistent conversation and execution context. When interacting with an agent, you rarely want a single one-off request; you usually build upon previous interactions.

Sessions are created using `createSession()`. Each session contains:
- A unique Session ID.
- The designated agent type (e.g., `coding`, `research`).
- An immutable chat history.

For follow-up interactions within the same context, you can use the `session.send()` method (or pass the `sessionId` to `kyronix.run()`), ensuring the agent remembers prior steps and context.

## Agents & Custom Agents

**Agents** are specialized runtime instances tuned for specific domains. Instead of providing a generic prompt, Kyronix provides pre-configured agents that come with optimal planning strategies, system prompts, and tool sets.

For instance, a `coding` agent has access to terminal, filesystem, and AST analysis tools, while a `research` agent is optimized for web research and summarization.

### Custom Agents 🤖

In addition to built-in agents, Kyronix allows you to create **Custom Agents** directly from your Developer Dashboard:
- **Custom Tool Schemas**: Define domain tools with specific names, descriptions, and dynamic parameter names.
- **Agent ID Hash**: Each custom agent is assigned a unique hashed ID (`8b5b6ad5...`) for SDK execution via `kyronix.runCustomAgent({ agentId })`.
- **Automatic Schema Injection**: Kyronix Cloud automatically injects your tool definitions into the LLM system prompt and validates returned KML tool calls.

## KML (Kyronix Markup Language)

**KML** is the proprietary XML format that Kyronix LLMs use to communicate intentions, plans, and tool calls. Using XML ensures strict schema adherence and robust parsing on the client side.

A typical KML response looks like this:

```xml
<kyronix>
  <plan>
    I need to create the utility functions file as requested by the user.
  </plan>
  <tool name="write_file">
    <path>src/utils/math.ts</path>
    <content>
      export const add = (a: number, b: number) => a + b;
    </content>
  </tool>
  <summary>Created the math.ts utility file successfully.</summary>
  <status>complete</status>
</kyronix>
```

## Tool Execution Pipeline

When the `@kyronixai/executer` SDK receives a KML payload, it processes it through a strict, multi-stage pipeline before any local action is taken.

```mermaid
graph TD;
    A[KML Payload] --> B[KML Parser]
    B --> C[Abstract Syntax Tree - AST]
    C --> D[Dispatcher]
    D --> E{Permission Check}
    E -- Approved --> F[Tool Handler]
    E -- Denied --> G[Throw SecurityError]
    F --> H[Result]
```

1. **Parser**: The raw XML is parsed securely.
2. **AST**: Converted into an Abstract Syntax Tree representing the intended execution graph.
3. **Dispatcher**: Routes the specific tool call to the correct execution module.
4. **Permission Check**: Verifies if the requested action is allowed under the current sandbox policy.
5. **Tool Handler**: Executes the actual code (e.g., writing to the disk).

## Permissions & Sandbox

Security is paramount when running agentic code on local machines. The Kyronix Executer enforces strict security models:

- **`ROOT_POLICIES`**: Grants the agent full access to the underlying system (use with extreme caution).
- **`SAFE_POLICIES`**: Grants read-only access or restricts modifications to specific directories.

The built-in sandbox actively prevents malicious operations. For instance, `Sandbox.isPathSafe()` ensures that path traversal attacks (like writing to `../../../../etc/passwd`) are blocked automatically before reaching the Tool Handler.

## Execution Models: WebSocket vs HTTP (Recommended: WebSocket 🚀)

Kyronix supports two primary models for connecting the cloud-hosted runtime with local executors: **HTTP Execution** (pull model) and **WebSocket Tunneling** (push model). 

While both have their place, **we highly encourage using the WebSocket model** for most production and local agent loops.

### Comparison Matrix

| Feature | WebSocket Model (Recommended 🚀) | HTTP Model (Legacy/Stateless 🔌) |
| :--- | :--- | :--- |
| **Connection Type** | Long-lived, Bidirectional | Stateless, Unidirectional HTTP |
| **Real-time Status** | Immediate streaming of logs and steps | Periodic polling or manual triggers |
| **Firewall Traversal** | **Seamless** (local executer dials outbound to server) | **Challenging** (requires public ports or ngrok) |
| **Latency** | Extremely low (less than 10ms transmission) | Higher overhead per action request |
| **Best For** | Desktop Apps, Dev sandboxes, Interactive tools | Serverless API routes, Cron jobs, Batch scripts |

---

### Why WebSockets Are Highly Encouraged

1. **Firewall & NAT Traversal (No Port Forwarding Required)**:
   In modern developer environments, local machines are hidden behind NATs and strict corporate firewalls. Setting up HTTP listeners locally requires opening ports, port-forwarding, or setting up complex tunnels like Ngrok.
   With WebSockets, the `@kyronixai/executer` SDK establishes an **outbound** persistent TCP connection to the Kyronix server. Since it is outbound, it passes through firewalls and NATs effortlessly, allowing the Kyronix cloud agent to push execution plans to your local machine safely.

2. **Sub-Millisecond Bidirectional Latency**:
   Stateless HTTP connections incur SSL handshake and network routing overhead on every request. WebSockets establish the handshake once, allowing KML action plans and local tool results to exchange instantly, significantly boosting multi-step agent speed.

3. **Interactive & Streaming Logs**:
   WebSocket channels enable the agent to stream terminal command output and filesystem updates back to the browser console live as they occur, providing a responsive and alive user experience.

## Credits & Usage Pricing 💳

Kyronix uses a **token-based credit billing model** (`Kyronix Charge = Groq Cost × Agent Multiplier`).

Instead of charging arbitrary fixed prices per invocation, credits directly reflect the AI compute consumed:

- **Formula**: `Kyronix Charge = LLM Provider Cost × Agent Multiplier (1.5x standard)`
- **Token Rates**: Derived from exact prompt/completion token usage returned by the model.
- **1 Credit ≈ ₹1 INR** usage balance.

You can monitor detailed token breakdowns and credit deductions per execution in your Kyronix Dashboard.

---

# Agents Reference 🤖

Kyronix provides both pre-configured domain agents and user-defined custom agents.

---

## 1. Coding Agent (`coding`)

The **Coding Agent** is optimized for software development, code refactoring, bug fixes, terminal command execution, and file manipulation.

- **Capabilities**: Shell execution, read/write files, line edits, directory navigation, git operations.
- **Price per execution**: 0.5 Credits
- **SDK Usage**:
  ```typescript
  const response = await kyronix.run({
    agent: 'coding',
    input: 'Create an Express.js API with TypeScript'
  });
  ```

---

## 2. Research Agent (`research`)

The **Research Agent** is specialized in web research, article summarization, documentation inspection, and browser automation.

- **Capabilities**: Browser navigation, clicking, typing, screenshots, HTTP requests.
- **Price per execution**: 0.5 Credits
- **SDK Usage**:
  ```typescript
  const response = await kyronix.run({
    agent: 'research',
    input: 'Summarize latest developments in WebAssembly'
  });
  ```

---

## 3. Database Agent (`database`)

The **Database Agent** specializes in SQL query generation, schema inspection, query optimization, and data migrations.

- **Capabilities**: SQL generation, schema parsing, read/write database queries.
- **Price per execution**: 0.5 Credits
- **SDK Usage**:
  ```typescript
  const response = await kyronix.run({
    agent: 'database',
    input: 'Write a Postgres migration script for users table'
  });
  ```

---

## 4. Sales Agent (`sales`)

The **Sales Agent** is tuned for customer outreach generation, lead qualification, email copy drafting, and CRM interaction.

- **Capabilities**: Email drafting, HTTP integrations, text synthesis.
- **Price per execution**: 0.5 Credits
- **SDK Usage**:
  ```typescript
  const response = await kyronix.run({
    agent: 'sales',
    input: 'Draft a cold outreach email for enterprise software'
  });
  ```

---

## 5. Custom Agents (`custom_agents`)

User-defined AI personas created in the **Kyronix Dashboard** with specialized tool definitions and dynamic parameter schemas.

- **Capabilities**: User-defined custom tools executed locally via `@kyronixai/executer`.
- **Price per execution**: 0.5 Credits
- **SDK Usage**:
  ```typescript
  const response = await kyronix.runCustomAgent({
    agentId: '8b5b6ad518947f52745da...',
    input: 'Execute custom workflow'
  });
  ```

---

# Custom Agents Guide 🤖

Kyronix **Custom Agents** enable developers to define domain-specific AI personas with dynamic custom tool definitions, parameter schemas, and specialized runtime execution capabilities managed by the Kyronix Platform.

> 🚀 **Recommended Architecture**: We highly recommend running your Custom Agent execution using the **WebSocket Tunnel Flow** (`wsUrl` + `executeKmlOverWs`), enabling real-time bi-directional tool dispatches without firewall overhead.

---

## 1. What Are Custom Agents?

While Kyronix provides built-in specialized agents (such as `coding`, `research`, `database`, and `sales`), **Custom Agents** let you create tailored AI agents for your own unique business logic or domain tools (e.g. specialized database query engines, third-party API orchestrators, or custom code generators).

Each Custom Agent consists of:
- **Agent Name & Description**: High-level identity and role of the agent.
- **Unique Agent ID Hash**: Hashed string identifier used in `@kyronixai/runtime` (`runCustomAgent`).
- **Custom Tools Registry**: Dynamic array of tool schemas containing tool names, descriptions, and parameter string arrays.

---

## 2. Step-by-Step: How to Create a Custom Agent

### Step 1: Define Your Custom Agent in the Dashboard
1. Log into your [Kyronix Dashboard](/dashboard).
2. Click on the **My Agents** tab in the left sidebar.
3. Click the **+ Create Custom Agent** button.
4. Enter an **Agent Name** (e.g., `Database Assistant`) and **Description** (e.g., `Queries analytics tables and generates summary reports`).

### Step 2: Configure Custom Tool Schemas
1. Under **Custom Tools**, click **+ Add Tool**.
2. Enter the **Tool Name** (e.g. `execute_sql`).
3. Enter the **Tool Description** (e.g. `Executes a SQL query on analytical database`).
4. Enter comma-separated **Parameters** (e.g. `sql_query, limit`).
5. Click **Save Agent**. Your Custom Agent will be generated with a unique **Agent ID** (e.g., `8b5b6ad518947f52745da...`). Click **Copy ID**.

---

## 3. Recommended WebSocket Client Setup (`@kyronixai/executer`)

On your local application server or client machine, initialize `KyronixExecuter` with `wsUrl` to automatically connect to the WebSocket execution tunnel and register custom tool handlers:

```typescript
import { KyronixExecuter } from '@kyronixai/executer';

// 1. Initialize local executor connected to WebSocket tunnel
const executor = new KyronixExecuter({
  wsUrl: 'ws://localhost:8080/ws'
});

// 2. Register local tool handler for custom tool 'execute_sql'
executor.register('execute_sql', async (args) => {
  const { sql_query, limit } = args;
  console.log(`Executing SQL Query: ${sql_query} (limit: ${limit})`);

  // Run database query logic
  const queryResults = await myDatabaseClient.query(sql_query);

  return {
    success: true,
    results: queryResults
  };
});

console.log('Custom Agent local executor listening over WebSocket tunnel...');
```

---

## 4. Running Custom Agents Over WebSocket (`@kyronixai/runtime`)

From your backend runtime or server process, execute your Custom Agent and dispatch KML over the WebSocket tunnel via `executeKmlOverWs`:

```typescript
import { Kyronix } from '@kyronixai/runtime';
import WebSocket from 'ws';

// Connect WebSocket client
const ws = new WebSocket('ws://localhost:8080/ws');

const kyronix = new Kyronix({
  apiKey: process.env.KYRONIX_API_KEY!,
  ws
});

async function runCustomAgentWebSocketFlow() {
  console.log('1. Generating plan with Custom Agent...');
  
  // 1. Single-shot Custom Agent execution
  const runResult = await kyronix.runCustomAgent({
    agentId: '8b5b6ad518947f52745da13120938bd7ae2fc5faf48fe334acc001907f90ec9e',
    input: 'Fetch top 5 active users from signup table',
  });

  console.log('2. LLM KML Response received:', runResult.response);

  // 2. Dispatch KML execution over WebSocket tunnel to connected executor
  console.log('3. Dispatching execution over WebSocket...');
  const outcomes = await kyronix.executeKmlOverWs(runResult.response);

  console.log('4. Execution Outcomes from local executor:', outcomes);
}

runCustomAgentWebSocketFlow().catch(console.error);
```

---

## 5. Multi-Turn Sessions with Custom Agents (WebSocket Recommended)

Maintain conversational context across multiple turns using custom agents:

```typescript
import { Kyronix } from '@kyronixai/runtime';
import WebSocket from 'ws';

const ws = new WebSocket('ws://localhost:8080/ws');
const kyronix = new Kyronix({ apiKey: process.env.KYRONIX_API_KEY!, ws });

async function runMultiTurnCustomSession() {
  // Create session context
  const session = await kyronix.createSession({ agent: 'coding' });

  // Send 1st prompt targeting your custom agent ID
  const response1 = await session.send('Summarize database schema', {
    customAgentId: '8b5b6ad518947f52745da13120938bd7ae2fc5faf48fe334acc001907f90ec9e'
  });

  // Dispatch execution over WebSocket
  const outcomes1 = await kyronix.executeKmlOverWs(response1.response);
  console.log('Turn 1 Outcomes:', outcomes1);

  // Send 2nd follow-up prompt in same session
  const response2 = await session.send('Now fetch users who signed up today');
  const outcomes2 = await kyronix.executeKmlOverWs(response2.response);
  console.log('Turn 2 Outcomes:', outcomes2);
}

runMultiTurnCustomSession().catch(console.error);
```

---

# @kyronixai/runtime SDK

The `@kyronixai/runtime` SDK is the client-facing & server-side library used to interact with the Kyronix Agentic Platform. It provides end-to-end management for executing built-in agents, running custom agents with custom tool schemas, establishing WebSocket execution tunnels (`executeKmlOverWs`), managing multi-turn conversational sessions, and streaming real-time responses.

---

## Installation

Install `@kyronixai/runtime` via your preferred package manager:

```bash
pnpm add @kyronixai/runtime
```

---

## Constructor & Configuration Options (`KyronixConfig`)

To initialize the `Kyronix` client instance, pass a `KyronixConfig` configuration object to the constructor.

```typescript
import { Kyronix } from '@kyronixai/runtime';

const kyronix = new Kyronix({
  apiKey: process.env.KYRONIX_API_KEY!,
  projectId: 'proj_8f92a10b',
  baseUrl: 'https://kyronix.harshitnakrani.me',
  timeout: 60000,
  ws: WebSocketInstance, // Optional custom WebSocket instance for Node/browser tunneling
});
```

### `KyronixConfig` Options Reference

| Option | Type | Required | Default | Description |
| :--- | :--- | :--- | :--- | :--- |
| `apiKey` | `string` | **Yes** | — | Your Kyronix API Key (starts with `kyr_`). |
| `projectId` | `string` | Optional | — | Default project ID to associate agent execution runs and sessions with. |
| `baseUrl` | `string` | Optional | `https://kyronix.harshitnakrani.me` | API endpoint origin URL. |
| `timeout` | `number` | Optional | `60000` | HTTP request timeout in milliseconds. |
| `ws` | `any` | Optional | `undefined` | Custom WebSocket client instance for real-time `executeKmlOverWs` calls. |

---

## Single-shot Agent Execution (`run`)

Runs built-in specialized agents (`coding`, `research`, `database`, `sales`) or delegates to a custom agent in a single HTTP request-response cycle.

```typescript
const result = await kyronix.run({
  agent: 'coding',
  input: 'Write a TypeScript function to parse CSV streams with backpressure',
  projectId: 'proj_8f92a10b',
  sessionId: 'sess_12345678',
  timeout: 45000
});

console.log('KML Plan Output:', result.response);
console.log('Session ID:', result.sessionId);
console.log('Credits Remaining:', result.creditsRemaining);
```

### `RunOptions` Reference

| Parameter | Type | Required | Default | Description |
| :--- | :--- | :--- | :--- | :--- |
| `agent` | `string` | Optional | `'coding'` | Built-in agent slug (`coding`, `research`, `database`, `sales`). |
| `input` | `string` | **Yes** | — | Prompt text instruction for the agent. |
| `projectId` | `string` | Optional | Client default | Project ID. Overrides client-level `projectId`. |
| `sessionId` | `string` | Optional | — | Existing session UUID to attach execution history to. |
| `customAgentId` | `string` | Optional | — | Target custom agent ID hash if delegating to a custom agent persona. |
| `timeout` | `number` | Optional | `60000` | Custom request timeout in milliseconds. |

---

## Custom Agents Execution (`runCustomAgent`)

Executes a user-defined Custom Agent registered in your Kyronix Dashboard with dynamic custom tool schemas.

```typescript
const result = await kyronix.runCustomAgent({
  agentId: '8b5b6ad518947f52745da13120938bd7ae2fc5faf48fe334acc001907f90ec9e',
  input: 'Analyze database metrics for active user signups in last 24h',
  projectId: 'proj_8f92a10b',
  sessionId: 'sess_99887766'
});

console.log('Custom Agent KML:', result.response);
```

### `RunCustomAgentOptions` Reference

| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `agentId` | `string` | **Yes** | Hashed unique identifier of your custom agent. |
| `input` | `string` | **Yes** | Prompt instruction passed to the custom agent. |
| `projectId` | `string` | Optional | Overrides default project ID. |
| `sessionId` | `string` | Optional | Session ID for context retention. |
| `timeout` | `number` | Optional | Timeout override in milliseconds. |

---

## Real-time Token Streaming (`stream` & `streamCustomAgent`)

Streams response tokens in real-time as Kyronix Cloud generates the response plan.

```typescript
await kyronix.stream({
  agent: 'coding',
  input: 'Refactor express route handlers to use async middleware wrappers',
  onChunk: (chunk: string) => {
    process.stdout.write(chunk);
  },
  onComplete: (result) => {
    console.log('\nStream completed. Credits left:', result.creditsRemaining);
  },
  onError: (err) => {
    console.error('Stream failure:', err.message);
  }
});
```

### `StreamOptions` Reference

| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `agent` | `string` | Optional | Built-in agent slug (default: `'coding'`). |
| `input` | `string` | **Yes** | Prompt string. |
| `onChunk` | `(chunk: string) => void` | **Yes** | Callback fired when a new token chunk arrives. |
| `onComplete` | `(result: RunResponse) => void` | Optional | Callback fired when generation completes. |
| `onError` | `(error: Error) => void` | Optional | Callback fired if stream encounters an error. |

---

## WebSocket Execution Tunnel (`executeKmlOverWs` & `close`)

When `ws` is configured in `KyronixConfig`, `executeKmlOverWs` sends KML requests over WebSocket and returns execution results asynchronously.

```typescript
import { Kyronix } from '@kyronixai/runtime';
import WebSocket from 'ws';

const ws = new WebSocket('wss://kyronix.harshitnakrani.me/ws');

const kyronix = new Kyronix({
  apiKey: process.env.KYRONIX_API_KEY!,
  ws
});

// Execute KML payload over WebSocket
const results = await kyronix.executeKmlOverWs('<tool name="write_file">...</tool>');
console.log('WebSocket execution results:', results);

// Close connection when done
await kyronix.close();
```

---

## Session Management API (`createSession`, `session`, `Session`)

Sessions maintain multi-turn conversational context across interactions.

```typescript
// Create session
const session = await kyronix.createSession({
  agent: 'coding',
  projectId: 'proj_8f92a10b'
});

console.log('Created Session ID:', session.getId());

// Send 1st prompt
const turn1 = await session.send('Create a database migration script for users table');

// Send 2nd prompt (inherits context of turn 1 automatically)
const turn2 = await session.send('Add an index on email field in that migration');

// Retrieve full chat history
const messages = await session.getMessages();
console.log('Total Messages:', messages.length);
```

### `Session` Methods Reference

| Method | Parameters | Returns | Description |
| :--- | :--- | :--- | :--- |
| `getId()` | — | `string` | Returns the session UUID. |
| `getHistory()` | — | `Promise` | Fetches session metadata and full chat history from `/api/sessions/:id`. |
| `getMessages()` | — | `Promise` | Returns array of chat messages. |
| `send(input, options?)` | `input: string`, `options?: { agent?, customAgentId?, timeout? }` | `Promise` | Sends prompt within session context. |

---

## Error Handling Reference (`KyronixError`)

All `@kyronixai/runtime` errors inherit from `KyronixError`, exposing `statusCode` and `details`.

```typescript
import { 
  KyronixError, 
  AuthenticationError, 
  InsufficientCreditsError, 
  ProjectNotFoundError 
} from '@kyronixai/runtime';

try {
  await kyronix.run({ agent: 'coding', input: 'Generate server' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('HTTP 401: Invalid API Key. Check process.env.KYRONIX_API_KEY');
  } else if (error instanceof InsufficientCreditsError) {
    console.error('HTTP 402: Account balance depleted.');
  } else if (error instanceof ProjectNotFoundError) {
    console.error('HTTP 404: Target project does not exist.');
  } else if (error instanceof KyronixError) {
    console.error(`Kyronix Error [Status ${error.statusCode}]: ${error.message}`);
  }
}
```

---

# @kyronixai/executer SDK

The `@kyronixai/executer` SDK runs on the end-user's local workstation, container sandbox, or application client. It securely parses Kyronix Markup Language (KML) emitted by agents via `@kyronixai/runtime`, dispatches tools to registered executor handlers, enforces path safety, and supports WebSocket tunneling for remote execution.

---

## Installation

Install `@kyronixai/executer` via your preferred package manager:

```bash
pnpm add @kyronixai/executer
```

---

## Constructor Options (`KyronixExecuter`)

Initialize `KyronixExecuter` with optional WebSocket tunnel support.

```typescript
import { KyronixExecuter } from '@kyronixai/executer';

const executor = new KyronixExecuter({
  wsUrl: 'ws://localhost:8080/ws' // Optional WebSocket connection URL
});
```

### Constructor Options Reference

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `wsUrl` | `string` | `undefined` | Optional WebSocket URL to automatically connect and process remote `kml_request` messages. |

---

## KML Execution (`execute`)

Parses a KML string returned by an agent and dispatches all tool calls.

```typescript
import { KyronixExecuter } from '@kyronixai/executer';

const executor = new KyronixExecuter();

const kmlResponse = `
<tool name="write_file">
  <path>src/utils/logger.ts</path>
  <content>export const log = (msg: string) => console.log('[LOG]', msg);</content>
</tool>
<tool name="terminal">
  <command>npm test</command>
</tool>
`;

// Parse and execute KML relative to a basePath (optional)
const results = await executor.execute(kmlResponse, '/path/to/project');

console.log('Execution Results:', results);
/*
Output: [
  { tool: 'write_file', args: { path: '/path/to/project/src/utils/logger.ts', content: '...' }, result: { success: true, output: '...', executionId: 'exec_...' } },
  { tool: 'terminal', args: { command: 'npm test', cwd: '/path/to/project' }, result: { success: true, output: '...', executionId: 'exec_...' } }
]
*/
```

---

## Built-in Tools & Argument Schemas

`@kyronixai/executer` includes **17 built-in tool executors**.

### 1. Filesystem Tools

| Tool | Parameters / Arguments | Description |
| :--- | :--- | :--- |
| `read_file` | `path` (`string`) | Reads entire file contents. |
| `write_file` | `path` (`string`), `content` (`string`) | Creates or overwrites file content. |
| `delete_file` | `path` (`string`) | Deletes file or directory recursively. |
| `move_file` | `source` (`string`), `destination` (`string`) | Moves or renames file/directory. |
| `copy_file` | `source` (`string`), `destination` (`string`) | Copies file/directory. |
| `list_dir` | `path` (`string`) | Lists directory contents. |
| `create_dir` | `path` (`string`) | Creates directory recursively (`mkdir -p`). |
| `write_in_between` | `path` (`string`), `content` (`string`), `linebefore` (`string`) | Inserts content at specified line number in file. |
| `modify_line_between` | `path` (`string`), `content` (`string`), `startline` (`string`), `endline` (`string`) | Replaces line range in file. |
| `delete_line` | `path` (`string`), `line` (`string`) | Deletes specific line from file. |
| `read_lines` | `path` (`string`), `start` (`string`), `end` (`string`) | Reads line range snippet from file. |

### 2. Terminal Tools

| Tool | Parameters / Arguments | Description |
| :--- | :--- | :--- |
| `terminal` | `command` (`string`), `cwd?` (`string`), `shell?` (`string`) | Executes shell commands in child process. |

### 3. Browser Automation Tools

| Tool | Parameters / Arguments | Description |
| :--- | :--- | :--- |
| `navigate` | `url` (`string`) | Navigates browser to URL. |
| `click` | `selector` (`string`) | Clicks DOM element by CSS selector. |
| `type` | `selector` (`string`), `text` (`string`) | Types string into input element. |
| `screenshot` | `path?` (`string`) | Captures page screenshot. |

### 4. Git Tools

| Tool | Parameters / Arguments | Description |
| :--- | :--- | :--- |
| `git_clone` | `repository` (`string`), `directory?` (`string`), `cwd?` (`string`) | Clones git repository. |
| `git_commit` | `message` (`string`), `cwd?` (`string`) | Stages and commits changes. |
| `git_branch` | `name` (`string`), `create?` (`boolean`), `cwd?` (`string`) | Checkouts or creates branch. |

### 5. Network Tools

| Tool | Parameters / Arguments | Description |
| :--- | :--- | :--- |
| `http_request` | `url` (`string`), `method?` (`string`), `headers?` (`object`), `body?` (`string`) | Makes HTTP network request. |

---

## Registering Custom Tools (`register`)

Extend `KyronixExecuter` with custom handlers matching custom agent schemas.

```typescript
import { KyronixExecuter } from '@kyronixai/executer';

const executor = new KyronixExecuter();

executor.register('custom_action', async (args) => {
  console.log('Running custom action with args:', args);
  return { success: true, output: 'Action performed' };
});
```

---

## WebSocket Messaging Protocol (`connectWebSocket` & `close`)

When `wsUrl` is passed to the constructor, `KyronixExecuter` listens for incoming WebSocket `kml_request` frames and replies with `kml_result` frames.

```typescript
// Received frame format (Server -> Executer)
{
  "type": "kml_request",
  "executionId": "exec_abc123",
  "kmlResponse": "<tool name=\"read_file\"><path>package.json</path></tool>"
}

// Sent frame format (Executer -> Server)
{
  "type": "kml_result",
  "executionId": "exec_abc123",
  "results": [
    { "tool": "read_file", "args": { "path": ".../package.json" }, "result": { "success": true, "output": "..." } }
  ]
}
```

---

## Permission Manager & Security (`PermissionManager`)

`KyronixExecuter` enforces permission checks before tool dispatch:

```typescript
import { PermissionManager, ROOT_POLICIES } from '@kyronixai/executer';

const permissions = new PermissionManager(ROOT_POLICIES);

// Check if tool action is allowed
const allowed = permissions.check('tool:write_file', '/path/to/file.txt');
console.log('Permission allowed:', allowed);
```

---

# API & KML Reference Specification

This document provides the technical specification for **Kyronix Markup Language (KML)**, HTTP REST Endpoints, and WebSocket messaging frame schemas based on the official SDK implementation.

---

## Kyronix Markup Language (KML) Format

Kyronix agents serialize planned action sequences using KML XML format.

```xml
<tool name="write_file" executionId="exec_99201">
  <path>src/index.ts</path>
  <content>
    console.log("Hello Kyronix!");
  </content>
</tool>
<tool name="terminal" executionId="exec_99202">
  <command>npm run build</command>
  <cwd>/app</cwd>
</tool>
```

### KML Syntax Rules

1. Tool invocations are wrapped in `<tool name="...">` tags.
2. Argument names match child tag names (`<path>`, `<content>`, `<command>`, `<cwd>`).
3. An optional `executionId` attribute is passed to correlate tool execution outcomes.

### KML AST Format (`KMLAST`)

Parsed output structure generated by `KMLParser`:

```typescript
export interface KMLAST {
  root: KMLNode;
}

export interface KMLNode {
  tag: string; // "tool" or parameter element tag name
  attributes: Record<string, string>; // { name: "write_file", executionId: "..." }
  children: (KMLNode | string)[];
}
```

---

## HTTP REST Endpoints Reference

All requests pass `Authorization: Bearer kyr_your_api_key`.

### Base URL
`https://kyronix.harshitnakrani.me`

---

### 1. Execute Agent (Built-in)
`POST /api/agents/:agent`

- **Path Param:** `agent` — `coding` | `research` | `database` | `sales` (Default: `coding`)
- **Body Schema:**
  ```json
  {
    "input": "Write a python script to convert JSON to CSV",
    "projectId": "proj_8f92a10b",
    "sessionId": "sess_12345678"
  }
  ```
- **Response (200 OK):**
  ```json
  {
    "response": "<tool name=\"write_file\"><path>script.py</path><content>...</content></tool>",
    "sessionId": "sess_12345678",
    "creditsRemaining": 485
  }
  ```

---

### 2. Execute Custom Agent
`POST /api/customagents/run`

- **Body Schema:**
  ```json
  {
    "agentId": "8b5b6ad518947f52745da13120938bd7ae2fc5faf48fe334acc001907f90ec9e",
    "input": "Query database for top active users",
    "projectId": "proj_8f92a10b",
    "sessionId": "sess_99887766"
  }
  ```

---

### 3. List Custom Agents
`GET /api/customagents`

- **Response (200 OK):**
  ```json
  [
    {
      "id": "8b5b6ad518947f52745da13120938bd7ae2fc5faf48fe334acc001907f90ec9e",
      "name": "Database Assistant",
      "description": "Queries analytics database and summarizes reports",
      "tools": [
        {
          "name": "execute_sql",
          "description": "Executes SQL query on analytics engine",
          "params": ["sql_query", "limit"],
          "disabled": false
        }
      ]
    }
  ]
  ```

---

### 4. Fetch Session History
`POST /api/sessions/:id`

- **Response (200 OK):**
  ```json
  {
    "id": "sess_12345678",
    "agentId": "coding",
    "chat": [
      { "role": "user", "content": "Create migration script" },
      { "role": "assistant", "content": "<tool name=\"write_file\">...</tool>" }
    ]
  }
  ```

---

## WebSocket Protocol Specification (`executeKmlOverWs`)

When WebSocket tunneling is enabled in `KyronixConfig`, `Kyronix` and `KyronixExecuter` exchange JSON frames.

### 1. KML Request Frame (`kml_request`)
Sent by `Kyronix` to `KyronixExecuter`:

```json
{
  "type": "kml_request",
  "executionId": "exec_abc123",
  "kmlResponse": "<tool name=\"write_file\"><path>test.txt</path><content>hello</content></tool>"
}
```

### 2. KML Result Frame (`kml_result`)
Returned by `KyronixExecuter` to `Kyronix`:

```json
{
  "type": "kml_result",
  "executionId": "exec_abc123",
  "results": [
    {
      "tool": "write_file",
      "args": { "path": "/full/path/test.txt", "content": "hello" },
      "result": {
        "success": true,
        "output": "Successfully wrote file to /full/path/test.txt",
        "executionId": "exec_xyz789"
      }
    }
  ]
}
```

---
