-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.go
More file actions
1643 lines (1458 loc) · 49.3 KB
/
agent.go
File metadata and controls
1643 lines (1458 loc) · 49.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package agent
import (
"context"
"crypto/ed25519"
"encoding/json"
"fmt"
"log/slog"
"strconv"
"sync"
"time"
"github.com/google/uuid"
"github.com/peerclaw/peerclaw-agent/conn"
"github.com/peerclaw/peerclaw-agent/discovery"
"github.com/peerclaw/peerclaw-agent/filetransfer"
"github.com/peerclaw/peerclaw-agent/peer"
"github.com/peerclaw/peerclaw-agent/platform"
"github.com/peerclaw/peerclaw-agent/sdkversion"
"github.com/peerclaw/peerclaw-agent/security"
pcsignaling "github.com/peerclaw/peerclaw-agent/signaling"
"github.com/peerclaw/peerclaw-agent/transport"
"github.com/peerclaw/peerclaw-core/agentcard"
"github.com/peerclaw/peerclaw-core/envelope"
"github.com/peerclaw/peerclaw-core/identity"
pccoresignaling "github.com/peerclaw/peerclaw-core/signaling"
"github.com/pion/webrtc/v4"
)
// MessageHandler is called when an incoming envelope is received.
type MessageHandler func(ctx context.Context, env *envelope.Envelope)
// ConnectionRequest describes a pending connection from an unknown peer.
type ConnectionRequest struct {
FromAgentID string
Timestamp time.Time
}
// ConnectionRequestHandler is called when a non-whitelisted peer requests a connection.
// Return true to allow, false to deny.
type ConnectionRequestHandler func(ctx context.Context, req *ConnectionRequest) bool
// NotificationPayload represents a notification pushed from the server via signaling.
type NotificationPayload struct {
ID string `json:"id"`
UserID string `json:"user_id"`
AgentID string `json:"agent_id"`
Type string `json:"type"`
Severity string `json:"severity"`
Title string `json:"title"`
Body string `json:"body"`
Metadata map[string]string `json:"metadata,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// Options configures an Agent.
type Options struct {
// Name is the agent's display name.
Name string
// ServerURL is the peerclaw-server base URL (e.g., "http://localhost:8080").
ServerURL string
// Capabilities lists what this agent can do (e.g., "chat", "search").
Capabilities []string
// Protocols lists supported communication protocols (e.g., "a2a", "mcp").
Protocols []string
// KeypairPath is the path to the Ed25519 keypair seed file.
// If empty or not found, a new keypair will be generated.
KeypairPath string
// TrustStorePath is the path to the trust store file.
TrustStorePath string
// NostrRelays is a list of Nostr relay WebSocket URLs for fallback transport.
// If non-empty, a transport Selector will be created wrapping WebRTC + Nostr.
NostrRelays []string
// Discovery is an optional custom discovery implementation.
// If nil, a RegistryClient is created using ServerURL.
Discovery discovery.Discovery
// Signaling is an optional custom signaling client implementation.
// If nil, a WebSocket Client is created using ServerURL.
Signaling pcsignaling.SignalingClient
// MessageCachePath is the file path for persisting offline message cache.
MessageCachePath string
// ClaimToken is a one-time pairing code (e.g., "PCW-XXXX-XXXX") obtained from
// the platform. When set, the agent uses the claim flow instead of direct
// registration, binding itself to the user who generated the token.
ClaimToken string
// InboxRelays is a list of Nostr relay URLs for the offline mailbox.
// When non-empty, a Mailbox will be created for offline message delivery.
InboxRelays []string
// MailboxTTL is how long mailbox messages are retained (default 7 days).
MailboxTTL time.Duration
// InboxSyncInterval is how often the inbox is polled for new messages (default 5 minutes).
InboxSyncInterval time.Duration
// OutboxStatePath is the file path for persisting the outbox queue.
OutboxStatePath string
// LastSyncPath is the file path for persisting the last inbox sync timestamp.
LastSyncPath string
// FileTransferDir is the directory to save received files.
// Defaults to the current directory.
FileTransferDir string
// ResumeStatePath is the directory for file transfer resume state files.
ResumeStatePath string
// OnFileTransferComplete is called when a file transfer reaches a terminal state
// (done, failed, or cancelled).
OnFileTransferComplete func(info filetransfer.TransferInfo)
// HealthCheck is an optional callback invoked before each heartbeat to
// determine the agent's current status. It runs with a 5-second timeout.
// If nil, the SDK reports "online" on every heartbeat.
// If the callback panics or times out, the SDK sends "degraded".
HealthCheck func(ctx context.Context) agentcard.AgentStatus
// Platform is an optional AI orchestration platform adapter.
// When set, the agent forwards P2P messages and server notifications
// to the platform and routes AI responses back via P2P.
Platform platform.Adapter
// SkipRegistration skips server registration on Start(). Use when the agent
// is already registered and you only need P2P connectivity.
SkipRegistration bool
// Logger is the structured logger. Uses slog.Default() if nil.
Logger *slog.Logger
}
// peerInboxInfo caches a peer's Nostr inbox details for mailbox delivery.
type peerInboxInfo struct {
InboxRelays []string
NostrPubKey string
}
// Agent is the top-level API that assembles all P2P SDK components:
// identity, peer management, discovery, signaling, and security.
type Agent struct {
opts Options
keypair *identity.Keypair
peerManager *peer.Manager
discovery discovery.Discovery
signaling pcsignaling.SignalingClient
trustStore *security.TrustStore
msgValidator *security.MessageValidator
sessionKeys map[string]*security.SessionKey // peer public key -> session key
pendingRequests map[string]chan *envelope.Envelope // traceID → response channel
taskTracker *TaskTracker
router *Router
handler MessageHandler
connRequestHandler ConnectionRequestHandler
notificationHandler func(n *NotificationPayload)
platformAdapter platform.Adapter
connManager *conn.Manager
mailbox *transport.Mailbox
fileTransfer *filetransfer.Manager
ftDCHandler func(peerID string, dc filetransfer.DataChannel)
peerInboxCache map[string]*peerInboxInfo // agentID → inbox info
msgCache *transport.MessageCache
agentID string
logger *slog.Logger
mu sync.RWMutex
wg sync.WaitGroup
running bool
versionWarned sync.Once
stopNonceCleaner context.CancelFunc
}
// agentTransportProvider adapts the Agent's peer/transport layer for the file transfer Manager.
type agentTransportProvider struct {
agent *Agent
}
func (p *agentTransportProvider) CreateFileDataChannel(peerID, label string) (filetransfer.DataChannel, error) {
pr, ok := p.agent.peerManager.GetPeer(peerID)
if !ok {
return nil, fmt.Errorf("no connection to peer %s", peerID)
}
wrtc, ok := pr.Transport.(*transport.WebRTCTransport)
if !ok {
return nil, fmt.Errorf("peer %s transport is not WebRTC", peerID)
}
ordered := true
dc, err := wrtc.CreateDataChannel(label, &webrtc.DataChannelInit{
Ordered: &ordered,
})
if err != nil {
return nil, err
}
return filetransfer.NewWebRTCDataChannel(dc), nil
}
func (p *agentTransportProvider) RegisterFileDataChannelHandler(prefix string, handler func(peerID string, dc filetransfer.DataChannel)) {
// We need to register on ALL existing and future WebRTC transports.
// The connection manager creates transports, so we register a callback
// that will be called for each new peer connection.
// For now, we'll register on peers as they connect.
// The handler needs to be registered after each connection is established.
p.agent.mu.Lock()
p.agent.ftDCHandler = func(peerID string, dc filetransfer.DataChannel) {
handler(peerID, dc)
}
p.agent.mu.Unlock()
}
// NewSimple creates an Agent with minimal configuration for enterprise intranet deployments.
// It uses server-based discovery and signaling only (no Nostr, no DHT, no STUN/TURN).
func NewSimple(name, serverURL string, capabilities ...string) (*Agent, error) {
return New(Options{
Name: name,
ServerURL: serverURL,
Capabilities: capabilities,
})
}
// New creates a new Agent with the given options.
func New(opts Options) (*Agent, error) {
logger := opts.Logger
if logger == nil {
logger = slog.Default()
}
// Load or generate keypair.
var kp *identity.Keypair
if opts.KeypairPath != "" {
var err error
kp, err = identity.LoadKeypair(opts.KeypairPath)
if err != nil {
logger.Info("generating new keypair", "path", opts.KeypairPath)
kp, err = identity.GenerateKeypair()
if err != nil {
return nil, fmt.Errorf("generate keypair: %w", err)
}
if err := identity.SaveKeypair(kp, opts.KeypairPath); err != nil {
return nil, fmt.Errorf("save keypair: %w", err)
}
}
} else {
var err error
kp, err = identity.GenerateKeypair()
if err != nil {
return nil, fmt.Errorf("generate keypair: %w", err)
}
}
// Initialize trust store with encryption from keypair seed.
ts := security.NewTrustStore()
storeKey, err := security.DeriveStoreKey(kp.PrivateKey.Seed())
if err != nil {
return nil, fmt.Errorf("derive trust store key: %w", err)
}
ts.SetEncryptionKey(storeKey)
// Zero derived key material — SetEncryptionKey copies internally.
for i := range storeKey {
storeKey[i] = 0
}
if opts.TrustStorePath != "" {
if err := ts.LoadFromFile(opts.TrustStorePath); err != nil {
return nil, fmt.Errorf("load trust store: %w", err)
}
}
// Use provided Discovery or fall back to RegistryClient.
disc := opts.Discovery
if disc == nil {
disc = discovery.NewRegistryClient(opts.ServerURL, logger)
}
// Use provided Signaling or fall back to WebSocket Client.
sig := opts.Signaling
if sig == nil {
sig = pcsignaling.NewClient(opts.ServerURL, "", logger)
}
// Initialize message cache if configured.
var mc *transport.MessageCache
if opts.MessageCachePath != "" {
mc = transport.NewMessageCache()
if err := mc.LoadFromFile(opts.MessageCachePath); err != nil {
logger.Warn("failed to load message cache", "error", err)
}
}
return &Agent{
opts: opts,
keypair: kp,
peerManager: peer.NewManager(logger),
discovery: disc,
signaling: sig,
trustStore: ts,
msgValidator: security.NewMessageValidator(),
sessionKeys: make(map[string]*security.SessionKey),
pendingRequests: make(map[string]chan *envelope.Envelope),
taskTracker: NewTaskTracker(),
router: NewRouter(logger),
peerInboxCache: make(map[string]*peerInboxInfo),
msgCache: mc,
logger: logger,
}, nil
}
// Start registers the agent with the platform and begins accepting connections.
func (a *Agent) Start(ctx context.Context) error {
a.mu.Lock()
if a.running {
a.mu.Unlock()
return fmt.Errorf("agent already running")
}
a.running = true
a.mu.Unlock()
if a.opts.SkipRegistration {
// Derive agent ID from public key without server registration.
a.agentID = a.keypair.PublicKeyString()
} else {
// Build platform metadata for registration.
var regMeta map[string]string
if a.opts.Platform != nil {
regMeta = map[string]string{
"platform_name": a.opts.Platform.Name(),
"platform_protocol": strconv.Itoa(a.opts.Platform.ProtocolVersion()),
}
}
// Register with the platform.
var regErr error
if a.opts.ClaimToken != "" {
// Claim mode: sign the token and use the claim endpoint.
claimer, ok := a.discovery.(discovery.ClaimRegisterer)
if !ok {
a.mu.Lock()
a.running = false
a.mu.Unlock()
return fmt.Errorf("discovery backend does not support claim registration")
}
sig, err := identity.Sign(a.keypair.PrivateKey, []byte(a.opts.ClaimToken))
if err != nil {
a.mu.Lock()
a.running = false
a.mu.Unlock()
return fmt.Errorf("sign claim token: %w", err)
}
card, err := claimer.ClaimRegister(ctx, discovery.ClaimRequest{
Token: a.opts.ClaimToken,
Name: a.opts.Name,
PublicKey: a.keypair.PublicKeyString(),
Capabilities: a.Capabilities(),
Protocols: a.opts.Protocols,
Endpoint: discovery.EndpointReq{URL: "p2p://" + a.keypair.PublicKeyString()},
Signature: sig,
Metadata: regMeta,
})
if err != nil {
regErr = fmt.Errorf("claim register: %w", err)
} else {
a.agentID = card.ID
}
} else {
// Standard registration mode.
card, err := a.discovery.Register(ctx, discovery.RegisterRequest{
Name: a.opts.Name,
PublicKey: a.keypair.PublicKeyString(),
Capabilities: a.Capabilities(),
Endpoint: discovery.EndpointReq{URL: "p2p://" + a.keypair.PublicKeyString()},
Protocols: a.opts.Protocols,
Metadata: regMeta,
})
if err != nil {
regErr = fmt.Errorf("register with platform: %w", err)
} else {
a.agentID = card.ID
}
}
if regErr != nil {
a.mu.Lock()
a.running = false
a.mu.Unlock()
return regErr
}
}
// Set up RegistryClient authentication and sync contacts from server.
if regClient, ok := a.discovery.(*discovery.RegistryClient); ok {
regClient.SetAuth(a.keypair.PrivateKey, a.keypair.PublicKeyString(), a.agentID)
// Sync server contacts → local TrustStore (additive only, non-fatal).
contacts, err := regClient.ListContacts(ctx, a.agentID)
if err != nil {
a.logger.Warn("failed to sync contacts from server", "error", err)
} else {
synced := 0
for _, c := range contacts {
if a.trustStore.Check(c.ContactAgentID) == security.TrustUnknown {
if err := a.trustStore.SetTrust(c.ContactAgentID, security.TrustVerified); err == nil {
synced++
}
}
}
if synced > 0 {
a.logger.Info("synced contacts from server", "added", synced, "total", len(contacts))
}
}
}
// Set up signaling connection.
a.signaling.SetAgentID(a.agentID)
if err := a.signaling.Connect(ctx); err != nil {
a.logger.Warn("signaling connect failed", "error", err)
// Non-fatal — agent can operate without signaling.
}
// Set up bridge message handler for relay-based messaging.
a.signaling.SetBridgeHandler(func(payload []byte) {
var env envelope.Envelope
if err := json.Unmarshal(payload, &env); err != nil {
a.logger.Warn("invalid bridge message", "error", err)
return
}
a.HandleIncomingEnvelope(context.Background(), &env)
})
// Set up notification handler for server notifications via signaling.
a.signaling.SetNotificationHandler(func(payload []byte) {
var n NotificationPayload
if err := json.Unmarshal(payload, &n); err != nil {
a.logger.Warn("invalid notification payload", "error", err)
return
}
// Handle re_register notification from server (e.g. after server restart).
if n.Type == "re_register" {
a.logger.Info("received re-register notification from server")
if regClient, ok := a.discovery.(*discovery.RegistryClient); ok {
a.reregister(ctx, regClient)
}
return
}
a.mu.RLock()
handler := a.notificationHandler
a.mu.RUnlock()
if handler != nil {
handler(&n)
}
})
// Start connection orchestrator with connection gate.
x25519Pub, _ := a.keypair.X25519PublicKeyString()
a.connManager = conn.New(conn.Config{
AgentID: a.agentID,
Signaling: a.signaling,
PeerManager: a.peerManager,
MsgHandler: a.HandleIncomingEnvelope,
X25519PubKey: x25519Pub,
OnSession: a.EstablishSession,
OnContactAdded: func(agentID string) {
if err := a.trustStore.SetTrust(agentID, security.TrustVerified); err != nil {
a.logger.Warn("failed to set trust for new contact", "agent_id", agentID, "error", err)
return
}
a.logger.Info("contact added via server notification", "agent_id", agentID)
},
ConnectionGate: func(peerID string) bool {
level := a.trustStore.Check(peerID)
if level == security.TrustBlocked {
return false
}
if a.trustStore.IsAllowed(peerID) {
return true
}
// Unknown peer: call owner's handler if registered.
a.mu.RLock()
handler := a.connRequestHandler
a.mu.RUnlock()
if handler != nil {
return handler(ctx, &ConnectionRequest{
FromAgentID: peerID,
Timestamp: time.Now(),
})
}
return false // default deny
},
Logger: a.logger,
})
a.connManager.Start(ctx)
// Initialize file transfer manager.
ftCfg := filetransfer.Config{
AgentID: a.agentID,
PrivateKey: a.keypair.PrivateKey,
SendEnvelope: func(sendCtx context.Context, env *envelope.Envelope) error {
return a.Send(sendCtx, env)
},
GetSessionKey: func(peerID string) []byte {
a.mu.RLock()
sk := a.sessionKeys[peerID]
a.mu.RUnlock()
if sk == nil {
return nil
}
// Export the raw key bytes for chunk encryption.
return sk.KeyBytes()
},
TrustCheck: func(peerID string) bool {
return a.trustStore.IsAllowed(peerID)
},
Transport: &agentTransportProvider{agent: a},
DownloadDir: a.opts.FileTransferDir,
ResumeStatePath: a.opts.ResumeStatePath,
Logger: a.logger,
}
if a.opts.OnFileTransferComplete != nil {
ftCfg.OnComplete = func(t *filetransfer.Transfer) {
a.opts.OnFileTransferComplete(t.Info())
}
}
a.fileTransfer = filetransfer.NewManager(ftCfg)
a.fileTransfer.SetPeerPublicKeyResolver(func(peerID string) ed25519.PublicKey {
pubKeyStr := a.resolvePeerPublicKey(peerID)
if pubKeyStr == "" {
return nil
}
pubKey, err := identity.ParsePublicKey(pubKeyStr)
if err != nil {
return nil
}
return pubKey
})
a.fileTransfer.Start()
a.Handle("file_transfer", a.fileTransfer.HandleEnvelope)
// Start nonce cleanup goroutine.
nonceCtx, nonceCancel := context.WithCancel(ctx)
a.stopNonceCleaner = nonceCancel
a.wg.Add(1)
go func() {
defer a.wg.Done()
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-nonceCtx.Done():
return
case <-ticker.C:
a.msgValidator.CleanExpiredNonces()
}
}
}()
// Initialize mailbox if inbox relays are configured.
if len(a.opts.InboxRelays) > 0 {
mb, err := transport.NewMailbox(transport.MailboxConfig{
InboxRelays: a.opts.InboxRelays,
Ed25519Seed: a.keypair.PrivateKey.Seed(),
AgentID: a.agentID,
TTL: a.opts.MailboxTTL,
SyncInterval: a.opts.InboxSyncInterval,
OutboxPath: a.opts.OutboxStatePath,
LastSyncPath: a.opts.LastSyncPath,
Logger: a.logger,
})
if err != nil {
a.logger.Warn("failed to initialize mailbox", "error", err)
} else {
mb.OnMessage(func(msgCtx context.Context, env *envelope.Envelope) {
a.HandleIncomingEnvelope(msgCtx, env)
})
mb.Start(ctx)
a.mailbox = mb
a.logger.Info("mailbox enabled", "inbox_relays", a.opts.InboxRelays)
}
}
// Initialize platform adapter integration.
if a.opts.Platform != nil {
pa := a.opts.Platform
// Verify adapter protocol compatibility before connecting.
if err := platform.CheckProtocolVersion(pa); err != nil {
a.mu.Lock()
a.running = false
a.mu.Unlock()
return fmt.Errorf("platform compatibility: %w", err)
}
// Advisory check: warn if SDK is outside adapter's declared compat range.
platform.CheckSDKCompat(pa, a.logger)
pa.SetOutboundHandler(func(sessionKey, text string) {
peerID := platform.ParsePeerFromSessionKey(sessionKey)
if peerID == "" {
return
}
env := envelope.New(a.agentID, peerID, "peerclaw", []byte(text))
_ = a.Send(context.Background(), env)
})
if err := pa.Connect(ctx); err != nil {
a.logger.Warn("platform connect failed", "platform", pa.Name(), "error", err)
} else {
a.platformAdapter = pa
// Log platform adapter compatibility summary.
attrs := []any{
"platform", pa.Name(),
"protocol_version", pa.ProtocolVersion(),
"sdk_version", sdkversion.Version,
}
if v, ok := pa.(platform.Versioned); ok {
attrs = append(attrs, "plugin_version", v.PluginVersion())
}
a.logger.Info("platform adapter connected", attrs...)
}
// Forward notifications to platform.
if a.platformAdapter != nil {
a.OnNotification(func(n *NotificationPayload) {
text := platform.FormatNotification(n.Severity, n.Title, n.Body)
_ = a.platformAdapter.InjectNotification(ctx, platform.NotificationSessionKey, text, "peerclaw-notification")
})
}
// Forward P2P messages to platform.
if a.platformAdapter != nil {
prevHandler := a.handler
a.OnMessage(func(msgCtx context.Context, env *envelope.Envelope) {
sessionKey := platform.SessionKeyForPeer(env.Source)
_ = a.platformAdapter.SendChat(msgCtx, sessionKey, string(env.Payload))
if prevHandler != nil {
prevHandler(msgCtx, env)
}
})
}
}
// Start periodic heartbeat loop.
if !a.opts.SkipRegistration {
a.wg.Add(1)
go func() {
defer a.wg.Done()
a.heartbeatLoop(ctx)
}()
}
a.logger.Info("agent started", "id", a.agentID, "name", a.opts.Name, "pubkey", a.keypair.PublicKeyString())
return nil
}
// Stop deregisters the agent and closes all connections.
func (a *Agent) Stop(ctx context.Context) error {
a.mu.Lock()
if !a.running {
a.mu.Unlock()
return nil
}
a.running = false
// Close all pending request channels.
for traceID, ch := range a.pendingRequests {
close(ch)
delete(a.pendingRequests, traceID)
}
a.mu.Unlock()
// Stop nonce cleanup goroutine.
if a.stopNonceCleaner != nil {
a.stopNonceCleaner()
}
// Deregister from platform.
if a.agentID != "" {
if err := a.discovery.Deregister(ctx, a.agentID); err != nil {
a.logger.Warn("failed to deregister", "error", err)
}
}
// Stop connection orchestrator.
if a.connManager != nil {
a.connManager.Stop()
}
// Stop mailbox.
if a.mailbox != nil {
a.mailbox.Stop()
}
// Save message cache.
if a.msgCache != nil && a.opts.MessageCachePath != "" {
if err := a.msgCache.SaveToFile(a.opts.MessageCachePath); err != nil {
a.logger.Warn("failed to save message cache", "error", err)
}
}
// Save trust store.
if a.opts.TrustStorePath != "" {
if err := a.trustStore.SaveToFile(a.opts.TrustStorePath); err != nil {
a.logger.Warn("failed to save trust store", "error", err)
}
}
// Close platform adapter.
if a.platformAdapter != nil {
a.platformAdapter.Close()
}
// Close signaling and peers.
a.signaling.Close()
a.peerManager.Close()
// Wait for background goroutines (heartbeat, nonce cleanup) to finish.
a.wg.Wait()
a.logger.Info("agent stopped", "id", a.agentID)
return nil
}
// heartbeatLoop sends periodic heartbeats to keep the agent online.
// It also checks version advisories from the server on each heartbeat.
func (a *Agent) heartbeatLoop(ctx context.Context) {
regClient, ok := a.discovery.(*discovery.RegistryClient)
if !ok {
return
}
const heartbeatInterval = 30 * time.Second
// Send the first heartbeat immediately.
a.sendHeartbeat(ctx, regClient)
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
a.mu.RLock()
running := a.running
a.mu.RUnlock()
if !running {
return
}
a.sendHeartbeat(ctx, regClient)
}
}
}
// HealthCheckTimeout is the maximum time allowed for a HealthCheck callback.
const HealthCheckTimeout = 5 * time.Second
// evaluateHealth determines the agent's current status by consulting the
// user-provided HealthCheck callback and (if present) the platform adapter's
// HealthChecker interface.
func (a *Agent) evaluateHealth(ctx context.Context) agentcard.AgentStatus {
userStatus := agentcard.StatusOnline
if a.opts.HealthCheck != nil {
hctx, cancel := context.WithTimeout(ctx, HealthCheckTimeout)
defer cancel()
ch := make(chan agentcard.AgentStatus, 1)
go func() {
defer func() {
if r := recover(); r != nil {
a.logger.Error("HealthCheck panicked", "recover", r)
ch <- agentcard.StatusDegraded
}
}()
ch <- a.opts.HealthCheck(hctx)
}()
select {
case s := <-ch:
userStatus = s
case <-hctx.Done():
a.logger.Warn("HealthCheck timed out")
userStatus = agentcard.StatusDegraded
}
}
// If the user says offline, honour it immediately.
if userStatus == agentcard.StatusOffline {
return agentcard.StatusOffline
}
// Check platform adapter health if it implements HealthChecker.
if a.platformAdapter != nil {
if hc, ok := a.platformAdapter.(platform.HealthChecker); ok {
ahctx, acancel := context.WithTimeout(ctx, HealthCheckTimeout)
defer acancel()
if err := hc.HealthCheck(ahctx); err != nil {
a.logger.Warn("platform adapter health check failed",
"adapter", a.platformAdapter.Name(), "error", err)
if userStatus == agentcard.StatusOnline {
return agentcard.StatusDegraded
}
}
}
}
return userStatus
}
// reregister attempts to re-register the agent with the server.
// This is called when the server has lost the agent record (e.g. after a restart).
func (a *Agent) reregister(ctx context.Context, regClient *discovery.RegistryClient) {
var regMeta map[string]string
if a.platformAdapter != nil {
regMeta = map[string]string{
"platform_name": a.platformAdapter.Name(),
"platform_protocol": strconv.Itoa(a.platformAdapter.ProtocolVersion()),
}
}
card, err := regClient.Register(ctx, discovery.RegisterRequest{
Name: a.opts.Name,
PublicKey: a.keypair.PublicKeyString(),
Capabilities: a.Capabilities(),
Endpoint: discovery.EndpointReq{URL: "p2p://" + a.keypair.PublicKeyString()},
Protocols: a.opts.Protocols,
Metadata: regMeta,
})
if err != nil {
a.logger.Error("re-register failed", "error", err)
return
}
a.logger.Info("re-registered with server", "id", card.ID)
}
// sendHeartbeat sends a single heartbeat and processes the server response.
func (a *Agent) sendHeartbeat(ctx context.Context, regClient *discovery.RegistryClient) {
status := string(a.evaluateHealth(ctx))
resp, err := regClient.Heartbeat(ctx, a.agentID, status)
if err != nil {
if discovery.IsNotFound(err) {
a.logger.Warn("agent not found on server, attempting re-register")
a.reregister(ctx, regClient)
} else {
a.logger.Debug("heartbeat failed", "error", err)
}
return
}
if resp.VersionAdvisory != nil && resp.VersionAdvisory.SDKUpdateAvailable {
a.versionWarned.Do(func() {
a.logger.Warn("a newer PeerClaw SDK is available",
"current", sdkversion.Version,
"latest", resp.VersionAdvisory.LatestSDK,
"release_url", resp.VersionAdvisory.ReleaseURL,
)
})
}
}
// Send sends an envelope to a peer using P2P (preferred) or signaling relay (fallback).
// The payload is encrypted (if a session key exists), then the envelope is signed
// covering the ciphertext + headers (encrypt-then-sign for pre-authentication).
func (a *Agent) Send(ctx context.Context, env *envelope.Envelope) error {
// Outbound whitelist check — bypass for contact requests.
isContactRequest := env.Metadata != nil && env.Metadata["peerclaw.type"] == "contact_request"
if !isContactRequest && !a.trustStore.IsAllowed(env.Destination) {
return fmt.Errorf("destination %s is not whitelisted", env.Destination)
}
// Set anti-replay fields.
env.Nonce = uuid.New().String()
env.Timestamp = time.Now()
env.Source = a.agentID
// Step 1: Encrypt payload if session key exists (encrypt-then-sign).
a.mu.RLock()
sk := a.sessionKeys[env.Destination]
a.mu.RUnlock()
if sk != nil {
sk.IncrementCount()
aad := envelopeAAD(env)
encrypted, err := sk.EncryptWithAAD(env.Payload, aad)
if err != nil {
return fmt.Errorf("encrypt payload: %w", err)
}
env.Payload = encrypted
env.Encrypted = true
x25519Pub, err := a.keypair.X25519PublicKeyString()
if err != nil {
return fmt.Errorf("get X25519 public key: %w", err)
}
env.SenderX25519 = x25519Pub
// Trigger rekey if thresholds exceeded.
if sk.NeedsRekey() {
go a.initiateRekey(env.Destination)
}
}
// Step 2: Sign the full envelope. When encrypted, the signature covers
// the ciphertext, enabling pre-authentication before decryption.
if err := identity.SignEnvelope(env, a.keypair.PrivateKey); err != nil {
return fmt.Errorf("sign envelope: %w", err)
}
// 1. Try existing P2P connection.
if err := a.peerManager.Send(ctx, env.Destination, env); err == nil {
return nil
}
// 2. Try establishing a new P2P connection.
if a.connManager != nil {
connCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
if err := a.connManager.Connect(connCtx, env.Destination); err == nil {
if err := a.peerManager.Send(ctx, env.Destination, env); err == nil {
return nil
}
}
a.logger.Debug("P2P connect failed, falling back to relay", "dest", env.Destination)
}
// 3. Fallback: send via signaling relay (WebSocket bridge_message).
if err := a.sendViaRelay(ctx, env); err == nil {
return nil
}
a.logger.Debug("relay send failed, trying mailbox", "dest", env.Destination)
// 4. Fallback: send via Nostr mailbox (offline inbox).
if a.mailbox != nil {
if err := a.sendViaMailbox(ctx, env); err == nil {
return nil
}
a.logger.Debug("mailbox send failed", "dest", env.Destination)
}
// 5. Last resort: queue in local message cache.
if a.msgCache != nil {
return a.msgCache.Enqueue(env.Destination, env)
}
return fmt.Errorf("all delivery channels failed for %s", env.Destination)
}
// sendViaRelay sends an envelope through the signaling server as a bridge message.
func (a *Agent) sendViaRelay(ctx context.Context, env *envelope.Envelope) error {
data, err := json.Marshal(env)
if err != nil {
return fmt.Errorf("marshal envelope: %w", err)
}
return a.signaling.Send(ctx, pccoresignaling.SignalMessage{
Type: pccoresignaling.MessageTypeBridgeMessage,
From: a.agentID,
To: env.Destination,
Payload: data,
Timestamp: time.Now(),
})
}
// sendViaMailbox sends an envelope via the Nostr mailbox channel.
func (a *Agent) sendViaMailbox(ctx context.Context, env *envelope.Envelope) error {
info, err := a.resolveInboxRelays(ctx, env.Destination)
if err != nil {
return err
}
return a.mailbox.SendToInbox(ctx, env, info.InboxRelays, info.NostrPubKey)
}
// resolveInboxRelays looks up a peer's inbox relays and Nostr public key.
// It checks the local cache first, then queries the discovery directory.
func (a *Agent) resolveInboxRelays(ctx context.Context, agentID string) (*peerInboxInfo, error) {
a.mu.Lock()
if info, ok := a.peerInboxCache[agentID]; ok {
a.mu.Unlock()
return info, nil
}
a.mu.Unlock()
// Try to get from peer manager.
if p, ok := a.peerManager.GetPeer(agentID); ok {
if len(p.InboxRelays) > 0 && p.NostrPubKey != "" {
info := &peerInboxInfo{
InboxRelays: p.InboxRelays,
NostrPubKey: p.NostrPubKey,
}
a.mu.Lock()
a.peerInboxCache[agentID] = info
a.mu.Unlock()
return info, nil
}
}
// Query discovery for the agent card.