-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacp-minimal.py
More file actions
2232 lines (2004 loc) · 96.8 KB
/
acp-minimal.py
File metadata and controls
2232 lines (2004 loc) · 96.8 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
#!/usr/bin/env python3
"""
ACP Minimal v1.0.6 - Full Spec Compliance
Endpoints: whoami, status, history, running, activity/{id}, action, start, complete,
stop, resume, clear_history, reset, reset_session, shutdown, restart,
nudge (GET+POST), nudge/ack,
notes, notes/add, notes/clear,
todos, todos/add, todos/update, todos/toggle, todos/clear,
shell, shell/add, shell/clear,
summary, summary/export,
stats/duration, activity/batch,
session, session/refresh, csrf-token,
files/list, files/view, files/download, files/stats (read-only)
NEW in 1.0.6:
contextId auto-created when SendMessage called without contextId
Agent Card URL dynamically set from request headers
All files synchronized to v1.0.6
NEW in 1.0.5:
primary_agent in /api/whoami response
Nudges delivered only to primary agent
NEW in 1.0.4:
agents (GET), agents/register (POST), agents/unregister (POST), agents/{name} (GET)
a2a/send (POST), a2a/history (GET)
.well-known/agent-card.json (GET)
jsonrpc, a2a, api/jsonrpc (POST) - JSON-RPC 2.0 endpoints
A2A Compliance: JSON-RPC 2.0, Agent Card, contextId support
"""
import json, os, sys, base64, time, signal, threading, uuid
from http.server import HTTPServer, BaseHTTPRequestHandler
from datetime import datetime, timedelta
from urllib.parse import urlparse, parse_qs
# --- CONFIG ---
PORT = int(os.environ.get("ACP_PORT", "8766"))
AUTH_USER = os.environ.get("ACP_USER", "admin")
AUTH_PASS = os.environ.get("ACP_PASS", "secret")
DATA_FILE = os.environ.get("ACP_DATA_FILE", "acp_data.json")
SUMMARY_FILE = os.environ.get("ACP_SUMMARY_FILE", "acp_session_summary.md")
CONTEXT_WINDOW = int(os.environ.get("ACP_CONTEXT_WINDOW", "200000"))
SESSION_TIMEOUT = int(os.environ.get("ACP_SESSION_TIMEOUT", "86400"))
ORPHAN_TIMEOUT = int(os.environ.get("ACP_ORPHAN_TIMEOUT", "300"))
SESSION_START = time.time()
def sanitize_path(base_dir, rel_path):
"""Prevent path traversal attacks. Returns resolved path or None if outside base_dir."""
abs_base = os.path.realpath(base_dir)
if not rel_path:
return abs_base
target = os.path.realpath(os.path.join(base_dir, rel_path))
if not target.startswith(abs_base + os.sep) and target != abs_base:
return None
return target
# --- JSON-RPC 2.0 Error Codes ---
JSONRPC_PARSE_ERROR = -32700
JSONRPC_INVALID_REQUEST = -32600
JSONRPC_METHOD_NOT_FOUND = -32601
JSONRPC_INVALID_PARAMS = -32602
JSONRPC_INTERNAL_ERROR = -32603
JSONRPC_TASK_NOT_FOUND = -32001
JSONRPC_TASK_NOT_RUNNING = -32002
# --- ACP Agent Card (1.0.4) ---
ACP_AGENT_CARD = {
"name": "ACP Server",
"description": "Agent Control Panel - Monitoring and observability server for AI agents",
"url": "",
"version": "1.0.6",
"capabilities": {
"streaming": False,
"pushNotifications": False
},
"defaultInputModes": ["text/plain", "application/json"],
"defaultOutputModes": ["text/plain", "application/json"],
"skills": [
{
"id": "activity_tracking",
"name": "Activity Tracking",
"description": "Log and monitor agent activities with token estimation",
"tags": ["monitoring", "observability", "tokens"],
"examples": ["Log a file read", "Track a bash command"]
},
{
"id": "a2a_messaging",
"name": "A2A Messaging",
"description": "Inter-agent communication via message queue",
"tags": ["messaging", "multi-agent", "coordination"],
"examples": ["Send message to another agent", "Check inbox"]
}
],
"authentication": {
"schemes": ["Basic"]
}
}
# --- DATA ---
def load_data():
defaults = {
"running": [],
"history": [],
"stop_flag": False,
"stop_reason": None,
"tokens": 0,
"startup_tokens": 0,
"files_read": [],
"files_read_tokens": {},
"nudge": None,
"primary_agent": None,
"last_agent": "Unknown",
"last_model": "Unknown",
"todos": [],
"notes": [],
"summary": "Session Reset.",
"session_start": SESSION_START,
"agent_tokens": {},
"shell_history": [],
"errors": [],
# NEW 1.0.4 fields
"agents": {}, # Agent Registry
"a2a_messages": [], # A2A Message Queue
"contexts": {}, # contextId -> session mapping
"agent_skills": {} # AgentSkill objects per agent
}
if os.path.exists(DATA_FILE):
try:
with open(DATA_FILE, 'r', encoding='utf-8') as f:
d = json.load(f)
merged = {**defaults, **d}
# Migrate notes from old string format to structured array
if isinstance(merged.get("notes"), str):
old = merged["notes"].strip()
merged["notes"] = []
if old:
for line in old.splitlines():
line = line.strip()
if line:
merged["notes"].append({
"id": make_activity_id(),
"timestamp": datetime.now().isoformat(),
"category": "context",
"content": line,
"importance": "normal"
})
return merged
except:
pass
return defaults
def save_data(data):
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
# --- HELPERS ---
def make_activity_id():
return datetime.now().strftime("%H%M%S-") + str(int(time.time() * 100) % 100)
def make_context_id():
return "ctx-" + uuid.uuid4().hex[:12]
def estimate_tokens(text_list, content_size=0):
return int((len("".join(map(str, text_list))) + content_size) / 3.5)
def get_session_info():
now = time.time()
elapsed = now - SESSION_START
return {
"session_start": SESSION_START,
"last_activity": now,
"elapsed_seconds": int(elapsed),
"idle_seconds": 0,
"timeout_seconds": SESSION_TIMEOUT,
"remaining_seconds": max(0, SESSION_TIMEOUT - int(elapsed)),
"is_expired": elapsed > SESSION_TIMEOUT,
"expires_at": datetime.fromtimestamp(SESSION_START + SESSION_TIMEOUT).isoformat()
}
def check_orphans(data):
now = time.time()
orphans = []
for a in data.get("running", []):
started = a.get("started_ts", now)
if now - started > ORPHAN_TIMEOUT:
orphans.append({
"id": a["id"],
"action": a["action"],
"target": a["target"],
"duration": int(now - started)
})
return orphans if orphans else None
def get_a2a_hints(data, agent_name):
"""Get A2A hints for an agent (pending messages). 1.0.4"""
if not agent_name:
return {}
hints = {}
messages_for_agent = []
now_ts = time.time()
for msg in data.get("a2a_messages", []):
if msg.get("to_agent") == agent_name:
try:
expires = datetime.fromisoformat(msg["expires_at"]).timestamp()
if expires > now_ts:
messages_for_agent.append(msg)
except:
pass
if messages_for_agent:
hints["pending_count"] = len(messages_for_agent)
hints["senders"] = list(set(m.get("from_agent") for m in messages_for_agent if m.get("from_agent")))
if messages_for_agent:
latest = messages_for_agent[0]
hints["preview"] = {
"from": latest.get("from_agent"),
"action": latest.get("action"),
"msg_id": latest.get("id")
}
return {"a2a": hints} if hints else {}
def get_hints(data, target, agent_name=None):
hints = {
"modified_this_session": False,
"modification_count": 0,
"last_action": None,
"recent_errors": 0,
"last_error": None,
"related_todos": [],
"loop_detected": False,
"loop_count": 0,
"suggestion": None,
"active_todos": len([t for t in data.get("todos", []) if t.get("status") == "in_progress"])
}
for a in data.get("history", []):
if a.get("target") == target:
hints["modified_this_session"] = True
hints["modification_count"] += 1
hints["last_action"] = a.get("action")
recent = data.get("history", [])[:10]
loop_count = sum(1 for a in recent if a.get("target") == target)
if loop_count >= 3:
hints["loop_detected"] = True
hints["loop_count"] = loop_count
hints["suggestion"] = f"Target '{target}' accessed {loop_count} times recently. Consider caching or alternative approach."
for t in data.get("todos", []):
if target and target.lower() in t.get("content", "").lower():
hints["related_todos"].append({
"id": t["id"],
"content": t["content"],
"status": t.get("status")
})
hints["recent_errors"] = len(data.get("errors", [])[-5:])
if data.get("errors"):
hints["last_error"] = data["errors"][-1].get("message")
# Add A2A hints if agent_name provided (1.0.4)
if agent_name:
a2a_hints = get_a2a_hints(data, agent_name)
if a2a_hints:
hints["a2a"] = a2a_hints.get("a2a", {})
return hints
def format_duration(ms):
if not ms:
return "0ms"
if ms < 1000:
return f"{ms}ms"
if ms < 60000:
return f"{ms/1000:.1f}s"
return f"{ms/60000:.1f}m"
def calc_duration_stats(data):
by_action = {}
slow_activities = []
total_duration = 0
count = 0
trend = []
for a in data.get("history", []):
dur = a.get("duration_ms", 0)
if not dur:
continue
action = a.get("action", "UNKNOWN")
if action not in by_action:
by_action[action] = {
"count": 0, "total_ms": 0,
"average_ms": 0, "average_str": "0ms",
"min_ms": dur, "max_ms": dur
}
by_action[action]["count"] += 1
by_action[action]["total_ms"] += dur
by_action[action]["min_ms"] = min(by_action[action]["min_ms"], dur)
by_action[action]["max_ms"] = max(by_action[action]["max_ms"], dur)
avg = by_action[action]["total_ms"] // by_action[action]["count"]
by_action[action]["average_ms"] = avg
by_action[action]["average_str"] = format_duration(avg)
total_duration += dur
count += 1
if dur > 30000:
slow_activities.append({
"id": a["id"],
"action": action,
"target": a.get("target"),
"duration_ms": dur,
"duration_str": format_duration(dur)
})
trend.append({
"action": action,
"duration_ms": dur,
"timestamp": a.get("started", "")
})
return {
"by_action": by_action,
"slow_activities": slow_activities[:10],
"total_duration_ms": total_duration,
"activities_with_duration": count,
"average_duration_ms": total_duration // max(1, count),
"slow_threshold_ms": 30000,
"trend": trend[-20:]
}
def get_token_summary(data):
"""Compute spec-compliant token fields. session_tokens = primary agent only."""
primary = data.get("primary_agent")
agent_tokens = data.get("agent_tokens", {})
session_tokens = data.get("tokens", 0)
startup_tokens = data.get("startup_tokens", 0)
activity_tokens = max(0, session_tokens - startup_tokens)
tokens_remaining = CONTEXT_WINDOW - session_tokens
tokens_percent = round(session_tokens / CONTEXT_WINDOW * 100, 2)
other_agents_tokens = sum(v for k, v in agent_tokens.items() if k != primary)
overflow_warning = "Context window over 90% full" if tokens_percent > 90 else None
return {
"session_tokens": session_tokens,
"startup_tokens": startup_tokens,
"activity_tokens": activity_tokens,
"tokens_remaining": tokens_remaining,
"tokens_percent": tokens_percent,
"overflow_warning": overflow_warning,
"other_agents_tokens": other_agents_tokens,
"tunnel_url": None,
}
def build_summary_struct(data):
"""Build structured summary object per spec §4.6."""
session = get_session_info()
tok = get_token_summary(data)
history = data.get("history", [])
breakdown = {}
for a in history:
act = a.get("action", "UNKNOWN")
breakdown[act] = breakdown.get(act, 0) + 1
files_read = list({a["target"] for a in history if a.get("action") == "READ"})
files_written = list({a["target"] for a in history if a.get("action") == "WRITE"})
files_edited = list({a["target"] for a in history if a.get("action") == "EDIT"})
return {
"session_overview": {
"duration": format_duration(session["elapsed_seconds"] * 1000),
"duration_seconds": session["elapsed_seconds"],
"total_activities": len(history),
"activity_breakdown": breakdown,
"currently_running": len(data.get("running", [])),
"stop_flag": data.get("stop_flag", False),
"stop_reason": data.get("stop_reason"),
"primary_agent": data.get("primary_agent"),
},
"token_usage": {
"session_tokens": tok["session_tokens"],
"tokens_percent": tok["tokens_percent"],
"context_window": CONTEXT_WINDOW,
"tokens_remaining": tok["tokens_remaining"],
},
"file_interactions": {
"files_read": files_read,
"files_written": files_written,
"files_edited": files_edited,
},
"ai_notes": data.get("notes", []),
"todos": data.get("todos", []),
"recent_activities": history[:20],
}
def write_summary_file(data):
"""Write summary to persistent markdown file. Returns (filepath, content)."""
s = build_summary_struct(data)
ov = s["session_overview"]
tu = s["token_usage"]
lines = [
"# ACP Session Summary",
f"\n**Generated:** {datetime.now().isoformat()}",
"\n## Session Info",
f"- **Duration:** {ov['duration']}",
f"- **Total Activities:** {ov['total_activities']}",
f"- **Primary Agent:** {ov.get('primary_agent') or 'Unknown'}",
f"- **Tokens Used:** {tu['session_tokens']:,}",
f"- **Context Usage:** {tu['tokens_percent']}%",
"\n## Agent Tokens",
]
for name, tokens in data.get("agent_tokens", {}).items():
badge = " (primary)" if name == data.get("primary_agent") else ""
lines.append(f"- {name}{badge}: {tokens} tokens")
lines.append("\n## Todos")
for t in data.get("todos", []):
icon = "✅" if t.get("status") == "completed" else "⬜"
lines.append(f"- {icon} [{t.get('priority', 'med')}] {t.get('content', '')}")
lines.append("\n## Activity History (last 20)")
for a in data.get("history", [])[:20]:
lines.append(f"- [{a.get('action')}] {a.get('target')}: {a.get('result', a.get('details', 'N/A'))}")
notes = data.get("notes", [])
if notes:
lines.append("\n## Notes")
for n in notes:
lines.append(f"- [{n.get('category', 'note')}] {n.get('content', '')}")
content = "\n".join(lines) + "\n"
filepath = os.path.abspath(SUMMARY_FILE)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
return filepath, content
def reset_state():
return {
"running": [],
"history": [],
"stop_flag": False,
"stop_reason": None,
"tokens": 0,
"startup_tokens": 0,
"files_read": [],
"files_read_tokens": {},
"nudge": None,
"primary_agent": None,
"last_agent": "Unknown",
"last_model": "---",
"todos": [],
"notes": [],
"summary": "Session Reset.",
"session_start": time.time(),
"agent_tokens": {},
"shell_history": [],
"errors": [],
# 1.0.4 fields
"agents": {},
"a2a_messages": [],
"contexts": {},
"agent_skills": {}
}
# --- A2A Helpers ---
def create_a2a_message(from_agent, to_agent, msg_type, action=None, payload=None, priority="normal", ttl=3600, reply_to=None):
"""Create an A2A message object."""
now = datetime.now()
return {
"id": make_activity_id(),
"from_agent": from_agent,
"to_agent": to_agent,
"type": msg_type, # request | response | notification
"action": action,
"payload": payload or {},
"priority": priority,
"reply_to": reply_to,
"created_at": now.isoformat(),
"expires_at": (now + timedelta(seconds=ttl)).isoformat(),
"ttl": ttl
}
def get_agent_status(data, agent_name):
"""Get agent status with online/offline computation."""
agents = data.get("agents", {})
if agent_name not in agents:
return None
agent = agents[agent_name].copy()
try:
last_seen = datetime.fromisoformat(agent.get("last_seen", "")).timestamp()
agent["online"] = (time.time() - last_seen) < 60
agent["status"] = "online" if agent["online"] else "offline"
except:
agent["online"] = False
agent["status"] = "offline"
return agent
# --- UI ---
_UI = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ACP Minimal v1.0.6</title>
<style>
:root { --bg:#0d1117; --card:#161b22; --border:#30363d; --text:#c9d1d9; --primary:#ff6b35; --success:#238636; --danger:#da3633; --warning:#d29922; --info:#58a6ff; }
body { font-family:'Segoe UI',system-ui,sans-serif; background:var(--bg); color:var(--text); margin:0; padding:20px; }
.container { max-width:1200px; margin:0 auto; }
.header { display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border); padding-bottom:15px; margin-bottom:20px; }
.sys-controls { display:flex; gap:8px; flex-wrap:wrap; }
.btn { padding:8px 14px; border-radius:6px; cursor:pointer; border:1px solid var(--border); font-weight:600; font-size:0.85rem; color:white; transition:0.2s; }
.btn:hover { opacity:0.8; }
.btn-stop { background:var(--danger); border:none; }
.btn-resume { background:var(--success); border:none; }
.btn-restart { background:#21262d; }
.btn-shutdown { background:#484f58; }
.btn-nudge { background:var(--primary); border:none; }
.btn-export { background:var(--info); border:none; }
.stop-banner { background:rgba(218,54,51,0.12); border:1px solid var(--danger); color:var(--danger); padding:12px 16px; border-radius:8px; margin-bottom:16px; display:flex; justify-content:space-between; align-items:center; font-weight:600; }
.stats-bar { display:grid; grid-template-columns:repeat(auto-fit,minmax(120px,1fr)); gap:10px; margin-bottom:20px; }
.stat-card { background:var(--card); border:1px solid var(--border); padding:12px; border-radius:8px; text-align:center; }
.stat-label { font-size:0.62rem; color:#8b949e; text-transform:uppercase; letter-spacing:0.5px; }
.stat-val { display:block; font-size:0.95rem; font-family:monospace; color:var(--primary); margin-top:4px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.stat-val.warn { color:var(--warning); } .stat-val.danger { color:var(--danger); }
.grid { display:grid; grid-template-columns:1fr 300px; gap:20px; }
@media (max-width:900px) { .grid { grid-template-columns:1fr; } }
.panel { background:var(--card); border:1px solid var(--border); border-radius:8px; margin-bottom:15px; overflow:hidden; animation:fadeIn 0.3s ease-out; }
@keyframes fadeIn { from { opacity:0; transform:translateY(5px); } to { opacity:1; transform:translateY(0); } }
.panel-header { background:rgba(255,255,255,0.03); padding:10px 15px; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border); }
.panel-title { font-weight:600; font-size:0.9rem; }
.panel-body { padding:12px; max-height:400px; overflow-y:auto; }
.panel-footer { background:rgba(0,0,0,0.2); padding:8px 15px; font-size:0.75rem; color:#8b949e; display:flex; gap:15px; border-top:1px solid var(--border); flex-wrap:wrap; }
.status-pill { font-size:0.65rem; padding:2px 8px; border-radius:10px; font-weight:bold; text-transform:uppercase; }
.status-running { background:rgba(56,139,253,0.15); color:#58a6ff; border:1px solid #58a6ff; }
.status-completed { background:rgba(63,185,80,0.15); color:#3fb950; border:1px solid #3fb950; }
.status-error,.status-cancelled { background:rgba(248,81,73,0.15); color:#f85149; border:1px solid #f85149; }
.tag { font-family:monospace; font-size:0.7rem; color:#8b949e; }
pre { background:#07090e; padding:10px; border-radius:6px; font-size:0.8rem; overflow-x:auto; border:1px solid #21262d; margin-top:8px; color:#88ee88; white-space:pre-wrap; word-break:break-all; }
.nudge-banner { background:rgba(255,107,53,0.1); border:1px solid var(--primary); color:var(--primary); padding:12px; border-radius:8px; margin-bottom:16px; display:flex; justify-content:space-between; align-items:center; }
.orphan-banner { background:rgba(210,153,34,0.1); border:1px solid var(--warning); color:var(--warning); padding:12px; border-radius:8px; margin-bottom:16px; }
.activity-item { border:1px solid var(--border); border-radius:6px; margin-bottom:10px; overflow:hidden; }
.activity-header { background:rgba(255,255,255,0.02); padding:8px 12px; display:flex; justify-content:space-between; align-items:center; gap:8px; }
.activity-body { padding:10px 12px; font-size:0.85rem; }
.activity-target { font-family:monospace; color:var(--info); margin-bottom:4px; word-break:break-all; }
.todo-item { display:flex; align-items:center; gap:10px; padding:8px; border-bottom:1px solid var(--border); }
.todo-item:last-child { border-bottom:none; }
.todo-checkbox { width:16px; height:16px; cursor:pointer; }
.todo-content { flex:1; font-size:0.85rem; }
.todo-priority { font-size:0.65rem; padding:2px 6px; border-radius:4px; flex-shrink:0; }
.priority-high { background:rgba(248,81,73,0.2); color:#f85149; }
.priority-medium { background:rgba(210,153,34,0.2); color:#d29922; }
.priority-low { background:rgba(56,139,253,0.2); color:#58a6ff; }
.shell-item { font-family:monospace; font-size:0.75rem; padding:6px 10px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; gap:8px; }
.shell-cmd { color:var(--info); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.agent-badge { display:inline-block; padding:2px 8px; border-radius:4px; font-size:0.7rem; }
.agent-primary { background:rgba(255,107,53,0.2); color:var(--primary); border:1px solid rgba(255,107,53,0.4); }
.agent-other { background:rgba(88,166,255,0.2); color:var(--info); }
.progress-bar { height:4px; background:var(--border); border-radius:2px; margin-top:6px; overflow:hidden; }
.progress-fill { height:100%; background:var(--primary); transition:width 0.3s; }
.progress-fill.warn { background:var(--warning); } .progress-fill.danger { background:var(--danger); }
.a2a-badge { background:rgba(136,238,136,0.2); color:#88ee88; border:1px solid #88ee88; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<div>
<h2 style="margin:0;color:var(--primary)">🤖 ACP Minimal <small style="color:#6e7681;font-size:0.8rem">v1.0.6</small></h2>
<div id="timer" style="font-family:monospace;font-size:0.8rem;color:#8b949e;margin-top:4px">Sync in 2.0s</div>
</div>
<div class="sys-controls">
<button class="btn btn-nudge" onclick="sendNudge()">📢 NUDGE</button>
<button class="btn btn-export" onclick="exportSummary()">📄 EXPORT</button>
<button class="btn btn-stop" onclick="doStop()">⛔ STOP</button>
<button class="btn btn-resume" onclick="doResume()" id="btn-resume" style="display:none">▶️ RESUME</button>
<button class="btn btn-restart" onclick="sys('reset')">🔄 RESET</button>
<button class="btn btn-shutdown" onclick="sys('shutdown')">💀 KILL</button>
</div>
</div>
<div id="stop-area"></div>
<div id="nudge-area"></div>
<div id="orphan-area"></div>
<div class="stats-bar">
<div class="stat-card"><span class="stat-label">Tokens</span><span id="stat-tokens" class="stat-val">0</span><div class="progress-bar"><div id="token-bar" class="progress-fill" style="width:0%"></div></div></div>
<div class="stat-card"><span class="stat-label">Context</span><span id="stat-pc" class="stat-val">0%</span></div>
<div class="stat-card"><span class="stat-label">Running</span><span id="stat-running" class="stat-val">0</span></div>
<div class="stat-card"><span class="stat-label">Completed</span><span id="stat-completed" class="stat-val">0</span></div>
<div class="stat-card"><span class="stat-label">Primary Agent</span><span id="stat-primary-agent" class="stat-val">---</span></div>
<div class="stat-card"><span class="stat-label">Last Agent</span><span id="stat-last-agent" class="stat-val">---</span></div>
<div class="stat-card"><span class="stat-label">Session</span><span id="stat-session" class="stat-val">0m</span></div>
<div class="stat-card"><span class="stat-label">Todos</span><span id="stat-todos" class="stat-val">0</span></div>
<div class="stat-card"><span class="stat-label">Errors</span><span id="stat-errors" class="stat-val">0</span></div>
<div class="stat-card"><span class="stat-label">A2A Pending</span><span id="stat-a2a" class="stat-val">0</span></div>
</div>
<div class="grid">
<div id="main-content">
<div id="running-section"></div>
<div id="history-section"></div>
</div>
<div id="sidebar">
<div id="todos-panel"></div>
<div id="agents-panel"></div>
<div id="shell-panel"></div>
<div id="hints-panel"></div>
</div>
</div>
</div>
<script>
const AUTH = btoa('__USER__:__PASS__');
let timeLeft = 2.0, lastData = null;
async function api(path, opts={}) {
try {
const r = await fetch(path, {...opts, headers:{'Authorization':'Basic '+AUTH,'Content-Type':'application/json'}});
return r.json();
} catch(e) { return {error:true}; }
}
async function sys(type) {
if(!confirm('Confirm '+type.toUpperCase()+'?')) return;
const r = await api('/api/'+type, {method:'POST'});
if(type==='shutdown') { document.body.innerHTML='<h1 style="color:#da3633;font-family:monospace;padding:40px">Server offline.</h1>'; return; }
timeLeft = 0.1;
}
async function doStop() {
const reason = prompt('Reason for STOP ALL (optional):') ?? '';
await api('/api/stop', {method:'POST', body:JSON.stringify({reason: reason||'User requested'})});
timeLeft = 0.1;
}
async function doResume() {
await api('/api/resume', {method:'POST'});
timeLeft = 0.1;
}
async function sendNudge() {
const m = prompt('Enter guidance message:');
if(m) { await api('/api/nudge', {method:'POST', body:JSON.stringify({message:m})}); timeLeft = 0.1; }
}
async function exportSummary() {
const r = await api('/api/summary/export');
if(r.summary) {
const blob = new Blob([r.summary], {type:'text/markdown'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href=url; a.download='acp-session-summary.md'; a.click();
URL.revokeObjectURL(url);
}
}
async function toggleTodo(id) {
await api('/api/todos/toggle', {method:'POST', body:JSON.stringify({id})});
timeLeft = 0.1;
}
function dur(ms) {
if(!ms) return '---';
if(ms<1000) return ms+'ms';
if(ms<60000) return (ms/1000).toFixed(1)+'s';
return (ms/60000).toFixed(1)+'m';
}
function sess(s) {
if(s<60) return s+'s';
if(s<3600) return Math.floor(s/60)+'m';
return Math.floor(s/3600)+'h '+Math.floor((s%3600)/60)+'m';
}
function esc(s) {
return String(s||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
async function refresh() {
const d = await api('/api/all');
if(d.error) return;
lastData = d;
const pct = d.tokens_percent || 0;
document.getElementById('stat-tokens').innerText = (d.session_tokens||0).toLocaleString();
document.getElementById('stat-pc').innerText = pct.toFixed(1)+'%';
document.getElementById('stat-pc').className = 'stat-val'+(pct>80?' danger':pct>50?' warn':'');
document.getElementById('stat-running').innerText = (d.running||[]).length;
document.getElementById('stat-completed').innerText = (d.history||[]).length;
document.getElementById('stat-primary-agent').innerText = d.primary_agent || '---';
document.getElementById('stat-last-agent').innerText = d.last_agent || '---';
document.getElementById('stat-session').innerText = sess(d.session?.elapsed_seconds||0);
document.getElementById('stat-todos').innerText = (d.todos||[]).length;
document.getElementById('stat-errors').innerText = (d.errors||[]).length;
// A2A pending count
const a2aPending = d.hints?.a2a?.pending_count || 0;
document.getElementById('stat-a2a').innerText = a2aPending;
document.getElementById('stat-a2a').className = 'stat-val'+(a2aPending>0?' a2a-badge':'');
const bar = document.getElementById('token-bar');
bar.style.width = Math.min(100,pct)+'%';
bar.className = 'progress-fill'+(pct>80?' danger':pct>50?' warn':'');
// STOP banner + resume button
const stopArea = document.getElementById('stop-area');
const resumeBtn = document.getElementById('btn-resume');
if(d.stop_flag) {
stopArea.innerHTML = '<div class="stop-banner">⛔ STOP ALL ACTIVE'+(d.stop_reason?' — '+esc(d.stop_reason):'')+' <span style="font-size:0.8rem;font-weight:normal">All agent operations halted.</span></div>';
resumeBtn.style.display = '';
} else {
stopArea.innerHTML = '';
resumeBtn.style.display = 'none';
}
document.getElementById('nudge-area').innerHTML = d.nudge
? '<div class="nudge-banner"><span><strong>📢 NUDGE:</strong> '+esc(d.nudge.message)+'</span><small>'+esc(d.nudge.timestamp||'')+'</small></div>'
: '';
document.getElementById('orphan-area').innerHTML = d.orphan_warning
? '<div class="orphan-banner"><strong>⚠️ ORPHAN WARNING:</strong> '+d.orphan_warning.count+' activit'+(d.orphan_warning.count===1?'y':'ies')+' running > 5min</div>'
: '';
function patchPanel(container, title, bodyHTML, bodyStyle) {
const existing = container.querySelector('.panel');
if (!existing) {
const style = bodyStyle ? ' style="'+bodyStyle+'"' : '';
container.innerHTML = '<div class="panel"><div class="panel-header"><span class="panel-title">'+title+'</span></div><div class="panel-body"'+style+'>'+bodyHTML+'</div></div>';
return;
}
existing.querySelector('.panel-title').innerHTML = title;
const pb = existing.querySelector('.panel-body');
if (bodyStyle) pb.setAttribute('style', bodyStyle);
const saved = pb.scrollTop;
pb.innerHTML = bodyHTML;
pb.scrollTop = saved;
}
// Running
const rs = document.getElementById('running-section');
if (d.running && d.running.length) {
const runBody = d.running.map(a => {
const m=a.metadata||{};
return '<div class="activity-item"><div class="activity-header"><span class="status-pill status-running">'+a.status+'</span><strong>'+esc(a.action)+'</strong><span class="tag">#'+a.id+'</span></div>'
+'<div class="activity-body"><div class="activity-target">'+esc(a.target||'N/A')+'</div><div>'+esc(a.details||'')+'</div></div>'
+'<div class="panel-footer"><span>👤 '+esc(m.agent_name||'---')+(m.model_name?' · '+esc(m.model_name):'')+'</span><span>🕒 '+esc(a.started||'---')+'</span></div></div>';
}).join('');
patchPanel(rs, '🔄 Running ('+d.running.length+')', runBody, '');
} else {
rs.innerHTML = '';
}
// History
const hs = document.getElementById('history-section');
if (d.history && d.history.length) {
const histBody = d.history.slice(0,25).map(a => {
const m=a.metadata||{};
const sc = a.status==='error'||a.status==='cancelled'?'error':'completed';
return '<div class="activity-item"><div class="activity-header"><span class="status-pill status-'+sc+'">'+a.status+'</span><strong>'+esc(a.action)+'</strong><span class="tag">#'+a.id+'</span></div>'
+'<div class="activity-body"><div class="activity-target">'+esc(a.target||'N/A')+'</div><div>'+esc(a.details||'')+'</div>'+(a.result?'<pre>'+esc(a.result)+'</pre>':'')+'</div>'
+'<div class="panel-footer"><span>👤 '+esc(m.agent_name||'---')+(m.model_name?' · '+esc(m.model_name):'')+'</span><span>🕒 '+esc(a.started||'---')+'</span><span>⏱️ '+dur(a.duration_ms)+'</span></div></div>';
}).join('');
patchPanel(hs, '📜 History ('+d.history.length+')', histBody, '');
} else {
hs.innerHTML = '<div style="text-align:center;padding:40px;color:#6e7681">No activity logged yet.</div>';
}
// Todos
const tp = document.getElementById('todos-panel');
if (d.todos && d.todos.length) {
const todoBody = d.todos.map(t => '<div class="todo-item"><input type="checkbox" class="todo-checkbox" data-id="'+t.id+'" '+(t.status==='completed'?'checked':'')+' onchange="toggleTodo(event.target.dataset.id)"><span class="todo-content" style="'+(t.status==='completed'?'text-decoration:line-through;opacity:0.6':'')+'">'+esc(t.content)+'</span><span class="todo-priority priority-'+(t.priority||'medium')+'">'+(t.priority||'med')+'</span></div>').join('');
patchPanel(tp, '📋 Todos ('+d.todos.length+')', todoBody, 'padding:0');
} else { tp.innerHTML = ''; }
// Agents — primary_agent gets orange star badge
const ap = document.getElementById('agents-panel');
const agents = d.agents || {};
const agentTokens = d.agent_tokens || {};
const allAgentNames = new Set([...Object.keys(agents), ...Object.keys(agentTokens)]);
if (allAgentNames.size) {
const agentBody = Array.from(allAgentNames).map(n => {
const ag = agents[n] || {};
const tok = agentTokens[n] || 0;
const isPrimary = n === d.primary_agent;
const status = ag.status || (isPrimary ? 'online' : 'offline');
const statusClass = status === 'online' ? 'status-running' : 'status-error';
return '<div style="display:flex;justify-content:space-between;align-items:center;padding:5px 0;border-bottom:1px solid var(--border)"><span class="agent-badge '+(isPrimary?'agent-primary':'agent-other')+'">'+esc(n)+(isPrimary?' ★':'')+'</span><span><span class="status-pill '+statusClass+'" style="font-size:0.6rem">'+status+'</span> <span class="tag">'+tok+' tok</span></span></div>';
}).join('');
patchPanel(ap, '🤖 Agents ('+allAgentNames.size+')', agentBody, '');
} else { ap.innerHTML = ''; }
// Shell
const sp = document.getElementById('shell-panel');
if (d.shell_history && d.shell_history.length) {
const shellBody = d.shell_history.slice(0,10).map(s => '<div class="shell-item"><span class="shell-cmd" title="'+esc(s.command||'')+'">'+esc(s.command||'---')+'</span><span class="shell-status '+(s.status==='error'?'status-error':'status-completed')+'">'+s.status+'</span></div>').join('');
patchPanel(sp, '💻 Shell ('+d.shell_history.length+')', shellBody, 'padding:0');
} else { sp.innerHTML = ''; }
// Hints
const hp = document.getElementById('hints-panel');
if (d.hints && (d.hints.loop_detected || d.hints.active_todos > 0 || (d.hints.a2a && d.hints.a2a.pending_count > 0))) {
const hintsBody = (d.hints.loop_detected?'<div style="color:var(--warning);margin-bottom:8px">⚠️ Loop detected: '+d.hints.loop_count+' repetitions</div>':'')
+ (d.hints.suggestion?'<div style="color:var(--info)">'+esc(d.hints.suggestion)+'</div>':'')
+ (d.hints.active_todos>0?'<div class="tag">📌 '+d.hints.active_todos+' active todos</div>':'')
+ (d.hints.a2a && d.hints.a2a.pending_count>0?'<div class="tag" style="color:#88ee88">📧 '+d.hints.a2a.pending_count+' A2A messages from: '+esc(d.hints.a2a.senders?.join(', ')||'unknown')+'</div>':'');
patchPanel(hp, '💡 Hints', hintsBody, '');
} else { hp.innerHTML = ''; }
}
setInterval(() => {
timeLeft -= 0.1;
if(timeLeft <= 0) { timeLeft = 2.0; refresh(); }
document.getElementById('timer').innerText = 'Sync in '+Math.max(0,timeLeft).toFixed(1)+'s';
}, 100);
refresh();
</script>
</body>
</html>
"""
def build_ui():
return _UI.replace('__USER__', AUTH_USER).replace('__PASS__', AUTH_PASS)
UI_HTML = build_ui()
# --- HANDLER ---
class ACPMinimalHandler(BaseHTTPRequestHandler):
def send_json(self, data, status=200):
body = json.dumps(data).encode('utf-8')
self.send_response(status)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def check_auth(self):
auth = self.headers.get('Authorization', '')
if auth.startswith('Basic '):
try:
u, p = base64.decodebytes(auth[6:].encode()).decode().split(':', 1)
if u == AUTH_USER and p == AUTH_PASS:
return True
except:
pass
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm="ACP"')
self.end_headers()
return False
def log_message(self, format, *args):
pass
def read_body(self):
"""Read and parse JSON body from request."""
try:
length = int(self.headers.get('Content-Length', 0))
if length > 0:
return json.loads(self.rfile.read(length))
except:
pass
return {}
# ============================================================
# OPTIONS (CORS preflight)
# ============================================================
def do_OPTIONS(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Authorization, Content-Type')
self.send_header('Content-Length', '0')
self.end_headers()
# ============================================================
# GET
# ============================================================
def do_GET(self):
if not self.check_auth():
return
# UI
if self.path in ['/', '/api']:
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write(UI_HTML.encode('utf-8'))
# /.well-known/agent-card.json — 1.0.4 A2A Discovery
elif self.path == '/.well-known/agent-card.json':
# Dynamic URL from request headers
host = self.headers.get('Host', f'localhost:{PORT}')
scheme = 'https' if self.headers.get('X-Forwarded-Proto', '').lower() == 'https' else 'http'
card = dict(ACP_AGENT_CARD)
card["url"] = f"{scheme}://{host}"
self.send_json(card)
# /api/whoami — spec §4.10: returns identity context for agent bootstrap
elif self.path == '/api/whoami':
d = load_data()
self.send_json({
"success": True,
"identity": {
"hint": "You are an AI agent. Identify yourself by name (e.g., 'Super Z', 'Claude', 'GPT-4').",
"suggestion": "Use the 'agent_name' field in activity metadata to attribute your actions.",
"example": {"metadata": {"agent_name": "Super Z", "source": "user_request"}},
"purpose": "Attribution helps track which agent/subagent performed each action."
},
"session": get_session_info(),
"primary_agent": d.get("primary_agent"),
"last_agent": d.get("last_agent", "Unknown"),
"agent_tokens": d.get("agent_tokens", {})
})
# /api/status — spec §4.3
elif self.path == '/api/status':
d = load_data()
tok = get_token_summary(d)
orphans = check_orphans(d)
self.send_json({
"success": True,
"stop_flag": d["stop_flag"],
"stop_reason": d.get("stop_reason"),
"running_count": len(d["running"]),
"running": d["running"],
"session_tokens": tok["session_tokens"],
"startup_tokens": tok["startup_tokens"],
"activity_tokens": tok["activity_tokens"],
"context_window": CONTEXT_WINDOW,
"tokens_remaining": tok["tokens_remaining"],
"tokens_percent": tok["tokens_percent"],
"overflow_warning": tok["overflow_warning"],
"primary_agent": d.get("primary_agent"),
"last_agent": d.get("last_agent", "Unknown"),
"agent_tokens": d.get("agent_tokens", {}),
"other_agents_tokens": tok["other_agents_tokens"],
"tunnel_url": tok["tunnel_url"],
"nudge": d["nudge"],
"session": get_session_info(),
"orphan_warning": {"count": len(orphans), "tasks": orphans} if orphans else None,
"errors": d.get("errors", [])[-5:],
"agents": d.get("agents", {})
})
# /api/all — combined convenience endpoint, spec §4.3
elif self.path == '/api/all':
d = load_data()
tok = get_token_summary(d)
orphans = check_orphans(d)
# Get hints with A2A info for primary agent
hints = get_hints(d, "", d.get("primary_agent"))
base_dir = os.environ.get("ACP_BASE_DIR", ".")
current_files = []
try:
for item in sorted(os.listdir(base_dir))[:20]:
ip = os.path.join(base_dir, item)
current_files.append({
"name": item,
"is_dir": os.path.isdir(ip),
"size": os.path.getsize(ip) if os.path.isfile(ip) else 0
})
except:
pass
self.send_json({
"success": True,
"stop_flag": d["stop_flag"],
"stop_reason": d.get("stop_reason"),
"running": d["running"],
"history": d["history"][:25],
"session_tokens": tok["session_tokens"],
"startup_tokens": tok["startup_tokens"],
"context_window": CONTEXT_WINDOW,
"tokens_remaining": tok["tokens_remaining"],
"tokens_percent": tok["tokens_percent"],
"overflow_warning": tok["overflow_warning"],
"primary_agent": d.get("primary_agent"),
"last_agent": d.get("last_agent", "Unknown"),
"agent_tokens": d.get("agent_tokens", {}),
"other_agents_tokens": tok["other_agents_tokens"],
"tunnel_url": tok["tunnel_url"],
"nudge": d["nudge"],
"session": get_session_info(),
"todos": d.get("todos", []),
"shell_history": d.get("shell_history", [])[-10:],
"errors": d.get("errors", []),
"orphan_warning": {"count": len(orphans), "tasks": orphans} if orphans else None,
"current_files": current_files,
"base_dir": os.path.abspath(base_dir),
"hints": hints,
"agents": d.get("agents", {})
})
# /api/running — spec §4.3
elif self.path == '/api/running':
d = load_data()
self.send_json({"success": True, "running": d["running"]})
# /api/history — spec §4.3
elif self.path == '/api/history':
d = load_data()
self.send_json({"success": True, "history": d["history"]})
# /api/activity/{id} — spec §4.3
elif self.path.startswith('/api/activity/') and '/batch' not in self.path:
aid = self.path.split('/')[-1]
d = load_data()
for a in d["running"] + d["history"]:
if a["id"] == aid:
return self.send_json({"success": True, "activity": a})