h2a

package module
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

h2a-go

A Go client for harnsy's h2a v1 contract. Your service connects to a harnsy node, gives a task to a project's lead or one of its roles, and gets the agents' answers in the same conversation, through disconnects and restarts. With the rights for it, it also sees the posts' state, wakes and puts to sleep a post's holder, and raises items.

The SDK talks contract h2a v1: messages and answers with harnsy 0.11 and later; state, wake, sleep and items need a harnsy with them (its release notes say so). Checked against harnsy at the commit named in testdata/codes.json (its first line).

Install

go get github.com/harnesy/h2a-go@latest

Go 1.23 or newer. One dependency: github.com/coder/websocket.

Before you start

  • A pass. The node's owner makes it on the dashboard (Settings › Services): the project, your service's name, and the posts it may write to (roles and/or «Project lead»). The token (h2a_…) is shown once: keep it as a secret.
  • The address. wss://<the node's gateway host>[:port]/h2a/v1. The node needs harnsy Max and its gateway on.

Quick start

c, err := h2a.Dial(ctx, h2a.Config{
	URL:    "wss://node.example/h2a/v1",
	Token:  os.Getenv("H2A_TOKEN"),
	Cursor: h2a.FileCursor("h2a.seq"), // the last answer handled, across restarts
})
if err != nil {
	log.Fatal(err) // *h2a.Error: its Code says why (h2a_auth, h2a_off, …)
}
defer c.Close()

w := c.Welcome() // the project and the addresses of the pass
acc, err := c.Send(ctx, h2a.Message{To: w.To[0].Address, Text: "The video is ready, look at scene 2"})
// acc.Conversation: write into it with h2a.Message{Conversation: acc.Conversation, Text: "…"}

err = c.Run(ctx, func(ctx context.Context, m h2a.Reply) error {
	fmt.Println(m.From.Role, ":", m.Text)
	return nil // acknowledged; an error: Run returns it and the answer comes again
})

Control, with Can: []string{"state", "wake", "item"} and the pass's rights (Control):

s, err := c.State(ctx, "")                         // the posts and their state
c.OnState(func(s h2a.State) { log.Println(s) })    // their changes
c.OnWelcome(func(w h2a.Welcome) { log.Println(w.To) }) // the pass's posts, again when the person changes them
err = c.Wake(ctx, "lead")                          // h2a_no_wake: a service may not wake it
err = c.Sleep(ctx, "lead", "")                     // after its turn; h2a_not_yours: not woken by this pass
ref, err := c.CreateItem(ctx, "lead", "Scene 2", "Look at scene 2") // ref.Item: its number

h2a-bot

A small command on top of the SDK (cmd/h2a-bot, under 260 lines):

go install github.com/harnesy/h2a-go/cmd/h2a-bot@latest
H2A_URL=wss://node.example/h2a/v1 H2A_TOKEN=h2a_… h2a-bot                      # list the addresses
H2A_URL=… H2A_TOKEN=… h2a-bot -to lead "Check the release is built"           # a task, then the answers
H2A_URL=… H2A_TOKEN=… h2a-bot -conv <conversation> "And the notes?"           # into a conversation
H2A_URL=… H2A_TOKEN=… h2a-bot -listen                                          # only the answers
H2A_URL=… H2A_TOKEN=… h2a-bot -state                                           # the posts and their state
H2A_URL=… H2A_TOKEN=… h2a-bot -wake lead                                       # wake the lead
H2A_URL=… H2A_TOKEN=… h2a-bot -sleep lead                                      # put it to sleep again
H2A_URL=… H2A_TOKEN=… h2a-bot -to role:11 -item "Scene 2" -text "Look at it"   # an item (no -text: stdin)
echo "Look at it" | H2A_URL=… H2A_TOKEN=… h2a-bot -item "Scene 2"              # an item to the lead (a pass of one project)

It prints [role · project] text for each answer, keeps the last seq in ~/.h2a-bot.seq, and survives disconnects; Ctrl+C loses nothing. States and refusals are said in plain words, with the code after them; control characters of the node's text are dropped before the terminal shows it.

A pass of several projects addresses a lead as lead:<project id> (the welcome lists them): -wake, -sleep and -item need it there, and -item without -to says which leads to choose from. A pass keeps one connection: a second run with the same pass replaces the first (a running -listen stops with «another copy … signed in»), so give one command at a time, or run your commands inside the program that listens.

Documentation

The contract itself is harnsy's: https://harnsy.dev/docs/h2a-v1. This SDK keeps no copy of it; it follows its «Client» column on every error and close, and decides nothing the node decides.

Versions

Before 1.0 the SDK's API may still change between minor versions; every v0.x.y speaks contract "1", and fields the contract adds within 1 come in minor versions (fields the SDK does not know are skipped). v0.1 sends and receives messages; v0.2 adds control: State, OnState, Wake, Sleep, CreateItem, Welcome.Projects; v0.3 takes a welcome the node sends again on the live connection (Welcome() is the newest) and adds OnWelcome; v0.4 adds inlets: Config.OnHTTP, Welcome.Inlets (harnsy 0.11). Contract "2" will be a new major version of the module.

Tests

go test -race ./...
H2A_TEST_URL=wss://… H2A_TEST_TOKEN=h2a_… H2A_TEST_TASK="ping" go test -run TestLiveNode -v   # against a node

The tests run a fake node, and check the SDK against harnsy's own frames and codes (testdata/, copied by scripts/update-vectors.sh <harnsy checkout>; never edited here).

License

MIT

Documentation

Overview

Package h2a is a client of harnsy's h2a v1 contract: an outside service holds one WebSocket to a harnsy node, gives tasks to a project's lead or a role, and gets the agents' answers, through disconnects.

The contract is harnsy's (https://harnsy.dev/docs/h2a-v1); this package decides nothing the node decides: it follows the contract's «Client» column on every refusal and close, and passes the node's errors on as they are.

Index

Constants

View Source
const (
	CodeVersion             = "h2a_version"
	CodeHelloRequired       = "h2a_hello_required"
	CodeAuth                = "h2a_auth"
	CodeOff                 = "h2a_off"
	CodeReplaced            = "h2a_replaced"
	CodePing                = "h2a_ping"
	CodeRate                = "h2a_rate"
	CodeBadFrame            = "h2a_bad_frame"
	CodeFrame               = "h2a_frame"
	CodePart                = "h2a_part"
	CodeTooBig              = "h2a_too_big"
	CodeAddress             = "h2a_address"
	CodeConversationUnknown = "h2a_conversation_unknown"
	CodeNoHolder            = "h2a_no_holder"
	CodeDaily               = "h2a_daily"
	CodeForbidden           = "h2a_forbidden"
	CodeNotYours            = "h2a_not_yours"
	CodeNoWake              = "h2a_no_wake"
	CodeSoftStop            = "h2a_soft_stop"
)

The codes of the contract's §5 (testdata/codes.json, from harnsy).

View Source
const (
	MoveReconnect = "reconnect"
	MoveStop      = "stop"
	MoveWait      = "wait retry_after"
	MoveCaller    = "caller"
	MoveWaitUntil = "wait until"
)

What a service does (the contract's «Client» column).

View Source
const (
	PostVacant       = "vacant" // nobody holds the post
	PostStarting     = "starting"
	PostUp           = "up"
	PostPartlyAsleep = "partly_asleep"
	PostAsleep       = "asleep"
	PostOff          = "off"
	PostArchived     = "archived"
)

The words of Post.State (harnsy's team-state v1). A word not here is passed on as it is.

View Source
const (
	RightTalk  = "talk"  // Send
	RightRead  = "read"  // State, OnState
	RightWake  = "wake"  // Wake, Sleep
	RightItems = "items" // CreateItem
)

The rights of a pass in a project (welcome.projects[].rights).

View Source
const InletBodyMax = 128 << 10

InletBodyMax bounds a request's and an answer's body: a larger request is refused by the node (413), a larger answer is not sent (the node gives the canned one).

View Source
const ItemTextBytes = 8000

ItemTextBytes is the contract's limit of an item's text: the text with harnsy's frame around it (§6). The frame's words are the node's, so the SDK refuses here only a text that is over the limit by itself; one under it may still be refused by the node with h2a_too_big.

View Source
const Protocol = "harnsy.h2a.v1"

Protocol is the WebSocket subprotocol of the contract.

View Source
const SleepAfterStep = "after_step"

SleepAfterStep is the sleep mode: after the holder's turn, the node's default and the only one it keeps (it takes "now" as after_step too).

View Source
const Version = "1"

Version is the contract version this SDK speaks.

Variables

View Source
var (
	// ErrVersion: the node's welcome is not version 1.
	ErrVersion = errors.New("h2a: the node does not speak h2a version " + Version)
	// ErrReplaced: another copy of the service signed in with the same pass.
	ErrReplaced = errors.New("h2a: replaced: another connection of this pass signed in")
	// ErrClosed: the client was closed.
	ErrClosed = errors.New("h2a: closed")
)
View Source
var ErrRunning = errors.New("h2a: Run is already running on this client")

ErrRunning: Run was called while another Run of the client runs.

Functions

This section is empty.

Types

type Accepted

type Accepted struct {
	ID           string // the message's ID
	Conversation string
}

Accepted is the node's answer to a Message.

type Address

type Address struct {
	Address string `json:"address"`
	Name    string `json:"name"`
	About   string `json:"about,omitempty"`
}

Address is one post a pass may write to: «lead» or «role:<id>».

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is one service's connection to the node: Dial signs in, Send gives tasks, Run takes the answers; the connection is kept up by the client, as the contract's «Client» column says.

func Dial

func Dial(ctx context.Context, cfg Config) (*Client, error)

Dial connects and signs in. A refused hello comes back as *Error (its Code says why: CodeAuth, CodeOff, CodeRate…), a welcome of another version as ErrVersion. The client then keeps the connection up until ctx ends, Close is called, or the contract says to stop.

func (*Client) Close

func (c *Client) Close() error

Close ends the connection; Send and Run return ErrClosed.

func (*Client) CreateItem added in v0.2.0

func (c *Client) CreateItem(ctx context.Context, to, title, text string) (ItemRef, error)

CreateItem raises a new item of the post's role. The node writes its title as its own ([service «…»] and title, one line, 120 characters) and frames text as data from outside. A text over ItemTextBytes is refused here (h2a_too_big), without a frame. Needs "item" in Config.Can.

func (*Client) OnState added in v0.2.0

func (c *Client) OnState(h func(State))

OnState sets h to get the node's state events: the posts whose state or counts changed (at most once per 5 s a post), of projects where the pass has read. h runs on one goroutine of the client, one event at a time. The events that come while h runs are coalesced: its next call has each post that changed once, in its newest state; the client never waits on h to read the node. nil: events are dropped. Needs "state" in Config.Can.

func (*Client) OnWelcome added in v0.3.0

func (c *Client) OnWelcome(h func(Welcome))

OnWelcome sets h to get the node's welcomes: the current one at once (the first of the connection, before OnWelcome was set), then every welcome after it — one the node sends again on the live connection when the person changes the pass's projects, rights or posts, and the one of each reconnect. h runs on the client's handler goroutine, one call at a time; the welcomes that come while it runs are coalesced to the newest, and the client never waits on h to read the node. nil: welcomes are not handed.

func (*Client) Run

func (c *Client) Run(ctx context.Context, h func(ctx context.Context, m Reply) error) error

Run hands each agent's reply to h, in seq order, one at a time. h returning nil acknowledges the reply (ack) and saves its seq in the Cursor; an error is returned by Run, and the next Run gets that reply again. A refusal of the connection without a frame's ID comes back as *Error. Run returns when ctx ends, or the client stops for good (the contract's «stop»: *Error with CodeAuth or CodeOff, ErrReplaced). One Run at a time per client (a second gets ErrRunning). Keep h short: while it runs, no new reply is read past the buffer, and a long stall loses the connection (the SDK reconnects and nothing is lost, but it costs time).

func (*Client) Send

func (c *Client) Send(ctx context.Context, m Message) (Accepted, error)

Send gives a task or a reply to the node and waits for its Accepted. A disconnect before it is resent with the same ID after the reconnect (the node answers a repeated ID with the same Accepted and delivers it once); h2a_rate is waited out once. A refusal comes back as *Error.

func (*Client) Sleep added in v0.2.0

func (c *Client) Sleep(ctx context.Context, to, mode string) error

Sleep puts to sleep the holder of to that this pass woke last (else h2a_not_yours), after its turn. mode "" is SleepAfterStep (the node's default, not sent). Needs "wake" in Config.Can.

func (*Client) State added in v0.2.0

func (c *Client) State(ctx context.Context, project string) (State, error)

State asks the posts and their state of project (its name, as Welcome().Projects has it), or of every project where the pass has read when project is "". Needs "state" in Config.Can.

func (*Client) Wake added in v0.2.0

func (c *Client) Wake(ctx context.Context, to string) error

Wake wakes the holder of the post to (an address of Welcome().Projects). The node wakes only a holder this pass or harnsy put to sleep: else h2a_no_wake. A holder awake already: nil. Needs "wake" in Config.Can.

func (*Client) Welcome

func (c *Client) Welcome() Welcome

Welcome is the node's welcome of the current connection: the newest one, also one the node sent again on it.

type Config

type Config struct {
	// URL is the gateway's address of the contract: wss://<host>[:port]/h2a/v1.
	URL string
	// Token is the pass's token (h2a_…): a secret. It goes in the hello
	// frame only, never in the URL, a header or a log of this package.
	Token string
	// Can is what the service takes and sends: "text" (always sent, also
	// when not listed), and by need "state" (State, OnState), "wake" (Wake
	// and Sleep), "item" (CreateItem). nil: ["text"].
	Can []string
	// OnHTTP answers the pass's inlets (harnsy 0.11, inlet.go): with it the
	// service names "http" and gets each request to an inlet; nil: none.
	OnHTTP OnHTTPFunc
	// Cursor keeps the last handled seq; nil: MemCursor.
	Cursor Cursor
	// HTTPClient dials the WebSocket; nil: http.DefaultClient.
	HTTPClient *http.Client
	// Logf, when set, gets a line on each connect and reconnect (never the
	// token).
	Logf func(format string, args ...any)
}

Config is how to reach the node and sign in.

type Counts added in v0.2.0

type Counts struct {
	Seats    int `json:"seats"`
	Working  int `json:"working"`
	Waiting  int `json:"waiting"`
	Starting int `json:"starting"`
	Idle     int `json:"idle"`
	Asleep   int `json:"asleep"`
	Off      int `json:"off"`
	Vacant   int `json:"vacant"`
}

Counts are the role's seats by what they do now.

type Cursor

type Cursor interface {
	Load() (int64, error)
	Save(seq int64) error
}

Cursor keeps the seq of the last reply the service handled, across restarts: the next hello asks for what came after it (resume_after).

func FileCursor

func FileCursor(path string) Cursor

FileCursor is a Cursor in a file: the seq as text, written atomically (a temp file renamed over it). A missing file is 0.

func MemCursor

func MemCursor() Cursor

MemCursor is a Cursor in memory: a restart starts from every reply not yet acknowledged.

type Error

type Error struct {
	Re         string // the refused frame's ID, "" for the connection
	Code       string
	Text       string // harnsy's words
	Field      string
	RetryAfter time.Duration
	Until      time.Time
	Close      int // the WebSocket close code that came with it, 0 none
}

Error is a refusal of the node (contract §5), or the SDK's own refusal of a frame it knows the node would refuse (CodeTooBig).

func (*Error) Error

func (e *Error) Error() string

type From

type From struct {
	Project string `json:"project"`
	Role    string `json:"role"`
}

From is who answered: never an agent's name, session or node.

type HTTPRequest added in v0.4.0

type HTTPRequest struct {
	ID     string // the node's id of the request
	Inlet  int64  // the inlet it came to (Welcome().Inlets)
	Method string // GET or POST
	Path   string // after the inlet's address: "/" or "/<more>"
	Query  string // the raw query, without "?"
	// Headers are the request's headers of the node's list, no other:
	// Content-Type, User-Agent, Accept, X-Slack-Signature,
	// X-Slack-Request-Timestamp, X-Telegram-Bot-Api-Secret-Token,
	// X-Hub-Signature-256. Never a cookie or Authorization.
	Headers map[string]string
	Remote  string // the visitor's address, as the node's gateway judges it
	Body    []byte // byte for byte: a signature over it checks
}

HTTPRequest is a request to one of the pass's inlets.

type HTTPResponse added in v0.4.0

type HTTPResponse struct {
	Status      int
	ContentType string
	Body        []byte
}

HTTPResponse is the service's answer to an HTTPRequest. The node sends it as an inert document: a Content-Type of application/json, text/plain, application/xml or text/xml as it is, any other as a download; no cookie, no redirect. Status 200..599; 0 is 200.

type Inlet added in v0.4.0

type Inlet struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	// URL is the inlet's public address; "" while the node is not reached
	// from outside (the inlet works only then).
	URL string `json:"url"`
}

Inlet is one of the pass's inlets on, as Welcome lists it to a service with Config.OnHTTP: the service may register its URL as a webhook itself.

type ItemRef added in v0.2.0

type ItemRef struct {
	ID   string // the frame's id
	Item int64  // the item's number on the node
}

ItemRef is the node's answer to an item: its number.

type Limits

type Limits struct {
	FramesPerMinute int `json:"frames_per_minute"`
	MessagesPerDay  int `json:"messages_per_day"`
	TextBytes       int `json:"text_bytes"`
	FrameBytes      int `json:"frame_bytes"`
	Queue           int `json:"queue"`
	QueueHours      int `json:"queue_hours"`
	PingSeconds     int `json:"ping_seconds"`
	IdleSeconds     int `json:"idle_seconds"`
}

Limits are the node's limits from the welcome (contract §6).

type Message

type Message struct {
	// ID is the service's id of the frame; empty: the SDK sets a unique one.
	// A repeated ID gets the same Accepted for 24 h and is not delivered twice.
	ID           string
	To           string
	Conversation string
	Text         string
}

Message is a task or a reply the service sends. Without Conversation it starts a new conversation to To; with one it writes into it.

type OnHTTPFunc added in v0.4.0

type OnHTTPFunc func(ctx context.Context, r HTTPRequest) HTTPResponse

OnHTTPFunc is the handler of the pass's inlets (Config.OnHTTP): ctx ends when the client closes. Keep it within the inlet's wait.

type Post added in v0.2.0

type Post struct {
	Address string `json:"address"`
	Name    string `json:"name"`
	State   string `json:"state"` // PostVacant, PostStarting, PostUp, …
	Counts  Counts `json:"counts"`
}

Post is one post (an address) and its state: harnsy's team-state words for the role, word for word. Never a seat, an agent, a session or a node.

type ProjectAccess added in v0.2.0

type ProjectAccess struct {
	Project string    `json:"project"`
	Rights  []string  `json:"rights"`
	To      []Address `json:"to"`
}

ProjectAccess is one project of the pass: its name, the rights the pass has there (RightTalk, RightRead, RightWake, RightItems), and the addresses of its posts (lead:<project id> on a pass of several projects).

type ProjectState added in v0.2.0

type ProjectState struct {
	Project string `json:"project"`
	Posts   []Post `json:"posts"`
}

ProjectState is one project's posts.

type Reply

type Reply struct {
	Seq          int64
	Conversation string
	From         From
	Text         string
	At           time.Time
}

Reply is an agent's answer.

type State added in v0.2.0

type State struct {
	Projects []ProjectState `json:"projects"`
}

State is the posts of the pass's projects and their state: the answer to a request, or an event (only the posts that changed).

type Welcome

type Welcome struct {
	V       string    `json:"v"`
	Project string    `json:"project"`
	To      []Address `json:"to"`
	Limits  Limits    `json:"limits"`
	// Projects are every project of the pass with its rights and posts;
	// the node sends them only to a service whose Can names "state",
	// "wake" or "item".
	Projects []ProjectAccess `json:"projects,omitempty"`
	// Inlets are the pass's inlets on; the node sends them only to a
	// service with Config.OnHTTP (harnsy 0.11).
	Inlets []Inlet `json:"inlets,omitempty"`
}

Welcome is the node's answer to a good hello.

Directories

Path Synopsis
cmd
h2a-bot command
Command h2a-bot gives a task to a harnsy project's lead or role and prints the agents' answers, through disconnects.
Command h2a-bot gives a task to a harnsy project's lead or role and prints the agents' answers, through disconnects.
examples
alice-skill command
Command alice-skill is a skill of Yandex Alice that talks to a harnsy project: «Алиса, попроси Харнси …» — the phrase goes to the project's lead, the skill answers «Принято» at once, and the lead's answer is read out the next time you ask «что ответил Харнси».
Command alice-skill is a skill of Yandex Alice that talks to a harnsy project: «Алиса, попроси Харнси …» — the phrase goes to the project's lead, the skill answers «Принято» at once, and the lead's answer is read out the next time you ask «что ответил Харнси».
alice-speaker command
Command alice-speaker is a skill of Yandex Alice that talks to a harnsy project and reads the agent's answers aloud on your Yandex speaker: a phrase said in the skill goes to the post (the pass's first, or -to), the skill answers «Принято» at once, and when the agent answers, the program asks the speaker over its local protocol (glagol) «попроси Харнси прочитать ответ» — the skill then gives the answer and Alice speaks it.
Command alice-speaker is a skill of Yandex Alice that talks to a harnsy project and reads the agent's answers aloud on your Yandex speaker: a phrase said in the skill goes to the post (the pass's first, or -to), the skill answers «Принято» at once, and when the agent answers, the program asks the speaker over its local protocol (glagol) «попроси Харнси прочитать ответ» — the skill then gives the answer and Alice speaks it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址