-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkshop.bb
More file actions
1430 lines (1255 loc) · 54.7 KB
/
workshop.bb
File metadata and controls
1430 lines (1255 loc) · 54.7 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 bb
;;
;; workshop.bb — shared workspace for a small trusted mesh of agents
;;
;; WHAT THIS IS:
;; Stupid-simple structured IRC with file sharing and tasks.
;; Agent-first. Human-observable. Runs on a VPS. No auth ceremony —
;; the mesh (Tailscale/ZeroTier) handles trust.
;;
;; WHAT THIS IS NOT:
;; Not MCP. Not ACP. Not A2A. Not Kafka. Not a wiki.
;;
;; RUN: bb workshop.bb
;; PORT: 4242 (set PORT env to override)
;; DATA: ./workshop.db (sqlite, WAL mode)
;; FILES: ./blobs/ (content-addressed)
;;
;; IDENTITY CONVENTION: "agent-name.owner" e.g. "harvester.alice"
;; No enforcement. Honor system. Mesh handles real trust.
;;
;; MESSAGE ENVELOPE:
;; {:id "01J4..." ;; ULID, sortable+unique
;; :ts 1708123456.789 ;; unix float
;; :from "harvester.alice" ;; agent-name.owner
;; :ch "general" ;; channel name
;; :type "task.claimed" ;; dot-namespaced, agents pattern-match
;; :v 1 ;; schema version hint
;; :body {} ;; free-form, type-specific payload
;; :files ["sha256:abc..."] ;; optional blob refs
;; :reply-to "01J3..."} ;; optional threading
;;
;; API:
;; POST /ch/:ch publish message
;; GET /ch/:ch SSE stream (live)
;; GET /ch/:ch/history last N messages, ndjson ?since=<id>&n=<int>&type=<prefix>
;; GET /history last N messages across all channels
;; GET /channels list all channels seen
;; POST /tasks create task
;; GET /tasks list tasks ?status=open&for=agent
;; GET /tasks/:id fetch single task
;; POST /tasks/:id/claim claim (first write wins, 409 if taken)
;; POST /tasks/:id/update progress note (any agent)
;; POST /tasks/:id/done complete + optional files (claiming agent only)
;; POST /tasks/:id/abandon release back to pool (claiming agent only)
;; POST /tasks/:id/interrupt signal interrupt (any agent)
;; POST /files upload blob → {hash size}
;; GET /files/:hash fetch blob
;; POST /presence heartbeat {from channels meta}
;; GET /presence who's alive (seen in last 60s)
;; GET / SSE of everything (all channels merged)
;; GET /ui human terminal web view
;; GET /status health + counts
(require '[org.httpkit.server :as http]
'[cheshire.core :as json]
'[clojure.string :as str]
'[clojure.java.io :as io]
'[babashka.pods :as pods])
(pods/load-pod 'org.babashka/go-sqlite3 "0.3.13")
(require '[pod.babashka.go-sqlite3 :as sqlite])
;; ─────────────────────────────────────────────
;; CONFIG
;; ─────────────────────────────────────────────
(def port (Integer/parseInt (or (System/getenv "PORT") "4242")))
(def db-path (or (System/getenv "DB_PATH") "workshop.db"))
(def blobs-dir (or (System/getenv "BLOBS_DIR") "blobs"))
(def history-limit 200)
(def presence-ttl-ms 60000)
(def max-file-size (* 100 1024 1024)) ;; 100MB
(def verbose? (= "true" (System/getenv "WORKSHOP_VERBOSE")))
(def retention-days (try (Integer/parseInt (or (System/getenv "WORKSHOP_RETENTION_DAYS") "30"))
(catch Exception _ 30)))
;; ─────────────────────────────────────────────
;; ULID (sortable unique id, url-safe)
;; ─────────────────────────────────────────────
(def ^:private ulid-chars "0123456789ABCDEFGHJKMNPQRSTVWXYZ")
(def ^:private ulid-len 26)
(defn new-ulid []
(let [ts (System/currentTimeMillis)
sb (StringBuilder. ulid-len)
rng (java.util.concurrent.ThreadLocalRandom/current)]
;; 10 timestamp chars — built LSB-first with insert-at-0, so final order is MSB-first (correct)
(loop [t ts i 0]
(when (< i 10)
(.insert sb 0 (.charAt ulid-chars (int (mod t 32))))
(recur (quot t 32) (inc i))))
;; 16 random chars
(dotimes [_ 16]
(.append sb (.charAt ulid-chars (.nextInt rng 32))))
(str sb)))
;; ─────────────────────────────────────────────
;; DATABASE
;; ─────────────────────────────────────────────
(defn db-exec! [sql & params]
(sqlite/execute! db-path (into [sql] params)))
(defn db-query [sql & params]
(sqlite/query db-path (into [sql] params)))
(defn init-db! []
;; Create parent directories for db-path if they don't exist
(io/make-parents (io/file db-path))
(db-exec! "PRAGMA journal_mode=WAL")
(db-exec! "PRAGMA synchronous=NORMAL")
(db-exec!
"CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
ts REAL NOT NULL,
from_id TEXT NOT NULL,
ch TEXT NOT NULL,
type TEXT NOT NULL,
v INTEGER DEFAULT 1,
body TEXT NOT NULL DEFAULT '{}',
files TEXT NOT NULL DEFAULT '[]',
reply_to TEXT
)")
(db-exec! "CREATE INDEX IF NOT EXISTS idx_messages_ch ON messages(ch)")
(db-exec! "CREATE INDEX IF NOT EXISTS idx_messages_ts ON messages(ts)")
;; Composite index covers both channel-filtered and type-prefix history queries
(db-exec! "CREATE INDEX IF NOT EXISTS idx_messages_ch_type ON messages(ch, type)")
(db-exec!
"CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
created_at REAL NOT NULL,
updated_at REAL NOT NULL,
created_by TEXT NOT NULL,
assigned_to TEXT,
claimed_by TEXT,
claimed_at REAL,
status TEXT NOT NULL DEFAULT 'open',
title TEXT NOT NULL,
context TEXT NOT NULL DEFAULT '{}',
result TEXT,
files TEXT NOT NULL DEFAULT '[]',
ch TEXT NOT NULL DEFAULT 'tasks'
)")
(db-exec! "CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)")
(db-exec! "CREATE INDEX IF NOT EXISTS idx_tasks_ch ON tasks(ch)")
(db-exec!
"CREATE TABLE IF NOT EXISTS presence (
agent_id TEXT PRIMARY KEY,
last_seen REAL NOT NULL,
channels TEXT NOT NULL DEFAULT '[]',
meta TEXT NOT NULL DEFAULT '{}'
)")
(println "db ready:" db-path))
;; ─────────────────────────────────────────────
;; SSE FAN-OUT
;;
;; subscribers atom shape: {ch #{client ...}, :all #{client ...}}
;;
;; IMPORTANT: always snapshot the inner set before iterating
;; (into [] ...) before doseq prevents ConcurrentModificationException
;; when unsub! is called from another thread mid-iteration.
;; Dead clients are removed on first failed send rather than accumulating forever.
;; ─────────────────────────────────────────────
(def subscribers (atom {}))
(defn sub! [ch client]
(swap! subscribers update ch (fnil conj #{}) client))
(defn unsub! [ch client]
(swap! subscribers update ch disj client))
(defn broadcast! [ch msg-str msg-id]
;; Include SSE id: field so browsers can send Last-Event-ID on reconnect
(let [payload (str "id: " msg-id "\ndata: " msg-str "\n\n")]
(doseq [client (into [] (get @subscribers ch #{}))]
(try (http/send! client payload)
(catch Exception _ (unsub! ch client))))
;; also fan out to god-view (:all) subscribers
(when (not= ch :all)
(doseq [client (into [] (get @subscribers :all #{}))]
(try (http/send! client payload)
(catch Exception _ (unsub! ch :all)))))))
(defn sse-keepalive! []
(future
(loop []
(Thread/sleep 20000)
(let [ping ": keepalive\n\n"]
(doseq [[ch clients] @subscribers
client (into [] clients)]
(try (http/send! client ping)
(catch Exception _ (unsub! ch client)))))
(recur))))
;; ─────────────────────────────────────────────
;; HELPERS
;; ─────────────────────────────────────────────
(defn now [] (/ (System/currentTimeMillis) 1000.0))
(defn parse-body [req]
(let [raw (try (slurp (:body req)) (catch Exception _ ""))]
(if (str/blank? raw)
{}
(try (json/parse-string raw true)
(catch Exception _
(throw (ex-info "invalid JSON body" {:status 400})))))))
(defn json-resp [status body]
{:status status
:headers {"Content-Type" "application/json"
"Access-Control-Allow-Origin" "*"}
:body (json/encode body)})
(defn ok [body] (json-resp 200 body))
(defn created [body] (json-resp 201 body))
(defn bad [msg] (json-resp 400 {:error msg}))
(defn not-found [msg] (json-resp 404 {:error msg}))
(defn conflict [msg] (json-resp 409 {:error msg}))
(defn forbidden [msg] (json-resp 403 {:error msg}))
(def sse-headers
{"Content-Type" "text/event-stream"
"Cache-Control" "no-cache"
"X-Accel-Buffering" "no" ;; critical: prevents nginx from buffering the stream
"Connection" "keep-alive"
"Access-Control-Allow-Origin" "*"})
(defn row->msg [row]
(-> row
(update :body #(json/parse-string % true))
(update :files #(json/parse-string % true))
(dissoc :reply_to)
(assoc :reply-to (:reply_to row))))
(defn msg->row [msg]
{:id (:id msg)
:ts (:ts msg)
:from_id (:from msg)
:ch (:ch msg)
:type (:type msg)
:v (or (:v msg) 1)
:body (json/encode (or (:body msg) {}))
:files (json/encode (or (:files msg) []))
:reply_to (:reply-to msg)})
(defn parse-task-row [r]
(-> r
(update :context #(json/parse-string % true))
(update :files #(json/parse-string % true))))
;; ─────────────────────────────────────────────
;; CHANNEL HANDLERS
;; ─────────────────────────────────────────────
(defn handle-publish! [req ch]
(let [body (parse-body req)
msg (merge body {:id (new-ulid) :ts (now) :ch ch})
row (msg->row msg)
encoded (json/encode msg)]
(when (str/blank? (:from msg))
(throw (ex-info "missing :from" {:status 400})))
(when (str/blank? (:type msg))
(throw (ex-info "missing :type" {:status 400})))
(db-exec!
"INSERT INTO messages (id,ts,from_id,ch,type,v,body,files,reply_to)
VALUES (?,?,?,?,?,?,?,?,?)"
(:id row) (:ts row) (:from_id row) (:ch row)
(:type row) (:v row) (:body row) (:files row) (:reply_to row))
(broadcast! ch encoded (:id msg))
(created {:id (:id msg) :ts (:ts msg)})))
(defn handle-stream [req ch]
(let [method (:request-method req)]
(if (= method :head)
{:status 200 :headers sse-headers}
(let [last-id (get-in req [:headers "last-event-id"])
missed (when last-id
(if (= ch :all)
(->> (db-query
"SELECT * FROM messages WHERE id>? ORDER BY id ASC"
last-id)
(map row->msg))
(->> (db-query
"SELECT * FROM messages WHERE ch=? AND id>? ORDER BY id ASC"
ch last-id)
(map row->msg))))]
(http/as-channel req
{:on-open (fn [client]
;; First send MUST include status+headers+body together.
;; The body here is a SSE comment, which flushes the response
;; and transitions Firefox EventSource from CONNECTING to OPEN.
;; Headers are only applied on this first send; subsequent sends
;; are treated as stream chunks (status/headers stripped).
(http/send! client
{:status 200
:headers sse-headers
:body ": open\n\n"}
false)
;; Replay any missed messages (reconnect support)
(doseq [msg missed]
(http/send! client
(str "id: " (:id msg) "\ndata: " (json/encode msg) "\n\n")
false))
;; Subscribe for live broadcasts
(sub! ch client))
:on-close (fn [client _] (unsub! ch client))})))))
(defn handle-history [req ch]
(let [params (:query-params req)
since (get params "since")
type-filter (get params "type")
n-req (try (Integer/parseInt (get params "n" (str history-limit)))
(catch Exception _ history-limit))
n (min n-req history-limit)
rows (cond
(and since type-filter)
(db-query
"SELECT * FROM messages WHERE ch=? AND id>? AND type LIKE ? ORDER BY id DESC LIMIT ?"
ch since (str type-filter "%") n)
since
(db-query
"SELECT * FROM messages WHERE ch=? AND id>? ORDER BY id DESC LIMIT ?"
ch since n)
type-filter
(db-query
"SELECT * FROM messages WHERE ch=? AND type LIKE ? ORDER BY id DESC LIMIT ?"
ch (str type-filter "%") n)
:else
(db-query
"SELECT * FROM messages WHERE ch=? ORDER BY id DESC LIMIT ?"
ch n))
msgs (->> rows (map row->msg) reverse)]
{:status 200
:headers {"Content-Type" "application/x-ndjson"
"Access-Control-Allow-Origin" "*"}
:body (str/join "\n" (map json/encode msgs))}))
(defn handle-global-history [req]
(let [params (:query-params req)
n-req (try (Integer/parseInt (get params "n" "100")) (catch Exception _ 100))
n (min n-req history-limit)
rows (db-query "SELECT * FROM messages ORDER BY id DESC LIMIT ?" n)
msgs (->> rows (map row->msg) reverse)]
{:status 200
:headers {"Content-Type" "application/x-ndjson"
"Access-Control-Allow-Origin" "*"}
:body (str/join "\n" (map json/encode msgs))}))
(defn handle-channels [_req]
(let [rows (db-query "SELECT DISTINCT ch FROM messages ORDER BY ch")
chs (map :ch rows)]
(ok chs)))
;; ─────────────────────────────────────────────
;; TASK HELPERS
;; ─────────────────────────────────────────────
(defn get-task [id]
(first (db-query "SELECT * FROM tasks WHERE id=?" id)))
(defn task-announce! [ts ch from type body files]
(let [msg {:id (new-ulid) :ts ts :from from :ch ch :type type :body body}]
(db-exec!
"INSERT INTO messages (id,ts,from_id,ch,type,v,body,files)
VALUES (?,?,?,?,?,1,?,?)"
(:id msg) ts from ch type
(json/encode body) (json/encode (or files [])))
(broadcast! ch (json/encode (assoc msg :files (or files []))) (:id msg))))
;; ─────────────────────────────────────────────
;; TASK HANDLERS
;; ─────────────────────────────────────────────
(defn handle-task-create! [req]
(let [body (parse-body req)
id (new-ulid)
ts (now)
ch (or (:ch body) "tasks")
from (or (:from body) (:created_by body))]
(when (str/blank? from)
(throw (ex-info "missing :from or :created_by" {:status 400})))
(when (str/blank? (:title body))
(throw (ex-info "missing :title" {:status 400})))
(db-exec!
"INSERT INTO tasks (id,created_at,updated_at,created_by,assigned_to,status,title,context,files,ch)
VALUES (?,?,?,?,?,?,?,?,?,?)"
id ts ts from (:for body) "open" (:title body)
(json/encode (or (:context body) {}))
(json/encode [])
ch)
(task-announce! ts ch from "task.created"
{:task-id id :title (:title body) :for (:for body)} nil)
(created {:id id})))
(defn handle-task-get [_req id]
(let [task (get-task id)]
(if task
(ok (parse-task-row task))
(not-found "task not found"))))
(defn handle-task-list [req]
(let [params (:query-params req)
status (get params "status")
for-who (get params "for")
;; ?for= matches assigned_to OR claimed_by — intentional, shows "my tasks" either way
sql (cond
(and status for-who)
["SELECT * FROM tasks WHERE status=? AND (assigned_to=? OR claimed_by=?) ORDER BY created_at DESC"
status for-who for-who]
status
["SELECT * FROM tasks WHERE status=? ORDER BY created_at DESC" status]
for-who
["SELECT * FROM tasks WHERE assigned_to=? OR claimed_by=? ORDER BY created_at DESC"
for-who for-who]
:else
["SELECT * FROM tasks ORDER BY created_at DESC LIMIT 100"])
rows (apply db-query sql)]
(ok (map parse-task-row rows))))
(defn handle-task-claim! [req id]
(let [body (parse-body req)
agent (:from body)
task (get-task id)]
(when (str/blank? agent)
(throw (ex-info "missing :from" {:status 400})))
(cond
(nil? task) (not-found "task not found")
(not= (:status task) "open") (conflict (str "task is " (:status task) ", not open"))
:else
(do
(db-exec!
"UPDATE tasks SET status='claimed', claimed_by=?, claimed_at=?, updated_at=?
WHERE id=? AND status='open'"
agent (now) (now) id)
(let [updated (get-task id)]
(if (= (:claimed_by updated) agent)
(do
(task-announce! (now) (:ch task) agent "task.claimed"
{:task-id id :title (:title task)} nil)
(ok {:id id :status "claimed" :claimed-by agent}))
;; lost the race — another agent claimed between our check and update
(conflict "lost claim race — already claimed")))))))
(defn handle-task-update! [req id]
(let [body (parse-body req)
task (get-task id)]
(when (nil? task)
(throw (ex-info "task not found" {:status 404})))
(when (str/blank? (:from body))
(throw (ex-info "missing :from" {:status 400})))
(db-exec! "UPDATE tasks SET updated_at=? WHERE id=?" (now) id)
(task-announce! (now) (:ch task) (:from body) "task.updated"
(merge {:task-id id} (dissoc body :from)) nil)
(ok {:id id})))
(defn handle-task-done! [req id]
(let [body (parse-body req)
task (get-task id)
files (or (:files body) [])]
(when (nil? task)
(throw (ex-info "task not found" {:status 404})))
(when (str/blank? (:from body))
(throw (ex-info "missing :from" {:status 400})))
;; Only the claiming agent can mark done (or if unclaimed, the creator)
(when (and (:claimed_by task)
(not= (:from body) (:claimed_by task)))
(throw (ex-info "only the claiming agent can mark this task done" {:status 403})))
(when (not= (:status task) "claimed")
(throw (ex-info (str "task must be claimed to mark done, currently: " (:status task))
{:status 409})))
(db-exec!
"UPDATE tasks SET status='done', updated_at=?, result=?, files=? WHERE id=?"
(now) (json/encode (or (:result body) {})) (json/encode files) id)
(task-announce! (now) (:ch task) (:from body) "task.done"
{:task-id id :title (:title task)} files)
(ok {:id id :status "done"})))
(defn handle-task-abandon! [req id]
(let [body (parse-body req)
task (get-task id)]
(when (nil? task)
(throw (ex-info "task not found" {:status 404})))
(when (str/blank? (:from body))
(throw (ex-info "missing :from" {:status 400})))
;; Only the claiming agent can abandon
(when (and (:claimed_by task)
(not= (:from body) (:claimed_by task)))
(throw (ex-info "only the claiming agent can abandon this task" {:status 403})))
(when (not= (:status task) "claimed")
(throw (ex-info (str "task must be claimed to abandon, currently: " (:status task))
{:status 409})))
(db-exec!
"UPDATE tasks SET status='open', claimed_by=NULL, claimed_at=NULL, updated_at=? WHERE id=?"
(now) id)
(task-announce! (now) (:ch task) (:from body) "task.abandoned"
{:task-id id :title (:title task)} nil)
(ok {:id id :status "open"})))
(defn handle-task-interrupt! [req id]
(let [body (parse-body req)
task (get-task id)]
(when (nil? task)
(throw (ex-info "task not found" {:status 404})))
(when (str/blank? (:from body))
(throw (ex-info "missing :from" {:status 400})))
(task-announce! (now) (:ch task) (:from body) "task.interrupt"
{:task-id id :title (:title task) :reason (:reason body)} nil)
(ok {:id id :signalled true})))
;; ─────────────────────────────────────────────
;; FILE HANDLERS
;; ─────────────────────────────────────────────
(defn sha256-hex [bytes]
(let [md (java.security.MessageDigest/getInstance "SHA-256")
h (.digest md bytes)]
(apply str (map #(format "%02x" (bit-and % 0xff)) h))))
(defn handle-file-upload! [req]
(let [content-length (some-> req :headers (get "content-length") Integer/parseInt)]
(when (and content-length (> content-length max-file-size))
(throw (ex-info (str "file too large, max " max-file-size " bytes") {:status 413})))
(let [bytes (.readAllBytes (:body req))]
(when (> (count bytes) max-file-size)
(throw (ex-info (str "file too large, max " max-file-size " bytes") {:status 413})))
(let [hash (str "sha256:" (sha256-hex bytes))
path (str blobs-dir "/" hash)]
(.mkdirs (io/file blobs-dir))
(when-not (.exists (io/file path))
(with-open [out (io/output-stream path)]
(.write out bytes)))
(created {:hash hash :size (count bytes)})))))
(defn handle-file-fetch [_req hash]
;; Validate hash format to prevent path traversal
(when-not (re-matches #"sha256:[0-9a-f]{64}" hash)
(throw (ex-info "invalid hash format" {:status 400})))
(let [f (io/file blobs-dir hash)]
(if (.exists f)
{:status 200
:headers {"Content-Type" "application/octet-stream"
"Content-Length" (str (.length f))
"Access-Control-Allow-Origin" "*"}
:body f}
(not-found "blob not found"))))
;; ─────────────────────────────────────────────
;; PRESENCE HANDLERS
;; ─────────────────────────────────────────────
(defn handle-presence-heartbeat! [req]
(let [body (parse-body req)
agent (:from body)]
(when (str/blank? agent)
(throw (ex-info "missing :from" {:status 400})))
(db-exec!
"INSERT INTO presence (agent_id, last_seen, channels, meta)
VALUES (?,?,?,?)
ON CONFLICT(agent_id) DO UPDATE SET
last_seen=excluded.last_seen,
channels=excluded.channels,
meta=excluded.meta"
agent (now)
(json/encode (or (:channels body) []))
(json/encode (or (:meta body) {})))
(ok {:ok true})))
(defn handle-presence-list [_req]
(let [cutoff (- (now) (/ presence-ttl-ms 1000))
rows (db-query "SELECT * FROM presence WHERE last_seen > ?" cutoff)]
(ok (map (fn [r]
(-> r
(update :channels #(json/parse-string % true))
(update :meta #(json/parse-string % true))))
rows))))
;; ─────────────────────────────────────────────
;; STATUS
;; ─────────────────────────────────────────────
(def start-time (System/currentTimeMillis))
(defn handle-status [_req]
(let [msg-count (:count (first (db-query "SELECT COUNT(*) as count FROM messages")))
task-count (:count (first (db-query "SELECT COUNT(*) as count FROM tasks")))
agent-count (:count (first (db-query
"SELECT COUNT(*) as count FROM presence WHERE last_seen > ?"
(- (now) (/ presence-ttl-ms 1000)))))
uptime-s (/ (- (System/currentTimeMillis) start-time) 1000.0)
sub-count (reduce + 0 (map count (vals @subscribers)))]
(ok {:uptime-s uptime-s
:messages msg-count
:tasks task-count
:agents-live agent-count
:subscribers sub-count})))
;; ─────────────────────────────────────────────
;; CLEANUP
;; ─────────────────────────────────────────────
(defn cleanup! []
(try
(let [msg-cutoff (- (now) (* retention-days 24 60 60))
presence-cutoff (- (now) (* 7 24 60 60))]
;; Messages
(db-exec! "DELETE FROM messages WHERE ts < ?" msg-cutoff)
;; Stale presence rows (7-day TTL, independent of retention-days)
(db-exec! "DELETE FROM presence WHERE last_seen < ?" presence-cutoff)
(println (format "[cleanup] done — retention %dd, presence 7d" retention-days)))
(catch Exception e
(println "[cleanup] error:" (.getMessage e)))))
(defn start-cleanup! []
(future
(loop []
(Thread/sleep (* 60 60 1000)) ;; hourly
(cleanup!)
(recur))))
;; ─────────────────────────────────────────────
;; UI (terminal-aesthetic, embedded)
;; ─────────────────────────────────────────────
(def ui-html
"<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>workshop</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Berkeley+Mono:ital,wght@0,100..700;1,100..700&family=Space+Mono:ital,wght@0,400;0,700;1,400&display=swap');
:root {
--bg: #0d0f11;
--bg2: #131619;
--bg3: #1a1e22;
--border: #2a2f36;
--dim: #4a5260;
--muted: #6b7585;
--text: #c8d0db;
--bright: #e8edf5;
--task: #4da6ff;
--file: #4dffaa;
--agent: #ffd24d;
--err: #ff6b6b;
--general: #cc88ff;
--accent: #4da6ff;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: var(--bg);
color: var(--text);
font-family: 'Berkeley Mono', 'Space Mono', 'Fira Code', monospace;
font-size: 12px;
height: 100vh;
display: grid;
grid-template-rows: 40px 1fr 48px;
grid-template-columns: 180px 1fr 220px;
grid-template-areas:
'header header header'
'sidebar feed presence'
'sidebar compose presence';
overflow: hidden;
}
header {
grid-area: header;
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
padding: 0 16px;
gap: 12px;
background: var(--bg2);
}
.logo { color: var(--bright); font-weight: 700; letter-spacing: 0.15em; font-size: 13px; }
.logo span { color: var(--accent); }
.status-dot {
width: 7px; height: 7px; border-radius: 50%;
background: var(--file);
box-shadow: 0 0 6px var(--file);
animation: pulse 2s ease-in-out infinite;
flex-shrink: 0;
}
.status-dot.err { background: var(--err); box-shadow: 0 0 6px var(--err); animation: none; }
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
.header-stats { color: var(--muted); font-size: 11px; }
.header-right { margin-left: auto; display: flex; gap: 8px; align-items: center; }
.btn {
font-family: inherit; font-size: 11px;
background: transparent; color: var(--text);
border: 1px solid var(--border);
padding: 4px 10px; border-radius: 3px; cursor: pointer;
}
.btn:hover { border-color: var(--accent); color: var(--accent); }
#sidebar {
grid-area: sidebar;
border-right: 1px solid var(--border);
display: flex; flex-direction: column;
background: var(--bg2); overflow: hidden;
}
.sidebar-section {
padding: 10px 12px 4px;
color: var(--dim); font-size: 10px;
letter-spacing: 0.12em; text-transform: uppercase;
}
.ch-list { overflow-y: auto; flex: 1; }
.ch-item {
padding: 6px 16px; cursor: pointer;
color: var(--muted);
display: flex; align-items: center; gap: 6px;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
transition: all 0.1s;
}
.ch-item:hover { background: var(--bg3); color: var(--text); }
.ch-item.active { background: var(--bg3); color: var(--bright); }
.ch-item.active::before { content: '▶'; font-size: 8px; color: var(--accent); }
.unread {
margin-left: auto;
background: var(--accent); color: var(--bg);
border-radius: 8px; padding: 1px 5px;
font-size: 9px; font-weight: 700;
}
#feed {
grid-area: feed;
overflow-y: auto; padding: 8px 0;
display: flex; flex-direction: column;
}
.filter-bar {
padding: 6px 12px; border-bottom: 1px solid var(--border);
display: flex; gap: 4px; flex-wrap: wrap; background: var(--bg2);
}
.filter-btn {
font-family: inherit; font-size: 10px;
padding: 2px 7px; border-radius: 3px;
border: 1px solid var(--border);
background: transparent; color: var(--muted); cursor: pointer; transition: all 0.1s;
}
.filter-btn:hover, .filter-btn.active {
border-color: var(--accent); color: var(--accent);
background: rgba(77,166,255,0.08);
}
.msg {
padding: 4px 16px;
border-left: 2px solid transparent;
transition: background 0.1s; cursor: pointer; line-height: 1.6;
}
.msg:hover { background: var(--bg2); }
.msg.expanded { background: var(--bg2); border-left-color: var(--accent); }
.msg-header {
display: flex; align-items: baseline;
gap: 8px; flex-wrap: wrap;
}
.msg-ts { color: var(--dim); font-size: 10px; flex-shrink: 0; }
.msg-from { color: var(--agent); font-weight: 700; font-size: 11px; }
.msg-ch { color: var(--dim); font-size: 10px; }
.msg-type {
font-size: 10px; padding: 1px 6px;
border-radius: 3px; font-weight: 700; letter-spacing: 0.05em;
}
.type-task { background: rgba(77,166,255,0.15); color: var(--task); }
.type-file { background: rgba(77,255,170,0.15); color: var(--file); }
.type-agent { background: rgba(255,210,77,0.15); color: var(--agent); }
.type-general { background: rgba(204,136,255,0.15); color: var(--general); }
.type-error { background: rgba(255,107,107,0.15); color: var(--err); }
.msg-body-preview {
color: var(--muted); font-size: 11px; margin-top: 2px;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 600px;
}
.msg-detail {
display: none; margin-top: 8px; padding: 10px;
background: var(--bg3); border-radius: 4px; border: 1px solid var(--border);
font-size: 11px; white-space: pre-wrap; word-break: break-all;
color: var(--text); max-height: 300px; overflow-y: auto;
}
.msg.expanded .msg-detail { display: block; }
.file-badge {
display: inline-block; font-size: 10px; color: var(--file);
padding: 1px 5px; border: 1px solid rgba(77,255,170,0.3);
border-radius: 3px; margin-top: 3px; margin-right: 4px;
cursor: pointer; text-decoration: none;
}
.file-badge:hover { background: rgba(77,255,170,0.1); }
.empty-state { padding: 32px 16px; color: var(--dim); text-align: center; line-height: 2; }
#presence {
grid-area: presence;
border-left: 1px solid var(--border);
background: var(--bg2); overflow-y: auto; padding-bottom: 16px;
}
.presence-header {
padding: 10px 12px 4px; color: var(--dim); font-size: 10px;
letter-spacing: 0.12em; text-transform: uppercase;
border-bottom: 1px solid var(--border); margin-bottom: 4px;
}
.agent-item { padding: 8px 12px; border-bottom: 1px solid rgba(42,47,54,0.5); }
.agent-name { color: var(--agent); font-weight: 700; font-size: 11px; }
.agent-channels { color: var(--dim); font-size: 10px; margin-top: 2px; }
.agent-dot {
display: inline-block; width: 6px; height: 6px;
border-radius: 50%; background: var(--file); margin-right: 5px; vertical-align: middle;
}
#compose {
grid-area: compose;
border-top: 1px solid var(--border);
background: var(--bg2);
display: flex; align-items: center; gap: 8px; padding: 0 12px;
}
#compose input, #compose select, #compose .type-input {
font-family: inherit; font-size: 11px;
background: var(--bg3); border: 1px solid var(--border);
color: var(--text); padding: 4px 8px; border-radius: 3px; outline: none;
}
#compose input:focus, #compose select:focus { border-color: var(--accent); }
#compose input[name=from] { width: 110px; }
#compose select[name=ch] { width: 80px; }
#compose input[name=mtype] { width: 90px; }
#compose input[name=body] { flex: 1; }
#compose button {
font-family: inherit; font-size: 11px;
background: var(--accent); color: var(--bg);
border: none; padding: 4px 12px; border-radius: 3px; cursor: pointer; font-weight: 700;
}
::-webkit-scrollbar { width: 4px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
/* task panel overlay */
#task-overlay {
display: none; position: fixed; inset: 0;
background: rgba(0,0,0,0.6); z-index: 10;
align-items: center; justify-content: center;
}
#task-overlay.open { display: flex; }
#task-modal {
background: var(--bg2); border: 1px solid var(--border);
border-radius: 6px; padding: 20px; width: 420px; display: flex;
flex-direction: column; gap: 10px;
}
#task-modal h3 { color: var(--bright); font-size: 13px; }
#task-modal input, #task-modal textarea, #task-modal select {
font-family: inherit; font-size: 11px;
background: var(--bg3); border: 1px solid var(--border);
color: var(--text); padding: 6px 8px; border-radius: 3px; outline: none; width: 100%;
}
#task-modal input:focus, #task-modal textarea:focus { border-color: var(--accent); }
#task-modal textarea { height: 60px; resize: vertical; }
#task-modal .row { display: flex; gap: 8px; }
#task-modal .row input { flex: 1; }
#task-modal .actions { display: flex; gap: 8px; align-items: center; }
#task-modal .actions button {
font-family: inherit; font-size: 11px;
background: var(--task); color: var(--bg);
border: none; padding: 5px 14px; border-radius: 3px; cursor: pointer; font-weight: 700;
}
#task-modal .actions .cancel {
background: transparent; color: var(--muted); border: 1px solid var(--border);
}
#task-modal .err { color: var(--err); font-size: 10px; }
/* reconnect notice */
#reconnect-notice {
display: none; position: fixed; bottom: 60px; left: 50%; transform: translateX(-50%);
background: var(--bg3); border: 1px solid var(--err); border-radius: 4px;
color: var(--err); font-size: 11px; padding: 6px 14px; z-index: 20;
}
#reconnect-notice.show { display: block; }
</style>
</head>
<body>
<header>
<div class='logo'>work<span>shop</span></div>
<div class='status-dot' id='dot'></div>
<div id='hstats' class='header-stats'>connecting...</div>
<div class='header-right'>
<button class='btn' onclick='openTaskPanel()'>+ task</button>
</div>
</header>
<div id='sidebar'>
<div class='sidebar-section'>channels</div>
<div class='ch-list' id='chlist'>
<div class='ch-item active' data-ch='*' onclick='switchCh(this)'>✦ all channels</div>
</div>
</div>
<div id='feed'>
<div class='filter-bar' id='filterbar'>
<button class='filter-btn active' onclick='setFilter(this,null)'>all</button>
<button class='filter-btn' onclick='setFilter(this,\"task\")'>task.*</button>
<button class='filter-btn' onclick='setFilter(this,\"file\")'>file.*</button>
<button class='filter-btn' onclick='setFilter(this,\"agent\")'>agent.*</button>
<button class='filter-btn' onclick='setFilter(this,\"msg\")'>msg.*</button>
</div>
<div id='msgs'><div class='empty-state'>⬡ loading...</div></div>
</div>
<div id='compose'>
<input type='text' name='from' placeholder='from' value='human.you'>
<select name='ch'></select>
<input type='text' name='mtype' placeholder='type' value='msg.human'>
<input type='text' name='body' placeholder='message (JSON body or plain text)...'
onkeydown='if(event.key===\"Enter\")composeSend()'>
<button onclick='composeSend()'>send</button>
</div>
<div id='presence'>
<div class='presence-header'>agents online</div>
<div id='agentlist'></div>
</div>
<div id='task-overlay' onclick='e=>e.target===this&&closeTaskPanel()'>
<div id='task-modal'>
<h3>new task</h3>
<input type='text' id='t-title' placeholder='title (required)'>
<textarea id='t-context' placeholder='context (optional JSON)'></textarea>
<div class='row'>
<input type='text' id='t-ch' placeholder='channel' value='tasks'>
<input type='text' id='t-for' placeholder='for agent (optional)'>
</div>
<div class='actions'>
<button onclick='createTask()'>create</button>
<button class='cancel' onclick='closeTaskPanel()'>cancel</button>
<span class='err' id='task-err'></span>
</div>
</div>
</div>
<div id='reconnect-notice'>⚡ reconnecting...</div>
<script>
const BASE = window.location.origin;
// ── state ──
let currentCh = '*';
let typeFilter = null;
let allMessages = [];
const seenIds = new Set(); // global dedup — prevents duplicate renders on reconnect
let channels = new Set(['general', 'tasks']);
let unread = {};
let eventSource = null;
let reconnectTimer = null;
// ── type styling ──
function typeClass(type) {
if (!type) return 'type-general';
const ns = type.split('.')[0];
return {task:'type-task', file:'type-file', agent:'type-agent',
error:'type-error', msg:'type-general'}[ns] || 'type-general';
}
function fmtTs(ts) {
return new Date(ts * 1000).toLocaleTimeString('en',
{hour12:false, hour:'2-digit', minute:'2-digit', second:'2-digit'});
}
function fmtBody(body) {
if (!body || Object.keys(body).length === 0) return '';
return JSON.stringify(body).slice(0, 140);
}
// ── rendering ──