-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2115 lines (1987 loc) · 87.6 KB
/
Copy pathserver.py
File metadata and controls
2115 lines (1987 loc) · 87.6 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
"""
OpenForge server v0.4 — JSONL-backed multi-agent topic tracker.
Product (v0.4): every thread is a Slack-style topic; @mention assigns the next
agent (routing not yet wired; posts land as-is and are visible in the UI).
Routes:
GET / -> index.html
GET /style.css -> static
GET /app.js -> static
GET /api/squads -> [squads]
POST /api/squads -> create squad
GET /api/squads/<id> -> { squad, threads }
DELETE /api/squads/<id> -> delete squad
POST /api/squads/<id>/threads -> create thread + opening post
body: { content, created_by? }
GET /api/threads/<id> -> thread detail (posts)
POST /api/threads/<id>/posts -> append post
body: { content, speaker? }
PATCH /api/threads/<id> -> rename title { title }
POST /api/threads/<id>/close -> mark closed
POST /api/threads/<id>/posts/<pid>/reactions -> toggle {emoji, actor?}
Reads: ~/.openforge/squads.json,
~/.openforge/threads/<thread-id>/events.jsonl
Writes: thread events (squads.json under ~/.openforge/).
Legacy: pre-refactor installs kept state at ~/.openclaw/openforge/. The first
start after upgrade auto-migrates that directory to ~/.openforge/ (see
`forge_paths.migrate_legacy_home_if_needed`).
"""
from __future__ import annotations
import argparse
import base64
import binascii
import json
import os
import re
import secrets
import signal
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from queue import Empty
from urllib.parse import parse_qs, urlparse
ROOT = Path(__file__).parent
WEB_DIR = ROOT / "web"
BRAND_DIR = ROOT / "branding"
sys.path.insert(0, str(ROOT))
import forge_avatar
import forge_config
import forge_context
import forge_employees
import forge_favorites
import forge_files
import forge_identity
import forge_paths
import forge_refs
import forge_session_search
import forge_store as store
import forge_uploads
import forge_xiaof
import post_router
FILE_NAME_ROUTE_RE = r"([A-Za-z0-9_.\-]+\.md)"
ROOT_ID_ROUTE_RE = r"([A-Za-z0-9_\-]{1,32})"
# ─────────────────────────────────────────────────────────────────────
# OPERATOR_ID — the single human who is allowed to close a thread.
#
# V1.0.0 conscious limitation (see docs/AGENT-COLLAB-OPEN-QUESTIONS.md Q2):
# OpenForge is a local cockpit for one human ("scott"). Close permission is
# hard-coded here rather than derived from auth/identity, because:
# - There is no multi-user auth story yet.
# - PRD-v1.0 Rule 6 explicitly says "only Scott closes".
# The day a second human operator shows up — or we expose OpenForge beyond
# loopback for real — this constant is the FIRST place to change. Replace
# the equality check with an identity-aware lookup (bearer token → operator
# id, or role tag on the speaker) and the close handler will be the only
# site that needs to follow.
# ─────────────────────────────────────────────────────────────────────
OPERATOR_ID = "scott"
REF_ID_ROUTE_RE = r"(ref_[A-Za-z0-9]{4,16})"
AGENT_ID_ROUTE_RE = r"([A-Za-z0-9][A-Za-z0-9._\-]{0,63})"
# v0.6 deprecated routes: keep working but emit warning headers.
DEPRECATION_DATE = "Fri, 22 May 2026 00:00:00 GMT"
SUNSET_DATE = "Wed, 01 Jul 2026 00:00:00 GMT"
SQUAD_ID_RE = re.compile(r"^[A-Za-z0-9][\w-]{0,31}$")
SQUAD_ROUTE_RE = r"([\w-]{1,32})"
THREAD_ROUTE_RE = r"(th_[0-9a-f]+_[0-9a-f]+)"
POST_ID_ROUTE_RE = r"(p_[A-Za-z0-9_]+)"
STATUS_PHASES = {"thinking", "running", "done", "failed", "skipped", "cancelled"}
def _is_local(host: str) -> bool:
return host in ("127.0.0.1", "::1", "localhost")
def _serializable_thread(m: dict) -> dict:
return {
"thread_id": m["thread_id"],
"squad_id": m["squad_id"],
"title": m.get("title", ""),
"created_by": m["created_by"],
"started_at": m["started_at"],
"last_post_at": m["last_post_at"],
"closed_at": m["closed_at"],
"closed_by": m["closed_by"],
"in_progress": m["in_progress"],
"preview": m["preview"],
"post_count": m["post_count"],
"participants": m["participants"],
"posts": [
{
"id": p["id"],
"ts": p["ts"],
"time": p["time"],
"speaker": p["speaker"],
"content": p["content"],
"mentions": p["mentions"],
"parent_post_id": p.get("parent_post_id"),
"post_type": p.get("post_type") or "message",
"phase": p.get("phase"),
"duration_ms": p.get("duration_ms"),
"error": p.get("error"),
"tool_name": p.get("tool_name"),
"trigger_post_id": p.get("trigger_post_id"),
"from_chip_post_id": p.get("from_chip_post_id"),
"superseded": p["superseded"],
"superseded_by": p.get("superseded_by"),
"reactions": p.get("reactions") or {},
}
for p in m["posts"]
],
"pinned_refs": m.get("pinned_refs") or [],
}
def _serializable_post(p: dict) -> dict:
return {
"id": p["id"],
"ts": p.get("ts"),
"time": p.get("time"),
"speaker": p.get("speaker"),
"content": p.get("content", ""),
"mentions": p.get("mentions") or [],
"parent_post_id": p.get("parent_post_id"),
"post_type": p.get("post_type") or "message",
"phase": p.get("phase"),
"duration_ms": p.get("duration_ms"),
"error": p.get("error"),
"tool_name": p.get("tool_name"),
"trigger_post_id": p.get("trigger_post_id"),
"from_chip_post_id": p.get("from_chip_post_id"),
"superseded": p.get("superseded", False),
"superseded_by": p.get("superseded_by"),
"reactions": p.get("reactions") or {},
}
def _agent_id_from_chip(post: dict) -> str:
content = (post.get("content") or "").strip()
if not content:
return ""
return content.split(None, 1)[0].lstrip("@").strip()
def _validate_squad_payload(payload: dict) -> tuple[dict | None, str | None]:
squad_id = payload.get("id")
members = payload.get("members")
if not isinstance(squad_id, str) or not SQUAD_ID_RE.fullmatch(squad_id):
return None, "id 必须以字母/数字开头,仅允许 [A-Za-z0-9_-],最长 32 字符"
if not isinstance(members, list) or not members:
return None, "members must contain at least one member"
clean_members = []
for member in members:
if not isinstance(member, str) or not member.strip():
return None, "members must be non-empty strings"
clean_members.append(member.strip())
chair = payload.get("chair") or clean_members[0]
if not isinstance(chair, str) or chair not in clean_members:
return None, "chair must be one of members"
# v0.5 PR-A: project_dir is optional. Empty string / None / missing all
# collapse to None ("discussion squad"). If provided, must be a string
# AND an absolute path. Existence / git-repo checks are runtime concerns
# (see /api/fs/validate); we do NOT block writes on them.
project_dir: str | None = None
if "project_dir" in payload:
raw_pd = payload.get("project_dir")
if raw_pd is None or raw_pd == "":
project_dir = None
elif not isinstance(raw_pd, str):
return None, "project_dir must be a string or null"
else:
pd = raw_pd.strip()
if not pd:
project_dir = None
elif not pd.startswith("/"):
return None, "project_dir must be an absolute path"
else:
project_dir = pd
clean = {
"id": squad_id,
"name": str(payload.get("name") or squad_id).strip(),
"description": str(payload.get("description") or "").strip(),
"emoji": str(payload.get("emoji") or "#").strip()[:8] or "#",
"members": clean_members,
"chair": chair,
"project_dir": project_dir,
}
return clean, None
# ─── /api/fs/validate cache (PR-A → PR-B1: now lives in forge_project) ─
# project_dir validation hits the filesystem (stat + .git lookup). Squads
# list views and individual squad GETs need the `project_dir_valid` derived
# field on every render — without a cache, each render does N stats. PR-B1
# extracted the cache + helpers to forge_project so post_router can share
# them when deciding whether to inject the `[project]` segment.
from datetime import UTC
import forge_project
def _fs_validate_path(path: str) -> dict:
return forge_project.validate(path)
def _fs_validate_invalidate(*paths: str | None) -> None:
forge_project.invalidate(*paths)
def _squad_with_validity(squad: dict | None) -> dict | None:
"""Add derived project_dir_valid: bool | None to a squad dict.
- None → field not configured
- True → path exists AND is a git repo
- False → configured but exists/git check failed
"""
if squad is None:
return None
out = dict(squad)
out["project_dir_valid"] = forge_project.derive_validity(out.get("project_dir"))
return out
# ─── Activity feed helpers (v0.5+) ─────────────────────────────────────
_ROUTER_SPEAKER = "__router__"
_IDLE_THRESHOLD_SEC = 60 * 60 # 1h → idle
def _format_http_date(iso_ts: str | None) -> str | None:
if not iso_ts:
return None
try:
from datetime import datetime
dt = datetime.fromisoformat(iso_ts)
dt = dt.astimezone(UTC)
return dt.strftime("%a, %d %b %Y %H:%M:%S GMT")
except Exception:
return None
def _activity_row_for_thread(thread_id: str, squad_name_by_id: dict[str, str]) -> dict | None:
m = store.project_thread(thread_id)
if m is None:
return None
posts = [p for p in m.get("posts") or [] if not p.get("superseded")]
if not posts:
return None
latest_human = None
for p in reversed(posts):
spk = p.get("speaker") or ""
if spk and spk != _ROUTER_SPEAKER:
latest_human = p
break
latest = latest_human or posts[-1]
snippet_src = (latest.get("content") or "").strip()
snippet = " ".join(snippet_src.split())[:120]
last_post_at = posts[-1].get("ts") or m.get("last_post_at") or m.get("started_at")
closed = m.get("closed_at") is not None
status = "in-progress"
if closed:
status = "resolved"
else:
try:
from datetime import datetime
dt = datetime.fromisoformat(last_post_at) if last_post_at else None
if dt is not None:
now = datetime.now(UTC)
if (now - dt.astimezone(UTC)).total_seconds() > _IDLE_THRESHOLD_SEC:
status = "idle"
except Exception:
pass
return {
"thread_id": thread_id,
"title": m.get("title") or (m.get("preview") or "")[:60] or "(empty)",
"squad_id": m.get("squad_id"),
"squad_name": squad_name_by_id.get(m.get("squad_id") or "", m.get("squad_id") or ""),
"latest_post_at": last_post_at,
"latest_snippet": snippet,
"latest_author": latest.get("speaker") or "",
"latest_author_human": (latest_human or {}).get("speaker") or "",
"post_count": len(posts),
"participant_count": len(m.get("participants") or []),
"started_by": m.get("created_by"),
"status": status,
"closed": closed,
}
def _build_activity_rows() -> tuple[list[dict], str | None]:
squad_name_by_id: dict[str, str] = {}
for sq in store.list_squads(include_archived=True):
squad_name_by_id[sq.get("id") or ""] = sq.get("name") or sq.get("id") or ""
rows: list[dict] = []
for tid in store.list_thread_ids():
row = _activity_row_for_thread(tid, squad_name_by_id)
if row is not None:
rows.append(row)
rows.sort(key=lambda r: r.get("latest_post_at") or "", reverse=True)
newest = rows[0]["latest_post_at"] if rows else None
return rows, _format_http_date(newest)
# ─── HTTP handler ─────────────────────────────────────────────────────
class OpenForgeHandler(BaseHTTPRequestHandler):
server_version = "OpenForge/0.4"
auth_token: str | None = None # populated by main()
bind_host: str = "127.0.0.1"
def log_message(self, format, *args):
pass
# ─── helpers ──────────────────────────────────────────────────
def _check_auth(self) -> bool:
"""Required when binding to a non-loopback host."""
if _is_local(self.bind_host) and self.auth_token is None:
return True
token = self.headers.get("Authorization", "")
token = token.removeprefix("Bearer ").strip()
if self.auth_token and token == self.auth_token:
return True
# EventSource cannot send custom headers; allow ?token= for SSE.
try:
qs = parse_qs(urlparse(self.path).query or "")
qtok = (qs.get("token") or [""])[0]
return bool(self.auth_token) and qtok == self.auth_token
except Exception:
return False
# ─── SSE ───────────────────────────────────────────
def _sse_stream(self, thread_id: str) -> None:
"""Long-lived text/event-stream of thread events."""
try:
self.send_response(200)
self.send_header("Content-Type", "text/event-stream; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Connection", "keep-alive")
self.send_header("X-Accel-Buffering", "no")
self.end_headers()
except (BrokenPipeError, ConnectionResetError):
return
q = store.subscribe_thread(thread_id)
try:
self._sse_send_raw(
f"event: hello\ndata: {{\"thread_id\":\"{thread_id}\"}}\n\n"
)
last_keepalive = time.time()
while True:
try:
ev = q.get(timeout=5.0)
except Empty:
ev = None
if ev is not None:
payload = json.dumps(ev, ensure_ascii=False)
if not self._sse_send_raw(f"data: {payload}\n\n"):
return
last_keepalive = time.time()
continue
if time.time() - last_keepalive >= 15.0:
if not self._sse_send_raw(":keepalive\n\n"):
return
last_keepalive = time.time()
finally:
try:
store.unsubscribe_thread(thread_id, q)
except Exception:
pass
def _sse_send_raw(self, frame: str) -> bool:
try:
self.wfile.write(frame.encode("utf-8"))
self.wfile.flush()
return True
except (BrokenPipeError, ConnectionResetError, ValueError, OSError):
return False
# ─── 小F (global agent) — M1 ─────────────────────────────────
def _xiaof_open_sse(self) -> bool:
"""Open SSE response headers. Returns False if the client dropped.
Uses Connection: close so simple HTTP clients (urllib, fetch with
a non-streaming reader) know the stream is done when the socket
closes after the final `done` event. Long-lived broadcast SSE
(see _sse_stream) keeps the socket open; xiaof streams are
bounded by `done` so closing the connection is the right signal.
"""
try:
self.send_response(200)
self.send_header("Content-Type", "text/event-stream; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Connection", "close")
self.send_header("X-Accel-Buffering", "no")
self.end_headers()
except (BrokenPipeError, ConnectionResetError):
return False
# Force the BaseHTTPRequestHandler to close the connection after
# this response so the client's blocking read() returns.
self.close_connection = True
return True
def _xiaof_ask(self) -> None:
"""
POST /api/xiaof/ask — streaming SSE per API contract v0.1 §2.
Contract red lines enforced here:
- Event order: meta → token* → chips → done
(forge_xiaof.stream_to_sse_frames raises if an adapter
violates this; we surface the violation as `internal`.)
- Error codes: unauth | rate_limited | upstream_failed | internal.
`forbidden` MUST NOT appear (A-7.5).
- Validation errors before headers go out: respond as SSE
so the front-end has a single error path.
"""
opts = self._read_json()
if opts is None:
# _read_json already wrote a 4xx for parse errors.
return
try:
normalised = forge_xiaof.validate_ask_request(opts)
except forge_xiaof.XiaofRequestError as e:
if not self._xiaof_open_sse():
return
self._sse_send_raw(
forge_xiaof.sse_frame(
"error",
{"code": e.code, "message": str(e)},
)
)
return
if not self._xiaof_open_sse():
return
adapter = forge_xiaof.get_adapter()
try:
stream = adapter(normalised)
for frame in forge_xiaof.stream_to_sse_frames(stream):
if not self._sse_send_raw(frame):
return
except forge_xiaof.XiaofRequestError as e:
self._sse_send_raw(
forge_xiaof.sse_frame(
"error",
{"code": e.code, "message": str(e)},
)
)
except Exception as e: # noqa: BLE001 — adapter must not crash the route
# Map ANY adapter / framing failure to the contract's
# `internal` (never `forbidden`); details go to server log.
try:
self._sse_send_raw(
forge_xiaof.sse_frame(
"error",
{"code": "internal", "message": "adapter failure"},
)
)
finally:
sys.stderr.write(f"[xiaof] adapter failure: {e!r}\n")
def _json(self, obj, status: int = 200, extra_headers: dict | None = None):
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for k, v in (extra_headers or {}).items():
self.send_header(k, v)
self.end_headers()
self.wfile.write(body)
def _deprecated_v06_headers(self) -> dict:
return {
"Deprecation": DEPRECATION_DATE,
"Sunset": SUNSET_DATE,
"Warning": '299 - "v0.6 /api/files/<name> is deprecated; use /api/files/<root>/<name>"',
"Link": '</api/file-roots>; rel="successor-version"',
}
def _file(self, path: Path, content_type: str):
if not path.exists() or not path.is_file():
self.send_error(404)
return
data = path.read_bytes()
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(data)
# ─── routes ───────────────────────────────────────────────────
# ─── speaker spoofing guard ────────────────────────────────────
# The browser cockpit is the only trusted caller allowed to post as
# scott. Agents and stray scripts can hit the loopback API too, so we
# require an explicit speaker on every post and refuse `scott` unless
# the caller proves it's the UI (sends `X-OpenForge-UI: 1`, which
# web/app.js adds to every POST and which no agent prompt teaches).
#
# Before this guard a missing/empty speaker silently defaulted to
# "scott", which let any sub-agent that curled the loopback API
# impersonate the CEO in a thread (real incident 2026-05-25: designer
# posted a "forge pipeline" summary as scott). See AGENT-THREAD-
# COLLABORATION.md §4.1 for the envelope-vs-content discussion.
def _resolve_speaker(self, opts: dict, *, field: str = "speaker"):
"""Validate and return the caller-claimed speaker, or None on error.
On error the JSON response is already written.
"""
raw = opts.get(field)
speaker = (raw or "").strip() if isinstance(raw, str) else ""
if not speaker:
self._json(
{"error": f"{field} required (no default; UI sends 'scott',"
f" agents must send their own agent id)"},
400,
)
return None
low = speaker.lower()
if low == "__router__":
self._json({"error": f"{field}='{speaker}' is reserved"}, 400)
return None
if low == "scott":
ui_marker = (self.headers.get("X-OpenForge-UI") or "").strip()
if ui_marker != "1":
self._json(
{"error": "posting as 'scott' is reserved for the"
" OpenForge UI; agents must use their own"
" agent id as speaker"},
403,
)
return None
return speaker
def _read_json(self, default=None):
"""Parse JSON body; on parse error, write a 400 response and return None.
Pass `default={}` to return that value for empty bodies instead of failing.
"""
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length).decode("utf-8") if length else ""
if not raw:
return default if default is not None else {}
try:
return json.loads(raw)
except Exception:
self._json({"error": "bad json"}, 400)
return None
def do_GET(self):
url = urlparse(self.path)
path = url.path
if path in ("/", "/index.html"):
self._file(WEB_DIR / "index.html", "text/html; charset=utf-8")
return
if path == "/style.css":
self._file(WEB_DIR / "style.css", "text/css; charset=utf-8")
return
if path == "/app.js":
self._file(WEB_DIR / "app.js",
"application/javascript; charset=utf-8")
return
if path == "/xiaof.js":
self._file(WEB_DIR / "xiaof.js",
"application/javascript; charset=utf-8")
return
if path == "/xiaof.css":
self._file(WEB_DIR / "xiaof.css", "text/css; charset=utf-8")
return
if path == "/src/avatar.js":
self._file(WEB_DIR / "src" / "avatar.js",
"application/javascript; charset=utf-8")
return
m = re.match(r"^/assets/avatars/default/([A-Za-z0-9_-]+\.png)$", path)
if m:
self._file(WEB_DIR / "assets" / "avatars" / "default" / m.group(1),
"image/png")
return
# Brand assets (Forge F logo, favicon, OG cards). Whitelisted file
# names only — branding/ holds in-repo design assets and we don't
# want it to act as an arbitrary file server.
m = re.match(r"^/branding/([A-Za-z0-9._-]+)$", path)
if m:
fname = m.group(1)
ext = fname.rsplit(".", 1)[-1].lower()
mime = {
"svg": "image/svg+xml",
"png": "image/png",
"ico": "image/x-icon",
}.get(ext)
if mime:
self._file(BRAND_DIR / fname, mime)
return
if path == "/favicon.ico":
self._file(BRAND_DIR / "favicon.ico", "image/x-icon")
return
# PWA shell: web app manifest + service worker. Both are needed for
# Chrome/Edge to surface the "Install app" affordance and turn the
# browser tab into a standalone Dock app. /sw.js MUST be served from
# site root (not /branding/) so its default scope covers everything,
# and we explicitly set Service-Worker-Allowed: / for clarity.
if path == "/manifest.webmanifest":
self._file(WEB_DIR / "manifest.webmanifest",
"application/manifest+json; charset=utf-8")
return
if path == "/sw.js":
sw_path = WEB_DIR / "sw.js"
if not sw_path.exists():
self.send_error(404)
return
data = sw_path.read_bytes()
self.send_response(200)
self.send_header("Content-Type",
"application/javascript; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
self.send_header("Service-Worker-Allowed", "/")
self.end_headers()
self.wfile.write(data)
return
# api endpoints
if not self._check_auth():
self.send_error(401, "auth required for non-local host")
return
if path == "/api/squads":
qs = parse_qs(url.query or "")
include_archived = (qs.get("include_archived") or ["0"])[0] in ("1", "true", "yes")
squads = store.list_squads(include_archived=include_archived)
squads = [_squad_with_validity(s) for s in squads]
self._json(squads)
return
# v0.5+: Activity feed — all threads across all squads, latest first.
# Supports If-Modified-Since for cheap 304s on the 10s poll loop.
if path == "/api/activity":
qs = parse_qs(url.query or "")
flt = (qs.get("filter") or ["all"])[0]
rows, last_mod = _build_activity_rows()
ims = self.headers.get("If-Modified-Since")
if ims and last_mod and ims.strip() == last_mod:
self.send_response(304)
self.send_header("Last-Modified", last_mod)
self.send_header("Cache-Control", "no-store")
self.end_headers()
return
# filter=me/unread/squads → v0.1 no backend data, return same as all
payload = {"filter": flt, "threads": rows}
extra = {"Last-Modified": last_mod} if last_mod else None
self._json(payload, extra_headers=extra)
return
if path == "/api/agents":
# Discoverable agents = union(squad members, every agent profile
# under ~/.openclaw/agents/<id>/, ACP employees opted in via
# OpenClaw config). Used by the @-picker.
#
# Historically we required ~/.openclaw/agents/<id>/sessions/ to
# exist as proof the agent had been used at least once, but on a
# fresh OpenClaw install that filter hides codex/claude-code/gemini
# entirely (their profile dir exists, but `sessions/` only gets
# created on first run). Result: brand-new users saw only `main`
# in the Agents component. Drop the sessions requirement and also
# union the ACP allowlist so opted-in runtimes show up even before
# their profile dir gets materialised.
ids: set[str] = set()
for sq in store.list_squads():
for m in sq.get("members") or []:
if m:
ids.add(m)
agents_root = forge_paths.openclaw_agents_root()
if agents_root.exists():
for child in agents_root.iterdir():
if child.is_dir():
ids.add(child.name)
try:
ids.update(forge_employees.acp_employee_ids())
except Exception:
pass
self._json(sorted(ids))
return
if path == "/api/employees":
# Curated employee roster. Returns list[str] of agent ids
# (back-compat) OR list[{id,name,emoji}] when ?with_identity=1.
# V1.2 (Scott 2026-05-24 21:22): the enriched form drives
# display-name rendering in the UI; the bare-string form is
# still consumed by older code paths (squad member picker
# validation, isEmployee() lookups). Keeping both behind one
# endpoint instead of forking the URL keeps the auth /
# caching surface area unchanged.
qs = parse_qs(url.query or "")
if (qs.get("with_identity") or ["0"])[0] in ("1", "true", "yes"):
self._json(forge_identity.list_identities())
else:
self._json(forge_employees.list_employees())
return
if path == "/api/config":
# V1.0.0 §4.3: front-end pulls this at boot to learn the
# webchat base URL (employee-avatar deep-links). Cheap GET,
# never blocks rendering on the client side — client falls
# back to its hardcoded default if this 5xx's.
self._json(forge_config.get_config())
return
if path == "/api/fs/validate":
# PR-A: cheap fs check used by the squad-editor blur handler.
# Returns 200 with {exists, is_git_repo, error} for any absolute
# path; 400 only for malformed input. Cached 60s server-side.
qs = parse_qs(url.query or "")
raw = (qs.get("path") or [""])[0]
if not raw:
self._json({"error": "path is required"}, 400)
return
if not raw.startswith("/"):
self._json({"error": "path must be absolute"}, 400)
return
self._json(_fs_validate_path(raw))
return
m = re.match(rf"^/api/squads/{SQUAD_ROUTE_RE}$", path)
if m:
squad_id = m.group(1)
squad = store.get_squad(squad_id)
if squad is None:
self._json({"error": "not found"}, 404)
return
self._json({
"squad": _squad_with_validity(squad),
"threads": store.list_threads_for_squad(squad_id),
})
return
m = re.match(rf"^/api/threads/{THREAD_ROUTE_RE}/events$", path)
if m:
tid = m.group(1)
if store.project_thread(tid) is None:
self._json({"error": "not found"}, 404)
return
self._sse_stream(tid)
return
m = re.match(rf"^/api/threads/{THREAD_ROUTE_RE}/pinned-refs$", path)
if m:
# v0.10 thread-pin: list pinned refs for a thread (ordered, oldest first).
tid = m.group(1)
if store.project_thread(tid) is None:
self._json({"error": "not found"}, 404)
return
self._json({
"thread_id": tid,
"pinned_refs": store.list_thread_pinned_refs(tid),
"cap": store.PIN_CAP,
})
return
m = re.match(rf"^/api/threads/{THREAD_ROUTE_RE}$", path)
if m:
tid = m.group(1)
data = store.project_thread(tid)
if data is None:
self._json({"error": "not found"}, 404)
return
self._json(_serializable_thread(data))
return
# uploads (paste-image feature): GET /api/uploads/<filename>
m = re.match(r"^/api/uploads/([A-Za-z0-9._-]+)$", path)
if m:
resolved = forge_uploads.get_upload_path(m.group(1))
if resolved is None:
self._json({"error": "not found"}, 404)
return
up_path, up_mime = resolved
self._file(up_path, up_mime)
return
# v0.7: list file roots
if path == "/api/file-roots":
self._json({"roots": forge_files.list_file_roots()})
return
# v0.7: list files in a root: /api/files?root=<id> OR /api/files (default)
if path == "/api/files":
qs = parse_qs(url.query or "")
rid = (qs.get("root") or [None])[0]
try:
files = forge_files.list_files(rid)
except forge_files.NotFoundError:
self._json({"error": "unknown root"}, 404)
return
root_id = rid or forge_files.default_root().id
self._json({"files": files, "root": root_id})
return
# v0.7: read with explicit root /api/files/<root>/<name>
m = re.match(rf"^/api/files/{ROOT_ID_ROUTE_RE}/{FILE_NAME_ROUTE_RE}$", path)
if m:
rid, name = m.group(1), m.group(2)
if forge_files.get_root(rid) is None:
self._json({"error": "unknown root"}, 404)
return
try:
self._json(forge_files.read_file(name, rid))
except forge_files.FileNameError:
self._json({"error": "invalid filename"}, 400)
except forge_files.NotFoundError:
self._json({"error": "not found"}, 404)
return
# v0.6 compat: /api/files/<name> → first root, with Deprecation header
m = re.match(rf"^/api/files/{FILE_NAME_ROUTE_RE}$", path)
if m:
try:
self._json(forge_files.read_file(m.group(1)),
extra_headers=self._deprecated_v06_headers())
except forge_files.FileNameError:
self._json({"error": "invalid filename"}, 400)
except forge_files.NotFoundError:
self._json({"error": "not found"}, 404)
return
# invalid filename inside /api/files/<...> → 400 (not 404) per PRD
if path.startswith("/api/files/"):
self._json({"error": "invalid filename"}, 400)
return
# ─── v0.8 refs ────────────────────────────────────────
m = re.match(rf"^/api/refs/{REF_ID_ROUTE_RE}/content$", path)
if m:
self._refs_get_content(m.group(1))
return
m = re.match(rf"^/api/refs/{REF_ID_ROUTE_RE}/exists$", path)
if m:
# v0.10 thread-pin: single failure rule for chip greying.
self._json({"id": m.group(1), "exists": forge_refs.ref_exists(m.group(1))})
return
m = re.match(rf"^/api/refs/{REF_ID_ROUTE_RE}$", path)
if m:
ref = forge_refs.get_ref(m.group(1))
if not ref:
self._json({"error": "not found"}, 404)
return
self._json(ref)
return
if path == "/api/refs":
qs = parse_qs(url.query or "")
agent = (qs.get("agent") or [None])[0]
thread = (qs.get("thread") or [None])[0]
squad = (qs.get("squad") or [None])[0]
try:
refs = forge_refs.list_refs(agent=agent, thread=thread, squad=squad)
except forge_refs.RefValidationError as e:
self._json({"error": str(e)}, 400)
return
self._json({"refs": refs})
return
# ─── favorites (PRD v1.1) ─────────────────────────────
# GET /api/favorites — time-desc list with preview + missing_state.
# Concurrent stat with 100ms per-path timeout (AC-12); spun-down
# external disks fall to 'unknown' instead of 'missing' so the UI
# never tricks scott into deleting real favorites.
if path == "/api/favorites":
items = forge_favorites.list_with_status()
self._json({"favorites": items, "count": len(items)})
return
# PRD v1.2 follow-up: observability for v0.7 chip usage.
if path == "/api/v07-chip-hits":
try:
import forge_v07_telemetry
self._json(forge_v07_telemetry.snapshot())
except Exception:
self._json({})
return
# v0.9: GET /api/agents/<id>/status
m = re.match(rf"^/api/agents/{AGENT_ID_ROUTE_RE}/avatar$", path)
if m:
try:
info = forge_avatar.avatar_info(m.group(1))
except FileNotFoundError:
self._json({"error": "not found"}, 404)
return
except forge_avatar.AvatarError as e:
self._json({"error": str(e)}, 400)
return
qs = parse_qs(url.query or "")
if (qs.get("meta") or [""])[0] in ("1", "true", "yes"):
self._json(info)
else:
self._file(Path(info["abs_path"]), info.get("content_type") or "image/png")
return
# v0.9: GET /api/agents/<id>/status
m = re.match(rf"^/api/agents/{AGENT_ID_ROUTE_RE}/status$", path)
if m:
try:
info = forge_context.read_status(m.group(1))
except forge_context.StatusError as e:
self._json({"error": str(e)}, 400)
return
if info is None:
self._json({"error": "not found", "agent": m.group(1)}, 404)
return
self._json(info)
return
# v0.9: GET /api/agents/<id>/context-bundle?refresh=1&query=...
m = re.match(rf"^/api/agents/{AGENT_ID_ROUTE_RE}/context-bundle$", path)
if m:
qs = parse_qs(url.query or "")
refresh = (qs.get("refresh") or [""])[0] in ("1", "true", "yes")
query_hint = (qs.get("query") or [None])[0]
try:
bundle = forge_context.build_context_bundle(
m.group(1), query_hint=query_hint, force_refresh=refresh,
)
except forge_context.StatusError as e:
self._json({"error": str(e)}, 400)
return
d = bundle.to_dict()
d["rendered"] = bundle.render()
self._json(d)
return
# v0.9.2: GET /api/agents/<id>/session-search?q=...&days=30&max=10&scope=main
m = re.match(rf"^/api/agents/{AGENT_ID_ROUTE_RE}/session-search$", path)
if m:
qs = parse_qs(url.query or "")
q = (qs.get("q") or qs.get("query") or [""])[0]
days_raw = (qs.get("days") or [str(forge_session_search.DEFAULT_DAYS)])[0]
max_raw = (qs.get("max") or [str(forge_session_search.DEFAULT_MAX_HITS)])[0]
scope = (qs.get("scope") or ["main"])[0]
try:
days = int(days_raw)
max_hits = int(max_raw)
except ValueError:
self._json({"error": "days/max must be integers"}, 400)
return
try:
result = forge_session_search.search(
m.group(1), q, days=days, max_hits=max_hits, scope=scope,
)
except forge_session_search.SessionSearchError as e:
self._json({"error": str(e)}, 400)
return
self._json(result)
return
self.send_error(404)
def _refs_get_content(self, ref_id: str) -> None:
try:
data, mime, ref = forge_refs.read_content(ref_id)
except forge_refs.RefNotFoundError:
self._json({"error": "not found"}, 404)
return
except forge_refs.RefMissingError:
self._json({"error": "file gone"}, 404)
return
except forge_refs.RefTooLargeError:
self._json({"error": "file too large"}, 413)
return
except forge_refs.RefBlockedError as e: