{"modulePath":"github.com/pilot-protocol/common","version":"v0.6.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package daemonapi\n\nPackage daemonapi is the dependency-free contract layer between the daemon engine and its plugins.\n\nThe cycle problem: handshake / runtime / libpilot are daemon plugins that historically imported web4/pkg/daemon for the concrete Daemon struct, Config, Connection, Listener, and assorted services. The daemon binary in turn imported the plugins to compose itself. This is a real cycle (web4 ↔ plugins) that survives only because of \\`replace\\` directives during local dev.\n\ndaemonapi breaks the cycle by hosting:\n\n 1. Pure-interface contracts (Daemon, Connection, Listener, TrustChecker, HandshakeService, PolicyManager, PolicyRunner, WebhookManager, ...). The concrete \\*daemon.Daemon and its members satisfy these via Go's structural typing — the daemon engine never imports daemonapi to register, and plugins never import the daemon engine.\n\n 2. A runtime plugin lifecycle (Plugin interface) and a process- global registry (RegisterPlugin, LoadAll). Plugins register themselves from an init() block in their own package; the daemon engine, with no compile-time knowledge of which plugins exist, iterates whatever the registry contains.\n\n\"Not static\" wiring means:\n\n  - The daemon engine has zero hardcoded list of plugins. Adding or removing a plugin from a binary is a single blank-import line in cmd/daemon/main.go; the daemon, plugin, and other plugin packages all stay unchanged.\n\n  - The Plugin contract is interface-based, so a plugin's source code is interchangeable: two \\`handshake\\` implementations satisfy the same Plugin interface, the daemon doesn't know the difference.\n\n  - The registration mechanism is identical for in-process plugins (Go packages linked into the binary) and for true runtime plugins (Go plugin.Open of .so files). The .so's init() block calls RegisterPlugin the same way; the daemon engine then iterates the registry.\n\nWhat this package does NOT do:\n\n  - It does not own daemon implementation code. Concrete types stay in web4/pkg/daemon (and plugins' own implementations stay in their own repos). Interfaces only.\n\n  - It does not specify how the daemon engine starts or shuts down. That's the daemon's job. The Plugin lifecycle methods (Init, Shutdown) tell plugins when the daemon is ready and when it's stopping; the daemon decides the broader sequencing.\n\n## Constants\n\n```go\nconst (\n\tPolicyEventConnect  = \"connect\"\n\tPolicyEventDial     = \"dial\"\n\tPolicyEventDatagram = \"datagram\"\n\tPolicyEventJoin     = \"join\"\n\tPolicyEventLeave    = \"leave\"\n\tPolicyEventCycle    = \"cycle\"\n)\n```\nPolicyEvent\\* are the event-type constants the daemon engine passes into PolicyManager / PolicyRunner. Match coreapi.PolicyEvent\\* values; both are aliases of string.\n\n## Functions\n\n```go\nfunc RegisterPlugin(name string, f Factory)\n```\nRegisterPlugin records a factory under name. Typical use:\n\n\tfunc init() {\n\t    daemonapi.RegisterPlugin(\"handshake\", func() daemonapi.Plugin {\n\t        return \u0026handshakePlugin{}\n\t    })\n\t}\n\nRegistering twice with the same name is a programming error and panics — two factories under one name would race in LoadAll. The panic surfaces during package init, not at runtime, which makes the conflict obvious in test output and at first daemon launch.\n\n```go\nfunc Registered() []string\n```\nRegistered returns the names of every registered plugin, sorted. Useful for status output and for tests that want to verify a blank-import set wired the expected plugins in.\n\n```go\nfunc ShutdownAll(ctx context.Context, plugins []Plugin) error\n```\nShutdownAll calls Shutdown on every plugin in REVERSE-sorted order (the inverse of LoadAll's startup order). Each Shutdown gets the same context — typically a deadline-bound context from the daemon's shutdown timeout. Errors are collected and returned as a wrapped multi-error so the daemon still attempts to shut down every plugin even if an earlier one returned an error.\n\n## Types\n\n```go\ntype ConnReadWriter interface {\n\tRead(p []byte) (int, error)\n\tWrite(p []byte) (int, error)\n\tClose() error\n}\n```\nConnReadWriter is the read/write adapter plugins use when they need net.Conn-style I/O on a Connection. Construct one via Daemon.NewConnReadWriter(conn).\n\n```go\ntype Connection interface {\n\t// Info returns an endpoint snapshot. The returned struct is a\n\t// value copy, so plugins may hold it across goroutines.\n\tInfo() ConnectionInfo\n}\n```\nConnection is the daemon-facing handle to a stream connection. Plugins receive Connection values from DialConnection / Accept and pass them back to SendData / CloseConnection / NewConnReadWriter.\n\nThe Info accessor returns a struct snapshot of the four endpoint quantities a plugin commonly needs (local/remote address + port). This avoids exposing every field of the concrete \\*daemon.Connection through the interface, and avoids name collisions between Go's exported struct fields and same-named methods on the interface.\n\n```go\ntype ConnectionInfo struct {\n\tLocalAddr  protocol.Addr\n\tLocalPort  uint16\n\tRemoteAddr protocol.Addr\n\tRemotePort uint16\n}\n```\nConnectionInfo is the endpoint snapshot returned by Connection.Info.\n\n```go\ntype Daemon interface {\n\n\t// Start brings the daemon online. Returns when the listeners are\n\t// bound and the daemon is ready to accept traffic, or with an\n\t// error if any step of bootstrap fails.\n\tStart() error\n\n\t// Stop drains in-flight work and tears down the daemon. Idempotent;\n\t// safe to call from a signal handler.\n\tStop() error\n\n\t// NodeID returns this daemon's stable 32-bit node ID. 0 when the\n\t// identity has not been loaded yet.\n\tNodeID() uint32\n\n\t// Identity returns the daemon's Ed25519 keypair holder. Returns\n\t// nil when the daemon was started without an identity file\n\t// (in-memory tests).\n\tIdentity() *crypto.Identity\n\n\t// IdentityPath returns the on-disk path to the identity file.\n\t// Empty when running in-memory.\n\tIdentityPath() string\n\n\t// Sign signs the message with the local Ed25519 private key.\n\t// Returns nil when no identity is loaded.\n\tSign(msg []byte) []byte\n\n\t// AdminToken returns the local admin token used to authenticate\n\t// privileged registry RPCs. Empty when not configured.\n\tAdminToken() string\n\n\t// TrustAutoApprove reports whether the daemon was started with\n\t// the auto-approve flag set. Plugins gating user-visible decisions\n\t// on this flag (handshake auto-accept) read it once at Init.\n\tTrustAutoApprove() bool\n\n\t// Addr returns the daemon's pilot-network address. Stable for\n\t// the life of the daemon process.\n\tAddr() protocol.Addr\n\n\t// DialConnection opens an outbound stream to (dstAddr, dstPort)\n\t// and returns an opaque Connection handle. The handle is passed\n\t// back to SendData, CloseConnection, NewConnReadWriter, etc.\n\tDialConnection(dstAddr protocol.Addr, dstPort uint16) (Connection, error)\n\n\t// DialConnectionContext is DialConnection with a deadline. The\n\t// context's Done channel cancels the dial.\n\tDialConnectionContext(ctx context.Context, dstAddr protocol.Addr, dstPort uint16) (Connection, error)\n\n\t// SendData writes the byte slice to the stream connection.\n\t// Blocks until the data is queued for transmission.\n\tSendData(conn Connection, data []byte) error\n\n\t// SendDatagram sends an unconnected (UDP-shaped) payload to\n\t// (dstAddr, dstPort). Best-effort, no retransmission.\n\tSendDatagram(dstAddr protocol.Addr, dstPort uint16, data []byte) error\n\n\t// CloseConnection tears down the connection. Idempotent.\n\tCloseConnection(conn Connection)\n\n\t// NewConnReadWriter wraps a stream Connection as a net.Conn-style\n\t// adapter. Plugins that need read/write semantics use this; the\n\t// daemon retains ownership of the underlying connection state.\n\tNewConnReadWriter(conn Connection) ConnReadWriter\n\n\t// Ports returns the daemon's port allocator. Opaque to most\n\t// plugins; usually handed off to other plugins (e.g. handshake)\n\t// that bind well-known ports through it.\n\tPorts() PortAllocator\n\n\t// Tunnels returns the daemon's tunnel registry. Opaque to most\n\t// plugins.\n\tTunnels() TunnelRegistry\n\n\t// RegistryClient returns the L8 registry-side-channel client.\n\t// nil when the daemon is running without a registry connection.\n\tRegistryClient() *registry.Client\n\n\t// RegConnListNodes is the privileged list_nodes RPC, used by the\n\t// policy plugin to enumerate per-network members.\n\tRegConnListNodes(netID uint16, token string) (map[string]any, error)\n\n\t// SetMemberTags updates the local node's per-network tag list\n\t// via the registry.\n\tSetMemberTags(netID uint16, tags []string)\n\n\t// PublishEvent is the bus.Publish wrapper, exposed at top level\n\t// because plugins commonly publish without holding a Bus reference.\n\tPublishEvent(topic string, payload map[string]any)\n\n\t// Bus returns the in-process event bus for plugins that subscribe.\n\tBus() EventBus\n\n\t// GetTrustChecker returns the currently-registered trust checker\n\t// (typically the trustedagents plugin). Returns nil when no\n\t// checker is wired.\n\tGetTrustChecker() TrustChecker\n\n\t// RegisterTrustChecker installs the given checker as the daemon's\n\t// trust authority. Called once at startup by the trustedagents\n\t// plugin via the runtime adapter.\n\tRegisterTrustChecker(tc TrustChecker)\n\n\t// HandshakeService returns the currently-registered handshake\n\t// service. Returns nil when no handshake plugin is wired (tests\n\t// that bypass plugins).\n\tHandshakeService() HandshakeService\n\n\t// RegisterHandshakeService installs the handshake plugin's\n\t// service. Called once at startup via the runtime adapter.\n\tRegisterHandshakeService(svc HandshakeService)\n\n\t// TrustedPeers proxies through to HandshakeService().TrustedPeers().\n\t// Returns nil when no handshake plugin is wired.\n\tTrustedPeers() []HandshakeTrustRecord\n\n\t// HandshakeRevokeTrust proxies through to HandshakeService().RevokeTrust.\n\tHandshakeRevokeTrust(nodeID uint32) error\n\n\t// HandshakeSendRequest proxies through to HandshakeService().SendRequest.\n\tHandshakeSendRequest(nodeID uint32, reason string) error\n\n\t// RegisterPolicyManager installs the policy plugin's manager.\n\tRegisterPolicyManager(pm PolicyManager)\n\n\t// SetWebhookURL hot-swaps the active webhook URL on the registered\n\t// webhook plugin. No-op when no plugin is registered.\n\tSetWebhookURL(url string)\n\n\t// RegisterWebhookManager installs the webhook plugin's manager.\n\tRegisterWebhookManager(wm WebhookManager)\n}\n```\nDaemon is the dependency-free contract a daemon engine exposes to plugins. The concrete \\*daemon.Daemon in web4/pkg/daemon satisfies this interface via Go's structural typing — neither side needs to import the other.\n\nEvery method here exists because at least one plugin (handshake, runtime, libpilot) calls it. Adding a method later is a backwards- compatible change as long as concrete daemon implementations grow the corresponding method first.\n\nReturn types deliberately use:\n\n  - Common-package concrete types (\\*crypto.Identity, \\*registry.Client, protocol.Addr) — those types already live in the dependency-free common module, so referencing them here doesn't create cycles.\n\n  - daemonapi-local interfaces (Connection, PortAllocator, EventBus, etc.) — where the concrete return type lives inside the daemon engine. The opaque-marker interfaces keep plugins from poking at engine internals while still letting the daemon hand the value back to plugins as a typed token.\n\n```go\ntype Event struct {\n\tTopic   string\n\tNodeID  uint32\n\tTime    time.Time\n\tPayload map[string]any\n}\n```\nEvent is the payload structure carried over the daemon event bus. Mirrors the layout of the concrete event type in web4/pkg/daemon so subscriber channels receive identical-shaped values across the interface boundary.\n\n```go\ntype EventBus interface {\n\t// Publish emits the topic + payload to every subscriber whose\n\t// pattern matches the topic. Non-blocking; events may be dropped\n\t// on per-subscriber backpressure.\n\tPublish(topic string, payload map[string]any)\n\n\t// Subscribe registers a pattern-matching subscriber and returns\n\t// the receive channel plus a cancellation closure. Calling the\n\t// closure stops delivery and drains the buffer.\n\tSubscribe(pattern string) (\u003c-chan Event, func())\n}\n```\nEventBus is the in-process pub/sub surface plugins consume. The concrete \\*inProcessBus in web4/pkg/daemon satisfies this; plugins retrieve it via Daemon.Bus() and Subscribe / Publish without knowing the underlying implementation.\n\n```go\ntype Factory func() Plugin\n```\nFactory builds a new instance of a plugin. Registered factories run when the daemon calls LoadAll; each call produces a fresh Plugin value, so plugins do not share state across daemon restarts.\n\n```go\ntype HandshakePendingRecord struct {\n\tNodeID        uint32\n\tPublicKey     string\n\tJustification string\n\tReceivedAt    time.Time\n}\n```\nHandshakePendingRecord mirrors the handshake plugin's PendingHandshake for the same reason as HandshakeTrustRecord.\n\n```go\ntype HandshakeService interface {\n\tIsTrusted(nodeID uint32) bool\n\tTrustedPeers() []HandshakeTrustRecord\n\tPendingRequests() []HandshakePendingRecord\n\tPendingCount() int\n\tSendRequest(peerNodeID uint32, justification string) error\n\tApproveHandshake(peerNodeID uint32) error\n\tRejectHandshake(peerNodeID uint32, reason string) error\n\tRevokeTrust(peerNodeID uint32) error\n\n\t// WaitForTrust blocks until the peer transitions to trusted, or\n\t// the timeout elapses. Returns true if trust was granted in\n\t// time. Wired through the daemon so callers (typically pilotctl\n\t// before a first send to a trusted-list peer) can block\n\t// bidirectional operations on trust establishment instead of\n\t// racing the data send against the handshake reply.\n\tWaitForTrust(peerNodeID uint32, timeout time.Duration) bool\n\n\t// ProcessRelayedRequest / ProcessRelayedApproval /\n\t// ProcessRelayedRejection are invoked from the daemon's relay\n\t// poller after parsing the registry-inbox payload.\n\tProcessRelayedRequest(fromNodeID uint32, justification string)\n\tProcessRelayedApproval(fromNodeID uint32)\n\tProcessRelayedRejection(fromNodeID uint32)\n\n\t// Stop drains background RPCs and stops the replay reaper.\n\tStop()\n}\n```\nHandshakeService is the daemon-facing surface of the manual trust-handshake plugin (port 444). The plugin's \\*Manager satisfies this via Go's structural typing — the daemon engine never imports the handshake package.\n\nAll trust-handshake operations route through this interface: IPC command dispatch, trust-gate checks on inbound SYN / datagrams, registry-relay polling, and trust-pair re-sync after reconnect.\n\n```go\ntype HandshakeTrustRecord struct {\n\tNodeID     uint32\n\tPublicKey  string\n\tApprovedAt time.Time\n\tMutual     bool\n\tNetwork    uint16\n}\n```\nHandshakeTrustRecord mirrors the handshake plugin's TrustRecord so the daemon-facing HandshakeService interface stays primitive- only (no upward import). Field set is identical to the plugin's TrustRecord — the plugin's adapter returns a converted \\[]HandshakeTrustRecord built from its own TrustRecord values.\n\n```go\ntype Listener interface {\n\t// Accept blocks until an inbound Connection lands on the\n\t// listener or the listener is closed. ok=false signals close\n\t// (no further Connections will arrive).\n\tAccept() (conn Connection, ok bool)\n\n\t// Port returns the bound port. Stable for the listener's lifetime.\n\tPort() uint16\n\n\t// Close releases the port and stops accepting new Connections.\n\tClose() error\n}\n```\nListener is a bound port that yields inbound Connection values via Accept. Plugins (notably handshake on PortHandshake) hold a Listener for the lifetime of their server loop.\n\n```go\ntype Plugin interface {\n\t// Name returns the registration key of this plugin. Must be\n\t// stable across releases of the plugin; the daemon engine may\n\t// use it for keyed lookups, persistence, and operator-facing\n\t// status output.\n\tName() string\n\n\t// Init wires the plugin to a running daemon engine. The plugin\n\t// retains the Daemon for the rest of its lifetime. Init returns\n\t// an error if the plugin cannot bootstrap; the daemon aborts\n\t// startup on any plugin Init failure.\n\tInit(d Daemon) error\n\n\t// Shutdown stops the plugin's background work and drains any\n\t// in-flight requests. The Daemon passed to Init is still valid\n\t// during Shutdown — plugins may use it for last-mile work — but\n\t// the daemon engine will not accept new traffic. Shutdown should\n\t// honor the context's deadline; the daemon will not wait\n\t// indefinitely on a stuck plugin.\n\tShutdown(ctx context.Context) error\n}\n```\nPlugin is the lifecycle contract every daemon plugin implements. The daemon calls Init once after the engine is running and Shutdown once when the engine is stopping. Name returns a stable identifier used for registration, log lines, and metrics labels.\n\nA plugin holds the Daemon it was initialized with for the rest of its lifetime; the daemon engine will not be replaced under it. If the daemon shuts down, plugins receive Shutdown before the engine finishes its own teardown — they are guaranteed to be able to use the Daemon during Shutdown for any final cleanup (closing pending streams, dispatching final webhook deliveries, etc.).\n\n```go\nfunc LoadAll(d Daemon) ([]Plugin, error)\n```\nLoadAll instantiates every registered plugin against d and calls Init in sorted-by-name order. Returns the slice of loaded plugins so the caller can drive Shutdown later, plus the first error encountered (subsequent plugins are not started after a failure).\n\nPlugins are returned in registration-sorted order so Shutdown can run them in reverse and respect inter-plugin ordering by giving later-named plugins priority during teardown. This matches the common pattern where alphabetic name choice doubles as a startup- order hint (a-something starts before z-something).\n\n```go\ntype PolicyEventType = string\n```\nPolicyEventType is the kind of protocol event a policy is evaluated against. Type alias to string so plugin signatures stay primitive end-to-end.\n\n```go\ntype PolicyManager interface {\n\tStart(netID uint16, policyJSON []byte) (PolicyRunner, error)\n\tStop(netID uint16)\n\tGet(netID uint16) PolicyRunner\n\tAll() []PolicyRunner\n\tStopAll()\n\tLoadPersisted() error\n}\n```\nPolicyManager owns the per-network registry of policy runners.\n\n```go\ntype PolicyRunner interface {\n\tNetworkID() uint16\n\tHasMember(peerNodeID uint32) bool\n\n\t// EvaluatePortGate takes a string event-type (\"connect\", \"dial\",\n\t// \"datagram\", ...). The plugin's EventType is a type alias to\n\t// coreapi.PolicyEventType which is itself a type alias to string,\n\t// so plugin signatures match this exactly.\n\tEvaluatePortGate(\n\t\teventType string,\n\t\tport uint16,\n\t\tpeerNodeID uint32,\n\t\tpayloadSize int,\n\t\tdirection string,\n\t\tlocalTags, nodeInfoTags []string,\n\t) bool\n\n\tEvaluateActions(eventType string, ctx map[string]any)\n\tStatus() map[string]any\n\tPeerList() []map[string]interface{}\n\tForceCycle() map[string]any\n\tReconcileNow()\n\tPolicyJSON() ([]byte, error)\n\tStop()\n}\n```\nPolicyRunner is the daemon-facing surface of a single network's running policy. The plugin's concrete \\*PolicyRunner satisfies this via structural typing.\n\n```go\ntype PortAllocator interface {\n\t// Bind takes ownership of the given port and returns a Listener\n\t// that will receive Connections targeting it. Returns an error\n\t// if the port is already bound.\n\tBind(port uint16) (Listener, error)\n\n\t// Unbind releases the port. The Listener returned by Bind also\n\t// stops accepting (its Accept loop returns ok=false). Idempotent;\n\t// unbinding an unbound port is a no-op.\n\tUnbind(port uint16)\n}\n```\nPortAllocator is the daemon's port table. Plugins receive it via Daemon.Ports() and bind / unbind well-known ports through it. The concrete \\*daemon.PortManager satisfies this via structural typing.\n\n```go\ntype TrustChecker interface {\n\tIsTrusted(nodeID uint32) (string, bool)\n}\n```\nTrustChecker is the daemon-facing surface of the trustedagents plugin. The handshake handler consults this for auto-accept.\n\n```go\ntype TunnelRegistry interface {\n\t// RemovePeer tears down the encrypted tunnel for the given peer.\n\t// All per-peer state (session keys, retransmit queues, routing\n\t// entries) is dropped. Safe to call when no tunnel exists.\n\tRemovePeer(nodeID uint32)\n}\n```\nTunnelRegistry is the daemon's tunnel table. Plugins use RemovePeer to tear down a peer's tunnel state when revoking trust or closing a connection. The concrete \\*daemon.TunnelManager satisfies this via structural typing.\n\n```go\ntype VersionInfo struct {\n\t// Version is the semver of the running daemon, e.g. \"v1.10.5\".\n\tVersion string\n\t// Commit is the git SHA the daemon was built from. Empty in dev builds.\n\tCommit string\n\t// BuildTime is the UTC timestamp the daemon binary was assembled.\n\tBuildTime string\n}\n```\nVersionInfo describes a daemon's currently-running version and build metadata. Plugins call Daemon.VersionInfo() to discover what they're hosted by, useful for compatibility checks before issuing version- sensitive RPCs.\n\n```go\ntype WebhookManager interface {\n\t// SetURL hot-swaps the active webhook URL. Empty URL disables\n\t// delivery (no-op until set again).\n\tSetURL(url string)\n\n\t// Stats returns dispatcher counters for daemon Info. All-zero\n\t// when no client is configured (nil-safe at the plugin level).\n\tStats() WebhookStats\n}\n```\nWebhookManager is the daemon-facing surface of the webhook plugin. The plugin owns the HTTP client; the daemon only needs to (a) hot-swap the URL when IPC's set-webhook fires and (b) read counters for the daemon info health snapshot.\n\n```go\ntype WebhookStats struct {\n\tDropped      uint64\n\tCircuitSkips uint64\n}\n```\nWebhookStats is the daemon-facing mirror of the webhook plugin's Stats. Same shape, different package — the daemon engine can hold the value type without importing the plugin.\n\n","path":"github.com/pilot-protocol/common/daemonapi","name":"daemonapi","synopsis":"Package daemonapi is the dependency-free contract layer between the daemon engine and its plugins.","isRedistributable":true}
