{"modulePath":"github.com/pilot-protocol/common","version":"v0.6.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package coreapi\n\nPackage coreapi defines the L10 plugin runtime contract.\n\nThe interfaces in this package are the only surface a plugin (L11) ever sees of the daemon. Plugins import coreapi; the daemon implements coreapi; the bridge happens at lifecycle bootstrap (cmd/daemon/main.go registers concrete plugins against the daemon's coreapi implementations).\n\nSee docs/architecture/01-LAYERS.md §10 for the layer's role, docs/architecture/03-INVARIANTS.md for the principles this package enforces, and docs/architecture/06-CHANGES.md §2 for the rationale of each interface signature.\n\nStability contract: every exported identifier in this package is part of the daemon-plugin ABI. Removing or renaming any of them breaks every plugin. Additions are forward-compatible.\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```\n\n## Variables\n\n```go\nvar (\n\t// ErrRegistryStarted is returned by ServiceRegistry.Register and\n\t// ServiceRegistry.StartAll when StartAll has already been called.\n\t// Plugins must register before bootstrap.\n\tErrRegistryStarted = errors.New(\"coreapi: service registry already started\")\n\n\t// ErrServiceNotReady indicates a Service.Start call was made on a\n\t// dependency that itself hasn't completed Start. Surface only —\n\t// Service implementations shouldn't return this; the registry will.\n\tErrServiceNotReady = errors.New(\"coreapi: dependency service not ready\")\n\n\t// ErrPeerNotFound is the canonical \"directory has no record\" error\n\t// from PeerResolver. Plugins should match on errors.Is.\n\tErrPeerNotFound = errors.New(\"coreapi: peer not found\")\n)\n```\nSentinel errors returned by the L10 surface.\n\n## Functions\n\n```go\nfunc IsPluginHealthy(name string) bool\n```\nIsPluginHealthy returns false when a plugin has exceeded maxPanicsBeforeUnhealthy panics caught by RecoverPlugin.\n\n```go\nfunc PluginPanicCount(name string) uint64\n```\nPluginPanicCount returns how many panics RecoverPlugin has caught for the named plugin since process start (or last reset).\n\n```go\nfunc PluginRecoveredPanicCount() uint64\n```\nPluginRecoveredPanicCount returns the total number of panics swallowed by RecoverPlugin since process start.\n\n```go\nfunc RecoverPlugin(plugin, op string, events EventBus, onPanic func(any))\n```\nRecoverPlugin is the L11 panic-recovery shim used at the top of every plugin entrypoint goroutine: Service.Start helper goroutines, acceptLoop, and per-connection handlers. Usage:\n\n\tdefer coreapi.RecoverPlugin(\"eventstream\", \"acceptLoop\", events, nil)\n\nOn panic it:\n\n 1. Recovers (caller goroutine continues / loop iteration is dropped)\n 2. Logs at ERROR with structured plugin/op fields, panic value, and full goroutine stack trace\n 3. Increments PluginRecoveredPanicCount and per-plugin panic count\n 4. Publishes a \"plugin.\\\u003cplugin\u003e.panic\" event on the bus (if events != nil) so observability subscribers see the recovery\n 5. When the per-plugin panic count reaches maxPanicsBeforeUnhealthy (3), publishes one \"plugin.\\\u003cplugin\u003e.unhealthy\" event — the daemon supervisor should react by restarting or unloading the plugin\n 6. Calls onPanic(r) if non-nil — typical use is per-conn close, or signaling a future per-plugin supervisor for restart\n\nThis must be the OUTERMOST defer in the goroutine: defers run LIFO, so other defers (conn.Close, mu.Unlock, removeSub) run first.\n\n```go\nfunc ResetPluginHealthForTest()\n```\nResetPluginHealthForTest clears all per-plugin panic counters.\n\n```go\nfunc ResetPluginRecoveredPanicCountForTest()\n```\nResetPluginRecoveredPanicCountForTest is test-only.\n\n## Types\n\n```go\ntype Addr = protocol.Addr\n```\nAddr is the 48-bit virtual address used throughout the protocol. Re-exported here so plugins can stay free of pkg/protocol if they want.\n\n```go\ntype Deps struct {\n\tStreams  Streams\n\tIdentity Identity\n\tResolver PeerResolver\n\tEvents   EventBus\n\tLogger   *slog.Logger\n\n\t// Optional — nil if the plugin providing them isn't registered.\n\tTrust TrustChecker\n}\n```\nDeps is the bag of capabilities a plugin can use. Optional fields may be nil if the corresponding plugin isn't loaded; plugins that hard-depend on them should error in Start().\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 one item published to the EventBus. Topics are dot-namespaced (e.g., \"tunnel.established\", \"security.nonce\\_replay\"). Payload keys/values are plugin-defined; subscribers parse them.\n\n```go\ntype EventBus interface {\n\tPublish(topic string, payload map[string]any)\n\tSubscribe(pattern string) (\u003c-chan Event, func())\n}\n```\nEventBus is the publish/subscribe channel that replaces inline webhook.Emit calls inside core layers. Core (L2-L7) publishes; the webhook plugin (and any other observability plugin) subscribes.\n\nPublish is non-blocking. If the bus is over capacity, the event is dropped (and a metric counter is incremented inside the daemon implementation). This keeps L2 readLoop / L6 decrypt latency bounded.\n\nSubscribe returns a buffered channel and an unsubscribe func. Pattern is a glob: \"tunnel.\\*\" matches \"tunnel.established\" but not \"security.nonce\\_replay\".\n\n```go\ntype Identity interface {\n\tNodeID() uint32\n\tAddress() Addr\n\tPublicKey() ed25519.PublicKey\n\tSign(msg []byte) ([]byte, error)\n}\n```\nIdentity is the daemon's own identity — its Ed25519 keypair, its stable nodeID, its 48-bit address. Plugins may sign arbitrary bytes (e.g., for plugin-level auth proofs) but cannot replace the identity.\n\n```go\ntype Listener interface {\n\tAccept() (Stream, error)\n\tClose() error\n\tAddr() Addr\n\tPort() uint16\n}\n```\nListener accepts inbound streams on a single well-known or ephemeral port. Returned by Streams.Listen.\n\n```go\ntype PeerInfo struct {\n\tNodeID    uint32\n\tAddr      Addr\n\tEndpoint  *net.UDPAddr // best-known reachable endpoint, or nil\n\tPubKey    ed25519.PublicKey\n\tPublic    bool\n\tHostname  string\n\tRelayOnly bool\n}\n```\nPeerInfo is the directory record for a remote node. Returned by PeerResolver.Resolve and PeerResolver.ListByNetwork.\n\n```go\ntype PeerResolver interface {\n\tResolve(ctx context.Context, nodeID uint32) (PeerInfo, error)\n\tResolveHostname(ctx context.Context, name string) (uint32, error)\n\tListByNetwork(ctx context.Context, networkID uint32) ([]PeerInfo, error)\n}\n```\nPeerResolver is the L8 directory surface. The daemon's implementation talks to the registry over the bootstrap TCP side-channel (see 01-LAYERS §L8).\n\n```go\ntype PolicyEventType = string\n```\nPolicyEventType is the kind of protocol event a policy is evaluated against. Type alias to string so daemon-local primitive interfaces can satisfy plugin signatures via structural typing without importing this package (T7.1).\n\n```go\ntype PolicyManager interface {\n\t// Start compiles a policy JSON for the given network and registers\n\t// a runner. Returns the runner handle; existing runners for the\n\t// same network are stopped first.\n\tStart(netID uint16, policyJSON []byte) (PolicyRunner, error)\n\n\t// Stop stops the runner for netID (no-op if absent).\n\tStop(netID uint16)\n\n\t// Get returns the runner for netID or nil.\n\tGet(netID uint16) PolicyRunner\n\n\t// All returns a snapshot of all running runners.\n\tAll() []PolicyRunner\n\n\t// StopAll stops every runner. Called during daemon shutdown.\n\tStopAll()\n\n\t// LoadPersisted runs at daemon-Start to restore runners from disk.\n\tLoadPersisted() error\n}\n```\nPolicyManager owns the per-network registry of policy runners. The daemon holds it as an interface field; cmd/daemon (L12) constructs the concrete plugin and calls Daemon.RegisterPolicyManager.\n\n```go\ntype PolicyRunner interface {\n\tNetworkID() uint16\n\n\t// HasMember returns true if peerNodeID is in this runner's\n\t// per-peer state. The daemon iterates all runners to consult\n\t// every network the peer belongs to (deny wins across networks).\n\tHasMember(peerNodeID uint32) bool\n\n\t// EvaluatePortGate is the daemon-facing gate API for inbound SYN\n\t// (Connect), outbound SYN (Dial), and datagram (in/out) events.\n\t// The plugin builds the per-peer ctx internally (peer_age_s,\n\t// peer_tags, members) using its peer state and the\n\t// daemon-supplied localTags + nodeInfoTags. Returns the\n\t// allow/deny verdict (default allow on no explicit deny).\n\tEvaluatePortGate(eventType PolicyEventType, port uint16, peerNodeID uint32, payloadSize int, direction string, localTags, nodeInfoTags []string) bool\n\n\t// EvaluateActions runs an action-event (cycle/join/leave) with a\n\t// caller-built ctx. Side-effect-only: no return value.\n\tEvaluateActions(eventType PolicyEventType, ctx map[string]any)\n\n\tStatus() map[string]any\n\tPeerList() []map[string]any\n\tForceCycle() map[string]any\n\tReconcileNow()\n\n\t// PolicyJSON returns the marshaled policy document. Used by IPC\n\t// handlers that read the current policy back to admin tools.\n\tPolicyJSON() ([]byte, error)\n\n\tStop()\n}\n```\nPolicyRunner is the daemon-facing surface of a single network's running policy. The plugin's concrete \\*PolicyRunner type implements this. The daemon never holds the concrete type — only this interface.\n\n```go\ntype Service interface {\n\tName() string\n\tOrder() int\n\tStart(ctx context.Context, deps Deps) error\n\tStop(ctx context.Context) error\n}\n```\nService is the lifecycle contract every L11 plugin implements.\n\nOrder determines the start sequence. Lower numbers start first; higher numbers stop first. Suggested ranges:\n\n\t 10-49   Foundation (none today)\n\t 50-79   Trust / identity-adjacent (trustedagents)\n\t 80-99   Observability (webhook)\n\t100-199  Application services (dataexchange, eventstream, tasks)\n\t200-249  Sidecars (skillinject)\n\t250+     Tooling-bound (updater)\n\nStart receives Deps (the L10 surface). Implementations must NOT retain references to anything outside Deps — that's the whole extraction contract.\n\nStop should drain in-flight work, close listeners, and signal background goroutines to exit. It must return within 5 seconds or the daemon shutdown gate will fail.\n\n```go\ntype ServiceRegistry struct {\n\t// contains filtered or unexported fields\n}\n```\nServiceRegistry coordinates plugin lifecycle. cmd/daemon/main.go constructs one, registers each plugin, and hands it to the daemon. The daemon calls StartAll during bootstrap and StopAll during shutdown.\n\n```go\nfunc (sr *ServiceRegistry) All() []Service\n```\nAll returns a snapshot of the registered services in start order.\n\n```go\nfunc (sr *ServiceRegistry) Register(s Service) error\n```\nRegister adds a service. Must be called before StartAll. After StartAll runs, Register is a no-op error.\n\n```go\nfunc (sr *ServiceRegistry) StartAll(ctx context.Context, deps Deps) error\n```\nStartAll sorts by Order and starts every service in sequence. The first failing Start aborts and returns its error; previously- started services are NOT auto-stopped (the caller's job, via Stop() or by passing a context that cancels).\n\n```go\nfunc (sr *ServiceRegistry) StopAll(ctx context.Context) error\n```\nStopAll stops every started service in reverse order. Each Stop is wrapped in stopWithPanicRecovery so a buggy plugin panicking during shutdown cannot crash the daemon; the panic is converted to an error and all remaining services still get their Stop call.\n\nTo prevent one hung plugin from blocking the entire shutdown sequence, each per-plugin Stop call is given its own 5-second timeout via a per-plugin context derived from the parent. If a plugin exceeds its deadline, context.DeadlineExceeded is surfaced as a Stop error and remaining plugins continue shutting down.\n\nErrors from individual Stop calls (including recovered panics and deadline expirations) are collected; the first one is returned but every service still gets its Stop call invoked.\n\n```go\ntype Stream interface {\n\tio.ReadWriteCloser\n\n\tLocalAddr() Addr\n\tLocalPort() uint16\n\tRemoteAddr() Addr\n\tRemotePort() uint16\n}\n```\nStream is one bidirectional ordered byte stream between two (Addr, port) endpoints. It satisfies io.ReadWriteCloser with Pilot Protocol addressing extensions. Deadline methods are intentionally excluded — the runtime currently cannot honor them, and removing them from the interface forces callers to get a compile-time signal rather than a silent no-op.\n\n```go\ntype Streams interface {\n\tDial(ctx context.Context, dst Addr, port uint16) (Stream, error)\n\tListen(port uint16) (Listener, error)\n\tSendDatagram(ctx context.Context, dst Addr, port uint16, data []byte) error\n}\n```\nStreams is the L7 surface plugins consume. The daemon-side implementation routes through L7 → L6 → L5 → L4 → L2.\n\nSendDatagram is the connectionless variant (one packet, no ACK, no retransmit). Used by plugins that don't need stream semantics.\n\n```go\ntype TrustChecker interface {\n\t// IsTrusted reports whether the peer is on the auto-approve allowlist.\n\t// Returns the agent's display name when known. Both return values are\n\t// zero on miss.\n\tIsTrusted(nodeID uint32) (name string, ok bool)\n}\n```\nTrustChecker is the trusted-agents gate consumed by L11/tasks (and any other plugin that gates on peer reputation).\n\nIsTrusted: returns true if the peer is on the auto-approve allowlist (loaded from the trusted-agents JSON, refreshed hourly).\n\n","path":"github.com/pilot-protocol/common/coreapi","name":"coreapi","synopsis":"Package coreapi defines the L10 plugin runtime contract.","isRedistributable":true}
