Claude Neam Programming Skill
Neam is a compiled, AI-native programming language for building agent systems. It provides first-class support for LLMs, RAG, multi-agent orchestration, multi-cloud deployment, and cost management. Written in C++17/20 with a tree-sitter parser.
When to Activate
- User writes or asks about
.neamfiles - User builds AI agents, RAG pipelines, multi-agent systems in Neam
- User asks about Neam syntax, keywords, built-in functions, or deployment
- User wants to connect agents to knowledge bases, skills, tools, or MCP servers
- User works with NeamClaw (claw agents, forge agents)
- User configures
neam.tomlor deploys Neam to cloud
Toolchain
# Install prerequisites (macOS)
brew install cmake curl openssl
# Clone and build
git clone https://github.com/neam-lang/Neam.git
cd Neam && mkdir -p build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build . --parallel $(sysctl -n hw.ncpu)
# Compile .neam to bytecode
neamc hello.neam -o hello.neamb
# Run bytecode
neam-cli hello.neamb
# Interactive REPL
neam-cli
neam> 1 + 2
3
Build Outputs
| Binary | Purpose |
|---|---|
neamc |
Compiler (.neam -> .neamb bytecode) |
neam-cli |
Runtime / REPL |
neam-lsp |
Language Server Protocol |
neam-dap |
Debug Adapter Protocol |
neam-pkg |
Package manager |
neam-api |
HTTP API server |
neam-gym |
Training/benchmarking |
Core Syntax
Variables
let name = "Alice"; // mutable
const MAX = 100; // immutable constant
let active = true;
let scores = [10, 20, 30];
Variables are block-scoped. let is reassignable, const is not.
Output
print("debug message"); // debug / logging (no newline)
emit result; // final output — use for results (newline)
F-Strings
emit f"Hello, {name}!";
emit f"{age + 1} next year";
Functions
fun greet(name) {
return "Hello, " + name + "!";
}
// Anonymous / lambda
let doubler = fn(x) { return x * 2; };
let concise = fn(x) { x * 2 }; // implicit return
// Multi-return with tuples
fun divide(a, b) {
return (a / b, a % b);
}
let (quotient, remainder) = divide(10, 3);
Visibility modifiers: pub (public), crate (package-internal), super (parent module), default is private.
Control Flow
// if / else if / else
if (score > 90) {
emit "A";
} else if (score > 70) {
emit "B";
} else {
emit "C";
}
// while loop
let i = 0;
while (i < 5) { print(i); i = i + 1; }
// for-in loop
for (item in ["apple", "banana"]) { emit item; }
// range() — three forms
for (i in range(5)) { ... } // 0..4
for (i in range(1, 6)) { ... } // 1..5
for (i in range(0, 20, 5)) { ... } // 0,5,10,15
// enumerate
for ((i, color) in colors.enumerate()) { emit f"{i}: {color}"; }
// break / continue
for (n in numbers) {
if (n < 0) { continue; }
if (n > 100) { break; }
emit str(n);
}
Comprehensions
let squares = [x * x for x in range(10)];
let evens = [x for x in range(20) if x % 2 == 0];
let word_lengths = {word: len(word) for word in words};
let unique_lens = set(len(w) for w in words);
let pairs = [(x, y) for x in range(3) for y in range(3)];
Pipe Operator
let result = data
|> filter(fn(x) { x % 2 == 0; })
|> map(fn(x) { x * x; })
|> fold(0, fn(acc, x) { acc + x; });
13 Data Types
| Type | Description | Example |
|---|---|---|
| Number | 64-bit IEEE 754 double | 42, 3.14 |
| String | Immutable, double-quoted | "hello" |
| Boolean | true / false |
true |
| Nil | Absence of value | nil |
| List | Ordered, mutable, mixed types | [1, "a", true] |
| Map | String-keyed key-value pairs | {"name": "Alice"} |
| Tuple | Immutable, fixed-size | (3.14, 2.72) |
| Set | Unordered unique elements | set(1, 2, 3) |
| Range | Lazy integer sequence | range(10) |
| Option | Some(value) or None |
Some(42) |
| TypedArray | Homogeneous numeric array | float_array([1.0, 2.0]) |
| Record | Named tuple (immutable) | record Point { x: number, y: number } |
| Table | Columnar data | table({"col": [1,2]}) |
Destructuring & Spread
let [first, second, ...rest] = [1, 2, 3, 4, 5];
let (x, y) = (3.14, 2.72);
let {name, age} = person;
let combined = [...front, ...back];
let config = {...defaults, ...overrides};
Slicing
items[2:5] // indices 2,3,4
items[::2] // every other
items[-2:] // last two
Operators
- Arithmetic:
+,-,*,/,% - Comparison:
==,!=,<,>,<=,>= - Logical:
&&,||,! - Membership:
in,not in - String repeat:
"ha" * 3->"hahaha" - Broadcasting:
[1, 2, 3] + 10->[11, 12, 13]
Type Conversion
str(42) // "42"
num("42") // 42
bool(0) // true (only false/nil are falsy)
int(3.7) // 3
typeof(42) // "number"
Structs, Traits, and Sealed Types
Structs
struct Point { x: number, y: number }
let p = Point(3, 4);
let p2 = p with (x: 10); // immutable copy
mut struct Counter { value: number }
let c = Counter(0);
c.value = c.value + 1;
Impl Blocks
impl Point {
fn distance_to(self, other) {
let dx = self.x - other.x;
let dy = self.y - other.y;
return math_sqrt(dx * dx + dy * dy);
}
fn origin() { return Point(0, 0); } // static
}
Traits
trait Describable {
fn describe(self) -> string;
}
impl Describable for Point {
fn describe(self) {
return f"Point({self.x}, {self.y})";
}
}
Sealed Types and Match
sealed Shape {
Circle(radius: number),
Rectangle(width: number, height: number),
Point
}
match shape {
Circle(r) => { return 3.14159 * r * r; },
Rectangle(w, h) => { return w * h; },
Point => { return 0; }
}
Error Handling
Try / Catch / Throw
try {
let result = risky_operation();
emit result;
} catch (err) {
emit "Error: " + str(err);
}
fun validate(age) {
if (age < 0) { throw "Age cannot be negative"; }
return age;
}
Panic (Unrecoverable)
panic("Missing required config"); // halts execution, uncatchable
Option Type
let maybe = Some(42);
let nothing = None;
maybe.unwrap() // 42
maybe.unwrap_or(0) // 42
nothing.unwrap_or(0) // 0
maybe.map(fn(x) { x * 2; }) // Some(84)
maybe.is_some() // true
Native Result Type
fun safe_divide(a, b) {
if (b == 0) { return Err("division by zero"); }
return Ok(a / b);
}
let answer = safe_divide(10, 3)
.map(fn(x) { x * 2; })
.unwrap_or(0);
// Chaining
parse_number("42")
.and_then(validate_positive)
.map(fn(n) { n * 2; });
Error Context
context(err, "while loading config");
with_context(fn() { read_file(path); }, "loading config from " + path);
Agents
Agents wrap an LLM with a system prompt. Three types: agent (stateless), claw agent (persistent sessions), forge agent (iterative builds).
Stateless Agent
agent Assistant {
provider: "openai",
model: "gpt-4o-mini",
system: "You are a helpful assistant.",
temperature: 0.7
}
let answer = Assistant.ask("What is the capital of France?");
emit answer;
Agent Properties
| Field | Type | Required | Default | Purpose |
|---|---|---|---|---|
provider |
string | Yes | -- | LLM provider |
model |
string | Yes | -- | Model identifier |
system |
string | No | "" |
System prompt |
temperature |
float | No | 0.7 | Randomness (0.0-2.0) |
api_key_env |
string | No | Provider default | API key env var |
endpoint |
string | No | Provider default | Custom endpoint URL |
skills |
list | No | [] |
Tool capabilities |
connected_knowledge |
list | No | [] |
RAG knowledge bases |
guardchains / guards |
list | No | [] |
Security guards |
budget |
ref/inline | No | -- | Cost/token limits |
env |
ref | No | -- | Environment config |
memory |
ref | No | -- | Session memory |
handoffs |
list | No | [] |
Agent transfer targets |
policy |
ref | No | -- | Security policy |
output_type |
map | No | -- | Structured output schema |
context_from |
string | No | -- | Path to AGENTS.md |
7 Supported Providers
| Provider | Value | Auth | Notes |
|---|---|---|---|
| Ollama | "ollama" |
None | Local, free, private |
| OpenAI | "openai" |
OPENAI_API_KEY |
GPT-4o, GPT-4o-mini |
| Anthropic | "anthropic" |
ANTHROPIC_API_KEY |
Claude Sonnet/Opus/Haiku |
| Gemini | "gemini" |
GEMINI_API_KEY |
1M+ token context |
| Azure OpenAI | "azure_openai" |
AZURE_OPENAI_API_KEY |
Enterprise |
| AWS Bedrock | "bedrock" |
AWS credentials (SigV4) | Native AWS |
| Vertex AI | "openai" adapter |
GCP credentials | Via OpenAI-compatible endpoint |
Vision / Multimodal
let desc = VisionBot.ask_with_image(
"What is in this image?",
"https://example.com/photo.jpg"
);
Multi-Agent Pipeline
agent Researcher { provider: "openai", model: "gpt-4o", system: "Research thoroughly." }
agent Writer { provider: "openai", model: "gpt-4o-mini", system: "Write from research notes." }
agent Editor { provider: "openai", model: "gpt-4o-mini", system: "Edit for clarity." }
let research = Researcher.ask("Research: " + topic);
let draft = Writer.ask("Write from: " + research);
let final = Editor.ask("Edit: " + draft);
emit final;
Runners (Orchestration)
runner CustomerService {
entry_agent: TriageAgent
max_turns: 5
tracing: enabled
input_guardrails: [InputChain]
output_guardrails: [OutputChain]
}
let result = CustomerService.run("user query");
// result.final_output, result.total_turns, result.completed
Handoffs
agent Triage {
provider: "openai", model: "gpt-4o-mini",
handoffs: [RefundAgent, BillingAgent, TechAgent]
}
// Advanced handoff config
handoff_to(UrgentAgent) {
tool_name: "urgent_support"
description: "Escalate urgent issues"
input_filter: sanitize_input
on_handoff: log_handoff
is_enabled: is_business_hours()
}
spawn and dag_execute
let result = spawn researcher("Analyze this topic");
let results = dag_execute([
{ "id": "research", "agent": "researcher", "task": "...", "depends_on": [] },
{ "id": "analysis", "agent": "analyst", "task": "...", "depends_on": ["research"] }
]);
Orchestration Patterns
- Triage Routing — classifier dispatches to specialists
- Sequential Pipeline — chain agent outputs
- Supervisor/Worker — worker + evaluator loop
- Debate/Adversarial — opposing agents + judge
- Planning Agent — decompose goals into steps
- Deep Search — sub-queries + synthesis
- Chain-of-Thought — explicit reasoning steps
- ReAct — Thought/Action/Observation loop
- Self-Reflection — writer + critic iterations
- Red Team/Blue Team — security analysis
Provider Failover
fun ask_with_fallback(prompt) {
try {
return PrimaryBot.ask(prompt);
} catch (err) {
try { return FallbackBot.ask(prompt); }
catch (err2) { return "All providers unavailable"; }
}
}
NeamClaw: Claw Agents (Persistent Sessions)
Claw agents maintain conversation history, auto-compaction, channels, lanes, and semantic memory.
channel support_cli { type: "cli", prompt: "you> " }
channel support_http { type: "http", port: 8080, path: "/chat" }
claw agent SupportBot {
provider: "openai"
model: "gpt-4o-mini"
channels: [support_cli, support_http]
skills: [lookup_order, escalate]
guards: [safety_chain]
system: "You are helpful support staff."
session: {
idle_reset_minutes: 30
daily_reset_hour: 4
max_history_turns: 100
compaction: "auto" // "auto", "manual", "disabled"
}
lanes: {
default: { concurrency: 4, priority: "normal" }
vip: { concurrency: 2, priority: "high" }
}
semantic_memory: {
backend: "sqlite"
embedding_model: "nomic-embed-text"
search: "hybrid" // "keyword", "vector", "hybrid"
top_k: 5
}
}
let r = SupportBot.ask("Where is my order?");
let history = SupportBot.history();
SupportBot.reset();
.ask() Pipeline (5 steps)
- Security checks — guards, budget, kill switch
- Session load — get/create session, check idle timeout
- Context build — history + semantic memory + RAG, auto-compact at 80% tokens
- Tool loop — LLM call + tool execution (up to 25 iterations)
- Response — output guards, persist, record metrics
NeamClaw: Forge Agents (Build-Verify Loop)
Forge agents iterate: fresh context per iteration, persistent state in filesystem.
fun check_output(ctx) {
let file = file_read("output.txt");
if (file != nil) { return VerifyResult.Done("Created."); }
return VerifyResult.Retry("File missing. Create output.txt.");
}
forge agent Builder {
provider: "openai"
model: "gpt-4o"
verify: check_output
system: "You are a code builder."
skills: [write_file, read_file, run_command]
workspace: "./project"
loop {
max_iterations: 30
max_cost: 12.0
max_tokens: 600000
prompt_file: "prompt.md"
plan_file: "plan.txt"
progress_file: "progress.jsonl"
learnings_file: "learnings.jsonl"
}
checkpoint: "git" // "git", "snapshot", "none"
}
let outcome = Builder.run();
match outcome {
Completed(msg) => { emit "Done: " + msg; },
MaxIterations => { emit "Hit iteration limit"; },
Aborted(reason) => { emit "Aborted: " + reason; },
BudgetExhausted => { emit "Budget exceeded"; }
}
VerifyResult (Sealed Type)
VerifyResult.Done(message) // advance to next task
VerifyResult.Retry(feedback) // retry with feedback
VerifyResult.Abort(reason) // stop loop
Verify Context Fields
ctx.iteration— current iteration (1-based)ctx.current_task— task descriptionctx.feedback— previous verify feedback (or nil)ctx.total_cost— cumulative USDctx.total_tokens— cumulative tokensctx.workspace— workspace path
Knowledge Bases (RAG)
knowledge ProductDocs {
vector_store: "usearch",
embedding_model: "nomic-embed-text",
chunk_size: 200,
chunk_overlap: 50,
sources: [
{ type: "file", path: "./docs/guide.md" },
{ type: "file", path: "./docs/faq.md" },
{ type: "text", content: "Inline documentation..." }
],
retrieval_strategy: "hybrid",
top_k: 5
}
agent DocBot {
provider: "openai", model: "gpt-4o-mini",
system: "Answer from documentation only.",
connected_knowledge: [ProductDocs]
}
8 Retrieval Strategies
| Strategy | LLM Calls | Latency | Use Case |
|---|---|---|---|
"basic" |
0 | Low | Simple factual lookups |
"mmr" |
0 | Low | Diverse, non-repetitive results |
"hybrid" |
0 | Low | Technical terms + semantic |
"hyde" |
1 | Medium | Abstract/conceptual queries |
"self_rag" |
1 | Medium | High-accuracy (medical, legal) |
"crag" |
1-3 | Medium | Complex multi-part questions |
"agentic" |
2-5+ | High | Deep research, iterative |
"graph_rag" |
1-2 | Medium | Entity relationships |
Skills and Tools
Skill (Preferred Syntax)
skill get_weather {
description: "Get weather for a city"
params: { city: string }
impl(city) {
let url = f"https://wttr.in/{city}?format=j1";
try {
return http_get(url);
} catch (err) {
return f"Unavailable: {err}";
}
}
}
Tool (Classic Syntax with JSON Schema)
tool Calculator {
description: "Perform math",
params: [
{ name: "operation", schema: { "type": "string" } },
{ name: "a", schema: { "type": "number" } },
{ name: "b", schema: { "type": "number" } }
],
impl(operation, a, b) {
if (operation == "add") { return a + b; }
if (operation == "sub") { return a - b; }
if (operation == "mul") { return a * b; }
if (operation == "div") {
if (b == 0) { return "Error: division by zero"; }
return a / b;
}
}
}
Extern Skill — HTTP Binding
extern skill get_weather {
description: "Get weather"
params: { city: string }
binding: http {
method: "GET"
url: "https://wttr.in/{city}?format=j1"
headers: ["Accept: application/json"]
response_path: "/current_condition/0/weatherDesc/0/value"
timeout: 5000
}
}
Extern Skill — MCP Binding
mcp_server filesystem {
command: "npx"
args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/user"]
}
extern skill read_file {
description: "Read a file"
params: { path: string }
binding: mcp {
server: "filesystem"
tool: "read_file"
}
}
// Bulk import MCP tools
adopt filesystem.*;
adopt filesystem.{read_file, write_file} as fs_;
MCP Server Transports
// Stdio
mcp_server GitHub {
transport: "stdio"
command: "npx"
args: ["-y", "@modelcontextprotocol/server-github"]
env: { GITHUB_TOKEN: env("GITHUB_TOKEN") }
}
// SSE
mcp_server Postgres {
transport: "sse"
url: "http://localhost:3001/sse"
}
agent DevBot {
provider: "openai", model: "gpt-4o",
mcp_servers: [GitHub, Postgres]
}
Sensitive Skills
skill delete_record {
description: "Delete a record"
params: { id: string }
sensitive: true // requires user approval
impl(id) { return db_delete(id); }
}
Structured Output
agent SentimentBot {
provider: "openai", model: "gpt-4o-mini",
output_type: {
"sentiment": "string",
"confidence": "number",
"explanation": "string"
}
}
Guards, Policies, and Security
Guards
guard InputValidator {
description: "Validates input"
on_tool_input(input) {
if (string_length(input) == 0) { return "block"; }
if (string_length(input) > 10000) { return "block"; }
return input;
}
}
guard OutputSanitizer {
description: "Removes secrets from output"
on_tool_output(output) {
if (output.contains("sk-")) { return "[REDACTED]"; }
return output;
}
}
guardchain SecurityChain = [InputValidator, OutputSanitizer];
6 Guard Handler Types
| Handler | Trigger | Purpose |
|---|---|---|
on_observation |
User input received | Filter prompts |
on_action |
Agent produces output | Filter responses |
on_tool_input |
Before tool execution | Validate args |
on_tool_output |
After tool executes | Validate results |
on_tool_call |
Tool invocation | Control which tools run |
on_result |
Final output | Last-chance filter |
Return "block" to reject, modified string to transform, original to pass through.
Policy Declarations
policy StrictSecurity {
prompt_injection: "deny"
pii_detection: "redact"
max_input_length: 10000
max_output_length: 50000
allowed_domains: ["api.example.com", "wttr.in"]
blocked_patterns: ["ignore previous", "system:"]
}
agent SecureBot {
provider: "openai", model: "gpt-4o-mini",
policy: StrictSecurity,
guards: [SecurityChain],
budget: ProdBudget
}
Budgets
budget ProductionBudget {
api_calls: 1000
tokens: 5000000
cost_usd: 50.0
reset: "daily" // daily, hourly, weekly, monthly
}
// Inline budget
agent BudgetBot {
provider: "openai", model: "gpt-4o-mini",
budget: { max_daily_calls: 100, max_daily_cost: 5.0, max_daily_tokens: 50000 }
}
Environment Configuration
env Production {
API_URL: "https://api.prod.com",
DEBUG: "false",
API_KEY: env("PROD_API_KEY")
}
agent ProdAgent {
provider: "openai", model: "gpt-4o",
env: Production
}
Memory, World Model, Planning
memory ConversationMemory {
backend: "redis",
retention: "session",
max_events: 10000
}
world_model TaskWorld {
tier: 1,
state_schema: "task_state_v1",
update_frequency: 1000
}
plan HierarchicalPlanner {
pattern: "hierarchical",
max_depth: 5,
backtrack: true
}
agent StrategicAgent {
provider: "openai", model: "gpt-4o",
memory: ConversationMemory,
world_model: TaskWorld,
plan: HierarchicalPlanner
}
Checkpoint and Rewind
checkpoint "safe_point";
let result = risky_operation();
if (!result) { rewind "safe_point"; }
emit result;
Module System
module my.app.agents;
import std.list;
import std.math::{sqrt, abs};
import my.app.config as cfg;
pub fun public_helper() { } // exported
fun internal_helper() { } // private
crate fun package_only() { } // package-internal
// Re-export
pub use my.lib.agents;
neam.toml (Project Manifest)
neam_version = "1.0"
[project]
name = "my-agent"
version = "0.1.0"
type = "binary"
[project.entry_points]
main = "src/main.neam"
[dependencies]
utils = "1.0.0"
ai-tools = { git = "https://github.com/neam/ai-tools" }
[agent]
provider = "openai"
model = "gpt-4o-mini"
tracing = true
[agent.limits]
max-tokens-per-request = 4096
timeout-seconds = 300
max-retries = 3
[security]
prompt_injection = "deny"
pii_detection = "redact"
max_input_length = 10000
[deploy]
target = "kubernetes"
[deploy.kubernetes]
namespace = "production"
replicas = 3
Package Manager
neam-pkg init my-project
neam-pkg install <pkg>
neam-pkg install --git <url>
neam-pkg check
neam-pkg publish
neam-pkg update
Testing
test "addition works" {
assert_eq(2 + 3, 5);
}
test "string concat" {
assert_eq("Hello" + " World", "Hello World");
}
| Assertion | Description |
|---|---|
assert_eq(a, b) |
a == b |
assert_ne(a, b) |
a != b |
assert_true(cond) |
Truthy |
assert_false(cond) |
Falsy |
assert_throws(fn) |
Throws error |
assert_some(val) |
Not nil |
assert_none(val) |
Is nil |
assert_ok(result) |
Is Ok |
assert_err(result) |
Is Err |
Deployment
# Docker
neamc deploy --target docker
docker build -t my-agent -f build/deploy/docker/Dockerfile .
docker run -e OPENAI_API_KEY=$OPENAI_API_KEY my-agent
# Kubernetes
neamc deploy --target kubernetes --output ./deploy/
# AWS Lambda
neamc deploy --target aws-lambda --memory 512 --timeout 15 --arch arm64
# GCP Cloud Run
neamc deploy --target gcp-cloudrun --region us-central1
# ECS Fargate
neamc deploy --target ecs-fargate --output ./deploy/
# Terraform
neamc deploy --target terraform
# Dry run (preview manifests)
neamc deploy --target kubernetes --dry-run
Cloud Configuration (neam.toml)
[state]
backend = "postgres"
connection-string = "secret://DATABASE_URL"
[llm]
default-provider = "openai"
[llm.rate-limits.openai]
requests-per-minute = 500
[llm.circuit-breaker]
failure-threshold = 5
reset-timeout-seconds = 60
[llm.cache]
enabled = true
max-entries = 5000
ttl-seconds = 300
[llm.cost]
daily-budget-usd = 500.0
[llm.fallback-chain]
providers = ["openai", "anthropic"]
[telemetry]
enabled = true
endpoint = "http://otel-collector:4318"
service-name = "my-agent"
[secrets]
provider = "aws-secrets-manager"
State Backends
| Backend | Use Case |
|---|---|
| SQLite | Local development |
| PostgreSQL | Production multi-node |
| Redis | High-throughput |
| DynamoDB | AWS-native |
| CosmosDB | Azure-native |
| Firestore | GCP-native |
Built-in Functions
Core
len(value) // length of string/list/map
str(value) // any -> string
num(text) // string -> number
int(x) // truncate to integer
bool(x) // to boolean
typeof(value) // type name string
print(value) // debug output
emit(value) // final output
input(prompt) // read user input
json_parse(text) // parse JSON
json_stringify(value) // to JSON string
Math
math_abs(x) math_floor(x)
math_ceil(x) math_round(x)
math_min(a, b) math_max(a, b)
math_clamp(x, min, max) math_sqrt(x)
math_pow(base, exp) math_sin(x)
math_cos(x) math_tan(x)
math_asin(x) math_acos(x)
math_atan(x) math_atan2(y, x)
math_exp(x) math_log(x)
math_log10(x) math_cbrt(x)
math_random() math_random_int(min, max)
String
contains(haystack, needle) starts_with(text, prefix)
ends_with(text, suffix) index_of(haystack, needle)
substring(text, start, end) replace(text, old, new)
split(text, delim) join(list, sep)
trim(text) str_lower(text)
str_upper(text) str_repeat(text, n)
str_pad_left(text, w, ch) str_pad_right(text, w, ch)
List
list_push(list, val) list_pop(list)
list_slice(list, start, end) list_contains(list, val)
list_index_of(list, val) list_reverse(list)
list_sort(list) list_map(list, fn)
list_filter(list, fn) list_reduce(list, init, fn)
list_flat_map(list, fn) list_unique(list)
list_zip(a, b)
Map
map_keys(m) map_values(m)
map_has(m, key) map_remove(m, key)
map_merge(base, overlay) map_entries(m)
File I/O
file_read_string(path) file_write_string(path, content)
file_read_bytes(path) file_write_bytes(path, bytes)
file_exists(path) file_remove(path)
file_copy(src, dst) file_rename(old, new)
file_open(path, mode) // mode: "r"/"w"/"a"
HTTP
http_get(url)
http_request(options) // { method, url, headers, body }
Crypto
crypto_hash(algo, data) // "sha256"/"sha384"/"sha512"/"md5"
crypto_hmac(algo, key, data)
crypto_random_bytes(count)
crypto_uuid_v4()
crypto_base64_encode(data) crypto_base64_decode(encoded)
crypto_hex_encode(data) crypto_hex_decode(hex)
Time
clock() // seconds since VM start
time_now() // UTC ISO 8601
time_now_millis() // Unix ms
time_now_micros() // Unix us
time_sleep(ms)
time_parse(text, fmt) // -> Unix seconds
time_format(ts, fmt) // -> formatted string
Regex
regex_match(pattern, text) // -> bool
regex_find(pattern, text) // -> first match
regex_find_all(pattern, text) // -> all matches
regex_replace(pattern, text, rep) // -> replaced text
Environment
env_get(name) env_get_or(name, default)
env_has(name)
Async / Futures
future_resolve(value) future_reject(error)
future_all(futures) future_race(futures)
await_all(futures) future_delay(ms)
Workspace & Memory (NeamClaw)
workspace_read(path) workspace_write(path, content)
workspace_append(path, content)
memory_search(query, top_k) // -> [{file_path, chunk, score}]
session_history(key, limit) // -> [{role, content}]
Higher-Order Functions
map(list, fn) filter(list, fn)
fold(list, initial, fn) find(list, fn)
sort_by(list, fn) group_by(list, fn)
Standard Library Modules
import std.math::{sqrt, abs, pi};
import std.crypto::{sha256, uuid_v4};
import std.time::{now, sleep};
import std.io::{read_file, write_file};
import std.collections::{list, map, set};
import std.core::{Option, Result};
import std.data::{json, csv};
import std.net::{http};
import std.text::{regex, format};
import std.agents::{prompts, redteam};
import std.rag::{pipeline, error};
import std.testing::{assert, runner};
Common Patterns
Simple Q&A Bot
agent QABot {
provider: "openai", model: "gpt-4o-mini",
system: "Answer questions clearly."
}
emit QABot.ask(input());
RAG Document Bot
knowledge Docs {
vector_store: "usearch", embedding_model: "nomic-embed-text",
chunk_size: 200, chunk_overlap: 50,
sources: [{ type: "file", path: "./docs/" }]
}
agent DocBot {
provider: "openai", model: "gpt-4o-mini",
system: "Answer from documentation only.",
connected_knowledge: [Docs]
}
emit DocBot.ask(input());
Production Agent with Safety
guard SafetyGuard {
on_observation(input) {
if (input.contains("ignore previous")) { return "block"; }
return input;
}
on_tool_output(output) {
if (output.contains("sk-")) { return "[REDACTED]"; }
return output;
}
}
guardchain Safety = [SafetyGuard];
policy Strict {
prompt_injection: "deny"
pii_detection: "redact"
}
budget Prod { api_calls: 1000, tokens: 5000000, cost_usd: 50.0, reset: "daily" }
agent ProdBot {
provider: "openai", model: "gpt-4o-mini",
system: "Production assistant.",
guards: [Safety], policy: Strict, budget: Prod
}
Customer Support (Claw Agent)
channel cli { type: "cli" }
skill lookup_order {
description: "Look up order status"
params: { order_id: string }
impl(order_id) { return {"status": "shipped", "eta": "2026-02-20"}; }
}
claw agent Support {
provider: "openai", model: "gpt-4o-mini",
channels: [cli], skills: [lookup_order],
session: { idle_reset_minutes: 30, compaction: "auto" },
semantic_memory: { backend: "sqlite", search: "hybrid", top_k: 5 }
}
Code Builder (Forge Agent)
fun verify_tests(ctx) {
let result = exec("npm test 2>&1");
if (result.exit_code == 0) {
return VerifyResult.Done(f"Task '{ctx.current_task}' passed.");
}
if (ctx.iteration > 5) {
return VerifyResult.Abort("Too many retries.");
}
return VerifyResult.Retry(f"Tests failed:\n{result.stdout}");
}
forge agent CodeBuilder {
provider: "anthropic", model: "claude-sonnet-4",
verify: verify_tests,
skills: [write_file, read_file, run_command],
workspace: "./project",
loop { max_iterations: 30, max_cost: 12.0, plan_file: "plan.txt" },
checkpoint: "git"
}
Multi-Provider Routing
agent Triage {
provider: "openai", model: "gpt-4o-mini", temperature: 0.1,
system: "Classify: TECHNICAL, BILLING, or GENERAL."
}
agent TechBot {
provider: "openai", model: "gpt-4o",
system: "Senior technical support."
}
agent BillingBot {
provider: "gemini", model: "gemini-2.0-flash",
system: "Billing specialist."
}
fun route(query) {
let cat = Triage.ask(query);
if (cat.contains("TECHNICAL")) { return TechBot.ask(query); }
if (cat.contains("BILLING")) { return BillingBot.ask(query); }
return "General: " + query;
}
Key Rules
- Never hardcode API keys — use
api_key_env: "ENV_VAR"orenv("VAR") - Always add a budget to production agents
- Use
emitfor output,printfor debug - Use
constfor values that never change - One agent, one job — keep system prompts focused
- Add guards for any agent receiving user input
- Layer defenses — guards + policy + budget
- Use claw agents for conversational/session-based systems
- Use forge agents for iterative build/generation tasks
- Test agents independently before composing multi-agent systems
v1.0–v1.4: Platform Evolution
Neam's post-1.0 releases layer production, security, knowledge, research, and wiki capabilities on top of the v0.9.x agent core. All v1.x keywords are contextual — any prior program that used them as variable names still compiles unchanged.
Version Overview
| Version | Codename | Theme | New Keywords |
|---|---|---|---|
| v1.0 | — | OWASP security, cloud stack, Neam-Gym eval | 21 (10 OWASP ASI + 3 MCP + AIBOM + 4 cloud + 3 special agents) |
| v1.1 | NeamOS | Knowledge fabric, personas, governance, blueprints | 10 (4 card types + context_assembly, agent_persona, locale, governance_rule, agent_adapter, blueprint + 3 agents) |
| v1.2 | NeamProd | Plugins, sessions, evaluation, artifacts, streaming, A2A | 7 (plugin, session_service, eval_test, eval_set, artifact_store, stream_config, a2a_config) |
| v1.3 | NeamLab | Autonomous research agents | 4 (program, metric_extractor, research agent, experiment_loop) |
| v1.4 | NeamWiki | Compiled LLM wikis with USearch + knowledge graph | 2 (wiki, wiki agent) |
What's New in v1.0 — Security, Cloud, Evaluation
OWASP Agentic Security (ASI01–ASI10) — 10 compiled security constructs. All are declarations, not runtime calls; the compiler validates them at build time.
goal_integrity ChurnGoal { // ASI01: declared_objectives + drift detection
declared_objectives: ["predict churn", "identify drivers"],
verification: { method: "semantic_similarity", threshold: 0.75, on_drift: "halt_and_escalate" }
}
tool_validator StrictValidator { // ASI02: schema enforcement + rate limits + recursion
schema_enforcement: "strict", max_call_depth: 5, detect_cycles: true,
rate_limits: { per_agent: 100, per_phase: 50 }
}
agent_identity SecureID { // ASI03: ephemeral, scoped credentials
credential_mode: "ephemeral", ttl: "15m", rotation: "per_phase"
}
supply_chain_policy SecureChain { // ASI04: signing + pinning + AIBOM
agent_md_signing: { algorithm: "ed25519", reject_unsigned: true },
tool_pinning: { method: "sha256", block_on_change: true }
}
code_sandbox ForgeSandbox { // ASI05: container/wasm/gvisor isolation
runtime: "container",
network: { allow_outbound: false },
resources: { max_cpu: "1 core", max_memory: "512MB", max_time: "60s" }
}
memory_integrity MemGuard { // ASI06: sha256 + provenance
hash_algorithm: "sha256", verify_on_read: true, verify_on_write: true
}
message_security InterAgentSec { // ASI07: sign + encrypt inter-agent
signing: { algorithm: "ecdsa_p256", sign_all_messages: true, max_age: "60s" },
encryption: { algorithm: "aes_256_gcm" }
}
circuit_breaker AgentCB { // ASI08: failure containment
failure_threshold: 3, half_open_timeout: "30s",
isolation: { scope: "per_agent", fallback: "graceful_degrade" }
}
human_gate HighRiskApproval { // ASI09: human-in-loop for risky actions
approve_before: ["deploy", "delete"],
workflow: { channel: "slack", timeout: "15m", default_on_timeout: "deny" }
}
agent_attestation HealthCheck { // ASI10: self-reporting + kill switch
attest_interval: "5m",
kill_switch: { api_enabled: true, auto_kill_on: ["budget_exhausted", "goal_drift_detected"] }
}
MCP Security & AIBOM
mcp_allowlist ApprovedServers { servers: [{ url: "https://filesystem.example.com" }], block_unlisted: true }
tool_pinning ToolHashes { method: "sha256", pin_descriptions: true, block_on_change: true }
context_guard TaskIsolation { compartmentalize: true, cross_task_sharing: "none", purge_on_completion: true }
aibom_config BOM { format: "cyclonedx", version: "1.6", auto_generate: true, output: "./aibom.cdx.json" }
Evaluation — Gym Evaluator (7 modes)
gym_evaluator ChurnEval {
mode: "unit", // "unit" | "trajectory" | "rag" | "multi_agent" | "security" | "cost" | "arena"
agent: "./build/churn_agent.neamb",
dataset: "./eval/churn_test.jsonl",
graders: {
primary: "llm_judge",
judge: { provider: "openai", model: "gpt-4o-mini",
rubric: { correctness: { weight: 0.4, scale: "1-5" },
safety: { weight: 0.2, scale: "1-5" } } }
},
thresholds: { pass_rate: 0.85, exit_on_fail: true },
reproducibility: { repetitions: 5, seed: 42 }
}
Cloud Stack
gateway AgentAPI { // Managed entry point
auth: { method: "oauth2" },
rate_limit: { per_api_key: 1000, burst: 50 },
routes: { tasks: { handler: "TaskRouter", methods: ["POST"] } },
observability: { metrics: { format: "prometheus" }, tracing: { provider: "opentelemetry" } }
}
model_router SmartRouter { // Cost/quality/latency routing
strategy: "cost_optimized", // "cost_optimized" | "quality_first" | "latency_first"
routes: { simple: { provider: "anthropic", model: "claude-haiku-4-5" },
complex: { provider: "anthropic", model: "claude-opus-4-6" } },
fallback_chain: ["anthropic", "openai", "ollama"]
}
marketplace NeamSkillStore {
package_format: { manifest: "skill.neam.json", signature: "ed25519", integrity: "sha256" },
install_policy: { verify_signature: true, scan_for_vulnerabilities: true, sandbox_on_first_run: true }
}
Three new special agents (v1.0) — 2-keyword pattern:
securitysentinel agent Sentinel {
provider: "openai", model: "gpt-4o", budget: B,
monitors: { goal_integrity: { check: "per_phase" },
behavioral_anomaly: { check: "continuous", sigma: 3.0 } },
actions: { on_anomaly: "alert_and_log", on_critical: "kill_switch", on_breach: "halt_all_and_escalate" }
}
protocolbridge agent Bridge {
provider: "openai", model: "gpt-4o", budget: B,
protocols: { mcp: { servers: ["filesystem"], security: { verify_server_identity: true, sign_messages: true } },
a2a: { peers: [...], security: { mutual_tls: true, replay_protection: true } } },
firewall: { allowed_actions: ["read", "query"], blocked_actions: ["delete", "admin"] }
}
costguardian agent CostOps {
provider: "ollama", model: "llama3:8b", budget: B,
tracking: { per_agent: true, per_phase: true, per_model: true },
optimization: { model_downgrade: { enabled: true, condition: "budget_remaining < 20 percent" },
cache_responses: { enabled: true, ttl: "1h" } },
alerts: { budget_warning: 0.75, budget_critical: 0.90 }
}
What's New in v1.1 — Knowledge Fabric & Portable Blueprints
Knowledge Cards (4 types) — compiler-validated organizational knowledge:
knowledge_card CustomerChurn { // type: "concept"
type: "concept", term: "Customer Churn",
definition: "Inactive 90+ days with no login in 60+ days.",
domain: "telecom.customer.retention", version: "2.1.0",
owner: ChurnAnalyst, // cross-ref validated at compile time
provenance: { verified_by: "DomainExpert", last_reviewed: "2026-03-15" }
}
knowledge_card PIIPolicy { // type: "policy"
type: "policy", name: "PII Handling", scope: "all_agents",
rules: ["Mask PII before logging", "365-day retention max"],
enforcement: "runtime_guard", // "runtime_guard" | "compile_check" | "advisory"
regulatory_basis: ["PDPA", "GDPR"]
}
knowledge_card ModelChoice { // type: "decision"
type: "decision",
context: "Model selection for SEA markets",
decision: "XGBoost for batch, logistic for realtime",
decided_by: DSAgent, rationale: "AUC 0.89 vs 50ms SLA",
alternatives_considered: ["Random Forest — larger model"]
}
knowledge_card FEskill { // type: "skill"
type: "skill", skill_name: "Temporal Feature Engineering",
prerequisites: ["Sliding window aggregations"],
quality_expectations: ["<5% null rate"],
certification_required: true
}
Context Assembly — Minimum Viable Context (MVC) per agent/phase:
context_assembly ChurnFEContext {
target_agent: ChurnDS,
phase: "feature_engineering",
cards: [CustomerChurn, PIIPolicy, FEskill],
max_context_tokens: 4000,
assembly_strategy: "relevance_ranked", // | "chronological" | "priority"
fallback: "prioritize" // | "truncate" | "error"
}
Agent Persona & Locales — UI-level display + multilingual:
agent_persona SingtelPersona {
target_agent: SingtelAssistant,
display_name: "Singtel Assistant",
voice: { engine: "kokoro", voice_id: "en_singapore", speed: 1.0 },
personality: { helpfulness: 0.95, formality: 0.7 }, // all values 0.0-1.0
locales: {
"ms": { voice_id: "ms_amira", catchphr
…(truncated)