AgentSkillsCN

nex-codebase-navigation

导航并索引 NATS NEX 代码库。重点代码路径、文件结构与架构概览。

SKILL.md
--- frontmatter
name: nex-codebase-navigation
description: Navigate and index the NATS NEX codebase. Key codepaths, file structure, and architecture overview.
triggers:
  - "NEX codebase"
  - "NEX source"
  - "NEX architecture"
  - "nex code"
  - "synadia-io/nex"
  - "NEX internals"

NEX Codebase Navigation

Overview

NEX (NATS Execution Engine) is a workload deployment and execution system built on NATS. This skill indexes the codebase structure for efficient navigation.

Repository Structure (synadia-io/nex)

Top-Level Directories

DirectoryPurposeKey Files
cmd/nex/CLI entry pointmain.go, node.go, workload.go
client/Go client libraryclient.go, options.go
node/NexNode implementationnode.go, handlers.go, minter.go
agent/Agent interface + SDKagent.go
models/Shared data modelsevents.go, subjects.go, nexfile.go
natsext/NATS utilitiesrequestmany.go
_test/Test fixturesnexlet_inmem/inmemagent.go
docs/DocumentationArchitecture guides

Key Codepaths

1. CLI → Workload Deployment

code
cmd/nex/main.go           # Entry point, Kong CLI parsing
  └─ cmd/nex/workload.go  # `nex workload start` handler
       └─ client/client.go
            ├─ Auction()           # Bid for workload placement
            └─ StartWorkload()     # Deploy to winning bidder

Key functions:

  • client.Auction() - Broadcasts auction request, collects bids
  • client.StartWorkload() - Sends deployment request to selected node

2. Node Startup + Agent Registration

code
node/node.go: NewNexNode()     # Create node with identity
  └─ node/node.go: Start()     # Start NATS handlers
       └─ node/handlers.go     # NATS microservice endpoints
            ├─ handleAuction()              # Respond to auction requests
            ├─ handleAuctionDeployWorkload() # Mint creds + deploy
            └─ handleAgentRegister()        # Accept agent registration

Key functions:

  • NewNexNode() - Initializes node with config, identity keys
  • Start() - Registers NATS micro handlers, starts heartbeat
  • handleAuction() - Evaluates auction request, returns bid
  • handleAuctionDeployWorkload() - Mints credentials, deploys to agent

3. Agent Lifecycle

code
agent/agent.go: Agent interface   # 9 required methods
  └─ Register()                   # Declare capabilities
  └─ StartWorkload()              # Deploy + emit WorkloadStartedEvent
  └─ StopWorkload()               # Terminate + emit WorkloadStoppedEvent
  └─ Heartbeat()                  # Report health every 30s

_test/nexlet_inmem/inmemagent.go  # Reference implementation

Agent interface methods:

go
type Agent interface {
    // Lifecycle
    Start(ctx context.Context) error
    Stop() error

    // Registration
    Register(parentId string) error
    AgentID() string

    // Workload management
    StartWorkload(request *StartWorkloadRequest) (*WorkloadInfo, error)
    StopWorkload(workloadId string) error
    ListWorkloads() ([]WorkloadInfo, error)

    // Health
    Heartbeat() AgentHeartbeat
}

4. Credential Minting

code
node/minter.go: SigningKeyMinter
  └─ Mint()                       # Create JWT with scoped permissions
       └─ WorkloadClaims()        # Pub: _INBOX.>, Sub: logs.{ns}.>, _INBOX.>

Workload permissions (scoped JWT):

  • Publish: _INBOX.> (request-reply responses)
  • Subscribe: logs.{namespace}.>, _INBOX.> (requests)
  • Response limit: 1 message per request

File Quick Reference

Need to...FileFunction/Type
Understand CLI commandscmd/nex/*.goKong command structs
See client SDK methodsclient/client.goClient struct
Implement custom agentagent/agent.goAgent interface
Find event typesmodels/events.go*Event structs
See NATS subjectsmodels/subjects.goSubject constants
Check Nexfile formatmodels/nexfile.goNexfile struct
Understand auctionnode/handlers.gohandleAuction()
See credential mintingnode/minter.goSigningKeyMinter

Architecture Diagram

code
┌─────────────────────────────────────────────────────────────────────┐
│                         NEX Architecture                             │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────────────────┐  │
│  │   Client    │───▶│  NexNode    │───▶│   Agent (Nexlet)        │  │
│  │  (CLI/SDK)  │    │  (Host)     │    │   (Runtime Executor)    │  │
│  └─────────────┘    └─────────────┘    └─────────────────────────┘  │
│        │                  │                       │                  │
│        │    1. Auction    │    2. Deploy          │    3. Execute    │
│        ▼                  ▼                       ▼                  │
│  ┌─────────────────────────────────────────────────────────────────┐│
│  │                    NATS Messaging Fabric                         ││
│  │  $NEX.SVC.<namespace>.control.*  (auction, deploy)               ││
│  │  $NEX.FEED.<namespace>.event.*   (lifecycle events)              ││
│  │  $NEX.FEED.<namespace>.logs.*    (workload logs)                 ││
│  └─────────────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────────┘

NATS Subjects

Control Plane (Request-Reply)

SubjectPurposeHandler
$NEX.SVC.<ns>.control.AUCTIONWorkload placement auctionhandleAuction()
$NEX.SVC.<ns>.control.AUCTIONDEPLOY.<bid>Deploy to winning bidderhandleAuctionDeployWorkload()
$NEX.SVC.<ns>.workloads.LISTList running workloadshandleListWorkloads()
$NEX.SVC.<ns>.workloads.STOPStop a workloadhandleStopWorkload()
$NEX.SVC.<ns>.nodes.INFOGet node informationhandleNodeInfo()
$NEX.SVC.<ns>.agents.REGISTERAgent registrationhandleAgentRegister()

Data Plane (Pub/Sub)

SubjectPurposePayload
$NEX.FEED.<ns>.event.*Lifecycle events*Event structs
$NEX.FEED.<ns>.logs.<wid>.outWorkload stdoutRaw bytes
$NEX.FEED.<ns>.logs.<wid>.errWorkload stderrRaw bytes
$NEX.FEED.<ns>.metrics.<wid>Workload metricsJSON metrics

deepwiki Queries

Use deepwiki MCP for detailed exploration:

typescript
// Get wiki structure
mcp__deepwiki__read_wiki_structure({ repoName: "synadia-io/nex" })

// Ask about specific components
mcp__deepwiki__ask_question({
  repoName: "synadia-io/nex",
  question: "How does the auction system work?"
})

// Explore agent interface
mcp__deepwiki__ask_question({
  repoName: "synadia-io/nex",
  question: "What methods must an agent implement?"
})

// Understand credential minting
mcp__deepwiki__ask_question({
  repoName: "synadia-io/nex",
  question: "How are workload credentials scoped?"
})

Wiki Pages Index

SectionTopicKey Concepts
1IntroductionOverview, use cases
2Getting StartedInstallation, quickstart
3Core ConceptsNodes, Agents, Workloads
4System ArchitectureComponent, Node, Agent arch
5NexNodeLifecycle, Handlers, Config, Auction
6AgentsInterface, Native, Lifecycle, Custom
7WorkloadsTypes, Deployment, Nexfile
8Client LibraryNode Ops, Workload Ops
9CLI ToolConfig, Node Commands, Workload Commands
10SecurityCredentials, JWT, Secrets
11Data ModelsSchemas, Events
12DevelopmentBuild, Test, Debug

Workload Lifecycles

LifecycleBehaviorAuto-restartUse Case
serviceLong-runningYes (on failure)API servers, processors
jobRun-to-completionNoBatch tasks, migrations
functionEvent-triggeredPer-invocationWebhooks, transforms

Event Types

go
// Node events
type NexNodeStartedEvent struct { ... }
type NexNodeStoppedEvent struct { ... }

// Agent events
type AgentStartedEvent struct { ... }
type AgentStoppedEvent struct { ... }

// Workload events
type WorkloadStartedEvent struct {
    WorkloadId    string
    NodeId        string
    WorkloadName  string
    Namespace     string
    Type          string
    Lifecycle     string
}
type WorkloadStoppedEvent struct { ... }
type WorkloadTriggeredEvent struct { ... }  // For functions

Configuration Files

Node Configuration

json
{
  "node_name": "my-node",
  "nexus": "default",
  "tags": {
    "env": "production",
    "region": "us-west"
  },
  "agents": ["native"],
  "nats": {
    "servers": ["nats://localhost:4222"],
    "credentials": "/path/to/creds.creds"
  },
  "events": {
    "destinations": ["nats", "logs"]
  }
}

Nexfile Format

yaml
name: my-workload
type: native
lifecycle: service
description: My workload description
tags:
  env: production
start_request:
  uri: "file:///path/to/binary"
  argv: ["--config", "/etc/app.yaml"]
  environment:
    LOG_LEVEL: "debug"
  workdir: "/app"

Building Custom Agents

Reference the in-memory test agent:

go
// _test/nexlet_inmem/inmemagent.go

type InMemoryAgent struct {
    id        string
    parentId  string
    workloads map[string]*WorkloadInfo
    nc        *nats.Conn
}

func (a *InMemoryAgent) Register(parentId string) error {
    a.parentId = parentId
    // Register capabilities with parent node
    return a.nc.Publish(
        fmt.Sprintf("$NEX.SVC.%s.agents.REGISTER", a.parentId),
        registerPayload,
    )
}

func (a *InMemoryAgent) StartWorkload(req *StartWorkloadRequest) (*WorkloadInfo, error) {
    // Validate request
    // Start execution
    // Return workload info
}

Debugging Tips

  1. Enable verbose logging:

    bash
    nex -v node up
    
  2. Subscribe to events:

    bash
    nats sub "$NEX.FEED.default.event.>"
    
  3. Watch logs:

    bash
    nats sub "$NEX.FEED.default.logs.>"
    
  4. Check node status:

    bash
    nex node list --json
    

Related Skills

  • /nex-cli-guide - Complete CLI reference
  • /nex-effect-services - Effect-TS integration patterns

References