Home Docs GitHub npm
01 — Overview

What is Shingeki?

Shingeki is a distributed cognitive mesh for multi-agent AI systems. Multiple nodes collaborate to solve multi-step tasks in parallel, each node running its own genome (model + strategy), competing on quality, and evolving automatically when output falls below threshold.

Every decision is logged to 0G's tamper-proof storage so any participant can independently verify what ran, on what model, and with what result.

The Problem It Solves

Most AI agent frameworks run one LLM call after another on a single node with a static prompt. When quality drops, there is no recovery — the system just produces a bad answer. There is no competition, no evolution, and no on-chain proof.

Shingeki changes all three:

ProblemShingeki's Answer
Single point of failureMultiple nodes compete — best output wins
Static promptsGenome evolves when fitness score drops below threshold
No verificationEvery step TEE-attested via 0G Router + logged to 0G Log Store
Siloed agentsDistributed mesh — nodes run on separate machines

How It Compares

FrameworkArchitectureEvolutionVerified
LangChainSingle chain, single nodeStatic promptsNone
AutoGenAgent pairs, static rolesStaticNone
CrewAIFixed crew, sequentialStaticNone
ShingekiDistributed meshGenome-driven (live TEE scoring)TEE ✓ 0G Log
02 — Core Concepts

Core Concepts

Genome

Every agent node runs with a genome — a configuration object that defines its identity:

{
  id: 'genome-v1',
  model: 'qwen/qwen-2.5-7b-instruct',
  strategy: 'plan-execute-reflect',
  tools: ['web', 'uniswap'],
  reflection_depth: 2,
  mutation_rate: 0.2,
}

The genome starts from your agentmesh.yaml and mutates automatically when output quality drops below a configurable threshold. Every mutation is recorded to the lineage store and visible live in the browser viewer.

Plan

A task is broken into a sequence of steps, each tagged with a domain:

{
  taskId: 'task-1234',
  steps: [
    { id: 'task-1234-step-1', description: 'Research GPU options',  domain: 'research'  },
    { id: 'task-1234-step-2', description: 'Extract specs',         domain: 'research'  },
    { id: 'task-1234-step-3', description: 'Compare options',        domain: 'planning'  },
    { id: 'task-1234-step-4', description: 'Final recommendation',  domain: 'planning'  },
  ]
}

Domain tags drive routing — research steps go to research specialist nodes, planning steps to planning specialist nodes.

Competition

Step 1 of every plan runs on all available nodes in parallel. Each node produces a response, the fitness scorer evaluates all outputs, and the highest-scoring node's output chains into step 2. This is competition — quality selection before the work begins.

Round-Robin Routing (Steps 2–N)

After the competition step, subsequent steps route to domain-matched nodes in round-robin order with retry fallback. If a node fails, the orchestrator retries on the next available node.

Fitness Scoring — Two Paths

After every step, the output is evaluated by the fitness scorer:

Path A — Heuristic 0 tokens
Structural signals: response length, bullet points, numbers, tables, domain keywords. Fast, synchronous, no API call.
Path B — LLM Judge TEE
Only when heuristic score < threshold (~128 tokens). TEE-verified via 0G Router. Returns {score, reason}.

Genome Evolution

If the score is below threshold (default 0.55), the genome mutates before the next step. Mutations cycle through three axes:

  1. Prompt — adjust the system instruction strategy
  2. Model — switch to the next fallback model
  3. Strategy — change the reasoning strategy

Verification

Every step is:

  • TEE-attested — the 0G Router runs with verify_tee: true, producing a cryptographic trace
  • Logged on-chain — full input/output/TEE flag/rootHash submitted to the 0G Log Store
  • Checkpointed — atomic crash-recovery checkpoints let you resume any task after failure
03 — Getting Started

Getting Started

Prerequisites

  • Node.js >= 22
  • A ROUTER_API_KEY from pc.0g.ai → Dashboard → API Keys

Install

npm install shingeki

Set Your Environment Variables

Create a .env file:

# Required
ROUTER_API_KEY=sk-your-key-here

# Optional — enables on-chain logging to 0G Log Store + KV
PRIVATE_KEY=0xYourWalletPrivateKey
BLOCKCHAIN_RPC=https://evmrpc-testnet.0g.ai
INDEXER_RPC=https://indexer-storage-testnet-turbo.0g.ai
FLOW_CONTRACT=0x22e03a6a89b950f1c82ec5e74f8eca321a105296
KV_NODE_URL=http://3.101.147.150:6789

# Optional — DeFi preset
UNISWAP_API_KEY=your-uniswap-api-key
AGENT_WALLET=0xYourWalletAddress
Tip: Get testnet OG tokens from faucet.0g.ai if you want Log Store uploads to land on-chain.

Run the Demo

# GPU research — find the best GPU under $1000 for local LLMs
npx shingeki demo

# 5-day Japan trip planner under $1500
npx shingeki demo --preset japan

# DeFi swap analysis + Uniswap quote (needs UNISWAP_API_KEY)
npx shingeki demo --preset defi

# Run your own task
npx shingeki run --task "Compare the top 3 L2s for a DeFi app launch"

# Resume after crash
npx shingeki demo --resume task-1234567890

What You'll See

─── Shingeki run ───
Goal: Find the best GPU under $1000 for running local LLMs in 2026
Preset: gpu | local (in-process nodes)

Shingeki spawned 4 nodes: 2 research specialists, 2 planning specialists

[Orchestrator] Plan:
  1. Search GPUs     (executor [research])
  2. Extract specs   (executor [research])
  3. Compare         (critic   [planning])
  4. Recommend       (critic   [planning])

[Routing] Step 1 → PARALLEL node-1 + node-2
[node-1] calling 0G Compute (qwen/qwen-2.5-7b-instruct) — 3.3s
[node-2] calling 0G Compute (qwen/qwen-2.5-7b-instruct) — 3.3s
[Orchestrator] competition scores: node-1=0.85, node-2=0.85
[Orchestrator] winner → node-1

[Verification]
  Step 1 logged to 0G
  Trace ID   : 0xd7f342...
  Router TEE : true
  Eval score : 0.85 (heuristic)

[0G KV] genome checkpoint written version 1777808537684

─── Final synthesis ───
Recommendation: NVIDIA RTX 3060 — 12GB VRAM, 125W TDP, handles 7B and 13B models.
04 — Programmatic API

Programmatic API

Minimal Example — Run a Plan In-Process

import 'dotenv/config';
import { MeshOrchestrator, NodeRuntime, planResearchAnalyzeDecide } from 'shingeki';

const genome = {
  id: 'g1',
  model: 'qwen/qwen-2.5-7b-instruct',
  strategy: 'plan-execute-reflect',
  tools: ['web'],
  reflection_depth: 2,
  mutation_rate: 0.2,
};

const taskId = `task-${Date.now()}`;
const plan = planResearchAnalyzeDecide(taskId);

const nodes = [
  { id: 'node-1', capabilities: ['llm', 'research'], specialization: ['research'] },
  { id: 'node-2', capabilities: ['llm', 'planning'], specialization: ['planning'] },
];

const orch = new MeshOrchestrator(nodes);
let currentGenome = genome;

const results = await orch.executePlan(
  plan,
  async ({ node, step }) => {
    const runtime = new NodeRuntime({ nodeId: node.id }, currentGenome);
    return runtime.executeStep(step);
  },
  {
    log: (msg) => console.log(msg),
    onGenomeUpdate: (g) => { currentGenome = g; },
  },
);

console.log(results.at(-1)?.output);

Load Genome from YAML

import { genomeFromConfig } from 'shingeki';
import { parse } from 'yaml';
import { readFileSync } from 'node:fs';

const cfg = parse(readFileSync('agentmesh.example.yaml', 'utf8'));
const genome = genomeFromConfig(cfg, 'my-genome-v1');

agentmesh.example.yaml:

agent:
  name: research-agent
  strategy: plan-execute-reflect

genome:
  model: qwen/qwen-2.5-7b-instruct
  tools: [web, code]
  reflection_depth: 2
  mutation_rate: 0.2

mesh:
  min_nodes: 2

Split a Free-Form Task Into a Plan

import { splitCompoundTask } from 'shingeki';

const plan = splitCompoundTask(
  'task-001',
  'Research Ethereum L2s; Compare fees and TPS; Recommend the best one for a DeFi launch',
);

// Each step gets a domain tag automatically:
// step 1 → domain: 'research'
// step 2 → domain: 'planning'
// step 3 → domain: 'planning'

Use a Built-In Preset Plan

import {
  planResearchAnalyzeDecide,  // 4-step research + recommendation pipeline
  planJapanTrip,              // 6-step travel planner
  defiPlan,                   // 4-step DeFi swap analysis
} from 'shingeki';

const plan = defiPlan(`task-${Date.now()}`);

Evaluate Output and Evolve the Genome Manually

import { evaluateOutput, applyMutation } from 'shingeki';

const result = await evaluateOutput(stepOutput, taskContext, 0.55);
// result.score        — 0.0 to 1.0
// result.path         — 'heuristic' | 'llm'
// result.tee_verified — true when LLM judge path ran

if (result.score < 0.55) {
  const evolved = applyMutation(currentGenome);
  // evolved.id       — new genome id
  // evolved.model    — may have changed
  // evolved.strategy — may have changed
}

Resume After Crash

import {
  readCheckpoint,
  buildPriorContextFromResults,
  listCheckpointSummaries,
} from 'shingeki';

// List all saved tasks
const saved = await listCheckpointSummaries('.checkpoints');
console.log(saved.map(s => `${s.taskId} — step ${s.nextStepIndex}/${s.totalSteps}`));

// Resume a specific task
const checkpoint = await readCheckpoint('.checkpoints', 'task-1234567890');
if (checkpoint) {
  const priorContext = buildPriorContextFromResults(plan.steps, checkpoint.results);
  // pass priorContext into executePlan to continue from where it stopped
}
05 — Genome & Evolution

Genome & Evolution

Genome Fields

FieldTypeDescription
idstringUnique identifier, increments on mutation (genome-v1, v2, …)
modelstringLLM model name sent to 0G Router
strategystringReasoning strategy (e.g. plan-execute-reflect, chain-of-thought)
toolsstring[]Enabled tools: web, code, uniswap
reflection_depthnumberHow many reflection passes the node runs
mutation_ratenumberProbability weight for mutation selection

Fitness Scorer — Heuristic Path

Scores structural signals of the output text. Synchronous, zero tokens:

SignalMax Contribution
Response length ≥ 80 charsBase 0.2
Line count+0.02/line, max 0.25
Bullet points+0.04/bullet, max 0.20
Numbers / figures+0.02/number, max 0.15
Domain keywords (GPU specs, DeFi terms, travel)+0.03/match, max 0.20
Markdown tables+0.05/row, max 0.10

Fitness Scorer — LLM Judge Path

Triggered only when heuristic score < threshold (default 0.55). Sends the step output to 0G Router with verify_tee: true and receives {"{ score, reason }"}. The tee_verified flag is stored on the step result.

Mutation Axes

When a step scores below threshold, the genome mutates before the next step. Mutations cycle through three axes in order:

genome-v1 (score 0.42) → mutate prompt   → genome-v2
genome-v2 (score 0.48) → mutate model    → genome-v3
genome-v3 (score 0.51) → mutate strategy → genome-v4
genome-v4 (score 0.71) → promoted ✓
Prompt Mutation
Adjusts the system instruction to be more structured or precise
Model Mutation
Switches to the next fallback model from FALLBACK_MODELS list
Strategy Mutation
Changes the reasoning strategy string passed to the prompt builder
Lineage Recording
Every mutation appended to lineage store, visible live at /viewer

Lineage Store Entry

{
  genome_id: 'genome-v3',
  parent_id: 'genome-v2',
  model: 'meta-llama/llama-3.1-8b-instruct',
  strategy: 'chain-of-thought',
  fitness_score: 0.51,
  tee_verified: true,
  timestamp: 1746000000000,
  step_count: 3,
}

Exposed at GET /lineage on the hub and rendered live in the browser viewer at http://localhost:8765/viewer.

Configuring the Threshold

SHINGEKI_EVOLVE_THRESHOLD=0.60   # stricter — mutate more often
SHINGEKI_EVOLVE_THRESHOLD=0.40   # lenient  — only mutate on very poor output
06 — 0G Integration

0G Integration

Shingeki uses three 0G primitives: the Router for every LLM call, the Log Store for per-step execution traces, and the KV Store for genome checkpoints.

0G Router

Every LLM call goes through the 0G Router at router-api.0g.ai/v1. Two flags are always on:

  • verify_tee: true — validates TEE attestation server-side; returns tee_verified boolean
  • provider: {"{ sort: \"latency\" }"} — auto-selects the fastest available provider
const result = await routerInfer(prompt, systemPrompt, {
  model: genome.model,
  max_tokens: 1024,
  verify_tee: true,
  provider: { sort: 'latency' },
});

result.text                 // LLM response text
result.trace.tee_verified   // true | false

0G Log Store

After every completed step, the full execution trace is uploaded:

{
  step: 1,
  node: 'node-1',
  input: '...prompt...',
  output: '...response...',
  tee_verified: true,
  timestamp: 1746000000000,
  rootHash: '0xd7f342...',
}

The rootHash is content-addressed — anyone can verify the trace by hashing the payload and comparing to the on-chain rootHash.

0G KV Store

After the task completes, the final genome state is written to the KV Store as a checkpoint:

[0G KV] genome checkpoint written version 1777808537684

Setup for On-Chain Verification

PRIVATE_KEY=0xYourWalletPrivateKey
BLOCKCHAIN_RPC=https://evmrpc-testnet.0g.ai
INDEXER_RPC=https://indexer-storage-testnet-turbo.0g.ai
FLOW_CONTRACT=0x22e03a6a89b950f1c82ec5e74f8eca321a105296
KV_NODE_URL=http://3.101.147.150:6789
Note: Without PRIVATE_KEY, all LLM calls still run through the 0G Router with full TEE verification. Only Log Store and KV uploads are skipped.

0G Primitives Summary

PrimitiveEndpointUsed ForWhen
0G Routerrouter-api.0g.ai/v1Every LLM step + fitness judgeEvery plan step
TEE attestationvia Router verify_tee: trueProof of executionAlways on
0G Log Store@0gfoundation/0g-ts-sdkPer-step trace (append-only)After each step
0G KV Store@0gfoundation/0g-ts-sdkFinal genome stateAfter task completes
07 — Uniswap Integration

Uniswap Integration

Shingeki includes a first-class Uniswap Trade API integration. When 'uniswap' is in the genome's tool list, the NodeRuntime automatically detects embedded tool calls in LLM output and executes them — no manual wiring needed.

How It Works

The LLM embeds a JSON block in its response when a swap quote is relevant:

{
  "tool": "uniswap_quote",
  "tokenIn": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
  "tokenOut": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
  "amount": "1000000000000000000",
  "chainId": 1,
  "swapper": "0xYourWalletAddress"
}

Quote summary appended automatically to the step output:

**Uniswap Quote:**
routing=V3 | tokenIn=1.0 WETH | tokenOut=3,241.50 USDC | gas=$2.14 | priceImpact=0.03%

Enable the Uniswap Tool

# .env
UNISWAP_API_KEY=your-api-key-from-developers.uniswap.org
AGENT_WALLET=0xYourWalletAddress

// In your genome config
const genome = {
  id: 'g1',
  model: 'qwen/qwen-2.5-7b-instruct',
  strategy: 'plan-execute-reflect',
  tools: ['web', 'uniswap'],
  reflection_depth: 2,
  mutation_rate: 0.2,
};

Direct API Usage

import { getUniswapQuote, buildUniswapSwap, checkUniswapApproval } from 'shingeki';

// Step 1 — get a quote
const quote = await getUniswapQuote({
  tokenIn:  '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
  tokenOut: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
  amount:   '1000000000000000000',                        // 1 ETH in wei
  chainId:  1,
  swapper:  '0xYourWalletAddress',
  slippageTolerance: 0.5,
});

console.log(quote.routing);          // 'V3' | 'V4' | 'DUTCH_V2' | ...
console.log(quote.tokenOut.amount);  // USDC out amount
console.log(quote.gasFeeUSD);        // estimated gas cost in USD

// Step 2 — build the swap calldata
const tx = await buildUniswapSwap(quote);
console.log(tx.to);       // router contract address
console.log(tx.data);     // encoded calldata
console.log(tx.gasLimit); // estimated gas

// Step 3 — check approval
const approval = await checkUniswapApproval(
  quote.tokenIn.token, quote.tokenIn.amount, '0xYourWalletAddress', 1,
);
Routing Guard: Dutch order routing (DUTCH_V2, DUTCH_V3, PRIORITY) is blocked in the current release — requires off-chain order signing. Classic routing (V4, V3, V2) is fully supported.
08 — Distributed Mesh

Distributed Mesh

Run agent nodes across multiple machines. The orchestrator routes plan steps to whichever node has the right specialization, with automatic retry if a node fails.

Architecture

Hub (machine 1)
  ├── WebSocket server for workers + orchestrators
  ├── HTTP: /health /ready /metrics /status /lineage /viewer /api/run
  └── Lineage viewer (browser UI)

Worker A (machine 2) — research specialist
Worker B (machine 3) — planning specialist

Orchestrator (machine 4) — dispatches plan steps

Step 1 — Start the Hub

SHINGEKI_HUB_TOKEN=my-secret npx shingeki hub

# Custom port and bind address
SHINGEKI_HUB_PORT=9000 SHINGEKI_HUB_HOST=0.0.0.0 npx shingeki hub

The hub starts on port 8765 by default. The genome lineage viewer opens automatically at http://localhost:8765/viewer.

Step 2 — Start Worker Nodes

# Worker A — research specialist
NODE_ID=node-1 \
NODE_ROLE=executor \
NODE_SPECIALIZATION=research \
SHINGEKI_HUB_URL=ws://hub-host:8765 \
SHINGEKI_HUB_TOKEN=my-secret \
npx shingeki node

# Worker B — planning specialist
NODE_ID=node-2 \
NODE_ROLE=reasoning \
NODE_SPECIALIZATION=planning \
SHINGEKI_HUB_URL=ws://hub-host:8765 \
SHINGEKI_HUB_TOKEN=my-secret \
npx shingeki node

Step 3 — Run a Task Against the Mesh

SHINGEKI_HUB_URL=ws://hub-host:8765 \
SHINGEKI_HUB_TOKEN=my-secret \
npx shingeki demo --mesh

Submit via HTTP

curl -X POST http://hub-host:8765/api/run \
  -H "Authorization: Bearer my-secret" \
  -H "Content-Type: application/json" \
  -d '{ "task": "Compare the top 3 Ethereum L2s", "mesh": true }'

Hub HTTP Endpoints

EndpointMethodDescription
/healthGET{"{ \"ok\": true }"}
/readyGET{"{ \"ready\": true }"} when minimum workers connected
/metricsGETPrometheus text format
/statusGETJSON snapshot — worker list, lineage count
/lineageGETFull genome lineage array
/viewerGETSelf-contained browser lineage viewer
/checkpointsGETList task checkpoint summaries
/checkpoint?id=task-…GETSingle checkpoint JSON
/api/runPOSTSubmit a task, returns step results

Node Roles & Specializations

RoleDescription
executorResearch and data-gathering
criticEvaluates, compares, recommends
reasoningPlanning and multi-step analysis
memoryContext aggregation
generalHandles any step type
SpecializationBest for
researchWeb search, fact extraction
planningStrategy, recommendation
codingCode generation, debugging
defiDeFi analysis, token routing

Production Security

NODE_ENV=production
SHINGEKI_HUB_TOKEN=a-strong-random-secret
SHINGEKI_HUB_STRICT_HTTP_AUTH=1
SHINGEKI_HUB_TLS_CERT=/path/to/fullchain.pem
SHINGEKI_HUB_TLS_KEY=/path/to/privkey.pem
09 — AXL P2P Transport

AXL P2P Transport

AXL replaces the WebSocket hub with broker-free peer-to-peer transport via the Gensyn AXL sidecar. No central hub process is needed — workers and orchestrators discover and communicate directly.

WebSocket Hub vs AXL P2P

WebSocket HubAXL P2P
Setup complexityLow — one hub processMedium — sidecar on each machine
Central brokerYesNo
Best forLocal dev, single datacenterMulti-region, decentralised
Requiresnpm run hubGensyn AXL sidecar binary

Enable AXL

AXL_ENABLED=true                    # use AXL instead of WebSocket
AXL_API_URL=http://127.0.0.1:9002   # AXL sidecar URL (default)

Start Hub with AXL

AXL_ENABLED=true npx shingeki hub
# Prints: AXL peer ID: 12D3Koo...

Start Workers with AXL

AXL_ENABLED=true \
AXL_HUB_PEER_ID=12D3Koo... \
NODE_ID=node-1 \
NODE_SPECIALIZATION=research \
npx shingeki node

Programmatic AXL Usage

import {
  createAxlTransport, runAxlWorkerHost,
  runAxlOrchestratorSession, createAxlStepExecutor,
} from 'shingeki';

const axl = createAxlTransport('http://127.0.0.1:9002');
const identity = await axl.getIdentity();
console.log(identity.peerId);

// Start a worker
await runAxlWorkerHost({
  axl, hubPeerId: 'hub-peer-id',
  nodeId: 'node-1', specialization: ['research'], genome,
});

// Start an orchestrator session
const session = await runAxlOrchestratorSession({
  axl, workerPeerIds: ['worker-1-peer-id', 'worker-2-peer-id'],
});
const executor = createAxlStepExecutor(session);

AXL Message Protocol

MessageDirectionPayload
NODE_JOINWorker → Hub/Orch{"{ nodeId, role, specialization }"}
ORCH_JOINOrchestrator → Workers{"{ orchestratorPeerId }"}
ORCH_WORKERSHub → Orchestrator{"{ workers: NodeCapabilities[] }"}
TASK_ASSIGNOrchestrator → Worker{"{ step, priorContext }"}
STEP_RESULTWorker → Orchestrator{"{ stepId, output, latencyMs, teeTrace }"}
HEARTBEATWorker → Hub{}
HEARTBEAT_ACKHub → Worker{}
10 — Lineage Viewer

Lineage Viewer

The lineage viewer is a self-contained browser UI that renders the genome mutation tree in real time. It opens automatically when the hub starts.

What It Shows

Genome Tree
parent → child arrows showing which genome mutated into which
Fitness Bars
Score for each genome version at the step it was promoted or rejected
TEE Badges
Which evaluations were verified by the LLM judge with TEE attestation
Live Updates
Polls /lineage every 3 seconds — no page refresh needed

Lineage API

curl http://localhost:8765/lineage

[
  {
    "genome_id": "genome-v1",
    "parent_id": null,
    "model": "qwen/qwen-2.5-7b-instruct",
    "strategy": "plan-execute-reflect",
    "fitness_score": 0.85,
    "tee_verified": false,
    "timestamp": 1746000000000,
    "step_count": 1
  },
  {
    "genome_id": "genome-v2",
    "parent_id": "genome-v1",
    "model": "meta-llama/llama-3.1-8b-instruct",
    "strategy": "plan-execute-reflect",
    "fitness_score": 0.42,
    "tee_verified": true,
    "timestamp": 1746000010000,
    "step_count": 2
  }
]

Programmatic Lineage Access

import { MeshHub } from 'shingeki';

const hub = new MeshHub({ port: 8765 });
await hub.listen();

const lineage = hub.getLineage();
lineage.forEach(entry => {
  console.log(`${entry.genome_id} → score ${entry.fitness_score} (tee: ${entry.tee_verified})`);
});
11 — Environment Variables

Environment Variables

Required

VariableDescription
ROUTER_API_KEYRequired. From pc.0g.ai → Dashboard → API Keys

0G On-Chain Verification

VariableDescription
PRIVATE_KEYWallet private key — enables 0G Log Store + KV uploads
BLOCKCHAIN_RPCEVM RPC URL. Testnet: https://evmrpc-testnet.0g.ai
INDEXER_RPC0G indexer URL. Testnet: https://indexer-storage-testnet-turbo.0g.ai
FLOW_CONTRACT0G Flow contract. Testnet: 0x22e03a6a89b950f1c82ec5e74f8eca321a105296
KV_NODE_URL0G KV node. Testnet: http://3.101.147.150:6789
ROUTER_BASE_URLOverride Router URL

Genome / Evolution

VariableDefaultDescription
SHINGEKI_EVOLVE_THRESHOLD0.55Fitness below this triggers genome mutation
SHINGEKI_AGENTMESH_CONFIGagentmesh.example.yamlPath to custom genome YAML config

Hub

VariableDefaultDescription
SHINGEKI_HUB_PORT8765Hub WebSocket + HTTP port
SHINGEKI_HUB_HOST0.0.0.0Hub bind address
SHINGEKI_HUB_TOKENShared secret — required in production
SHINGEKI_HUB_STRICT_HTTP_AUTH1 → enforce Bearer on all requests
SHINGEKI_HUB_TLS_CERTPath to TLS certificate
SHINGEKI_HUB_TLS_KEYPath to TLS key
SHINGEKI_HUB_READY_MIN_WORKERS2Min workers for /ready to return true
SHINGEKI_HUB_URLws://localhost:8765Hub URL for workers and orchestrators

Worker

VariableDefaultDescription
NODE_IDrandom UUIDWorker identity
NODE_ROLEgeneralexecutor | critic | reasoning | memory | general
NODE_SPECIALIZATIONComma-separated: research,planning,coding,defi

Uniswap

VariableDescription
UNISWAP_API_KEYFrom developers.uniswap.org
AGENT_WALLETWallet address used as swapper in Uniswap quote requests

AXL P2P

VariableDefaultDescription
AXL_ENABLEDfalsetrue → use AXL P2P instead of WebSocket hub
AXL_API_URLhttp://127.0.0.1:9002AXL sidecar base URL
AXL_HUB_PEER_IDHub peer ID (workers need this)
AXL_WORKER_PEER_IDSComma-separated worker peer IDs

Checkpoints & Logging

VariableDefaultDescription
SHINGEKI_CHECKPOINT_DIR.checkpoints/Directory for crash-recovery checkpoints
LOG_LEVELinfodebug | info | warn | error
LOG_PRETTY1 → human-readable logs instead of JSON lines
12 — API Reference

Full API Reference

Install: npm install shingeki  ·  npmjs.com/package/shingeki

MeshOrchestrator

import { MeshOrchestrator } from 'shingeki';

const orch = new MeshOrchestrator(nodes);

await orch.executePlan(plan, stepExecutor, options);
// options.log             — (msg: string) => void
// options.onGenomeUpdate  — (genome: Genome) => void
// options.nextStepIndex   — resume from this step (default 0)
// options.priorResults    — prior results for resume

NodeRuntime

import { NodeRuntime } from 'shingeki';

const runtime = new NodeRuntime({ nodeId: 'node-1' }, genome);
const result = await runtime.executeStep(step);
// result.stepId     — string
// result.nodeId     — string
// result.output     — LLM response text (+ Uniswap quote if tool triggered)
// result.latencyMs  — number
// result.teeTrace   — 0G Router trace object
// result.evalResult — EvaluationResult after scoring

Genome Functions

import { genomeFromConfig, evaluateOutput, heuristicScore, applyMutation, mutateGenome } from 'shingeki';

genomeFromConfig(config, id?)       // AgentMeshConfig → Genome
evaluateOutput(output, ctx?, thr?)  // string → Promise<EvaluationResult>
heuristicScore(output)              // string → number (0–1), synchronous
applyMutation(genome)               // Genome → Genome (one axis mutated)
mutateGenome(genome)                // Genome → Genome[] (all 3 variants)

Coordination — WebSocket

import {
  MeshHub, runWorkerHost,
  openOrchestratorSession, createMeshStepExecutor, hubUrlFromEnv,
} from 'shingeki';

new MeshHub({ port, token?, tlsCert?, tlsKey? })
hub.listen()                     // → Promise<void>
hub.close()
hub.getLineage()                 // → LineageEntry[]

runWorkerHost({ hubUrl, token?, nodeId, role, specialization, genome })
openOrchestratorSession(url, token?)   // → Promise<WebSocket>
createMeshStepExecutor(ws)             // → StepExecutor
hubUrlFromEnv()                        // reads SHINGEKI_HUB_URL

Coordination — AXL P2P

import {
  createAxlTransport, runAxlWorkerHost,
  runAxlOrchestratorSession, createAxlStepExecutor,
} from 'shingeki';

createAxlTransport(apiUrl)
axl.getIdentity()                  // → Promise<AxlIdentity>
axl.send(peerId, data)
axl.recv()                          // → Promise<AxlMessage | null>
axl.recvWait(timeoutMs)             // → Promise<AxlMessage>
axl.isReady()                       // → Promise<boolean>

Uniswap Tools

import { getUniswapQuote, buildUniswapSwap, checkUniswapApproval } from 'shingeki';

getUniswapQuote(params)                               // → Promise<UniswapQuoteResult>
buildUniswapSwap(quote)                               // → Promise<UniswapSwapTx>
checkUniswapApproval(token, amount, wallet, chainId)  // → Promise<UniswapSwapTx | null>

Plans / Presets

import {
  planResearchAnalyzeDecide,  // 4-step research + recommendation pipeline
  planJapanTrip,              // 6-step travel planner
  defiPlan,                   // 4-step DeFi swap analysis
  splitCompoundTask,          // infers steps + domains from free-form text
  planToRequiredRoles,        // → NodeCapability[] (nodes the plan needs)
} from 'shingeki';

Infrastructure

import {
  writeCheckpointAtomic, readCheckpoint, listCheckpointSummaries,
  buildPriorContextFromResults, createLogger,
} from 'shingeki';

writeCheckpointAtomic(dir, checkpoint)       // → Promise<void>
readCheckpoint(dir, taskId)                  // → Promise<DemoCheckpoint | null>
listCheckpointSummaries(dir)                 // → Promise<CheckpointSummary[]>
buildPriorContextFromResults(steps, results) // → string
createLogger(component)                      // → Logger

TypeScript Types

import type {
  Genome,               // { id, model, strategy, tools, reflection_depth, mutation_rate }
  AgentMeshConfig,      // shape of agentmesh.yaml
  Plan,                 // { taskId, steps }
  Step,                 // { id, description, domain?, role?, title? }
  StepResult,           // { stepId, nodeId, output, latencyMs, teeTrace?, evalResult? }
  EvaluationResult,     // { score, path, reason?, tee_verified? }
  LineageEntry,         // { genome_id, parent_id, model, strategy, fitness_score, ... }
  NodeCapability,       // { id, capabilities, specialization?, role? }
  NodeCapabilities,     // { role, latency_ms, cost_weight, specialization }
  MeshMessage,          // { type: CoordinationEventType, payload }
  UniswapQuoteParams,   // getUniswapQuote input
  UniswapQuoteResult,   // getUniswapQuote output
  UniswapSwapTx,        // { to, data, value, gasLimit }
  DemoCheckpoint,       // checkpoint file shape
  CheckpointSummary,    // list entry shape
} from 'shingeki';