File size: 73,045 Bytes
c20fc12
eba35b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c20fc12
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>parley — A2A network console</title>
<style>
  :root {
    --blue: #2a78d6; --orange: #eb6834;
    --bg: #f6f7f9; --surface: #ffffff; --surface-2: #f0f2f5;
    --text: #14161b; --muted: #5b6270; --border: #dfe3e9;
    --ok: #1f8a55; --fail: #c0392b;
    --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
    --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #0e1015; --surface: #161920; --surface-2: #1d212a;
      --text: #e7e9ee; --muted: #98a0af; --border: #262c37;
      --ok: #3fbf83; --fail: #ef6f5e;
    }
  }
  * { box-sizing: border-box; }
  body {
    margin: 0; background: var(--bg); color: var(--text); font-family: var(--sans);
    font-size: 15px; line-height: 1.55; -webkit-font-smoothing: antialiased;
  }
  a { color: var(--blue); }
  header {
    border-bottom: 1px solid var(--border); background: var(--surface);
    padding: 18px 26px; display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap;
  }
  header h1 { margin: 0; font-size: 21px; letter-spacing: -0.3px; }
  header h1 span { color: var(--blue); }
  header p { margin: 0; color: var(--muted); font-size: 13.5px; flex: 1 1 320px; }
  .pill {
    font-family: var(--mono); font-size: 11px; padding: 3px 8px; border-radius: 999px;
    border: 1px solid var(--border); color: var(--muted); background: var(--surface-2);
    white-space: nowrap;
  }
  main { display: grid; grid-template-columns: 320px minmax(0, 1fr); gap: 22px; padding: 22px 26px 40px; align-items: start; }
  @media (max-width: 940px) { main { grid-template-columns: 1fr; } }
  .card {
    background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
    padding: 16px 18px; margin-bottom: 16px;
  }
  h2 { font-size: 12px; text-transform: uppercase; letter-spacing: 0.09em; color: var(--muted); margin: 0 0 12px; font-weight: 600; }
  svg#topology { width: 100%; max-width: 330px; height: auto; display: block; margin: 0 auto; }
  svg#topology text { font-family: var(--mono); font-size: 9.5px; fill: var(--muted); }
  svg#topology .node rect { fill: var(--surface-2); stroke: var(--border); stroke-width: 1; }
  svg#topology .node.lit rect { stroke: var(--blue); stroke-width: 2; fill: color-mix(in srgb, var(--blue) 12%, var(--surface-2)); }
  svg#topology .node.lit text { fill: var(--text); }
  svg#topology .edge { stroke: var(--border); stroke-width: 1.4; fill: none; }
  svg#topology .edge.lit { stroke: var(--blue); stroke-width: 2.2; }
  svg#topology .edge.lit.peer { stroke: var(--orange); stroke-dasharray: 4 3; }
  .legend { margin: 10px 0 0; font-size: 11.5px; color: var(--muted); display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
  .swatch { width: 15px; height: 0; border-top: 2.2px solid var(--blue); display: inline-block; }
  .swatch.peer { border-top-style: dashed; border-top-color: var(--orange); }
  .agent { border-top: 1px solid var(--border); padding: 11px 0 4px; }
  .agent:first-of-type { border-top: 0; }
  .agent-name { font-family: var(--mono); font-size: 12.5px; font-weight: 600; }
  .agent-desc { color: var(--muted); font-size: 12.5px; margin: 3px 0 7px; }
  .skills { display: flex; flex-wrap: wrap; gap: 5px; }
  .skill {
    font-family: var(--mono); font-size: 10.5px; padding: 2.5px 7px; border-radius: 5px;
    background: var(--surface-2); border: 1px solid var(--border); color: var(--muted); cursor: help;
  }
  .skill.lit { border-color: var(--blue); color: var(--blue); background: color-mix(in srgb, var(--blue) 10%, transparent); }
  form { display: flex; flex-direction: column; gap: 10px; }
  textarea {
    width: 100%; min-height: 74px; resize: vertical; padding: 11px 13px; font: inherit;
    border-radius: 9px; border: 1px solid var(--border); background: var(--surface-2); color: var(--text);
  }
  textarea:focus { outline: 2px solid color-mix(in srgb, var(--blue) 45%, transparent); outline-offset: 1px; }
  .controls { display: flex; gap: 9px; flex-wrap: wrap; align-items: center; }
  button {
    font: inherit; font-size: 14px; padding: 8px 15px; border-radius: 8px; cursor: pointer;
    border: 1px solid var(--border); background: var(--surface-2); color: var(--text);
  }
  button:hover:not(:disabled) { border-color: var(--blue); }
  button:disabled { opacity: 0.55; cursor: progress; }
  button.primary { background: var(--blue); border-color: var(--blue); color: #fff; font-weight: 600; }
  select { font: inherit; font-size: 13px; padding: 7px 9px; border-radius: 8px; border: 1px solid var(--border); background: var(--surface-2); color: var(--text); }
  label.inline { font-size: 12.5px; color: var(--muted); display: flex; align-items: center; gap: 6px; }
  .answer { font-size: 15.5px; line-height: 1.65; }
  .answer .cite {
    font-family: var(--mono); font-size: 10.5px; padding: 1.5px 6px; border-radius: 5px; margin-left: 3px;
    background: color-mix(in srgb, var(--orange) 15%, transparent); color: var(--orange);
    border: 1px solid color-mix(in srgb, var(--orange) 40%, transparent); white-space: nowrap;
  }
  .metrics { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
  .metric {
    background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px;
    padding: 7px 11px; min-width: 92px;
  }
  .metric b { display: block; font-size: 16px; font-variant-numeric: tabular-nums; }
  .metric span { font-size: 10.5px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
  ol.trace { list-style: none; margin: 0; padding: 0; }
  ol.trace li {
    border: 1px solid var(--border); border-radius: 9px; margin-bottom: 8px; background: var(--surface-2);
    overflow: hidden; animation: pop 260ms ease-out both;
  }
  @keyframes pop { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
  ol.trace li.depth-1 { margin-left: 26px; border-left: 3px solid var(--orange); }
  .hop-head {
    display: flex; align-items: center; gap: 9px; padding: 9px 12px; cursor: pointer;
    font-family: var(--mono); font-size: 12px; flex-wrap: wrap;
  }
  .hop-head .arrow { color: var(--muted); }
  .hop-head .callee { font-weight: 600; }
  .hop-head .skill { background: transparent; border: 0; padding: 0; color: var(--blue); cursor: pointer; }
  .hop-head .state { margin-left: auto; font-size: 10.5px; color: var(--ok); }
  .hop-head .state.fail { color: var(--fail); }
  .hop-head .ms { font-size: 10.5px; color: var(--muted); font-variant-numeric: tabular-nums; }
  pre {
    margin: 0; padding: 11px 13px; background: var(--surface); border-top: 1px solid var(--border);
    font-family: var(--mono); font-size: 11.5px; overflow-x: auto; max-height: 320px; line-height: 1.5;
  }
  details.wire summary { cursor: pointer; font-size: 12.5px; color: var(--muted); }
  details.wire pre { border: 1px solid var(--border); border-radius: 8px; margin-top: 8px; }
  .muted { color: var(--muted); font-size: 13px; }
  .error { color: var(--fail); font-size: 13.5px; }
  footer { padding: 0 26px 34px; color: var(--muted); font-size: 12.5px; }
  .hidden { display: none; }
</style>
</head>
<body>
<header>
  <h1>par<span>ley</span></h1>
  <p>Four agents, one protocol. Ask about a Python dependency and watch the delegations cross the network.</p>
  <span class="pill" id="protocol-pill">A2A v1.0 · HTTP+JSON</span>
  <span class="pill" id="model-pill">router: …</span>
</header>


<div class="card" id="space-banner" style="margin:16px 26px 0;border-color:var(--blue)">
  <h2 style="margin-bottom:8px">Browser build</h2>
  <p class="muted" style="margin:0">
    The three agents are running <strong>in this page</strong>, calling PyPI, OSV.dev and the
    GitHub REST API live. Routing uses the deterministic keyword baseline, because a public page
    cannot carry an API key — switch the router to <strong>recorded</strong> on any sample
    question to replay a real Gemini-routed run.
    <a href="https://github.com/UsmarHaider/parley">Source and evaluation &rarr;</a>
  </p>
</div>
<main>
  <aside>
    <div class="card">
      <h2>Network</h2>
      <svg id="topology" viewBox="0 0 300 130" role="img" aria-label="Agent network topology"></svg>
      <p class="legend"><span class="swatch orch"></span>orchestrator&nbsp;&rarr;&nbsp;agent
        <span class="swatch peer"></span>agent&nbsp;&rarr;&nbsp;peer</p>
    </div>
    <div class="card">
      <h2>Discovered agent cards</h2>
      <div id="agents"><p class="muted">Reading <code>/.well-known/agent-card.json</code></p></div>
    </div>
  </aside>

  <section>
    <div class="card">
      <h2>Ask the network</h2>
      <form id="ask">
        <textarea id="question" placeholder="e.g. We pin requests==2.19.0 in production — is that a security problem?"></textarea>
        <div class="controls">
          <button type="submit" class="primary" id="send">Send to orchestrator</button>
          <button type="button" id="sample">Try a sample</button>
          <label class="inline">router
            <select id="router"></select>
          </label>
          <span class="muted" id="status"></span>
        </div>
      </form>
    </div>

    <div class="card hidden" id="answer-card">
      <h2>Answer <span class="muted" style="text-transform:none;letter-spacing:0">— every fact carries the agent it came from</span></h2>
      <div class="answer" id="answer"></div>
      <div class="metrics" id="metrics"></div>
    </div>

    <div class="card hidden" id="trace-card">
      <h2>Message trace</h2>
      <ol class="trace" id="trace"></ol>
      <details class="wire">
        <summary>Raw A2A envelope sent to the orchestrator</summary>
        <pre id="wire"></pre>
      </details>
    </div>
  </section>
</main>

<footer>
  parley speaks the HTTP+JSON binding of A2A v1.0. This page is itself an A2A client: it POSTs a
  <code>SendMessage</code> to <code>/agents/orchestrator/message:send</code> and renders the task that comes back.
</footer>

<script>window.PARLEY_STATIC = {"cards":[{"name":"registry-agent","description":"Answers questions about Python packages as published on PyPI: versions, licences, release history and which source repository a distribution comes from.","supportedInterfaces":[{"url":"https://static.example/agents/registry","protocolBinding":"HTTP+JSON","protocolVersion":"1.0"}],"provider":{"url":"https://github.com/UsmarHaider/parley","organization":"parley"},"version":"0.1.0","documentationUrl":"https://docs.pypi.org/api/json/","capabilities":{"streaming":false,"pushNotifications":false,"extendedAgentCard":false},"defaultInputModes":["application/json","text/plain"],"defaultOutputModes":["application/json"],"skills":[{"id":"package_metadata","name":"Package metadata","description":"Current published facts about a PyPI distribution: latest version, licence, supported Python range, summary, whether the release is yanked, and its declared URLs. Arguments: package (required, a PyPI project name).","tags":["pypi","metadata","license","version"],"examples":["What licence is httpx published under?","What is the latest version of pydantic and which Pythons does it support?"]},{"id":"release_history","name":"Release history","description":"Release cadence for a PyPI distribution: total number of releases, the dates of the most recent ones, days since the last release, and the median gap between releases. Arguments: package (required), limit (optional, how many recent releases to list).","tags":["pypi","releases","maintenance","cadence"],"examples":["How often does flask cut a release?","When was the last release of six?"]},{"id":"resolve_repository","name":"Resolve source repository","description":"Map a PyPI distribution to its GitHub owner/repo by reading the project URLs it publishes. Other agents call this when they hold a package name but need a repository. Arguments: package (required).","tags":["pypi","github","resolution","linking"],"examples":["Which GitHub repository does the package 'pillow' come from?"]}]},{"name":"advisory-agent","description":"Answers security questions about Python packages using the OSV.dev advisory database: which versions are affected, how severe, and what fixes them.","supportedInterfaces":[{"url":"https://static.example/agents/advisory","protocolBinding":"HTTP+JSON","protocolVersion":"1.0"}],"provider":{"url":"https://github.com/UsmarHaider/parley","organization":"parley"},"version":"0.1.0","documentationUrl":"https://google.github.io/osv.dev/api/","capabilities":{"streaming":false,"pushNotifications":false,"extendedAgentCard":false},"defaultInputModes":["application/json","text/plain"],"defaultOutputModes":["application/json"],"skills":[{"id":"vulnerability_scan","name":"Vulnerability scan","description":"Known security advisories affecting a specific version of a PyPI package, from the OSV.dev database: advisory ids, severities, and the versions that fix them. If no version is given, the agent asks registry-agent for the latest published version first. Arguments: package (required), version (optional, e.g. \"2.19.0\").","tags":["security","osv","cve","vulnerability","advisory"],"examples":["Is requests 2.19.0 affected by any known vulnerabilities?","Are there CVEs in the current release of pillow?"]},{"id":"advisory_detail","name":"Advisory detail","description":"The full OSV record for one advisory identifier (GHSA-\u2026, CVE-\u2026, PYSEC-\u2026): summary, details, aliases, affected ranges and references. Arguments: advisoryId (required, e.g. \"GHSA-9wx4-h78v-vm56\" or \"CVE-2023-50447\").","tags":["security","osv","cve","ghsa","lookup"],"examples":["What is GHSA-9wx4-h78v-vm56 about?","Explain CVE-2023-50447."]}]},{"name":"repo-agent","description":"Answers questions about the health and activity of the GitHub repository behind a Python package: stars, issues, archival status, and recent commits.","supportedInterfaces":[{"url":"https://static.example/agents/repo","protocolBinding":"HTTP+JSON","protocolVersion":"1.0"}],"provider":{"url":"https://github.com/UsmarHaider/parley","organization":"parley"},"version":"0.1.0","documentationUrl":"https://docs.github.com/en/rest/repos/repos","capabilities":{"streaming":false,"pushNotifications":false,"extendedAgentCard":false},"defaultInputModes":["application/json","text/plain"],"defaultOutputModes":["application/json"],"skills":[{"id":"repo_health","name":"Repository health","description":"Maintenance signals for the GitHub repository behind a package: stars, forks, open issues, licence, whether it is archived, and how long since the last push. Accepts a package name and resolves the repository through registry-agent. Arguments: package (required unless owner and repo are given).","tags":["github","maintenance","stars","archived","health"],"examples":["Is the repository behind 'six' still maintained?","How many open issues does the httpx repository have?"]},{"id":"recent_activity","name":"Recent commit activity","description":"Commit activity on the default branch over a recent window: number of commits, number of distinct authors, and the date of the newest commit. Distinguishes a project that is quiet from one that is abandoned. Arguments: package (required unless owner and repo are given), windowDays (optional, default 90).","tags":["github","commits","contributors","activity"],"examples":["Has anyone committed to the flask repository in the last 90 days?","How many people are actively contributing to pydantic?"]}]}],"orchestrator":{"name":"orchestrator","description":"Answers open questions about the health and safety of a Python dependency by discovering the specialist agents on the network, delegating to the ones that can help, and writing an answer in which every fact carries the agent it came from.","supportedInterfaces":[{"url":"https://static.example/agents/orchestrator","protocolBinding":"HTTP+JSON","protocolVersion":"1.0"}],"provider":{"url":"https://github.com/UsmarHaider/parley","organization":"parley"},"version":"0.1.0","documentationUrl":"https://github.com/UsmarHaider/parley","capabilities":{"streaming":false,"pushNotifications":false,"extendedAgentCard":false},"defaultInputModes":["application/json","text/plain"],"defaultOutputModes":["application/json"],"skills":[{"id":"supply_chain_review","name":"Dependency review","description":"Answer a free-text question about a Python package by routing it across the network. Arguments: question (required), router (optional: 'llm' or 'rules').","tags":["orchestration","routing","supply-chain","python"],"examples":["Should I be worried about using requests 2.19.0?","Is 'six' still maintained, and does it have any open vulnerabilities?"]}]},"samples":[{"label":"A pinned version with a known problem","question":"We still pin requests==2.19.0 in production. Is that a security problem, and is the project still actively maintained?"},{"label":"Is this dependency abandoned?","question":"Is the 'six' package still maintained? When was its last release and has anyone committed to it recently?"},{"label":"Licence and Python support","question":"What licence is httpx published under and which Python versions does the current release support?"},{"label":"One advisory, explained","question":"What is GHSA-9wx4-h78v-vm56 about and which versions fix it?"},{"label":"Latest release, security only","question":"Does the current release of pillow have any known vulnerabilities?"},{"label":"Out of scope \u2014 and the network says so","question":"How many times was requests downloaded from PyPI last month?"}],"stopwords":["abandoned","able","about","above","active","advisories","advisory","after","again","against","all","also","an","and","any","anyone","archived","are","as","at","back","be","because","been","before","being","below","between","both","but","by","can","case","cases","check","close","come","commit","commits","contributor","contributors","could","current","cve","day","dependencies","dependency","deploy","deployed","did","distinct","do","does","doing","downgrade","during","each","ecosystem","even","everyone","everything","fact","facts","few","find","first","for","from","full","get","ghsa","github","give","go","good","had","has","have","help","her","here","him","his","how","if","in","install","into","is","issue","issues","it","its","just","kind","know","known","last","latest","less","libraries","library","licence","license","licensed","like","long","look","made","maintained","maintainer","maintenance","make","many","may","me","might","module","modules","more","most","much","must","my","need","new","next","no","not","nothing","now","npm","number","numbers","of","off","on","once","one","only","open","or","other","our","out","over","package","packages","part","parts","pin","pinned","please","point","points","project","projects","pypi","pysec","python","recent","repo","repos","repositories","repository","said","same","say","security","see","shall","she","should","show","so","some","someone","something","sort","star","stars","still","such","take","tell","tells","than","that","the","their","them","then","there","they","thing","things","think","this","through","time","to","too","two","under","up","upgrade","us","use","very","vulnerabilities","vulnerability","vulnerable","want","was","way","we","well","were","what","when","where","which","while","who","whom","whose","why","will","with","work","would","year","you","your"],"keywords":{"vulnerability_scan":["vulnerab","cve","ghsa","security","exploit","advisor","safe","unsafe","risk","patched"],"advisory_detail":["ghsa-","cve-","pysec-"],"repo_health":["maintain","archiv","star","issue","abandon","fork","popular","healthy","repo","github","licence of the repo"],"recent_activity":["commit","activity","active","contributor","recently worked","still alive"],"release_history":["release","cadence","how often","last updated","last version","changelog","stale","since"],"package_metadata":["licen","version","python","summary","what is","yanked","metadata"]},"transcripts":[{"question":"We still pin requests==2.19.0 in production. Is that a security problem, and is the project still actively maintained?","answer":"Pinning requests==2.19.0 is a security problem because a vulnerability scan shows 10 vulnerabilities, including 1 high-severity and 4 moderate-severity issues [advisory-agent.vulnerability_scan]. Despite these security concerns, the project is still actively maintained with the repository showing a last push on 2026-08-03 and 233 open issues [repo-agent.repo_health].","plan":{"router":"llm:gemini-3.5-flash-lite","reasoning":"To answer whether requests==2.19.0 has security vulnerabilities, we use vulnerability_scan on advisory-agent. To answer whether the project is still actively maintained, we use repo_health on repo-agent.","delegations":[{"agent":"advisory-agent","skill":"vulnerability_scan","args":{"package":"requests","version":"2.19.0"}},{"agent":"repo-agent","skill":"repo_health","args":{"package":"requests"}}],"rejected":[]},"trace":{"contextId":"04b9ba91-f51d-4d77-8030-9b0bdc155173","hops":[{"caller":"orchestrator","callee":"advisory-agent","skill":"vulnerability_scan","args":{"package":"requests","version":"2.19.0"},"state":"TASK_STATE_COMPLETED","elapsedMs":3.4,"taskId":"f48f63bf-4c29-4df7-8068-39104c12c624","result":{"package":"requests","version":"2.19.0","versionResolvedVia":"caller","safe":false,"vulnerabilityCount":10,"worstSeverity":"HIGH","bySeverity":{"HIGH":1,"MODERATE":4,"UNKNOWN":5},"advisories":[{"id":"GHSA-x84v-xcm2-53pg","aliases":["CVE-2018-18074","PYSEC-2018-28"],"summary":"Insufficiently Protected Credentials in Requests","severity":"HIGH","published":"2018-10-29","fixedVersions":["2.20.0"]},{"id":"GHSA-9hjg-9r4m-mvj7","aliases":["CVE-2024-47081","PYSEC-2026-1872"],"summary":"Requests vulnerable to .netrc credentials leak via malicious URLs","severity":"MODERATE","published":"2025-06-09","fixedVersions":["2.32.4"]},{"id":"GHSA-9wx4-h78v-vm56","aliases":["CVE-2024-35195","PYSEC-2026-1873"],"summary":"Requests `Session` object does not verify requests after making first request with verify=False","severity":"MODERATE","published":"2024-05-20","fixedVersions":["2.32.0"]},{"id":"GHSA-gc5v-m9x4-r6x2","aliases":["CVE-2026-25645","PYSEC-2026-2275"],"summary":"Requests has Insecure Temp File Reuse in its extract_zipped_paths() utility function","severity":"MODERATE","published":"2026-03-25","fixedVersions":["2.33.0"]},{"id":"GHSA-j8r2-6x86-q33q","aliases":["CVE-2023-32681","PYSEC-2023-74"],"summary":"Unintended leak of Proxy-Authorization header in requests","severity":"MODERATE","published":"2023-05-22","fixedVersions":["2.31.0"]},{"id":"PYSEC-2018-28","aliases":["CVE-2018-18074","GHSA-x84v-xcm2-53pg"],"summary":"The Requests package before 2.20.0 for Python sends an HTTP Authorization header to an http URI upon receiving a same-hostname https-to-http redirect, which mak","severity":"UNKNOWN","published":"2018-10-09","fixedVersions":["c45d7c49ea75133e52ab22a8e9e13173938e36ff","2.20.0"]},{"id":"PYSEC-2023-74","aliases":["CVE-2023-32681","GHSA-j8r2-6x86-q33q"],"summary":"Requests is a HTTP library. Since Requests 2.3.0, Requests has been leaking Proxy-Authorization headers to destination servers when redirected to an HTTPS endpo","severity":"UNKNOWN","published":"2023-05-26","fixedVersions":["74ea7cf7a6a27a4eeb2ae24e162bcc942a6706d5","2.31.0"]},{"id":"PYSEC-2026-1872","aliases":["CVE-2024-47081","GHSA-9hjg-9r4m-mvj7"],"summary":"Requests vulnerable to .netrc credentials leak via malicious URLs","severity":"UNKNOWN","published":"2026-07-07","fixedVersions":["2.32.4"]},{"id":"PYSEC-2026-1873","aliases":["CVE-2024-35195","GHSA-9wx4-h78v-vm56"],"summary":"Requests `Session` object does not verify requests after making first request with verify=False","severity":"UNKNOWN","published":"2026-07-07","fixedVersions":["2.32.0"]},{"id":"PYSEC-2026-2275","aliases":["CVE-2026-25645","GHSA-gc5v-m9x4-r6x2"],"summary":"Requests is a HTTP library. Prior to version 2.33.0, the `requests.utils.extract_zipped_paths()` utility function uses a predictable filename when extracting fi","severity":"UNKNOWN","published":"2026-03-25","fixedVersions":["2.33.0"]}]},"error":null,"depth":0},{"caller":"orchestrator","callee":"repo-agent","skill":"repo_health","args":{"package":"requests"},"state":"TASK_STATE_COMPLETED","elapsedMs":5.2,"taskId":"6403857f-7dd1-46e1-a51e-2f52f411c3dc","result":{"owner":"psf","repo":"requests","repoUrl":"https://github.com/psf/requests","repositoryResolvedVia":"registry-agent.resolve_repository","stars":54257,"forks":10073,"openIssues":233,"watchers":1305,"archived":false,"license":"Apache-2.0","defaultBranch":"main","lastPush":"2026-08-03","daysSinceLastPush":3,"ageYears":15.5,"description":"A simple, yet elegant, HTTP library."},"error":null,"depth":0},{"caller":"repo-agent","callee":"registry-agent","skill":"resolve_repository","args":{"package":"requests"},"state":"TASK_STATE_COMPLETED","elapsedMs":3.5,"taskId":"fa997eea-81bd-4854-9151-38750166a37f","result":{"package":"requests","owner":"psf","repo":"requests","repoUrl":"https://github.com/psf/requests"},"error":null,"depth":1}]},"grading":{"sentences":2,"citedSentences":2,"citationCoverage":1.0,"citations":2,"invalidCitations":[],"unusedFacts":["registry-agent.resolve_repository"]},"elapsedMs":1880.3,"llmCalls":2,"error":null,"partial":[]},{"question":"Is the 'six' package still maintained? When was its last release and has anyone committed to it recently?","answer":"The 'six' package is not archived, meaning it is still considered active, but there has been no recent commit activity [repo-agent.repo_health, repo-agent.recent_activity]. Its last release was version 1.17.0 on 2024-12-04 [registry-agent.release_history]. There were 0 commits made by distinct authors in the 90-day window, though a code push occurred on 2026-02-23 [repo-agent.repo_health, repo-agent.recent_activity].","plan":{"router":"llm:gemini-3.5-flash-lite","reasoning":"To answer whether 'six' is maintained, when its last release was, and if anyone has committed to it recently, we need to check its repository health, release history, and recent commit activity. We can use repo_health from repo-agent, release_history from registry-agent, and recent_activity from repo-agent.","delegations":[{"agent":"repo-agent","skill":"repo_health","args":{"package":"six"}},{"agent":"registry-agent","skill":"release_history","args":{"package":"six"}},{"agent":"repo-agent","skill":"recent_activity","args":{"package":"six"}}],"rejected":[]},"trace":{"contextId":"ce2831a1-ce65-4722-ba3f-3b5953d00198","hops":[{"caller":"orchestrator","callee":"repo-agent","skill":"repo_health","args":{"package":"six"},"state":"TASK_STATE_COMPLETED","elapsedMs":6.1,"taskId":"97d45b72-3e32-4948-91bb-b755da001303","result":{"owner":"benjaminp","repo":"six","repoUrl":"https://github.com/benjaminp/six","repositoryResolvedVia":"registry-agent.resolve_repository","stars":1024,"forks":274,"openIssues":111,"watchers":26,"archived":false,"license":"MIT","defaultBranch":"main","lastPush":"2026-02-23","daysSinceLastPush":165,"ageYears":9.6,"description":"Python 2 and 3 compatibility library"},"error":null,"depth":0},{"caller":"repo-agent","callee":"registry-agent","skill":"resolve_repository","args":{"package":"six"},"state":"TASK_STATE_COMPLETED","elapsedMs":3.6,"taskId":"87a5d601-4fc5-438b-ae40-1e003a01769d","result":{"package":"six","owner":"benjaminp","repo":"six","repoUrl":"https://github.com/benjaminp/six"},"error":null,"depth":1},{"caller":"orchestrator","callee":"registry-agent","skill":"release_history","args":{"package":"six"},"state":"TASK_STATE_COMPLETED","elapsedMs":2.1,"taskId":"72f3f9e3-d441-43e9-b317-22168d9d775e","result":{"package":"six","releaseCount":29,"datedReleaseCount":29,"firstRelease":"2010-06-29","latestRelease":"2024-12-04","daysSinceLatestRelease":610,"medianDaysBetweenLast10":330.7,"yankedCount":0,"recent":[{"version":"1.17.0","released":"2024-12-04","yanked":false},{"version":"1.16.0","released":"2021-05-05","yanked":false},{"version":"1.15.0","released":"2020-05-21","yanked":false},{"version":"1.14.0","released":"2020-01-15","yanked":false},{"version":"1.13.0","released":"2019-11-05","yanked":false},{"version":"1.12.0","released":"2018-12-10","yanked":false},{"version":"1.11.0","released":"2017-09-17","yanked":false},{"version":"1.10.0","released":"2015-10-07","yanked":false}]},"error":null,"depth":0},{"caller":"orchestrator","callee":"repo-agent","skill":"recent_activity","args":{"package":"six"},"state":"TASK_STATE_COMPLETED","elapsedMs":3.0,"taskId":"7858f7af-4961-4ae7-ad00-96e199b55cb7","result":{"owner":"benjaminp","repo":"six","repositoryResolvedVia":"registry-agent.resolve_repository","windowDays":90,"commitsInWindow":0,"commitsTruncatedAt100":false,"distinctAuthors":0,"newestCommit":null,"daysSinceNewestCommit":null},"error":null,"depth":0},{"caller":"repo-agent","callee":"registry-agent","skill":"resolve_repository","args":{"package":"six"},"state":"TASK_STATE_COMPLETED","elapsedMs":1.5,"taskId":"1b1de190-1524-4039-b158-83db07a62c52","result":{"package":"six","owner":"benjaminp","repo":"six","repoUrl":"https://github.com/benjaminp/six"},"error":null,"depth":1}]},"grading":{"sentences":3,"citedSentences":3,"citationCoverage":1.0,"citations":5,"invalidCitations":[],"unusedFacts":["registry-agent.resolve_repository"]},"elapsedMs":2121.2,"llmCalls":2,"error":null,"partial":[]},{"question":"What licence is httpx published under and which Python versions does the current release support?","answer":"Httpx is published under the BSD-3-Clause license and requires Python version >=3.8 [registry-agent.package_metadata].","plan":{"router":"llm:gemini-3.5-flash-lite","reasoning":"The user is asking for the licence and supported Python versions of the httpx package. The package_metadata skill from the registry-agent directly provides the current published facts including licence and supported Python range.","delegations":[{"agent":"registry-agent","skill":"package_metadata","args":{"package":"httpx"}}],"rejected":[]},"trace":{"contextId":"28c4b03a-e193-4569-baa6-a72aab06de87","hops":[{"caller":"orchestrator","callee":"registry-agent","skill":"package_metadata","args":{"package":"httpx"},"state":"TASK_STATE_COMPLETED","elapsedMs":3.9,"taskId":"83d267ec-3a85-47d9-b151-ec6c5402dfae","result":{"package":"httpx","latestVersion":"0.28.1","summary":"The next generation HTTP client.","license":"BSD-3-Clause","requiresPython":">=3.8","yanked":false,"releaseCount":74,"repository":{"owner":"encode","repo":"httpx","repoUrl":"https://github.com/encode/httpx"},"projectUrls":{"Changelog":"https://github.com/encode/httpx/blob/master/CHANGELOG.md","Documentation":"https://www.python-httpx.org","Homepage":"https://github.com/encode/httpx","Source":"https://github.com/encode/httpx"}},"error":null,"depth":0}]},"grading":{"sentences":1,"citedSentences":1,"citationCoverage":1.0,"citations":1,"invalidCitations":[],"unusedFacts":[]},"elapsedMs":2295.6,"llmCalls":2,"error":null,"partial":[]},{"question":"What is GHSA-9wx4-h78v-vm56 about and which versions fix it?","answer":"GHSA-9wx4-h78v-vm56 is about a vulnerability in the Requests `Session` object where TLS certificate verification may remain disabled for all subsequent requests to an origin if the first request is made with `verify=False`, and it is fixed in version 2.32.0 [advisory-agent.advisory_detail]. When using a `requests.Session`, this occurs because the underlying connection is reused from the connection pool, causing the initial TLS verification setting to persist even if `verify=True` is explicitly specified later [advisory-agent.advisory_detail].","plan":{"router":"llm:gemini-3.5-flash-lite","reasoning":"The user is asking about a specific security advisory identifier (GHSA-9wx4-h78v-vm56), including what it is about and which versions fix it. The advisory-agent has the advisory_detail skill which accepts an advisoryId and returns the full OSV record including summary, details, and affected ranges.","delegations":[{"agent":"advisory-agent","skill":"advisory_detail","args":{"advisoryId":"GHSA-9wx4-h78v-vm56"}}],"rejected":[]},"trace":{"contextId":"505441fb-1899-4182-897f-8d022fd41430","hops":[{"caller":"orchestrator","callee":"advisory-agent","skill":"advisory_detail","args":{"advisoryId":"GHSA-9wx4-h78v-vm56"},"state":"TASK_STATE_COMPLETED","elapsedMs":3.2,"taskId":"336a7ea1-aca5-4cb4-bb47-9a9e82641392","result":{"id":"GHSA-9wx4-h78v-vm56","aliases":["CVE-2024-35195","PYSEC-2026-1873"],"summary":"Requests `Session` object does not verify requests after making first request with verify=False","details":"When using a `requests.Session`, if the first request to a given origin is made with `verify=False`, TLS certificate verification may remain disabled for all subsequent requests to that origin, even if `verify=True` is explicitly specified later.\n\nThis occurs because the underlying connection is reused from the session's connection pool, causing the initial TLS verification setting to persist for the lifetime of the pooled connection. As a result, applications may unintentionally send requests without certificate verification, leading to potential man-in-the-middle attacks and compromised confidentiality or integrity.\n\nThis behavior affects versions of `requests` prior to 2.32.0.","severity":"MODERATE","published":"2024-05-20","modified":"2026-07-07","affectedPackages":["requests"],"fixedVersions":["2.32.0"],"references":["https://github.com/psf/requests/security/advisories/GHSA-9wx4-h78v-vm56","https://nvd.nist.gov/vuln/detail/CVE-2024-35195","https://github.com/psf/requests/pull/6655","https://github.com/psf/requests/commit/a58d7f2ffb4d00b46dca2d70a3932a0b37e22fac","https://github.com/psf/requests","https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/IYLSNK5TL46Q6XPRVMHVWS63MVJQOK4Q"]},"error":null,"depth":0}]},"grading":{"sentences":2,"citedSentences":2,"citationCoverage":1.0,"citations":2,"invalidCitations":[],"unusedFacts":[]},"elapsedMs":1975.0,"llmCalls":2,"error":null,"partial":[]},{"question":"Does the current release of pillow have any known vulnerabilities?","answer":"No, the current release of Pillow (version 12.3.0) does not have any known vulnerabilities [advisory-agent.vulnerability_scan]. A vulnerability scan indicates that the package is safe with a vulnerability count of zero [advisory-agent.vulnerability_scan].","plan":{"router":"llm:gemini-3.5-flash-lite","reasoning":"The user is asking if the current release of pillow has any known vulnerabilities. The vulnerability_scan skill from the advisory-agent can check for vulnerabilities in a package, and if no version is given, it automatically fetches the latest published version.","delegations":[{"agent":"advisory-agent","skill":"vulnerability_scan","args":{"package":"pillow"}}],"rejected":[]},"trace":{"contextId":"73f8e0b0-46e1-408e-9a7e-13bf0dc6afc7","hops":[{"caller":"orchestrator","callee":"advisory-agent","skill":"vulnerability_scan","args":{"package":"pillow"},"state":"TASK_STATE_COMPLETED","elapsedMs":31.1,"taskId":"f4bb4a7a-c92f-454e-b901-65614b85e10d","result":{"package":"pillow","version":"12.3.0","versionResolvedVia":"registry-agent.package_metadata","safe":true,"vulnerabilityCount":0,"worstSeverity":null,"bySeverity":{},"advisories":[]},"error":null,"depth":0},{"caller":"advisory-agent","callee":"registry-agent","skill":"package_metadata","args":{"package":"pillow"},"state":"TASK_STATE_COMPLETED","elapsedMs":29.2,"taskId":"b772f472-7ff1-4a21-a950-e0500aa1e950","result":{"package":"pillow","latestVersion":"12.3.0","summary":"Python Imaging Library (fork)","license":"MIT-CMU","requiresPython":">=3.10","yanked":false,"releaseCount":107,"repository":{"owner":"python-pillow","repo":"Pillow","repoUrl":"https://github.com/python-pillow/Pillow"},"projectUrls":{"Changelog":"https://github.com/python-pillow/Pillow/releases","Documentation":"https://pillow.readthedocs.io","Funding":"https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pypi-pillow&utm_medium=pypi","Homepage":"https://python-pillow.github.io","Mastodon":"https://fosstodon.org/@pillow","Release notes":"https://pillow.readthedocs.io/en/stable/releasenotes/index.html","Source":"https://github.com/python-pillow/Pillow"}},"error":null,"depth":1}]},"grading":{"sentences":2,"citedSentences":2,"citationCoverage":1.0,"citations":2,"invalidCitations":[],"unusedFacts":["registry-agent.package_metadata"]},"elapsedMs":1609.7,"llmCalls":2,"error":null,"partial":[]},{"question":"How many times was requests downloaded from PyPI last month?","answer":"No agent on the network returned a usable result for this question (no agents were called).","plan":{"router":"llm:gemini-3.5-flash-lite","reasoning":"The user is asking for download statistics for the requests package from PyPI. None of the available skills cover download counts or PyPI download statistics.","delegations":[],"rejected":[]},"trace":{"contextId":"7e081d87-26f2-40a9-9b5b-352a767bf5b0","hops":[]},"grading":{"sentences":1,"citedSentences":0,"citationCoverage":0.0,"citations":0,"invalidCitations":[],"unusedFacts":[]},"elapsedMs":745.2,"llmCalls":1,"error":null,"partial":[]}]};</script>
<script>
/* parley — browser build.
 *
 * Hugging Face static Spaces serve files, not Python, so the network moves
 * into the page: the three specialist agents run here, calling PyPI, OSV.dev
 * and the GitHub REST API directly (all three send `Access-Control-Allow-
 * Origin: *`). Envelopes, task states, agent cards and the delegation between
 * agents are the same A2A shapes the FastAPI build produces — this file is a
 * port of the agents, not a mock of them.
 *
 * The one thing that cannot cross over is the model: shipping an API key to a
 * public page is not an option. So the browser build routes with the keyword
 * baseline and answers with the template summarizer, both ports of the Python
 * originals; the five sample questions additionally offer the *recorded*
 * Gemini run committed in reports/transcripts.json, clearly labelled.
 *
 * The console itself is unmodified. It talks to `/api/*` and
 * `/agents/orchestrator/message:send`; the fetch override below answers those
 * routes in-page.
 */
(() => {
  "use strict";
  const S = window.PARLEY_STATIC;
  const CARDS = S.cards;
  const ORCH_CARD = S.orchestrator;
  const STOPWORDS = new Set(S.stopwords);
  const uuid = () => (crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2));

  const COMPLETED = "TASK_STATE_COMPLETED";
  const FAILED = "TASK_STATE_FAILED";

  // ---- upstream calls ------------------------------------------------------
  const cache = new Map();
  async function getJson(url, { allow404 = false } = {}) {
    if (cache.has(url)) return cache.get(url);
    const response = await fetch(url, { headers: { accept: "application/json" } });
    if (response.status === 404 && allow404) { cache.set(url, null); return null; }
    if (response.status === 403) throw new Error("GitHub rate limit reached (60 requests/hour for anonymous callers)");
    if (!response.ok) throw new Error(`${url} -> HTTP ${response.status}`);
    const payload = await response.json();
    cache.set(url, payload);
    return payload;
  }
  async function postJson(url, body) {
    const key = url + JSON.stringify(body);
    if (cache.has(key)) return cache.get(key);
    const response = await fetch(url, {
      method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
    });
    if (!response.ok) throw new Error(`${url} -> HTTP ${response.status}`);
    const payload = await response.json();
    cache.set(key, payload);
    return payload;
  }

  const daysSince = (iso) => (iso ? Math.max(0, Math.floor((Date.now() - Date.parse(iso)) / 86400000)) : null);
  const median = (values) => {
    if (values.length < 2) return null;
    const gaps = [];
    for (let i = 1; i < values.length; i += 1) gaps.push((values[i] - values[i - 1]) / 86400000);
    gaps.sort((a, b) => a - b);
    const mid = Math.floor(gaps.length / 2);
    const value = gaps.length % 2 ? gaps[mid] : (gaps[mid - 1] + gaps[mid]) / 2;
    return Math.round(value * 10) / 10;
  };

  function requireArg(args, key) {
    const value = args[key];
    if (typeof value !== "string" || !value.trim()) throw new Error(`argument '${key}' is required and must be a non-empty string`);
    return value.trim();
  }

  // ---- registry-agent (PyPI) ----------------------------------------------
  const GITHUB_RE = /github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)/;
  const REPO_KEYS = ["source", "source code", "repository", "code", "github", "homepage", "home"];

  function extractRepo(info) {
    const candidates = [];
    const urls = info.project_urls || {};
    for (const [key, url] of Object.entries(urls)) {
      if (typeof url !== "string") continue;
      const rank = REPO_KEYS.indexOf(key.trim().toLowerCase());
      candidates.push([rank < 0 ? REPO_KEYS.length : rank, url]);
    }
    for (const fallback of [info.home_page, info.project_url, info.download_url]) {
      if (typeof fallback === "string" && fallback) candidates.push([REPO_KEYS.length + 1, fallback]);
    }
    candidates.sort((a, b) => a[0] - b[0]);
    for (const [, url] of candidates) {
      const match = GITHUB_RE.exec(url);
      if (!match) continue;
      const owner = match[1];
      const repo = match[2].replace(/\.git$/, "");
      if (!repo || new URL(url, location.href).hostname.endsWith("io")) continue;
      return { owner, repo, repoUrl: `https://github.com/${owner}/${repo}` };
    }
    return null;
  }

  async function fetchPackage(name) {
    if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,60}[A-Za-z0-9])?$/.test(name)) throw new Error(`'${name}' is not a valid PyPI project name`);
    const payload = await getJson(`https://pypi.org/pypi/${encodeURIComponent(name)}/json`, { allow404: true });
    if (!payload) throw new Error(`PyPI has no project named '${name}'`);
    return payload;
  }

  function datedReleases(payload) {
    const rows = [];
    for (const [version, files] of Object.entries(payload.releases || {})) {
      const stamps = files.map((f) => f.upload_time_iso_8601).filter(Boolean).sort();
      if (!stamps.length) continue;
      rows.push({ version, released: stamps[0], yanked: files.some((f) => f.yanked) });
    }
    rows.sort((a, b) => (a.released < b.released ? -1 : 1));
    return rows;
  }

  // ---- advisory-agent (OSV.dev) -------------------------------------------
  const SEVERITY_ORDER = ["CRITICAL", "HIGH", "MODERATE", "LOW", "UNKNOWN"];
  const severityOf = (vuln) => {
    const label = ((vuln.database_specific || {}).severity || "").toUpperCase();
    return SEVERITY_ORDER.includes(label) ? label : "UNKNOWN";
  };
  const fixedVersions = (vuln) => {
    const fixes = [];
    for (const affected of vuln.affected || []) {
      for (const range of affected.ranges || []) {
        for (const event of range.events || []) {
          if (event.fixed && !fixes.includes(event.fixed)) fixes.push(event.fixed);
        }
      }
    }
    return fixes;
  };
  function summariseVulns(vulns) {
    const bySeverity = {};
    const advisories = vulns.map((vuln) => {
      const severity = severityOf(vuln);
      bySeverity[severity] = (bySeverity[severity] || 0) + 1;
      return {
        id: vuln.id, aliases: vuln.aliases || [],
        summary: vuln.summary || (vuln.details || "").slice(0, 160),
        severity, published: (vuln.published || "").slice(0, 10) || null,
        fixedVersions: fixedVersions(vuln),
      };
    });
    advisories.sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity)
      || String(a.id).localeCompare(String(b.id)));
    const worst = SEVERITY_ORDER.find((level) => bySeverity[level]) || null;
    return { vulnerabilityCount: vulns.length, worstSeverity: worst, bySeverity, advisories };
  }
  function normaliseAdvisoryId(raw) {
    const text = raw.trim();
    const cut = text.indexOf("-");
    if (cut < 0) return text.toUpperCase();
    const prefix = text.slice(0, cut).toUpperCase();
    const rest = text.slice(cut + 1);
    return `${prefix}-${prefix === "GHSA" ? rest : rest.toUpperCase()}`;
  }

  // ---- the agents ----------------------------------------------------------
  // Each handler returns [payload, sources]; delegation goes through `peer`,
  // which records the nested hop exactly as the Python agents do.
  const HANDLERS = {
    "registry-agent": {
      async package_metadata(args) {
        const payload = await fetchPackage(requireArg(args, "package"));
        const info = payload.info;
        let licence = info.license_expression || info.license || null;
        if (typeof licence === "string" && licence.length > 120) licence = null;
        return [{
          package: info.name, latestVersion: info.version, summary: info.summary || null,
          license: licence, requiresPython: info.requires_python || null, yanked: !!info.yanked,
          releaseCount: Object.keys(payload.releases || {}).length,
          repository: extractRepo(info), projectUrls: info.project_urls || {},
        }, [`https://pypi.org/pypi/${info.name}/json`]];
      },
      async release_history(args) {
        const payload = await fetchPackage(requireArg(args, "package"));
        const rows = datedReleases(payload);
        const limit = Number(args.limit || 8);
        const latest = rows.length ? rows[rows.length - 1].released : null;
        return [{
          package: payload.info.name,
          releaseCount: Object.keys(payload.releases || {}).length,
          datedReleaseCount: rows.length,
          firstRelease: rows.length ? rows[0].released.slice(0, 10) : null,
          latestRelease: latest ? latest.slice(0, 10) : null,
          daysSinceLatestRelease: daysSince(latest),
          medianDaysBetweenLast10: median(rows.slice(-10).map((r) => Date.parse(r.released))),
          yankedCount: rows.filter((r) => r.yanked).length,
          recent: rows.slice(-limit).reverse().map((r) => ({ version: r.version, released: r.released.slice(0, 10), yanked: r.yanked })),
        }, [`https://pypi.org/pypi/${payload.info.name}/json`]];
      },
      async resolve_repository(args) {
        const payload = await fetchPackage(requireArg(args, "package"));
        const repo = extractRepo(payload.info);
        if (!repo) throw new Error(`'${payload.info.name}' publishes no GitHub repository URL on PyPI`);
        return [{ package: payload.info.name, ...repo }, [`https://pypi.org/pypi/${payload.info.name}/json`]];
      },
    },
    "advisory-agent": {
      async vulnerability_scan(args, peer) {
        const name = requireArg(args, "package");
        let version = typeof args.version === "string" ? args.version.trim() : "";
        let resolvedVia = "caller";
        if (!version || ["latest", "current", "newest"].includes(version.toLowerCase())) {
          const meta = await peer("registry-agent", "package_metadata", { package: name });
          version = meta.latestVersion;
          resolvedVia = "registry-agent.package_metadata";
        }
        const payload = await postJson("https://api.osv.dev/v1/query", {
          package: { name, ecosystem: "PyPI" }, version,
        });
        const vulns = payload.vulns || [];
        return [{
          package: name, version, versionResolvedVia: resolvedVia, safe: vulns.length === 0,
          ...summariseVulns(vulns),
        }, ["https://api.osv.dev/v1/query"]];
      },
      async advisory_detail(args) {
        const id = normaliseAdvisoryId(requireArg(args, "advisoryId"));
        const payload = await getJson(`https://api.osv.dev/v1/vulns/${encodeURIComponent(id)}`, { allow404: true });
        if (!payload) throw new Error(`OSV has no advisory with id '${id}'`);
        const affected = [...new Set((payload.affected || []).map((a) => (a.package || {}).name).filter(Boolean))].sort();
        return [{
          id: payload.id, aliases: payload.aliases || [], summary: payload.summary || null,
          details: (payload.details || "").slice(0, 1200), severity: severityOf(payload),
          published: (payload.published || "").slice(0, 10) || null,
          modified: (payload.modified || "").slice(0, 10) || null,
          affectedPackages: affected, fixedVersions: fixedVersions(payload),
          references: (payload.references || []).map((r) => r.url).slice(0, 6),
        }, [`https://api.osv.dev/v1/vulns/${id}`]];
      },
    },
    "repo-agent": {
      async repo_health(args, peer) {
        const { owner, repo, how } = await resolveTarget(args, peer);
        const payload = await getJson(`https://api.github.com/repos/${owner}/${repo}`, { allow404: true });
        if (!payload) throw new Error(`GitHub has no repository ${owner}/${repo}`);
        const created = Date.parse(payload.created_at);
        return [{
          owner, repo, repoUrl: `https://github.com/${owner}/${repo}`, repositoryResolvedVia: how,
          stars: payload.stargazers_count, forks: payload.forks_count,
          openIssues: payload.open_issues_count, watchers: payload.subscribers_count,
          archived: !!payload.archived, license: (payload.license || {}).spdx_id || null,
          defaultBranch: payload.default_branch,
          lastPush: (payload.pushed_at || "").slice(0, 10) || null,
          daysSinceLastPush: daysSince(payload.pushed_at),
          ageYears: created ? Math.round(((Date.now() - created) / 31557600000) * 10) / 10 : null,
          description: payload.description,
        }, [`https://api.github.com/repos/${owner}/${repo}`]];
      },
      async recent_activity(args, peer) {
        const { owner, repo, how } = await resolveTarget(args, peer);
        const windowDays = Number(args.windowDays || 90);
        const since = new Date(Date.now() - windowDays * 86400000).toISOString().slice(0, 10) + "T00:00:00Z";
        const url = `https://api.github.com/repos/${owner}/${repo}/commits?per_page=100&since=${since}`;
        const commits = (await getJson(url, { allow404: true })) || [];
        const authors = new Set(commits.map((c) => (c.author || {}).login || ((c.commit || {}).author || {}).name).filter(Boolean));
        const newest = commits.map((c) => ((c.commit || {}).committer || {}).date || "").sort().pop() || "";
        return [{
          owner, repo, repositoryResolvedVia: how, windowDays,
          commitsInWindow: commits.length, commitsTruncatedAt100: commits.length === 100,
          distinctAuthors: authors.size, newestCommit: newest.slice(0, 10) || null,
          daysSinceNewestCommit: daysSince(newest || null),
        }, [url]];
      },
    },
  };

  async function resolveTarget(args, peer) {
    if (typeof args.owner === "string" && args.owner && typeof args.repo === "string" && args.repo) {
      return { owner: args.owner, repo: args.repo, how: "caller" };
    }
    if (typeof args.package !== "string" || !args.package.trim()) {
      throw new Error("provide either {'owner', 'repo'} or {'package'}");
    }
    const resolved = await peer("registry-agent", "resolve_repository", { package: args.package.trim() });
    return { owner: resolved.owner, repo: resolved.repo, how: "registry-agent.resolve_repository" };
  }

  // ---- the A2A envelope ----------------------------------------------------
  async function invoke(agentName, skill, args, trace, caller, depth) {
    const handler = (HANDLERS[agentName] || {})[skill];
    const started = performance.now();
    const hop = {
      caller, callee: agentName, skill, args, state: FAILED,
      elapsedMs: 0, taskId: uuid(), result: null, error: null, depth,
    };
    if (!handler) {
      hop.error = `${agentName} declares no skill '${skill}'`;
      hop.elapsedMs = 0;
      trace.push(hop);
      return null;
    }
    // A peer call made on this agent's behalf lands one level deeper, which is
    // how the Python build reports delegations in its artifact metadata.
    const peer = async (name, peerSkill, peerArgs) => {
      const result = await invoke(name, peerSkill, peerArgs, trace, agentName, depth + 1);
      if (result === null) throw new Error(`${name}.${peerSkill} failed`);
      return result;
    };
    const parentIndex = trace.length;
    trace.push(hop);
    try {
      const [payload] = await handler(args, peer);
      hop.state = COMPLETED;
      hop.result = payload;
    } catch (err) {
      hop.error = `${err.name}: ${err.message}`;
    }
    hop.elapsedMs = Math.round((performance.now() - started) * 10) / 10;
    trace[parentIndex] = hop;
    return hop.state === COMPLETED ? hop.result : null;
  }

  // ---- routing: the keyword baseline, ported --------------------------------
  const ADVISORY_ID_RE = /\b(?:GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}|CVE-\d{4}-\d{4,7}|PYSEC-\d{4}-\d+)\b/gi;
  const PINNED_RE = /\b([A-Za-z][A-Za-z0-9._-]{1,40})\s*(?:==|@|\s)\s*v?(\d+\.\d+(?:\.\d+)?)\b/;
  const QUOTED_RE = /['"`]([A-Za-z][A-Za-z0-9._-]{1,40})['"`]/g;
  const TOKEN_RE = /\b[A-Za-z][A-Za-z0-9._-]{2,40}\b/g;
  const KEYWORDS = S.keywords;

  async function resolvesAsPackage(name) {
    try { await fetchPackage(name); return true; } catch { return false; }
  }

  async function extractSubject(question) {
    const pinned = PINNED_RE.exec(question);
    if (pinned && !STOPWORDS.has(pinned[1].toLowerCase())) return [pinned[1].toLowerCase(), pinned[2]];
    QUOTED_RE.lastIndex = 0;
    let quoted;
    while ((quoted = QUOTED_RE.exec(question))) {
      const candidate = quoted[1].toLowerCase();
      if (!STOPWORDS.has(candidate)) return [candidate, null];
    }
    const seen = [];
    for (const token of question.match(TOKEN_RE) || []) {
      const lowered = token.toLowerCase();
      if (STOPWORDS.has(lowered) || seen.includes(lowered)) continue;
      seen.push(lowered);
    }
    for (const candidate of seen.slice(0, 4)) {
      if (await resolvesAsPackage(candidate)) return [candidate, null];
    }
    return [null, null];
  }

  async function rulePlan(question) {
    const lowered = question.toLowerCase();
    const owner = {};
    for (const card of CARDS) for (const skill of card.skills) owner[skill.id] = card.name;

    let wanted = Object.entries(KEYWORDS)
      .filter(([id, words]) => owner[id] && words.some((w) => lowered.includes(w)))
      .map(([id]) => id);
    ADVISORY_ID_RE.lastIndex = 0;
    const ids = question.match(ADVISORY_ID_RE) || [];
    if (ids.length) wanted = ["advisory_detail", ...wanted.filter((s) => s !== "advisory_detail")];
    else wanted = wanted.filter((s) => s !== "advisory_detail");
    if (!wanted.length) wanted = ["package_metadata"];

    const [pkg, version] = await extractSubject(question);
    const delegations = [];
    for (const skill of wanted.slice(0, 6)) {
      if (skill === "advisory_detail") {
        delegations.push({ agent: owner[skill], skill, args: { advisoryId: ids[0].toUpperCase() } });
      } else if (pkg) {
        const args = { package: pkg };
        if (version && skill === "vulnerability_scan") args.version = version;
        delegations.push({ agent: owner[skill], skill, args });
      }
    }
    return { router: "rules", reasoning: `keyword match -> ${delegations.map((d) => d.skill)}`, delegations, rejected: [] };
  }

  // ---- answering -----------------------------------------------------------
  // A line-by-line port of parley/orchestrator/summarize.py, so the deployed
  // demo and a local run without an API key produce the same prose.
  const plural = (n, one, many) => (n === 1 ? one : many || one + "s");

  function summarizeFact(key, value) {
    if (!value || typeof value !== "object") return null;
    const skill = key.split(".").pop();

    if (skill === "package_metadata") {
      const bits = [`${value.package} ${value.latestVersion} is the current release on PyPI`];
      if (value.license) bits.push(`published under ${value.license}`);
      if (value.requiresPython) bits.push(`requiring Python ${value.requiresPython}`);
      return bits.join(", ") + ".";
    }
    if (skill === "release_history") {
      let text = `${value.package} has ${value.releaseCount} ${plural(value.releaseCount, "release")} on PyPI, `
        + `the most recent on ${value.latestRelease}`;
      if (value.daysSinceLatestRelease !== null && value.daysSinceLatestRelease !== undefined) {
        text += ` (${value.daysSinceLatestRelease} ${plural(value.daysSinceLatestRelease, "day")} ago)`;
      }
      if (value.medianDaysBetweenLast10 !== null && value.medianDaysBetweenLast10 !== undefined) {
        text += `; the median gap between the last ten releases is ${value.medianDaysBetweenLast10} days`;
      }
      return text + ".";
    }
    if (skill === "resolve_repository") return `${value.package} is developed at ${value.repoUrl}.`;
    if (skill === "vulnerability_scan") {
      const name = `${value.package} ${value.version}`;
      if (value.safe) return `OSV lists no known advisories affecting ${name}.`;
      let text = `OSV lists ${value.vulnerabilityCount} known `
        + `${plural(value.vulnerabilityCount, "advisory", "advisories")} affecting ${name}, `
        + `the worst rated ${value.worstSeverity}`;
      const worst = (value.advisories || [])[0];
      if (worst) {
        const fixes = worst.fixedVersions || [];
        text += ` (${worst.id}` + (fixes.length ? `, fixed in ${fixes[0]})` : ")");
      }
      return text + ".";
    }
    if (skill === "advisory_detail") {
      let text = `${value.id} is rated ${value.severity}`;
      if (value.summary) text += `: ${value.summary.replace(/\.$/, "")}`;
      const fixes = value.fixedVersions || [];
      if (fixes.length) text += `; fixed in ${fixes.join(", ")}`;
      return text + ".";
    }
    if (skill === "repo_health") {
      let text = `${value.owner}/${value.repo} has ${value.stars} stars and ${value.openIssues} open issues, `
        + `with its last push on ${value.lastPush}`;
      if (value.daysSinceLastPush !== null && value.daysSinceLastPush !== undefined) {
        text += ` (${value.daysSinceLastPush} ${plural(value.daysSinceLastPush, "day")} ago)`;
      }
      if (value.archived) text += ", and the repository is archived";
      return text + ".";
    }
    if (skill === "recent_activity") {
      let text = `${value.owner}/${value.repo} saw ${value.commitsInWindow} ${plural(value.commitsInWindow, "commit")} `
        + `from ${value.distinctAuthors} distinct ${plural(value.distinctAuthors, "author")} `
        + `in the last ${value.windowDays} days`;
      if (value.newestCommit) text += `, the newest on ${value.newestCommit}`;
      return text + ".";
    }
    return null;
  }

  function grade(answer, allowed) {
    const marker = "[a-z0-9-]+\\.[a-z0-9_]+";
    const re = new RegExp(`\\[(${marker}(?:\\s*,\\s*${marker})*)\\]`, "g");
    const sentences = answer.trim().split(/(?<=[.!?])\s+(?=[A-Z0-9-])|\n+/).filter(Boolean);
    let cited = 0, citations = 0;
    const invalid = [], used = new Set();
    for (const sentence of sentences) {
      const found = [];
      let match;
      re.lastIndex = 0;
      while ((match = re.exec(sentence))) found.push(...match[1].split(",").map((m) => m.trim()));
      citations += found.length;
      if (found.length) cited += 1;
      for (const m of found) {
        if (allowed.includes(m)) used.add(m);
        else if (!invalid.includes(m)) invalid.push(m);
      }
    }
    return {
      sentences: sentences.length, citedSentences: cited,
      citationCoverage: sentences.length ? Math.round((cited / sentences.length) * 1000) / 1000 : 0,
      citations, invalidCitations: invalid,
      unusedFacts: allowed.filter((k) => !used.has(k)).sort(),
    };
  }

  function factsOf(trace) {
    const facts = {};
    for (const hop of trace) if (hop.state === COMPLETED) facts[`${hop.callee}.${hop.skill}`] = hop.result;
    return facts;
  }

  function summarize(trace) {
    const facts = factsOf(trace);
    const keys = Object.keys(facts);
    if (!keys.length) {
      const failures = trace.map((h) => `${h.callee}.${h.skill}: ${h.error}`).join("; ");
      return `No agent on the network returned a usable result for this question (${failures || "no agents were called"}).`;
    }
    const sentences = [];
    for (const key of keys) {
      const rendered = summarizeFact(key, facts[key]);
      if (rendered) sentences.push(`${rendered} [${key}]`);
    }
    return sentences.length ? sentences.join(" ") : "The agents answered, but none of their results fit a summary template.";
  }

  async function answer(question, router) {
    const started = performance.now();
    const recorded = S.transcripts.find((t) => t.question === question);
    if (router === "recorded" && recorded) {
      return { ...recorded, recorded: true };
    }
    const plan = await rulePlan(question);
    const trace = [];
    const partial = [];
    for (const delegation of plan.delegations) {
      try {
        await invoke(delegation.agent, delegation.skill, delegation.args, trace, "orchestrator", 0);
      } catch (err) {
        partial.push(`${delegation.agent}.${delegation.skill}: ${err.message}`);
      }
    }
    const text = summarize(trace);
    return {
      question, answer: text, plan,
      trace: { contextId: uuid(), hops: trace },
      grading: grade(text, Object.keys(factsOf(trace))),
      elapsedMs: Math.round((performance.now() - started) * 10) / 10,
      llmCalls: 0, error: null, partial,
    };
  }

  // ---- the fetch override --------------------------------------------------
  const json = (payload, status = 200) =>
    new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });

  const realFetch = window.fetch.bind(window);
  window.fetch = async (input, init) => {
    const url = typeof input === "string" ? input : input.url;
    const path = url.startsWith("http") ? new URL(url).pathname + new URL(url).search : url;

    if (path.startsWith("/api/agents")) {
      return json({
        orchestrator: ORCH_CARD, agents: CARDS,
        routers: ["recorded", "rules"], defaultRouter: "rules",
        llm: null,
      });
    }
    if (path.startsWith("/api/samples")) return json({ samples: S.samples });
    if (path.startsWith("/api/sample")) {
      const index = Number(new URLSearchParams(path.split("?")[1] || "").get("index") || 0);
      return json(S.samples[index % S.samples.length]);
    }
    if (path.includes("/agents/orchestrator/message:send")) {
      const body = JSON.parse(init.body);
      const args = (body.message.parts.find((p) => p.data !== undefined) || {}).data || {};
      if (!args.question) {
        return json({ code: 3, status: "INVALID_ARGUMENT", message: "argument 'question' is required" }, 400);
      }
      const result = await answer(args.question, args.router || "rules");
      return json({
        task: {
          id: uuid(), contextId: body.message.contextId || null,
          status: { state: COMPLETED, timestamp: new Date().toISOString() },
          artifacts: [{
            artifactId: uuid(), name: "supply_chain_review",
            parts: [{ data: result, mediaType: "application/json" }],
          }],
        },
      });
    }
    if (path.includes("/.well-known/agent-card.json")) {
      const name = path.split("/agents/")[1].split("/")[0];
      const card = CARDS.find((c) => c.name.startsWith(name)) || ORCH_CARD;
      return json(card);
    }
    return realFetch(input, init);
  };
})();

</script>
<script>
(() => {
  "use strict";
  const $ = (id) => document.getElementById(id);
  const params = new URLSearchParams(location.search);
  const DEMO = params.get("demo") === "1";
  const ORCH = "/agents/orchestrator";
  const NODES = {};      // agent name -> svg group
  const SKILL_EL = {};   // "agent.skill" -> chip element
  let samples = [], sampleIndex = Number(params.get("sample") || 0), agentNames = [];

  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));

  // ---- topology ------------------------------------------------------------
  const SVG = "http://www.w3.org/2000/svg";
  function el(name, attrs, parent) {
    const node = document.createElementNS(SVG, name);
    for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);
    if (parent) parent.appendChild(node);
    return node;
  }

  function drawTopology(names) {
    const svg = $("topology");
    svg.textContent = "";
    const edges = el("g", {}, svg);
    const boxW = 108, boxH = 25, gap = 40;
    const left = { x: 6, y: 6 + gap };
    const right = names.map((_, i) => ({ x: 140, y: 6 + i * gap }));

    // Orchestrator fans out to every agent it discovered.
    names.forEach((name, i) => {
      const from = { x: left.x + boxW, y: left.y + boxH / 2 };
      const to = { x: right[i].x, y: right[i].y + boxH / 2 };
      const mid = (from.x + to.x) / 2;
      el("path", {
        class: "edge", "data-edge": `orchestrator|${name}`,
        d: `M${from.x},${from.y} C${mid},${from.y} ${mid},${to.y} ${to.x},${to.y}`,
      }, edges);
    });

    // Peer edges route around the right-hand side so they never overlap the
    // orchestrator's fan-out: an agent asking a peer is a different kind of
    // call and should look like one.
    const registry = names.indexOf("registry-agent");
    if (registry >= 0) {
      names.forEach((name, i) => {
        if (i === registry) return;
        const lane = 258 + (i - registry) * 8;
        const y1 = right[i].y + boxH / 2;
        const y2 = right[registry].y + boxH / 2;
        el("path", {
          class: "edge peer", "data-edge": `${name}|registry-agent`,
          d: `M${right[i].x + boxW},${y1} H${lane} V${y2} H${right[registry].x + boxW}`,
        }, edges);
      });
    }

    const box = (x, y, label, key) => {
      const g = el("g", { class: "node", "data-node": key }, svg);
      el("rect", { x, y, width: boxW, height: boxH, rx: 7 }, g);
      const t = el("text", { x: x + boxW / 2, y: y + boxH / 2 + 3.4, "text-anchor": "middle" }, g);
      t.textContent = label;
      NODES[key] = g;
      return g;
    };
    box(left.x, left.y, "orchestrator", "orchestrator");
    names.forEach((name, i) => box(right[i].x, right[i].y, name, name));
    svg.setAttribute("viewBox", `0 0 300 ${6 + names.length * gap + 4}`);
  }

  function lightUp(hop) {
    const node = NODES[hop.callee];
    if (node) node.classList.add("lit");
    const caller = NODES[hop.caller];
    if (caller) caller.classList.add("lit");
    const edge = document.querySelector(`[data-edge="${CSS.escape(hop.caller)}|${CSS.escape(hop.callee)}"]`);
    if (edge) edge.classList.add("lit");
    const chip = SKILL_EL[`${hop.callee}.${hop.skill}`];
    if (chip) chip.classList.add("lit");
  }

  function resetHighlights() {
    document.querySelectorAll(".node.lit, .edge.lit, .skill.lit").forEach((n) => n.classList.remove("lit"));
  }

  // ---- discovery -----------------------------------------------------------
  async function discover() {
    const info = await (await fetch("/api/agents")).json();
    agentNames = info.agents.map((c) => c.name);
    drawTopology(agentNames);

    $("agents").innerHTML = info.agents.map((card) => `
      <div class="agent">
        <div class="agent-name">${esc(card.name)}</div>
        <div class="agent-desc">${esc(card.description)}</div>
        <div class="skills">${card.skills.map((s) =>
          `<span class="skill" data-key="${esc(card.name)}.${esc(s.id)}" title="${esc(s.description)}">${esc(s.id)}</span>`
        ).join("")}</div>
      </div>`).join("");
    document.querySelectorAll(".skill").forEach((chip) => { SKILL_EL[chip.dataset.key] = chip; });

    const select = $("router");
    select.innerHTML = info.routers.map((r) =>
      `<option value="${esc(r)}"${r === info.defaultRouter ? " selected" : ""}>${esc(r)}</option>`).join("");
    if (params.get("router")) select.value = params.get("router");
    $("model-pill").textContent = info.llm ? `router model: ${info.llm}` : "no model key — keyword router only";

    const s = await (await fetch("/api/samples")).json();
    samples = s.samples;
    if (!$("question").value) $("question").value = samples[sampleIndex % samples.length].question;
  }

  // ---- asking --------------------------------------------------------------
  function envelope(question, router) {
    return {
      message: {
        messageId: crypto.randomUUID(),
        role: "ROLE_USER",
        parts: [{ data: { question, router }, mediaType: "application/json" }],
        metadata: { skill: "supply_chain_review" },
      },
      configuration: { acceptedOutputModes: ["application/json"], returnImmediately: false },
    };
  }

  function renderAnswer(text) {
    const marker = "[a-z0-9-]+\\.[a-z0-9_]+";
    const re = new RegExp(`\\[(${marker}(?:\\s*,\\s*${marker})*)\\]`, "g");
    return esc(text).replace(re, (_, group) =>
      group.split(",").map((m) => `<span class="cite">${m.trim()}</span>`).join(""));
  }

  function metric(value, label) {
    return `<div class="metric"><b>${esc(value)}</b><span>${esc(label)}</span></div>`;
  }

  async function playTrace(hops) {
    const list = $("trace");
    list.innerHTML = "";
    for (const hop of hops) {
      lightUp(hop);
      const ok = hop.state === "TASK_STATE_COMPLETED";
      const body = hop.error ? hop.error : JSON.stringify(hop.result, null, 2);
      const li = document.createElement("li");
      li.className = `depth-${hop.depth || 0}`;
      li.innerHTML = `
        <div class="hop-head">
          <span>${esc(hop.caller)}</span><span class="arrow">→</span>
          <span class="callee">${esc(hop.callee)}</span>
          <span class="skill">${esc(hop.skill)}</span>
          <span class="ms">${esc(hop.elapsedMs)} ms</span>
          <span class="state${ok ? "" : " fail"}">${esc(hop.state.replace("TASK_STATE_", ""))}</span>
        </div>
        <pre class="hidden">${esc(body)}</pre>`;
      const pre = li.querySelector("pre");
      li.querySelector(".hop-head").addEventListener("click", () => pre.classList.toggle("hidden"));
      list.appendChild(li);
      await new Promise((r) => setTimeout(r, 210));
    }
    if (hops.length) list.querySelector("pre").classList.remove("hidden");
  }

  async function ask(question) {
    const router = $("router").value;
    resetHighlights();
    $("send").disabled = true;
    $("status").textContent = "discovering, routing, delegating…";
    $("answer-card").classList.add("hidden");
    $("trace-card").classList.add("hidden");

    const body = envelope(question, router);
    $("wire").textContent = JSON.stringify(body, null, 2);
    try {
      const response = await fetch(`${ORCH}/message:send`, {
        method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
      });
      const payload = await response.json();
      if (!response.ok) throw new Error(payload.message || `HTTP ${response.status}`);
      const task = payload.task;
      const result = task.artifacts[0].parts.find((p) => p.data !== undefined).data;

      $("trace-card").classList.remove("hidden");
      $("answer-card").classList.remove("hidden");
      $("answer").innerHTML = renderAnswer(result.answer);
      const g = result.grading, hops = result.trace.hops;
      $("metrics").innerHTML = [
        metric(hops.length, "A2A hops"),
        metric(hops.filter((h) => (h.depth || 0) > 0).length, "peer-to-peer"),
        metric(`${Math.round(g.citationCoverage * 100)}%`, "cited sentences"),
        metric(g.invalidCitations.length, "invalid citations"),
        metric(`${(result.elapsedMs / 1000).toFixed(1)}s`, "end to end"),
      ].join("");
      if (result.partial.length) {
        $("metrics").insertAdjacentHTML("beforeend",
          `<div class="metric" style="flex:1 1 100%"><span class="error">${esc(result.partial.join(" · "))}</span></div>`);
      }
      await playTrace(hops);
      $("status").textContent = "";
    } catch (err) {
      $("status").innerHTML = `<span class="error">${esc(err.message)}</span>`;
    } finally {
      $("send").disabled = false;
    }
  }

  $("ask").addEventListener("submit", (event) => {
    event.preventDefault();
    const question = $("question").value.trim();
    if (question) ask(question);
  });

  $("sample").addEventListener("click", () => {
    if (!samples.length) return;
    sampleIndex = (sampleIndex + 1) % samples.length;
    $("question").value = samples[sampleIndex].question;
    ask(samples[sampleIndex].question);
  });

  discover().then(() => {
    // ?demo=1 auto-runs a sample so a headless capture lands on a populated page.
    if (DEMO) ask($("question").value.trim());
  });
})();
</script>
</body>
</html>