-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
1258 lines (1118 loc) · 49.3 KB
/
Copy pathcoverage.html
File metadata and controls
1258 lines (1118 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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>a2a-skill: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/jarancibia/a2a-skill/a2a_client.go (80.5%)</option>
<option value="file1">github.com/jarancibia/a2a-skill/cmd/a2a/main.go (0.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">// Package a2a provides a Go client for the a2a peer-to-peer messaging bus.
//
// Every connect() call applies the WAL invariant: creates the parent directory
// if missing (no prior `a2a init` required), then sets PRAGMA journal_mode=WAL
// and PRAGMA busy_timeout=5000 for concurrent-writer safety.
//
// See src/AGENTS.md for the authoritative WAL invariant documentation.
package a2a
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
_ "github.com/mattn/go-sqlite3"
)
// Client represents an a2a messaging client
type Client struct {
Project string
AgentID string
dbPath string
}
// Message represents a message in the bus
type Message struct {
ID int `json:"id"`
Sender string `json:"sender"`
Recipient *string `json:"recipient"`
Body string `json:"body"`
ThreadID *string `json:"thread_id"`
CreatedAt float64 `json:"created_at"`
}
// Peer represents an agent on the bus
type Peer struct {
ID string `json:"id"`
Role string `json:"role"`
Status string `json:"status"`
CLI string `json:"cli"`
}
// Stats represents bus statistics
type Stats struct {
Messages int `json:"messages"`
DirectMessages int `json:"direct_messages"`
Broadcasts int `json:"broadcasts"`
Threads int `json:"threads"`
AgentsActive int `json:"agents_active"`
AgentsDone int `json:"agents_done"`
TopSenders []struct {
Agent string `json:"agent"`
Count int `json:"count"`
} `json:"top_senders"`
}
// NewClient creates a new a2a client
func NewClient(project, agentID string) *Client <span class="cov8" title="1">{
dbDir := filepath.Join(os.Getenv("HOME"), ".a2a", project)
dbPath := filepath.Join(dbDir, "database.db")
return &Client{
Project: project,
AgentID: agentID,
dbPath: dbPath,
}
}</span>
// connect opens the database connection, applying the WAL invariant.
// Creates the parent directory if it does not exist.
func (c *Client) connect() (*sql.DB, error) <span class="cov8" title="1">{
if err := os.MkdirAll(filepath.Dir(c.dbPath), 0755); err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">db, err := sql.Open("sqlite3", c.dbPath)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">if _, err := db.Exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;"); err != nil </span><span class="cov0" title="0">{
db.Close()
return nil, err
}</span>
<span class="cov8" title="1">db.SetConnMaxLifetime(time.Second * 5)
return db, nil</span>
}
// Send sends a message to a peer (or broadcast if recipient is "all"/"*"/"broadcast").
// threadID may be empty string for no thread. ttlSeconds may be nil for no expiry.
func (c *Client) Send(to, message, threadID string, ttlSeconds *int) (int64, error) <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return 0, err
}</span>
<span class="cov8" title="1">defer db.Close()
recipient := to
if to == "all" || to == "*" || to == "broadcast" </span><span class="cov8" title="1">{
recipient = ""
}</span>
<span class="cov8" title="1">var tid *string
if threadID != "" </span><span class="cov8" title="1">{
tid = &threadID
}</span>
<span class="cov8" title="1">result, err := db.Exec(
"INSERT INTO messages(sender, recipient, body, thread_id, ttl_seconds, created_at) VALUES (?,?,?,?,?,?)",
c.AgentID, recipient, message, tid, ttlSeconds, nowSec(),
)
if err != nil </span><span class="cov0" title="0">{
return 0, err
}</span>
<span class="cov8" title="1">return result.LastInsertId()</span>
}
// SendSimple sends a message without thread or TTL. Backward-compat wrapper for old 3-arg calls.
func (c *Client) SendSimple(to, message string) (int64, error) <span class="cov8" title="1">{
return c.Send(to, message, "", nil)
}</span>
// Recv receives messages. Calls CleanupExpired and Touch at start.
func (c *Client) Recv(wait int, unreadOnly bool, includeSelf bool, limit int) ([]Message, error) <span class="cov8" title="1">{
c.CleanupExpired()
c.Touch()
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer db.Close()
deadline := time.Now().Add(time.Duration(wait) * time.Second)
pollInterval := 100 * time.Millisecond
for </span><span class="cov8" title="1">{
query := "SELECT id, sender, recipient, body, thread_id, created_at FROM messages WHERE (recipient = ? OR recipient IS NULL)"
args := []interface{}{c.AgentID}
if !includeSelf </span><span class="cov8" title="1">{
query += " AND sender != ?"
args = append(args, c.AgentID)
}</span>
<span class="cov8" title="1">if unreadOnly </span><span class="cov8" title="1">{
query += " AND NOT EXISTS (SELECT 1 FROM reads WHERE agent_id = ? AND message_id = messages.id)"
args = append(args, c.AgentID)
}</span>
<span class="cov8" title="1">query += " ORDER BY created_at ASC"
if limit > 0 </span><span class="cov8" title="1">{
query += " LIMIT ?"
args = append(args, limit)
}</span>
<span class="cov8" title="1">rows, err := db.Query(query, args...)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">var messages []Message
ts := nowSec()
for rows.Next() </span><span class="cov8" title="1">{
var m Message
err := rows.Scan(&m.ID, &m.Sender, &m.Recipient, &m.Body, &m.ThreadID, &m.CreatedAt)
if err != nil </span><span class="cov0" title="0">{
rows.Close()
return nil, err
}</span>
<span class="cov8" title="1">messages = append(messages, m)
// Mark as read
db.Exec("INSERT OR IGNORE INTO reads(agent_id, message_id, read_at) VALUES (?,?,?)",
c.AgentID, m.ID, ts)</span>
}
<span class="cov8" title="1">rows.Close()
if len(messages) > 0 </span><span class="cov8" title="1">{
return messages, nil
}</span>
<span class="cov8" title="1">if wait == 0 || time.Now().After(deadline) </span><span class="cov8" title="1">{
return messages, nil
}</span>
<span class="cov0" title="0">time.Sleep(pollInterval)</span>
}
}
// Peek views recent messages without marking read. Calls CleanupExpired first.
func (c *Client) Peek(limit int) ([]Message, error) <span class="cov8" title="1">{
c.CleanupExpired()
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer db.Close()
rows, err := db.Query(
"SELECT id, sender, recipient, body, thread_id, created_at FROM messages ORDER BY created_at DESC LIMIT ?",
limit,
)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer rows.Close()
var messages []Message
for rows.Next() </span><span class="cov8" title="1">{
var m Message
err := rows.Scan(&m.ID, &m.Sender, &m.Recipient, &m.Body, &m.ThreadID, &m.CreatedAt)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">messages = append(messages, m)</span>
}
// Reverse to get oldest first
<span class="cov8" title="1">for i, j := 0, len(messages)-1; i < j; i, j = i+1, j-1 </span><span class="cov8" title="1">{
messages[i], messages[j] = messages[j], messages[i]
}</span>
<span class="cov8" title="1">return messages, nil</span>
}
// ListPeers returns list of registered agents
func (c *Client) ListPeers() ([]Peer, error) <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer db.Close()
rows, err := db.Query("SELECT id, role, cli, status FROM agents ORDER BY created_at")
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer rows.Close()
var peers []Peer
for rows.Next() </span><span class="cov8" title="1">{
var p Peer
err := rows.Scan(&p.ID, &p.Role, &p.CLI, &p.Status)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">peers = append(peers, p)</span>
}
<span class="cov8" title="1">return peers, nil</span>
}
// SetStatus updates agent status
func (c *Client) SetStatus(status string) error <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">defer db.Close()
_, err = db.Exec(
"UPDATE agents SET status=?, last_seen=? WHERE id=?",
status, nowSec(), c.AgentID,
)
return err</span>
}
// GetStatus gets agent status
func (c *Client) GetStatus(agentID string) (string, error) <span class="cov8" title="1">{
if agentID == "" </span><span class="cov0" title="0">{
agentID = c.AgentID
}</span>
<span class="cov8" title="1">db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov8" title="1">defer db.Close()
var status string
err = db.QueryRow("SELECT status FROM agents WHERE id=?", agentID).Scan(&status)
if err == sql.ErrNoRows </span><span class="cov0" title="0">{
return "", nil
}</span>
<span class="cov8" title="1">return status, err</span>
}
// Search searches messages by content
func (c *Client) Search(query string, limit int) ([]Message, error) <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer db.Close()
rows, err := db.Query(
"SELECT id, sender, recipient, body, thread_id, created_at FROM messages WHERE body LIKE ? ORDER BY created_at DESC LIMIT ?",
fmt.Sprintf("%%%s%%", query), limit,
)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer rows.Close()
var messages []Message
for rows.Next() </span><span class="cov8" title="1">{
var m Message
err := rows.Scan(&m.ID, &m.Sender, &m.Recipient, &m.Body, &m.ThreadID, &m.CreatedAt)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">messages = append(messages, m)</span>
}
<span class="cov8" title="1">return messages, nil</span>
}
// Thread gets all messages in a thread
func (c *Client) Thread(threadID string) ([]Message, error) <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer db.Close()
rows, err := db.Query(
"SELECT id, sender, recipient, body, thread_id, created_at FROM messages WHERE thread_id = ? ORDER BY created_at ASC",
threadID,
)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer rows.Close()
var messages []Message
for rows.Next() </span><span class="cov8" title="1">{
var m Message
err := rows.Scan(&m.ID, &m.Sender, &m.Recipient, &m.Body, &m.ThreadID, &m.CreatedAt)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">messages = append(messages, m)</span>
}
<span class="cov8" title="1">return messages, nil</span>
}
// Stats returns bus statistics
func (c *Client) Stats() (*Stats, error) <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">defer db.Close()
stats := &Stats{}
// Message counts
db.QueryRow("SELECT COUNT(*) FROM messages").Scan(&stats.Messages)
db.QueryRow("SELECT COUNT(*) FROM messages WHERE recipient IS NULL").Scan(&stats.Broadcasts)
db.QueryRow("SELECT COUNT(DISTINCT thread_id) FROM messages WHERE thread_id IS NOT NULL").Scan(&stats.Threads)
stats.DirectMessages = stats.Messages - stats.Broadcasts
// Agent counts
db.QueryRow("SELECT COUNT(*) FROM agents WHERE status='active'").Scan(&stats.AgentsActive)
db.QueryRow("SELECT COUNT(*) FROM agents WHERE status='done'").Scan(&stats.AgentsDone)
// Top senders
rows, err := db.Query(
"SELECT sender, COUNT(*) as count FROM messages GROUP BY sender ORDER BY count DESC LIMIT 5",
)
if err == nil </span><span class="cov8" title="1">{
defer rows.Close()
for rows.Next() </span><span class="cov8" title="1">{
var sender string
var count int
if err := rows.Scan(&sender, &count); err == nil </span><span class="cov8" title="1">{
stats.TopSenders = append(stats.TopSenders, struct {
Agent string `json:"agent"`
Count int `json:"count"`
}{sender, count})
}</span>
}
}
<span class="cov8" title="1">return stats, nil</span>
}
// StatsJSON returns stats as JSON
func (c *Client) StatsJSON() (string, error) <span class="cov8" title="1">{
stats, err := c.Stats()
if err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov8" title="1">b, err := json.MarshalIndent(stats, "", " ")
return string(b), err</span>
}
// SchemaDDL matches a2a.py SCHEMA exactly
const SchemaDDL = `
CREATE TABLE IF NOT EXISTS agents (
id TEXT PRIMARY KEY,
role TEXT,
prompt TEXT,
cli TEXT,
status TEXT NOT NULL DEFAULT 'active',
pid INTEGER,
created_at REAL NOT NULL,
last_seen REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender TEXT NOT NULL,
recipient TEXT,
body TEXT NOT NULL,
thread_id TEXT,
ttl_seconds INTEGER,
created_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS reads (
agent_id TEXT NOT NULL,
message_id INTEGER NOT NULL,
read_at REAL NOT NULL,
PRIMARY KEY (agent_id, message_id)
);
CREATE INDEX IF NOT EXISTS idx_messages_recipient ON messages(recipient);
CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages(thread_id);
CREATE INDEX IF NOT EXISTS idx_messages_created ON messages(created_at);
`
// nowSec returns sub-second precision timestamp matching Python's time.time()
func nowSec() float64 <span class="cov8" title="1">{
return float64(time.Now().UnixNano()) / 1e9
}</span>
// InitProject creates the database and schema. No-op if already exists.
func (c *Client) InitProject() error <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">defer db.Close()
if _, err := db.Exec(SchemaDDL); err != nil </span><span class="cov0" title="0">{
return err
}</span>
// migrate: add ttl_seconds if missing (older dbs)
<span class="cov8" title="1">var hasTTL bool
_ = db.QueryRow("SELECT COUNT(*) FROM pragma_table_info('messages') WHERE name='ttl_seconds'").Scan(&hasTTL)
if !hasTTL </span><span class="cov0" title="0">{
db.Exec("ALTER TABLE messages ADD COLUMN ttl_seconds INTEGER")
}</span>
<span class="cov8" title="1">return nil</span>
}
// Register registers an agent. If upsert is true, updates existing.
func (c *Client) Register(role, prompt, cli string, pid int, upsert bool) error <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">defer db.Close()
ts := nowSec()
_, err = db.Exec(
`INSERT INTO agents(id, role, prompt, cli, status, pid, created_at, last_seen)
VALUES (?,?,?,?,?,?,?,?)`,
c.AgentID, role, prompt, cli, "active", pid, ts, ts,
)
if err != nil </span><span class="cov8" title="1">{
if upsert </span><span class="cov8" title="1">{
_, err = db.Exec(
`UPDATE agents SET role=COALESCE(?,role), prompt=COALESCE(?,prompt),
cli=COALESCE(?,cli), pid=COALESCE(?,pid), status='active', last_seen=?
WHERE id=?`,
role, prompt, cli, pid, ts, c.AgentID,
)
return err
}</span>
<span class="cov8" title="1">return fmt.Errorf("agent '%s' already registered (use upsert=true to update): %w", c.AgentID, err)</span>
}
<span class="cov8" title="1">return nil</span>
}
// Unregister removes an agent from the bus.
func (c *Client) Unregister() error <span class="cov0" title="0">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">defer db.Close()
_, err = db.Exec("DELETE FROM agents WHERE id=?", c.AgentID)
return err</span>
}
// Touch updates last_seen for the agent.
func (c *Client) Touch() error <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">defer db.Close()
_, err = db.Exec("UPDATE agents SET last_seen=? WHERE id=?", nowSec(), c.AgentID)
return err</span>
}
// CleanupExpired deletes messages past their TTL. Returns count deleted.
func (c *Client) CleanupExpired() (int, error) <span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return 0, err
}</span>
<span class="cov8" title="1">defer db.Close()
res, err := db.Exec(
"DELETE FROM messages WHERE ttl_seconds IS NOT NULL AND created_at + ttl_seconds < ?",
nowSec(),
)
if err != nil </span><span class="cov0" title="0">{
return 0, err
}</span>
<span class="cov8" title="1">n, _ := res.RowsAffected()
return int(n), nil</span>
}
// ProjectInfo returns resolved project information.
func (c *Client) ProjectInfo() map[string]interface{} <span class="cov8" title="1">{
_, err := os.Stat(c.dbPath)
return map[string]interface{}{
"project": c.Project,
"db": c.dbPath,
"exists": err == nil,
}
}</span>
// Clear deletes the database file entirely.
func (c *Client) Clear() error <span class="cov8" title="1">{
return os.Remove(c.dbPath)
}</span>
// Wait blocks until at least count unread messages exist for this agent,
// or until timeout seconds elapse. Returns the number of unread messages found.
func (c *Client) Wait(count int, timeoutSec float64) (int, error) <span class="cov8" title="1">{
deadline := time.Now().Add(time.Duration(timeoutSec * float64(time.Second)))
pollInterval := 500 * time.Millisecond
for </span><span class="cov8" title="1">{
db, err := c.connect()
if err != nil </span><span class="cov0" title="0">{
return 0, err
}</span>
<span class="cov8" title="1">var unread int
err = db.QueryRow(
`SELECT COUNT(*) FROM messages m
WHERE (m.recipient = ? OR m.recipient IS NULL)
AND m.sender != ?
AND NOT EXISTS (SELECT 1 FROM reads r WHERE r.agent_id = ? AND r.message_id = m.id)`,
c.AgentID, c.AgentID, c.AgentID,
).Scan(&unread)
db.Close()
if err != nil </span><span class="cov0" title="0">{
return 0, err
}</span>
<span class="cov8" title="1">if unread >= count </span><span class="cov8" title="1">{
return unread, nil
}</span>
<span class="cov0" title="0">if time.Now().After(deadline) </span><span class="cov0" title="0">{
return unread, nil
}</span>
<span class="cov0" title="0">time.Sleep(pollInterval)</span>
}
}
</pre>
<pre class="file" id="file1" style="display: none">package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/jarancibia/a2a-skill"
)
const Version = "1.0.0"
var _ = strconv.Itoa // ensure import
// hasFlag checks if a flag (--name) is present in os.Args[2:].
func hasFlag(name string) bool <span class="cov0" title="0">{
for _, a := range os.Args[2:] </span><span class="cov0" title="0">{
if a == name </span><span class="cov0" title="0">{
return true
}</span>
}
<span class="cov0" title="0">return false</span>
}
// getFlagValue returns the value after --name in os.Args[2:], or empty string.
func getFlagValue(name string) string <span class="cov0" title="0">{
for i, a := range os.Args[2:] </span><span class="cov0" title="0">{
if a == name && i+1 < len(os.Args[2:]) </span><span class="cov0" title="0">{
return os.Args[2+i+1]
}</span>
}
<span class="cov0" title="0">return ""</span>
}
// getFlagInt returns int value for --name.
func getFlagInt(name string) int <span class="cov0" title="0">{
v := getFlagValue(name)
if v == "" </span><span class="cov0" title="0">{
return 0
}</span>
<span class="cov0" title="0">n, _ := strconv.Atoi(v)
return n</span>
}
// getFlagFloat returns float64 for --name.
func getFlagFloat(name string) float64 <span class="cov0" title="0">{
v := getFlagValue(name)
if v == "" </span><span class="cov0" title="0">{
return 0
}</span>
<span class="cov0" title="0">n, _ := strconv.ParseFloat(v, 64)
return n</span>
}
// positionalArgs returns non-flag positional args from os.Args[2:],
// skipping known flag names and their values.
func positionalArgs() []string <span class="cov0" title="0">{
var args []string
skipNext := false
for i := 2; i < len(os.Args); i++ </span><span class="cov0" title="0">{
arg := os.Args[i]
if skipNext </span><span class="cov0" title="0">{
skipNext = false
continue</span>
}
<span class="cov0" title="0">if strings.HasPrefix(arg, "--") </span><span class="cov0" title="0">{
// --flag value: skip both unless it's --bool-flag without value
if i+1 < len(os.Args) && !strings.HasPrefix(os.Args[i+1], "--") </span><span class="cov0" title="0">{
skipNext = true
}</span>
<span class="cov0" title="0">continue</span>
}
<span class="cov0" title="0">args = append(args, arg)</span>
}
<span class="cov0" title="0">return args</span>
}
func main() <span class="cov0" title="0">{
if len(os.Args) < 2 </span><span class="cov0" title="0">{
printHelp()
os.Exit(1)
}</span>
<span class="cov0" title="0">cmd := os.Args[1]
switch cmd </span>{
case "init", "register", "unregister", "list", "status",
"send", "recv", "peek", "thread", "search", "stats",
"wait", "clear", "project", "version", "--version", "-v",
"help", "--help", "-h":<span class="cov0" title="0"></span>
default:<span class="cov0" title="0">
fmt.Fprintf(os.Stderr, "a2a: unknown command: %s\n", cmd)
printHelp()
os.Exit(1)</span>
}
<span class="cov0" title="0">switch cmd </span>{
case "version", "--version", "-v":<span class="cov0" title="0">
fmt.Printf("a2a v%s\n", Version)</span>
case "help", "--help", "-h":<span class="cov0" title="0">
printHelp()</span>
case "init":<span class="cov0" title="0">
cmdInit()</span>
case "register":<span class="cov0" title="0">
cmdRegister()</span>
case "unregister":<span class="cov0" title="0">
cmdUnregister()</span>
case "list":<span class="cov0" title="0">
cmdList()</span>
case "status":<span class="cov0" title="0">
cmdStatus()</span>
case "send":<span class="cov0" title="0">
cmdSend()</span>
case "recv":<span class="cov0" title="0">
cmdRecv()</span>
case "peek":<span class="cov0" title="0">
cmdPeek()</span>
case "thread":<span class="cov0" title="0">
cmdThread()</span>
case "search":<span class="cov0" title="0">
cmdSearch()</span>
case "stats":<span class="cov0" title="0">
cmdStats()</span>
case "wait":<span class="cov0" title="0">
cmdWait()</span>
case "clear":<span class="cov0" title="0">
cmdClear()</span>
case "project":<span class="cov0" title="0">
cmdProject()</span>
}
}
func printHelp() <span class="cov0" title="0">{
fmt.Println(`a2a — agent-to-agent peer messaging over SQLite
Usage:
a2a <command> [options]
Commands:
init create project database
register <id> register an agent
unregister <id> remove an agent
list [--json] list agents
status <state> --as <id> update agent status (active|idle|done|blocked)
send <to> <body> send a message (--from required)
recv --as <id> receive messages
peek [--limit N] show recent messages (no read-tracking)
thread <id> show all messages in a thread
search <query> search messages by content
stats [--json] show bus statistics
wait --as <id> block until N unread messages or timeout
clear --yes delete the project database
project show resolved project info
version show version information
Project resolution:
--project NAME > $A2A_PROJECT > basename($PWD)`)
}</span>
func resolveProject() string <span class="cov0" title="0">{
for i, arg := range os.Args </span><span class="cov0" title="0">{
if arg == "--project" && i+1 < len(os.Args) </span><span class="cov0" title="0">{
return os.Args[i+1]
}</span>
}
<span class="cov0" title="0">if env := os.Getenv("A2A_PROJECT"); env != "" </span><span class="cov0" title="0">{
return env
}</span>
<span class="cov0" title="0">wd, err := os.Getwd()
if err != nil </span><span class="cov0" title="0">{
return "default"
}</span>
<span class="cov0" title="0">return filepath.Base(wd)</span>
}
func newClient(agentID string) *a2a.Client <span class="cov0" title="0">{
return a2a.NewClient(resolveProject(), agentID)
}</span>
func printJSON(v interface{}) <span class="cov0" title="0">{
b, _ := json.MarshalIndent(v, "", " ")
fmt.Println(string(b))
}</span>
// ---------- commands ----------
func cmdInit() <span class="cov0" title="0">{
c := newClient("")
if err := c.InitProject(); err != nil </span><span class="cov0" title="0">{
fmt.Fprintf(os.Stderr, "a2a: init error: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">dbPath := filepath.Join(os.Getenv("HOME"), ".a2a", resolveProject(), "database.db")
fmt.Printf("a2a project '%s' ready at %s\n", resolveProject(), dbPath)</span>
}
func cmdRegister() <span class="cov0" title="0">{
if len(os.Args) < 3 || strings.HasPrefix(os.Args[2], "-") </span><span class="cov0" title="0">{
fmt.Fprintln(os.Stderr, "a2a: usage: a2a register <id> [--role R] [--prompt P] [--cli C] [--pid N] [--upsert]")
os.Exit(1)
}</span>
<span class="cov0" title="0">agentID := os.Args[2]
role := getFlagValue("--role")
prompt := getFlagValue("--prompt")
cli := getFlagValue("--cli")
pid := getFlagInt("--pid")
upsert := hasFlag("--upsert")
c := newClient(agentID)
if err := c.InitProject(); err != nil </span><span class="cov0" title="0">{
fmt.Fprintf(os.Stderr, "a2a: register error: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">if err := c.Register(role, prompt, cli, pid, upsert); err != nil </span><span class="cov0" title="0">{
fmt.Fprintf(os.Stderr, "a2a: register error: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">fmt.Printf("registered agent '%s' in project '%s'\n", agentID, resolveProject())</span>
}
func cmdUnregister() <span class="cov0" title="0">{
args := positionalArgs()
if len(args) < 1 </span><span class="cov0" title="0">{
fmt.Fprintln(os.Stderr, "a2a: usage: a2a unregister <id>")
os.Exit(1)
}</span>
<span class="cov0" title="0">c := newClient(args[0])
if err := c.Unregister(); err != nil </span><span class="cov0" title="0">{
fmt.Fprintf(os.Stderr, "a2a: unregister error: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">fmt.Printf("removed agent '%s'\n", args[0])</span>
}
func cmdList() <span class="cov0" title="0">{
c := newClient("")
peers, err := c.ListPeers()
if err != nil </span><span class="cov0" title="0">{
fmt.Fprintf(os.Stderr, "a2a: list error: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">if hasFlag("--json") </span><span class="cov0" title="0">{
printJSON(peers)
return
}</span>
<span class="cov0" title="0">if len(peers) == 0 </span><span class="cov0" title="0">{
fmt.Println("(no agents registered)")
return
}</span>
<span class="cov0" title="0">fmt.Printf("%-20s %-20s %-10s %-10s\n", "ID", "ROLE", "CLI", "STATUS")
for _, p := range peers </span><span class="cov0" title="0">{
role := p.Role
if role == "" </span><span class="cov0" title="0">{
role = "-"
}</span>
<span class="cov0" title="0">cli := p.CLI
if cli == "" </span><span class="cov0" title="0">{
cli = "-"
}</span>
<span class="cov0" title="0">fmt.Printf("%-20s %-20s %-10s %-10s\n", p.ID, role, cli, p.Status)</span>
}
}
func cmdStatus() <span class="cov0" title="0">{
agentID := getFlagValue("--as")
jsonFlag := hasFlag("--json")
args := positionalArgs()
if len(args) < 1 || agentID == "" </span><span class="cov0" title="0">{
fmt.Fprintln(os.Stderr, "a2a: usage: a2a status <state> --as <id> [--json]")
os.Exit(1)
}</span>
<span class="cov0" title="0">state := args[0]
c := newClient(agentID)
if err := c.SetStatus(state); err != nil </span><span class="cov0" title="0">{
fmt.Fprintf(os.Stderr, "a2a: status error: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">if jsonFlag </span><span class="cov0" title="0">{
printJSON(map[string]interface{}{
"agent": agentID,
"status": state,
})
}</span> else<span class="cov0" title="0"> {
fmt.Printf("agent '%s' status -> %s\n", agentID, state)
}</span>
}
func cmdSend() <span class="cov0" title="0">{
from := getFlagValue("--from")
thread := getFlagValue("--thread")
ttl := getFlagInt("--ttl")
jsonFlag := hasFlag("--json")
args := positionalArgs()
if from == "" || len(args) < 2 </span><span class="cov0" title="0">{
fmt.Fprintln(os.Stderr, "a2a: usage: a2a send <to> <body> --from <id> [--thread T] [--ttl N] [--json]")
os.Exit(1)
}</span>
<span class="cov0" title="0">to := args[0]
body := args[1]
if body == "-" </span><span class="cov0" title="0">{
stdin, _ := os.ReadFile(os.Stdin.Name())
body = strings.TrimSpace(string(stdin))
}</span>
<span class="cov0" title="0">var ttlPtr *int
if ttl > 0 </span><span class="cov0" title="0">{
ttlPtr = &ttl
}</span>
<span class="cov0" title="0">c := newClient(from)
mid, err := c.Send(to, body, thread, ttlPtr)
if err != nil </span><span class="cov0" title="0">{
fmt.Fprintf(os.Stderr, "a2a: send error: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">target := to
if to == "all" || to == "*" || to == "broadcast" </span><span class="cov0" title="0">{
target = "ALL"
}</span>
<span class="cov0" title="0">if jsonFlag </span><span class="cov0" title="0">{
printJSON(map[string]interface{}{
"id": mid,
"sender": from,
"recipient": target,
})
}</span> else<span class="cov0" title="0"> {
fmt.Printf("#%d %s -> %s\n", mid, from, target)
}</span>
}
func cmdRecv() <span class="cov0" title="0">{
agentID := getFlagValue("--as")
waitSec := getFlagFloat("--wait")
limit := getFlagInt("--limit")
includeAll := hasFlag("--all")
includeSelf := hasFlag("--include-self")
peekMode := hasFlag("--peek")
jsonFlag := hasFlag("--json")