Skip to content

z-tejani/Tricom

Repository files navigation

TriCom — Balanced Ternary AI Communication Protocol

Go Report Card Go Version License: MIT

GitHub: https://github.com/z-tejani/tricom

TriCom is a high-efficiency communication protocol and broker for AI-to-AI messaging, built on balanced ternary (base-3 with digits −1, 0, +1). It achieves 3× to 11× compression over JSON and operates at 99.06% of the Shannon theoretical maximum for a ternary system.


Why Balanced Ternary?

Binary was designed for electronics (on/off). AI reasoning is inherently probabilistic and three-valued: yes (+1), no (−1), uncertain (0). TriCom gives AI agents a communication medium that matches how they actually think.

Message Type JSON JSON+gzip TriCom Savings
Heartbeat 136 B 113 B 12 B 91%
Simple Confirmation 125 B 110 B 21 B 83%
Error Signal 140 B 120 B 27 B 81%
Delegation + Data 175 B 141 B 80 B 54%

Quick Start

Option 1: Run the broker

git clone https://github.com/z-tejani/tricom.git
cd tricom
go build -o tricom ./cmd/tricom/
./tricom serve --config tricom.toml

Option 2: Use the codec library

import "github.com/z-tejani/tricom/codec"

msg := codec.NewTextMessage(
    codec.IntentConfirm,  // intent
    0.95,                 // confidence
    codec.ScopeGlobal,    // scope: broadcast to all agents
    "Task complete",      // payload
    1,                    // agentID
)

data, err := msg.Encode()          // → compact binary bytes
decoded, err := codec.Decode(data) // → TriMessage struct

fmt.Println(decoded.Intent)        // "CONFIRM"
fmt.Println(decoded.Confidence)    // 0.9505
fmt.Println(decoded.PayloadText()) // "Task complete"

Deployment

Prerequisites

  • Go 1.22 or later
  • (Optional) API keys for Claude, OpenAI, Gemini
  • (Optional) Ollama for local model support

1. Build

git clone https://github.com/z-tejani/tricom.git
cd tricom
go mod tidy
go build -o tricom ./cmd/tricom/

2. Configure

Copy and edit the example config:

# tricom.toml

[broker]
port         = 7430
max_sessions = 1000
session_ttl  = "10m"
pool_size    = 20

[adapter.claude]
api_key = "${ANTHROPIC_API_KEY}"
model   = "claude-sonnet-4-5"
timeout = "30s"

[adapter.openai]
api_key = "${OPENAI_API_KEY}"
model   = "gpt-4o"
timeout = "30s"

[adapter.gemini]
api_key = "${GEMINI_API_KEY}"
model   = "gemini-1.5-flash"
timeout = "30s"

[adapter.ollama]
host    = "localhost:11434"
model   = "llama3"
timeout = "60s"

[log]
level  = "info"    # debug | info | warn | error
format = "json"    # json | text

API keys are read from environment variables using ${VAR} syntax — they are never stored in the config file.

3. Run

# Set API keys
export ANTHROPIC_API_KEY=sk-ant-...
export OPENAI_API_KEY=sk-...
export GEMINI_API_KEY=...

# Start the broker
./tricom serve --config tricom.toml

# Verify adapters are up
./tricom adapters list

4. Send a message

# Send a delegation task to Claude
./tricom send \
  --to claude \
  --intent DELEGATE \
  --confidence 0.9 \
  --payload "Summarise the following and return key points: ..."

# Encode a message to binary (piped to file or network)
./tricom encode --intent CONFIRM --confidence 0.95 --payload "done" > msg.tricom

# Decode binary back to human-readable
./tricom decode < msg.tricom

Running with Docker

FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o tricom ./cmd/tricom/

FROM alpine:latest
COPY --from=builder /app/tricom /usr/local/bin/tricom
EXPOSE 7430
CMD ["tricom", "serve", "--config", "/etc/tricom/tricom.toml"]
docker build -t tricom .
docker run -p 7430:7430 \
  -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \
  -v $(pwd)/tricom.toml:/etc/tricom/tricom.toml \
  tricom

HTTP API Reference

Method Path Description
POST /v1/send Send a TriCom message. Body: raw TriCom bytes or JSON with ?format=json. Optional ?target=<adapter> and ?session_id=<id>.
POST /v1/session Create a session. Body: {"agents": ["claude", "ollama"]}. Returns {"session_id": "..."}.
GET /v1/session/{id} Session info: agents, message count, age.
DELETE /v1/session/{id} Terminate session.
GET /v1/adapters List all registered adapters and their capabilities.
GET /v1/health Per-adapter health check. Returns 503 if any adapter is down.
GET /v1/metrics Prometheus-format counters.
GET /v1/ws WebSocket endpoint. Query params: ?agent_id=<id>&session_id=<sid>.

Message scopes

Scope Value Behaviour
local -1 Route to the single named adapter
chain 0 Route to adapter, then forward response to next in session chain
global +1 Fan out to all registered adapters concurrently

Project Structure

tricom/
├── codec/                ← Core library (zero external dependencies)
│   ├── trit.go           ← Trit type: Neg(-1), Zero(0), Pos(+1)
│   ├── bt.go             ← Balanced ternary arithmetic
│   ├── pack.go           ← 5-trits-per-byte packing (99.06% efficient)
│   ├── vocab.go          ← 10-word semantic vocabulary
│   ├── message.go        ← Message encode/decode
│   └── codec_test.go     ← 40+ unit tests, benchmarks, fuzz targets
├── adapter/              ← Adapter interface + shared intent→prompt map
│   ├── mock/             ← In-memory mock adapter (for tests)
│   ├── claude/           ← Anthropic Claude (ANTHROPIC_API_KEY)
│   ├── openai/           ← OpenAI GPT-4o (OPENAI_API_KEY)
│   ├── gemini/           ← Google Gemini (GEMINI_API_KEY)
│   └── ollama/           ← Local Ollama (no auth)
├── broker/               ← Central router: sessions, scope routing, HTTP + WS API
├── config/               ← TOML config loader with ${ENV_VAR} interpolation
├── cmd/tricom/           ← CLI binary
├── scripts/              ← Python cross-verification tools
└── Makefile

Vocabulary

Intent Trit Pattern Meaning
CONFIRM + + 0 0 0 0 Task complete / agreement
DENY - - 0 0 0 0 Negation / disagreement
UNCERTAIN 0 0 0 0 0 0 Unknown / needs more info
REQUEST + 0 + 0 0 0 Ask agent to perform action
RESPOND + 0 - 0 0 0 Reply to a request
DELEGATE 0 + + 0 0 0 Pass task to next agent
ABORT - 0 - 0 0 0 Stop current operation
ESCALATE 0 0 + + 0 0 Requires higher attention
COMPLETE + + + 0 0 0 All subtasks finished
ERROR - - - 0 0 0 Unrecoverable failure

CONFIRM/DENY and COMPLETE/ERROR are exact balanced ternary opposites — a mathematical property, not a design choice.


Wire Format

[2: version][4: agent_id][6: intent][6: confidence][1: scope][8: payload_len][N: payload]
 ─────────────────────── 27 trits fixed header = 6 bytes ────────────────────
  • Version: 2 trits → supports v0–v4
  • Agent ID: 4 trits → range ±40
  • Intent: 6 trits → one vocabulary word (729 possible slots, 10 used)
  • Confidence: 6 trits → float [0.0, 1.0] at 0.14% resolution
  • Scope: 1 trit → local / chain / global
  • Payload: each byte encoded as 6 trits

Development

# Run all tests
make test

# Run benchmarks (3 iterations each)
make bench

# Fuzz pack/unpack roundtrip for 30s
make fuzz-pack

# Generate Python reference output and cross-verify
make verify

# Run go vet
make vet

Running tests

go test ./... -count=1      # all 82 tests
go test ./codec/... -v      # codec tests verbose
go test ./broker/... -v     # broker + HTTP API tests

API-key-gated adapter tests skip automatically when the relevant environment variable is not set.


Technical Details

Property Value
Packing scheme 5 trits per byte (3⁵ = 243 ≤ 256, offset +121)
Packing efficiency 99.06% of Shannon theoretical maximum
Confidence precision ±0.14% (6 fractional trits)
Codec dependencies Zero (stdlib only)
Go version 1.22+
Cross-verified Python reference → byte-identical output

Contributing

Pull requests are welcome at https://github.com/z-tejani/tricom.

  1. Fork the repo and create a feature branch
  2. Add tests for new functionality
  3. Run make test && make vet before opening a PR
  4. API-key-gated tests must call t.Skip() when the key is absent

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors