@allansantos-dev/smart-tool 0.9.15 → 0.9.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/setup_ui.py CHANGED
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env python3
2
- """Tela de modelos do Smart Tool, servida pelo daemon em `GET /setup`.
2
+ """Tela de configuração do Smart Tool, servida pelo daemon em `GET /setup`.
3
3
 
4
- Esta tela aponta o gateway de modelos OpenAI-compatível (URL base + API key opcional),
5
- escolhe modelos, controla o autostart e recebe chaves opcionais de Tavily/Firecrawl,
6
- protegidas por DPAPI no config próprio do Smart Tool.
4
+ Uma seção por vez, escolhida na barra lateral: Overview (checklist do que precisa de
5
+ atenção, problemas primeiro), Agents (MCP, hook — inclusive desatualizado, com o que a
6
+ atualização muda — e controle de navegador), Models (gateway, modelos, modelos locais),
7
+ Web search (provedores e chaves protegidas por DPAPI), Agent rules, Redirects (métricas e
8
+ padrões de bloqueio), Setup audit e Startup (autostart).
7
9
 
8
10
  `SETUP_TOKEN` é gerado uma vez por processo (nunca persistido em disco) e embutido no
9
- HTML de `GET /setup`; as rotas que escrevem estado (`POST /setup/models`, `POST /setup/gateway`,
10
- `POST /setup/providers` e `POST /setup/autostart`) exigem
11
+ HTML de `GET /setup`; toda rota `POST /setup/...` que escreve estado exige
11
12
  esse token de volta no header `X-Setup-Token`. Não é uma
12
13
  trava contra quem já tem acesso de leitura à máquina (que também leria o token de
13
14
  `GET /setup`) — só impede escrever config sem nunca ter carregado a página.
@@ -71,6 +72,7 @@ def status_payload():
71
72
  models = model_defaults.ensure_recommended_models(gateway["status"] == "ready")
72
73
  cfg = config.load_config()
73
74
  return {
75
+ "version": version.VERSION,
74
76
  "gateway": gateway,
75
77
  "models_status": models["status"],
76
78
  "models_message": models["message"],
@@ -180,7 +182,8 @@ def handle_integration_get():
180
182
  for key, info in AGENT_CLIENTS.items():
181
183
  spec, state = client_hooks.CLIENTS[key], client_hooks.status(info)
182
184
  clients.append({"client": key, "label": spec["label"], "mcp_url": registered.get(key), "hook": state["installed"],
183
- "hook_error": state["error"], "file": spec["files"][0], "docs": spec["docs"],
185
+ "hook_state": state["state"], "hook_changes": state["changes"], "hook_error": state["error"],
186
+ "after_install": spec.get("after_install"), "file": spec["files"][0], "docs": spec["docs"],
184
187
  "register_command": " ".join(endpoint_sync.register_command(key, setup_origin())),
185
188
  "browser_control": browser.get(key), "browser_control_error": browser_error})
186
189
  try:
@@ -258,11 +261,21 @@ def handle_integration_save(body):
258
261
  def handle_audit(body):
259
262
  """Setup audit panel: `index` lists the registered projects with their last audit summary; `report` returns the
260
263
  last stored report of one of them; `run` audits it now (MCP servers contacted unless probe is false). Only
261
- registered project folders are accepted."""
264
+ registered project folders are accepted. The opt-in session-start report in Claude Code: `hook_state`,
265
+ `hook_preview` (the exact entry and a token), `hook_install` (with that token, after a backup) and `hook_remove`
266
+ (only Smart Tool's entry, after a backup)."""
262
267
  if not isinstance(body, dict):
263
268
  raise SetupError("Invalid request.")
264
269
  roots = sorted({p["root"] for p in project_store.all_projects() if p.get("root")}, key=str.casefold)
265
270
  try:
271
+ if body.get("action") == "hook_state":
272
+ return {"state": client_hooks.audit_state(), "file": client_hooks.CLIENTS["claude"]["files"][0]}
273
+ if body.get("action") == "hook_preview":
274
+ return client_hooks.audit_preview()
275
+ if body.get("action") == "hook_install":
276
+ return client_hooks.audit_install(body.get("token"), True)
277
+ if body.get("action") == "hook_remove":
278
+ return client_hooks.audit_remove()
266
279
  if body.get("action") == "index":
267
280
  stored = setup_audit.index()
268
281
  found = {root: stored[setup_audit.index_key(root)] for root in roots if setup_audit.index_key(root) in stored}
@@ -411,181 +424,237 @@ _PAGE_TEMPLATE = """<!doctype html>
411
424
  <head>
412
425
  <meta charset="utf-8">
413
426
  <meta name="viewport" content="width=device-width, initial-scale=1">
414
- <title>Smart Tool — Settings</title>
427
+ <title>Settings · Smart Tool</title>
415
428
  <style>
416
- :root {
417
- --bg: #e8ece7; --surface: #f6f8f4; --line: #cfd6cf; --ink: #1c2621; --muted: #5d6b63;
418
- --signal: #2450f0; --on-signal: #ffffff; --ok: #2d8a55; --bad: #c2381f; --warn: #a87400; --idle: #9aa69f;
419
- --display: "Bahnschrift", "DIN Alternate", "Segoe UI", sans-serif;
420
- --body: "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif;
421
- --mono: "Cascadia Mono", "Cascadia Code", Consolas, monospace;
422
- }
429
+ :root { color-scheme: light dark;
430
+ --bg: #f6f7f9; --surface: #ffffff; --line: #dde1e6; --ink: #1b2430; --muted: #5b6472; --soft: #eef1f5;
431
+ --accent: #2f6fed; --on-accent: #ffffff; --selected: #eaf1ff;
432
+ --ok: #18723c; --ok-bg: #e6f4ea; --warn: #805300; --warn-bg: #fdf3dc; --bad: #b52c2c; --bad-bg: #fbe9e9; --idle: #5b6472; --idle-bg: #eef1f5;
433
+ --body: "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif; --mono: "Cascadia Mono", Consolas, monospace; }
423
434
  @media (prefers-color-scheme: dark) {
424
- :root { --bg: #121815; --surface: #1a221e; --line: #2c3731; --ink: #e3e9e4; --muted: #93a199;
425
- --signal: #7d98ff; --on-signal: #0c1433; --ok: #59c786; --bad: #ff7a61; --warn: #e2b24a; --idle: #4b5850; }
435
+ :root { --bg: #14171c; --surface: #1c2027; --line: #39414e; --ink: #e6e9ee; --muted: #a6afbb; --soft: #232831;
436
+ --accent: #91baff; --on-accent: #14171c; --selected: #263751;
437
+ --ok: #68dc93; --ok-bg: #163322; --warn: #e0b565; --warn-bg: #3a2e14; --bad: #ff9696; --bad-bg: #3d1d1d; --idle: #a6afbb; --idle-bg: #262b33; }
426
438
  }
427
439
  * { box-sizing: border-box; }
428
- html { scroll-behavior: smooth; }
429
- body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.5 var(--body); }
430
- a { color: var(--signal); }
431
- main { max-width: 1080px; margin: 0 auto; padding: 36px 28px 72px; }
432
-
433
- .masthead { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
434
- .masthead h1 { display: inline; font: 700 2.1rem/1 var(--display); font-stretch: 87.5%; letter-spacing: -.01em; margin: 0; }
435
- .masthead .where { font: .8rem var(--mono); color: var(--muted); margin-left: 12px; }
436
- .masthead nav a { font: 600 .9rem var(--display); text-decoration: none; letter-spacing: .02em; }
437
- .masthead nav a:hover { text-decoration: underline; }
438
-
439
- .path { list-style: none; margin: 28px 0 36px; padding: 26px 28px 22px; display: grid;
440
- grid-template-columns: repeat(4, 1fr); background: var(--surface); border: 1px solid var(--line); border-radius: 14px; }
441
- .station { position: relative; }
442
- .station a { display: block; color: inherit; text-decoration: none; padding-right: 18px; border-radius: 8px; }
443
- .station a:focus-visible { outline: 2px solid var(--signal); outline-offset: 6px; }
444
- .node { display: flex; align-items: center; height: 22px; }
445
- .dot { width: 18px; height: 18px; border-radius: 50%; border: 3px solid var(--idle); background: var(--surface); flex: none; position: relative; z-index: 1; transition: border-color .3s, background .3s; }
446
- .wire { flex: 1; height: 3px; margin-left: -1px; background: var(--line); position: relative; overflow: hidden; }
447
- .wire::after { content: ""; position: absolute; inset: 0; background: var(--signal); transform: scaleX(0); transform-origin: left; }
448
- .station:last-child .wire { display: none; }
449
- .station[data-state="ok"] .dot { border-color: var(--ok); background: var(--ok); }
450
- .station[data-state="bad"] .dot { border-color: var(--bad); }
451
- .station[data-state="warn"] .dot { border-color: var(--warn); }
452
- .station[data-live="1"] .wire::after { transform: scaleX(1); transition: transform .45s cubic-bezier(.6,0,.2,1) var(--delay, 0s); }
453
- .station[data-break="1"] .wire { background: repeating-linear-gradient(90deg, var(--bad) 0 6px, transparent 6px 11px); }
454
- .station h2 { font: 600 1.05rem/1.2 var(--display); letter-spacing: .03em; margin: 14px 0 3px; }
455
- .station .detail { font: .78rem/1.35 var(--mono); color: var(--muted); overflow-wrap: anywhere; }
456
- .station .verdict { font-size: .84rem; margin-top: 6px; }
457
- .station[data-state="bad"] .verdict { color: var(--bad); }
458
- .station[data-state="warn"] .verdict { color: var(--warn); }
459
-
460
- .panels { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); gap: 22px; align-items: start; }
461
- .col { display: grid; grid-template-columns: minmax(0, 1fr); gap: 22px; }
462
- section { background: var(--surface); border: 1px solid var(--line); border-radius: 14px; padding: 22px 24px 24px; scroll-margin-top: 20px; }
463
- section > h2 { font: 600 1.2rem/1.2 var(--display); letter-spacing: .02em; margin: 0 0 4px; }
464
- section > .lede { color: var(--muted); font-size: .87rem; margin: 0 0 18px; }
465
- fieldset { border: 0; border-top: 1px solid var(--line); margin: 18px 0 0; padding: 16px 0 0; min-width: 0; }
466
- legend { font: 600 .78rem var(--display); letter-spacing: .12em; text-transform: uppercase; color: var(--muted); padding: 0 10px 0 0; }
467
- fieldset .lede { color: var(--muted); font-size: .82rem; margin: 2px 0 12px; }
468
- .field { margin-bottom: 12px; }
469
- .pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; }
470
- label { display: block; font-size: .8rem; font-weight: 600; margin-bottom: 4px; }
471
- .hint { display: block; font-size: .76rem; color: var(--muted); margin-top: 3px; }
472
- select, input:not([type]), input[type=text], input[type=url], input[type=number], input[type=password] {
473
- width: 100%; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line);
474
- background-color: var(--bg); color: var(--ink); font: .84rem var(--mono); min-width: 0; max-width: 100%; }
475
- select, input[list] { appearance: none; padding-right: 34px; cursor: pointer;
476
- background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%);
477
- background-position: calc(100% - 17px) 52%, calc(100% - 12px) 52%; background-size: 5px 5px; background-repeat: no-repeat; }
478
- input[list] { cursor: text; }
479
- input[list]::-webkit-calendar-picker-indicator { opacity: 0; cursor: pointer; }
480
- select:hover, input[list]:hover { border-color: var(--muted); }
481
- .code-preview { display: block; margin: 10px 0 0; padding: 12px 14px; max-height: 320px; overflow: auto; white-space: pre;
482
- font: .78rem/1.5 var(--mono); color: var(--ink); background: var(--bg); border: 1px solid var(--line); border-radius: 8px; }
483
- .plan { margin-top: 12px; padding-top: 12px; border-top: 1px dashed var(--line); }
440
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.55 var(--body); }
441
+ a { color: var(--accent); }
442
+ [hidden] { display: none !important; }
443
+ :focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
444
+
445
+ .top { max-width: 1240px; margin: 0 auto; padding: 26px 28px 18px; display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
446
+ .top h1 { margin: 0; font-size: 24px; letter-spacing: -.01em; }
447
+ .top .where { color: var(--muted); font: 12px var(--mono); }
448
+ .shell { max-width: 1240px; margin: 0 auto 60px; padding: 0 28px; display: grid; grid-template-columns: 250px minmax(0, 1fr); gap: 28px; align-items: start; }
449
+
450
+ .side { position: sticky; top: 16px; display: flex; flex-direction: column; gap: 2px; }
451
+ .side .group { margin: 16px 10px 6px; font-size: 12px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); }
452
+ .side .group:first-child { margin-top: 0; }
453
+ .side a { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 9px 12px; border-radius: 8px; color: var(--ink); text-decoration: none; border: 1px solid transparent; }
454
+ .side a:hover { background: var(--soft); }
455
+ .side a[aria-current="page"] { background: var(--selected); border-color: var(--accent); font-weight: 600; }
456
+ .side .count { min-width: 22px; padding: 0 7px; border-radius: 11px; font-size: 12px; font-weight: 700; text-align: center; background: var(--warn-bg); color: var(--warn); }
457
+ .side .count[data-tone="bad"] { background: var(--bad-bg); color: var(--bad); }
458
+ .side .rule { margin: 18px 10px 0; font-size: 12px; color: var(--muted); border-top: 1px solid var(--line); padding-top: 12px; }
459
+
460
+ .page-head { margin: 0 0 18px; }
461
+ .page-head h2 { margin: 0 0 4px; font-size: 26px; letter-spacing: -.01em; }
462
+ .page-head p { margin: 0; color: var(--muted); max-width: 70ch; }
463
+ .card { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 20px 22px; margin-bottom: 18px; }
464
+ .card > h3 { margin: 0 0 4px; font-size: 18px; }
465
+ .card > .lede { margin: 0 0 14px; color: var(--muted); font-size: 14px; max-width: 75ch; }
466
+ .card-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 4px; }
467
+ .card-head h3 { margin: 0; font-size: 18px; }
468
+
469
+ .pill { display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px 2px 4px; border-radius: 999px; font-size: 13px; font-weight: 600; white-space: nowrap; --tone: var(--idle); background: var(--idle-bg); color: var(--tone); }
470
+ .pill::before { content: "–"; display: inline-grid; place-items: center; width: 18px; height: 18px; border-radius: 50%; font-size: 12px; font-weight: 800; background: var(--tone); color: var(--surface); }
471
+ .pill[data-tone="ok"] { --tone: var(--ok); background: var(--ok-bg); }
472
+ .pill[data-tone="ok"]::before { content: "✓"; }
473
+ .pill[data-tone="warn"] { --tone: var(--warn); background: var(--warn-bg); }
474
+ .pill[data-tone="warn"]::before { content: "!"; }
475
+ .pill[data-tone="bad"] { --tone: var(--bad); background: var(--bad-bg); }
476
+ .pill[data-tone="bad"]::before { content: "✕"; }
477
+ .pill[data-tone="busy"]::before { content: "…"; }
478
+
479
+ .summary-banner { display: flex; gap: 14px; align-items: center; padding: 16px 20px; border-radius: 12px; margin-bottom: 18px; background: var(--ok-bg); color: var(--ok); font-weight: 600; }
480
+ .summary-banner[data-tone="warn"] { background: var(--warn-bg); color: var(--warn); }
481
+ .summary-banner[data-tone="bad"] { background: var(--bad-bg); color: var(--bad); }
482
+ .summary-banner[data-tone="busy"] { background: var(--idle-bg); color: var(--idle); }
483
+ .checklist { list-style: none; margin: 0; padding: 0; }
484
+ .check { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 16px; align-items: center; padding: 14px 0; border-top: 1px solid var(--line); }
485
+ .check:first-child { border-top: 0; padding-top: 0; }
486
+ .check-title { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font-weight: 600; }
487
+ .check-text { grid-column: 1; color: var(--muted); font-size: 14px; overflow-wrap: anywhere; }
488
+ .check-action { grid-column: 2; grid-row: 1 / span 2; }
489
+
490
+ .row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 16px; padding: 16px 0; border-top: 1px solid var(--line); align-items: start; }
491
+ .row:first-of-type { border-top: 0; }
492
+ .row-title { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font-weight: 600; }
493
+ .row-text { grid-column: 1; color: var(--muted); font-size: 14px; max-width: 72ch; overflow-wrap: anywhere; }
494
+ .row-side { grid-column: 2; grid-row: 1 / span 2; display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; }
495
+ .row-more { grid-column: 1 / -1; }
496
+ .callout { margin: 10px 0 0; padding: 12px 14px; border-radius: 8px; background: var(--warn-bg); color: var(--ink); font-size: 14px; }
497
+ .callout strong { color: var(--warn); }
498
+ .callout ul { margin: 6px 0 0; padding-left: 20px; }
499
+ .callout.info { background: var(--soft); }
500
+ .callout.info strong { color: var(--ink); }
501
+
502
+ fieldset.choice { border: 0; padding: 16px 0; margin: 0; border-top: 1px solid var(--line); min-width: 0; }
503
+ fieldset.choice:first-of-type { border-top: 0; padding-top: 4px; }
504
+ fieldset.choice legend { font-weight: 600; font-size: 16px; padding: 0; float: left; width: 100%; }
505
+ fieldset.choice legend + * { clear: both; }
506
+ .choice-intro { color: var(--muted); font-size: 14px; margin: 4px 0 10px; max-width: 75ch; }
507
+ .option { display: grid; grid-template-columns: 22px minmax(0, 1fr); gap: 2px 10px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; margin-top: 8px; cursor: pointer; }
508
+ .option:hover { border-color: var(--accent); }
509
+ .option:has(input:checked) { border-color: var(--accent); background: var(--selected); }
510
+ .option input { margin: 3px 0 0; width: 18px; height: 18px; accent-color: var(--accent); }
511
+ .option-title { font-weight: 600; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
512
+ .option-text { grid-column: 2; color: var(--muted); font-size: 14px; }
513
+ .tag { font-size: 11px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; color: var(--accent); border: 1px solid currentColor; border-radius: 4px; padding: 0 5px; }
514
+ .saved { font-size: 13px; margin-top: 8px; min-height: 1.3em; }
515
+
516
+ .field { margin: 0 0 14px; }
517
+ .field label { display: block; font-weight: 600; margin: 0 0 3px; }
518
+ .field .explain { display: block; color: var(--muted); font-size: 13px; margin: 0 0 6px; max-width: 72ch; }
519
+ .field .hint { display: block; color: var(--muted); font-size: 12px; margin-top: 4px; }
520
+ .pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 0 16px; }
521
+ input:not([type]), input[type=text], input[type=number], input[type=password], select {
522
+ width: 100%; max-width: 560px; padding: 9px 11px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); color: var(--ink); font: 14px var(--mono); }
484
523
  input[type=password] { font-family: var(--body); }
485
- input::placeholder { color: var(--idle); }
486
- select:focus-visible, input:focus-visible, button:focus-visible { outline: 2px solid var(--signal); outline-offset: 2px; }
487
- .actions { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin-top: 14px; }
488
- button { font: 600 .86rem var(--display); letter-spacing: .03em; border-radius: 8px; padding: 9px 16px; cursor: pointer;
489
- background: var(--signal); color: var(--on-signal); border: 1px solid var(--signal); }
490
- button.quiet { background: transparent; color: var(--ink); border-color: var(--line); }
491
- button:disabled { opacity: .45; cursor: default; }
492
- .state { display: inline-flex; align-items: center; gap: 8px; font-size: .86rem; }
493
- .state::before { content: ""; width: 9px; height: 9px; border-radius: 50%; background: var(--idle); }
494
- .state[data-state="ok"]::before { background: var(--ok); }
495
- .state[data-state="bad"]::before { background: var(--bad); }
496
- .state[data-state="warn"]::before { background: var(--warn); }
497
- .mono { font-family: var(--mono); font-size: .8rem; overflow-wrap: anywhere; }
498
- .msg { font-size: .84rem; min-height: 1.3em; margin-top: 10px; }
524
+ button { font: 600 14px var(--body); min-height: 38px; padding: 7px 15px; border-radius: 6px; cursor: pointer; border: 1px solid var(--line); background: var(--surface); color: var(--ink); }
525
+ button:hover { border-color: var(--accent); background: var(--selected); }
526
+ button.primary { background: var(--accent); border-color: transparent; color: var(--on-accent); }
527
+ button.primary:hover { filter: brightness(1.08); }
528
+ button.small { min-height: 30px; padding: 3px 10px; font-size: 13px; }
529
+ button:disabled { opacity: .5; cursor: default; }
530
+ .actions { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin-top: 12px; }
531
+ .msg { font-size: 14px; margin-top: 10px; min-height: 1.3em; overflow-wrap: anywhere; }
532
+ .msg:empty { min-height: 0; margin: 0; }
499
533
  .msg.error { color: var(--bad); }
500
534
  .msg.ok { color: var(--ok); }
501
535
  .msg.warn { color: var(--warn); }
502
- .provider + .provider { border-top: 1px solid var(--line); margin-top: 18px; padding-top: 18px; }
503
- .provider-head { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; margin-bottom: 8px; }
504
- .provider-head strong { font: 600 .98rem var(--display); letter-spacing: .02em; }
505
- .blocked { color: var(--muted); font-size: .88rem; border: 1px dashed var(--line); border-radius: 10px; padding: 14px 16px; }
506
- .pattern-panel, .pattern-blocking { margin-top: 16px; border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; }
507
- .pattern-head { display: flex; flex-direction: column; gap: 2px; }
508
- .pattern-tools { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; margin-top: 12px; }
509
- .pattern-bulk { margin-top: 10px; }
536
+ .mono { font: 13px var(--mono); overflow-wrap: anywhere; }
537
+ details.more { margin-top: 10px; }
538
+ details.more > summary { cursor: pointer; color: var(--accent); font-size: 14px; }
539
+ pre.code { margin: 8px 0 0; padding: 12px 14px; max-height: 320px; overflow: auto; font: 12px/1.5 var(--mono); background: var(--soft); border-radius: 8px; white-space: pre; }
540
+ .confirm-box { margin-top: 12px; padding: 14px 16px; border: 1px solid var(--accent); border-radius: 8px; background: var(--selected); }
541
+ .confirm-box p { margin: 0 0 6px; font-size: 14px; }
542
+
543
+ .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin: 6px 0 16px; }
544
+ .tile { border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; }
545
+ .tile .value { font-size: 28px; font-weight: 700; line-height: 1.1; }
546
+ .tile .label { color: var(--muted); font-size: 13px; }
547
+ .bars { list-style: none; margin: 6px 0 0; padding: 0; }
548
+ .bars li { display: grid; grid-template-columns: minmax(90px, 200px) minmax(0, 1fr) 54px; gap: 10px; align-items: center; padding: 4px 0; font-size: 14px; }
549
+ .bars .bar { height: 10px; border-radius: 5px; background: var(--soft); overflow: hidden; }
550
+ .bars .bar span { display: block; height: 100%; background: var(--accent); border-radius: 5px; }
551
+ .bars .num { text-align: right; font-variant-numeric: tabular-nums; }
552
+ .bars .name { overflow-wrap: anywhere; }
553
+
554
+ .provider-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 16px; padding: 16px 0; border-top: 1px solid var(--line); align-items: start; }
555
+ .provider-row:first-of-type { border-top: 0; padding-top: 4px; }
556
+ .provider-row .key-form { grid-column: 1 / -1; }
557
+
558
+ .pattern-tools { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); gap: 10px; margin-top: 12px; }
510
559
  .pattern-list { list-style: none; margin: 10px 0 0; padding: 0; border-top: 1px solid var(--line); }
511
- .pattern-row { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 10px; align-items: start;
512
- padding: 10px 0; border-bottom: 1px solid var(--line); }
513
- .pattern-blocking .pattern-row { grid-template-columns: minmax(0, 1fr); }
514
- .pattern-row input[type=checkbox] { margin-top: 6px; }
560
+ .pattern-row { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 10px; align-items: start; padding: 10px 0; border-bottom: 1px solid var(--line); }
561
+ .pattern-row.plain { grid-template-columns: minmax(0, 1fr); }
562
+ .pattern-row input[type=checkbox] { margin-top: 6px; width: 18px; height: 18px; accent-color: var(--accent); }
515
563
  .pattern-body summary { display: flex; gap: 8px; align-items: baseline; cursor: pointer; min-width: 0; }
516
- .pattern-tool { font: 600 .74rem var(--display); letter-spacing: .06em; text-transform: uppercase; color: var(--muted); flex: none; }
517
- .pattern-code { font: .78rem/1.4 var(--mono); overflow-wrap: anywhere; min-width: 0; display: -webkit-box;
518
- -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
564
+ .pattern-tool { font-size: 12px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; color: var(--muted); flex: none; }
565
+ .pattern-code { font: 13px/1.4 var(--mono); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
519
566
  .pattern-body[open] .pattern-code { -webkit-line-clamp: unset; }
520
- .pattern-main { min-width: 0; }
521
- .pattern-meta { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 6px; flex-wrap: wrap; }
522
- .pattern-detail { font-size: .84rem; padding: 4px 0 2px; }
567
+ .pattern-detail { font-size: 14px; }
523
568
  .pattern-detail p { margin: 4px 0; }
524
- .pattern-reach { font: .78rem var(--mono); color: var(--muted); white-space: nowrap; }
525
- .pattern-actions { display: flex; gap: 6px; }
526
- .pattern-actions button { padding: 4px 10px; font-size: .78rem; }
527
- .pattern-pager { justify-content: space-between; }
528
- .pattern-blocking > summary { cursor: pointer; font: 600 .9rem var(--display); }
569
+ .pattern-meta { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 6px; flex-wrap: wrap; }
570
+ .pattern-reach { font: 13px var(--mono); color: var(--muted); }
571
+ .pager { justify-content: space-between; }
572
+
529
573
  .audit-list { list-style: none; padding: 0; margin: 10px 0; }
530
- .audit-row { padding: 10px 0; border-bottom: 1px solid var(--line); }
531
- .audit-head { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; }
532
- .audit-sev { font: 600 .72rem var(--display); letter-spacing: .06em; text-transform: uppercase; }
533
- .audit-error { color: var(--bad); }
534
- .audit-warn { color: var(--warn); }
535
- .audit-info { color: var(--muted); }
536
- .audit-new { font: 600 .72rem var(--display); color: var(--signal); }
537
- .audit-detail { font-size: .84rem; margin: 4px 0 0; overflow-wrap: anywhere; }
538
-
539
- body:not(.ready) .station[data-live="1"] .wire::after { transform: scaleX(0); }
540
- @media (max-width: 900px) { .panels { grid-template-columns: minmax(0, 1fr); } }
541
- @media (max-width: 640px) {
542
- main { padding: 24px 16px 56px; }
543
- .path { grid-template-columns: minmax(0, 1fr); gap: 0; padding: 20px; }
544
- .station a { display: grid; grid-template-columns: 22px minmax(0, 1fr); column-gap: 14px; padding: 0 0 18px; }
545
- .node { flex-direction: column; height: auto; grid-row: span 3; }
546
- .wire { width: 3px; height: auto; flex: 1; margin: -1px 0 0; }
547
- .wire::after { transform: scaleY(0); transform-origin: top; }
548
- .station[data-live="1"] .wire::after { transform: scaleY(1); }
549
- body:not(.ready) .station[data-live="1"] .wire::after { transform: scaleY(0); }
550
- .station:last-child .wire { display: none; }
551
- .station h2 { margin-top: 0; }
552
- .pair { grid-template-columns: minmax(0, 1fr); }
553
- }
554
- @media (prefers-reduced-motion: reduce) {
555
- html { scroll-behavior: auto; }
556
- .station[data-live="1"] .wire::after, .dot { transition: none; }
574
+ .audit-row { padding: 10px 0; border-top: 1px solid var(--line); }
575
+ .audit-head { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
576
+ .audit-detail { font-size: 14px; margin: 4px 0 0; overflow-wrap: anywhere; color: var(--muted); }
577
+ .new-tag { font-size: 12px; font-weight: 700; color: var(--accent); }
578
+ dl.facts { margin: 0; }
579
+ dl.facts > div { display: grid; grid-template-columns: 200px minmax(0, 1fr); gap: 12px; padding: 10px 0; border-top: 1px solid var(--line); font-size: 14px; }
580
+ dl.facts > div:first-child { border-top: 0; }
581
+ dl.facts dt { color: var(--muted); }
582
+ dl.facts dd { margin: 0; overflow-wrap: anywhere; }
583
+
584
+ @media (max-width: 860px) {
585
+ .shell { grid-template-columns: minmax(0, 1fr); gap: 16px; }
586
+ .side { position: static; flex-direction: row; overflow-x: auto; gap: 6px; padding-bottom: 6px; }
587
+ .side .group, .side .rule { display: none; }
588
+ .side a { white-space: nowrap; }
589
+ .pair, .pattern-tools { grid-template-columns: minmax(0, 1fr); }
590
+ .row, .check, .provider-row { grid-template-columns: minmax(0, 1fr); }
591
+ .row-side, .check-action { grid-column: 1; grid-row: auto; justify-content: flex-start; }
592
+ .check-action { order: 1; justify-self: start; }
593
+ dl.facts > div { grid-template-columns: minmax(0, 1fr); gap: 2px; }
557
594
  }
558
595
  </style>
559
596
  </head>
560
597
  <body>
561
- <main>
562
- <header class="masthead">
563
- <div><h1>Smart Tool</h1><span class="where">__SETUP_ORIGIN__</span></div>
564
- <nav><a href="/projects">Projects and indexing →</a></nav>
565
- </header>
566
-
567
- <ol class="path" aria-label="Path of a search, from the agent to the models">
568
- <li class="station" id="st-agent" data-state="ok"><a href="#autostart">
569
- <div class="node"><span class="dot"></span><span class="wire"></span></div>
570
- <h2>Agent</h2><div class="detail">MCP at /mcp</div><div class="verdict">Claude Code, Codex and other MCP clients</div></a></li>
571
- <li class="station" id="st-daemon" data-state="ok"><a href="#autostart">
572
- <div class="node"><span class="dot"></span><span class="wire"></span></div>
573
- <h2>Smart Tool</h2><div class="detail">__SETUP_ORIGIN__</div><div class="verdict" id="st-daemon-verdict">Responding</div></a></li>
574
- <li class="station" id="st-gateway"><a href="#gateway">
575
- <div class="node"><span class="dot"></span><span class="wire"></span></div>
576
- <h2>Gateway</h2><div class="detail" id="st-gateway-detail">—</div><div class="verdict" id="st-gateway-verdict">Checking</div></a></li>
577
- <li class="station" id="st-models"><a href="#models">
578
- <div class="node"><span class="dot"></span><span class="wire"></span></div>
579
- <h2>Models</h2><div class="detail" id="st-models-detail">—</div><div class="verdict" id="st-models-verdict">Checking</div></a></li>
580
- </ol>
581
-
582
- <div class="panels">
583
- <div class="col">
584
- <section id="gateway">
585
- <h2>Model gateway</h2>
586
- <p class="lede">Where embedding, chat and, if available, rerank calls go. The OpenAI-compatible adapter covers OpenAI, OpenRouter, a LiteLLM proxy and Ollama; other adapters go in as a .py file in the folder shown below.</p>
587
- <div class="state" id="gateway-state" role="status">Checking</div>
588
- <div class="field" style="margin-top:16px">
598
+ <header class="top">
599
+ <div><h1>Smart Tool settings</h1><span class="where">__SETUP_ORIGIN__ · version <span id="app-version"></span></span></div>
600
+ <nav><a href="/projects">Projects and indexing →</a></nav>
601
+ </header>
602
+ <div class="shell">
603
+ <nav class="side" aria-label="Settings sections">
604
+ <a href="#overview" data-page="overview"><span>Overview</span><span class="count" data-count="overview" hidden></span></a>
605
+ <div class="group">Connect</div>
606
+ <a href="#agents" data-page="agents"><span>Agents</span><span class="count" data-count="agents" hidden></span></a>
607
+ <a href="#models" data-page="models"><span>Models</span><span class="count" data-count="models" hidden></span></a>
608
+ <a href="#web" data-page="web"><span>Web search</span><span class="count" data-count="web" hidden></span></a>
609
+ <div class="group">Behavior</div>
610
+ <a href="#rules" data-page="rules"><span>Agent rules</span><span class="count" data-count="rules" hidden></span></a>
611
+ <a href="#redirects" data-page="redirects"><span>Redirects</span><span class="count" data-count="redirects" hidden></span></a>
612
+ <div class="group">Maintenance</div>
613
+ <a href="#audit" data-page="audit"><span>Setup audit</span><span class="count" data-count="audit" hidden></span></a>
614
+ <a href="#startup" data-page="startup"><span>Startup</span><span class="count" data-count="startup" hidden></span></a>
615
+ <p class="rule">Choices apply as soon as you pick them. Typed values (addresses, keys, model names) are saved with the button next to them.</p>
616
+ </nav>
617
+
618
+ <main>
619
+ <section class="page" data-page="overview" aria-labelledby="h-overview">
620
+ <header class="page-head"><h2 id="h-overview" tabindex="-1">Overview</h2>
621
+ <p>Everything Smart Tool needs to work, checked on this machine. Anything that needs you comes first, with a button that takes you to the fix.</p></header>
622
+ <div class="summary-banner" id="overview-banner" data-tone="busy" role="status">Checking…</div>
623
+ <div class="card"><ul class="checklist" id="overview-list"></ul></div>
624
+ </section>
625
+
626
+ <section class="page" data-page="agents" aria-labelledby="h-agents" hidden>
627
+ <header class="page-head"><h2 id="h-agents" tabindex="-1">Agents</h2>
628
+ <p>Connect your coding agents to Smart Tool. Each agent needs two things: the connection (MCP server), which gives it smart_search, web_search and web_fetch, and the redirect hook, which sends its folder searches and web lookups to those tools.</p></header>
629
+ <div class="msg" id="agents-msg" role="status"></div>
630
+ <div id="agents-list"></div>
631
+ </section>
632
+
633
+ <section class="page" data-page="rules" aria-labelledby="h-rules" hidden>
634
+ <header class="page-head"><h2 id="h-rules" tabindex="-1">Agent rules</h2>
635
+ <p>How the hook treats your agents' tool calls. These apply to every connected agent on its next tool call; nothing needs reinstalling.</p></header>
636
+ <div class="card" id="rules-card"></div>
637
+ </section>
638
+
639
+ <section class="page" data-page="redirects" aria-labelledby="h-redirects" hidden>
640
+ <header class="page-head"><h2 id="h-redirects" tabindex="-1">Redirects</h2>
641
+ <p>What the hook did with your agents' native searches, and what the agent did next. Below, the block patterns a model proposed from calls the fixed rule let through.</p></header>
642
+ <div class="card" id="redirects-card"><p class="lede">Loading…</p></div>
643
+ <div class="card">
644
+ <h3>Block patterns</h3>
645
+ <p class="lede">The hook decides with a fixed rule: content searches over a project folder go to smart_search. A model reviews the calls the rule let through, afterwards and without delaying them, and proposes patterns. Each proposal shows how many logged calls it would have blocked. Nothing blocks until you accept it.</p>
646
+ <div class="msg" id="patterns-msg" role="status"></div>
647
+ <div id="patterns-list"></div>
648
+ </div>
649
+ </section>
650
+
651
+ <section class="page" data-page="models" aria-labelledby="h-models" hidden>
652
+ <header class="page-head"><h2 id="h-models" tabindex="-1">Models</h2>
653
+ <p>Smart Tool uses models for code search (embedding and rerank), for deciding where a search goes, and for web research. They come through a model gateway you connect here.</p></header>
654
+ <div class="card" id="gateway">
655
+ <div class="card-head"><h3>1. Model gateway</h3><span class="pill" id="gateway-pill" data-tone="busy">Checking</span></div>
656
+ <p class="lede">Where embedding, chat and rerank calls go. The OpenAI-compatible adapter covers OpenAI, OpenRouter, a LiteLLM proxy and Ollama. Other adapters go in as a .py file in the folder shown below.</p>
657
+ <div class="field">
589
658
  <label for="gateway-adapter">Adapter</label>
590
659
  <select id="gateway-adapter"></select>
591
660
  <span class="hint mono" id="gateway-dir"></span>
@@ -593,185 +662,279 @@ _PAGE_TEMPLATE = """<!doctype html>
593
662
  <div id="gateway-fields"></div>
594
663
  <div class="msg error" id="gateway-errors" role="status" hidden></div>
595
664
  <div class="actions">
596
- <button type="button" id="gateway-save">Test and save</button>
597
- <button type="button" class="quiet" id="gateway-clear">Disconnect</button>
665
+ <button type="button" class="primary" id="gateway-save">Test and save</button>
666
+ <button type="button" id="gateway-clear">Disconnect</button>
598
667
  </div>
599
668
  <div class="msg" id="gateway-msg" role="status"></div>
600
- </section>
669
+ </div>
601
670
 
602
- <section id="models">
603
- <h2>Models</h2>
604
- <p class="lede">Any id the gateway accepts; the published catalog shows up as suggestions. Rerank is optional: without it the hybrid order applies.</p>
605
- <div class="blocked" id="models-blocked" hidden>Connect the gateway to list the catalog and choose models.</div>
671
+ <div class="card" id="models-card">
672
+ <div class="card-head"><h3>2. Models</h3><span class="pill" id="models-pill" data-tone="busy">Checking</span></div>
673
+ <p class="lede">Any model id your gateway accepts. The gateway's catalog shows up as suggestions while you type.</p>
674
+ <p class="callout info" id="models-blocked" hidden><strong>Connect the gateway first.</strong> The catalog and the model choice open once the gateway answers.</p>
606
675
  <div id="models-form" hidden>
607
- <fieldset>
608
- <legend>Code search</legend>
609
- <p class="lede">Indexing and smart_search.</p>
610
- <div class="pair">
611
- <div class="field"><label for="sel-embedding">Embedding</label><input id="sel-embedding" list="dl-embedding" autocomplete="off" spellcheck="false"><datalist id="dl-embedding"></datalist></div>
612
- <div class="field"><label for="sel-rerank">Rerank</label><input id="sel-rerank" list="dl-rerank" autocomplete="off" spellcheck="false"><datalist id="dl-rerank"></datalist></div>
676
+ <div class="pair">
677
+ <div class="field"><label for="sel-embedding">Embedding</label><span class="explain">Turns code into vectors for indexing and smart_search.</span><input id="sel-embedding" list="dl-embedding" autocomplete="off" spellcheck="false"><datalist id="dl-embedding"></datalist></div>
678
+ <div class="field"><label for="sel-rerank">Rerank (optional)</label><span class="explain">Reorders search results by relevance. Empty keeps the hybrid order.</span><input id="sel-rerank" list="dl-rerank" autocomplete="off" spellcheck="false"><datalist id="dl-rerank"></datalist></div>
679
+ </div>
680
+ <div class="pair">
681
+ <div class="field"><label for="sel-scope">Index classification</label><span class="explain">Decides scope, code or documentation, and languages while indexing. Runs once per project.</span><input id="sel-scope" list="dl-scope" autocomplete="off" spellcheck="false"><datalist id="dl-scope"></datalist></div>
682
+ <div class="field"><label for="sel-router">Router</label><span class="explain">Decides before each agent Grep, Read or Bash. Use a small model without reasoning: above 10 s routing turns off.</span><input id="sel-router" list="dl-router" autocomplete="off" spellcheck="false"><datalist id="dl-router"></datalist></div>
683
+ </div>
684
+ <div class="field"><label for="sel-research">Web research</label><span class="explain">Used by web_search with depth=research. Empty uses the router model.</span><input id="sel-research" list="dl-research" autocomplete="off" spellcheck="false"><datalist id="dl-research"></datalist></div>
685
+ <details class="more">
686
+ <summary>Advanced web research limits</summary>
687
+ <div class="pair" style="margin-top:12px">
688
+ <div class="field"><label for="num-research-iterations">Maximum research rounds</label><span class="explain">How many search rounds a research may run before answering.</span><input type="number" id="num-research-iterations" step="1"><span class="hint" id="research-iterations-hint"></span></div>
689
+ <div class="field"><label for="num-quick-timeout">Quick search time limit (s)</label><span class="explain">How long a quick web search waits for its sources.</span><input type="number" id="num-quick-timeout" step="1"><span class="hint" id="quick-timeout-hint"></span></div>
613
690
  </div>
614
- <div class="field"><label for="sel-scope">Index classification</label><input id="sel-scope" list="dl-scope" autocomplete="off" spellcheck="false"><datalist id="dl-scope"></datalist>
615
- <span class="hint">Decides scope, code vs. documentation and languages during indexing. Runs once per project.</span></div>
616
- </fieldset>
617
- <fieldset>
618
- <legend>Router</legend>
619
- <div class="field"><label for="sel-router">Router model</label><input id="sel-router" list="dl-router" autocomplete="off" spellcheck="false"><datalist id="dl-router"></datalist>
620
- <span class="hint">Decides before each agent Grep/Read/Bash. Use a small model without reasoning: above 10 s routing is turned off.</span></div>
621
- </fieldset>
622
- <fieldset>
623
- <legend>Web research</legend>
624
- <div class="field"><label for="sel-research">Iterative research model</label><input id="sel-research" list="dl-research" autocomplete="off" spellcheck="false"><datalist id="dl-research"></datalist>
625
- <span class="hint">Used by web_search with depth=research. Empty uses the router model.</span></div>
626
- <div class="pair">
627
- <div class="field"><label for="num-research-iterations">Maximum rounds</label><input type="number" id="num-research-iterations" step="1"><span class="hint" id="research-iterations-hint"></span></div>
628
- <div class="field"><label for="num-quick-timeout">Quick search time limit (s)</label><input type="number" id="num-quick-timeout" step="1"><span class="hint" id="quick-timeout-hint"></span></div>
629
- </div>
630
- <div class="field"><label for="num-site-memory-threshold">Minimum per-site memory similarity</label><input type="number" id="num-site-memory-threshold" step="0.01"><span class="hint" id="site-memory-threshold-hint"></span></div>
631
- </fieldset>
632
- <div class="actions"><button type="button" id="btn-save-models">Save models</button></div>
691
+ <div class="field"><label for="num-site-memory-threshold">Per-site memory similarity</label><span class="explain">How close a new question must be to a remembered page of the same site to reuse it.</span><input type="number" id="num-site-memory-threshold" step="0.01"><span class="hint" id="site-memory-threshold-hint"></span></div>
692
+ </details>
693
+ <div class="actions"><button type="button" class="primary" id="btn-save-models">Save models</button></div>
633
694
  <div class="msg" id="models-msg" role="status"></div>
634
695
  </div>
635
- </section>
636
- </div>
637
-
638
- <div class="col">
639
- <section id="autostart">
640
- <h2>Start automatically</h2>
641
- <p class="lede">Starts Smart Tool when you sign in to Windows.</p>
642
- <div class="state" id="autostart-status" role="status">Checking</div>
643
- <div class="actions"><button type="button" class="quiet" id="btn-autostart-toggle" disabled>Checking</button></div>
644
- <div class="msg" id="autostart-msg" role="status"></div>
645
- </section>
646
-
647
- <section id="local-models-section">
648
- <h2>Local models</h2>
649
- <p class="lede">Embedding from the mcp-memory sidecar on this machine. Switching between gateway and local rebuilds the project indexes; going back to a model used before reuses the vector cache.</p>
650
- <div class="field"><label for="sel-local-models">Usage</label>
651
- <select id="sel-local-models">
652
- <option value="fallback">Fallback: only when the gateway lacks the model</option>
653
- <option value="prefer">Prefer local: even when the gateway has the model</option>
654
- <option value="off">Off: never use local</option>
655
- </select>
656
- <span class="hint" id="local-models-hint">Checking the sidecar</span></div>
657
- <div class="actions"><button type="button" id="btn-save-local-models">Save</button></div>
658
- <div class="msg" id="local-models-msg" role="status"></div>
659
- </section>
660
-
661
- <section id="agents-section">
662
- <h2>Agents</h2>
663
- <p class="lede">The Smart Tool MCP server and the hook that redirects Grep/Read/Bash to smart_search and WebSearch/WebFetch to web_search/web_fetch. In Claude Code the hook is a direct HTTP call to the daemon; in Codex, a thin command that forwards to the daemon. If the port changes, the daemon rewrites these URLs on its own.</p>
664
- <div class="field"><label for="sel-hook-mode">Hook behavior</label>
665
- <select id="sel-hook-mode">
666
- <option value="redirect">Redirect: block the native tool and point to Smart Tool (default)</option>
667
- <option value="advise">Advise only: let the native tool run and tell the agent what Smart Tool would do</option>
668
- <option value="off">Off: no routing</option>
669
- </select>
670
- <span class="hint" id="hook-mode-hint">Applies to every client on the next tool call; nothing is reinstalled.</span></div>
671
- <div class="actions"><button type="button" id="btn-save-hook-mode">Save behavior</button></div>
672
- <div class="field" style="margin-top:16px"><label for="sel-doc-mode">Documentation on edit</label>
673
- <select id="sel-doc-mode">
674
- <option value="remind">Remind: the edit runs; the agent is told which touched functions lack a docstring (default)</option>
675
- <option value="require">Require: an edit that leaves a touched function without a docstring is blocked until it adds one</option>
676
- <option value="off">Off: no documentation checks</option>
677
- </select>
678
- <span class="hint">Only public functions the edit touches (private, nested and override functions are exempt, as in pydocstyle, eslint-plugin-jsdoc and Checkstyle). A documented function is mentioned again only when its signature changes; body-only edits stay silent.</span></div>
679
- <div class="actions"><button type="button" id="btn-save-doc-mode">Save documentation</button></div>
680
- <div class="field" style="margin-top:16px"><label for="sel-duplicate-mode">Duplicate functions on edit</label>
681
- <select id="sel-duplicate-mode">
682
- <option value="warn">Warn: the edit runs; the agent is told when a written function copies one already in the project (default)</option>
683
- <option value="off">Off: no duplicate checks on edit</option>
684
- </select>
685
- <span class="hint">Compares functions the edit writes with the indexed code: identical bodies, and near-identical ones with only local names changed. Never blocks.</span></div>
686
- <div class="actions"><button type="button" id="btn-save-duplicate-mode">Save duplicates</button></div>
687
- <div class="field" style="margin-top:16px"><label for="sel-pattern-proposals">Block patterns proposed by a model</label>
688
- <select id="sel-pattern-proposals">
689
- <option value="on">On: searches the rule lets run are reviewed in the background and may become proposals (default)</option>
690
- <option value="off">Off: no review</option>
691
- </select>
692
- <span class="hint">The hook decides with a fixed rule: content searches over a project folder go to smart_search. The scope model (else the router model) never delays a call: it reviews, afterwards, bulk reads the rule could not measure and proposes patterns, each checked against the logged calls. Nothing blocks until you accept it here.</span></div>
693
- <div class="actions"><button type="button" id="btn-save-pattern-proposals">Save proposals setting</button></div>
694
- <div id="patterns-list"></div>
695
- <div id="redirects-panel" class="pattern-panel"></div>
696
- <div class="msg" id="agents-msg" role="status"></div>
697
- <div id="agents-list"></div>
698
- </section>
699
-
700
- <section id="audit-section">
701
- <h2>Setup audit</h2>
702
- <p class="lede">What Claude Code and Codex load for a project, and where they collide: hooks deciding on the same tool at once, hooks or MCP servers that do not work, tools offered twice, skills and instructions one agent never sees. It runs on its own every 30 minutes for the registered projects; nothing is changed.</p>
696
+ </div>
697
+
698
+ <div class="card" id="local-models-card">
699
+ <div class="card-head"><h3>3. Local models</h3><span class="pill" id="local-pill" data-tone="busy">Checking</span></div>
700
+ <p class="lede">Embedding from the mcp-memory sidecar on this machine. Switching between gateway and local rebuilds the project indexes; going back to a model used before reuses its vector cache.</p>
701
+ <fieldset class="choice" id="local-models-choice"><legend>When to use the local model</legend></fieldset>
702
+ </div>
703
+ </section>
704
+
705
+ <section class="page" data-page="web" aria-labelledby="h-web" hidden>
706
+ <header class="page-head"><h2 id="h-web" tabindex="-1">Web search</h2>
707
+ <p>web_search asks several providers at once. All of them work without a key on their public free tier; add your own key only if you need more volume.</p></header>
708
+ <div class="card">
709
+ <h3>Providers</h3>
710
+ <p class="lede">A key is tested with a real search before it is saved, and is protected by DPAPI in this Windows profile.</p>
711
+ <div id="provider-list"><p class="lede">Loading…</p></div>
712
+ </div>
713
+ <div class="card">
714
+ <h3>Your contact (optional)</h3>
715
+ <p class="lede">Wikimedia asks tools to name a contact in their User-Agent. It stays on this machine and is sent only to the search APIs.</p>
716
+ <div class="field"><label for="contact-input">Email or website</label>
717
+ <input id="contact-input" autocomplete="off" spellcheck="false" placeholder="you@example.com or https://your.site">
718
+ <span class="hint mono" id="contact-hint"></span></div>
719
+ <div class="actions"><button type="button" class="primary" id="btn-save-contact">Save contact</button></div>
720
+ <div class="msg" id="contact-msg" role="status"></div>
721
+ </div>
722
+ </section>
723
+
724
+ <section class="page" data-page="audit" aria-labelledby="h-audit" hidden>
725
+ <header class="page-head"><h2 id="h-audit" tabindex="-1">Setup audit</h2>
726
+ <p>What Claude Code and Codex load for a project, and where they collide: hooks deciding on the same tool at once, hooks or MCP servers that do not work, tools offered twice, skills and instructions one agent never sees. It runs on its own for the registered projects and never changes anything.</p></header>
727
+ <div class="card">
728
+ <div class="card-head"><h3>Report at session start (Claude Code)</h3><span class="pill" id="audit-hook-pill" data-tone="busy">Checking</span></div>
729
+ <p class="lede">Off by default. When on, every new Claude Code session starts with one short line about the stored audit of its folder (errors and warnings only, nothing runs). It adds a SessionStart entry to <span class="mono" id="audit-hook-file"></span>, written after a backup, and turning it off removes only that entry. Without it, the agent gets the same line once, on its first search.</p>
730
+ <div class="actions"><button type="button" class="primary" id="btn-audit-hook-on" hidden>Turn on</button><button type="button" id="btn-audit-hook-off" hidden>Turn off</button></div>
731
+ <div id="audit-hook-confirm" hidden>
732
+ <p class="hint" id="audit-hook-where"></p>
733
+ <pre class="mono" id="audit-hook-preview"></pre>
734
+ <div class="actions"><button type="button" class="primary" id="btn-audit-hook-write">Write it</button><button type="button" id="btn-audit-hook-cancel">Cancel</button></div>
735
+ </div>
736
+ <div class="msg" id="audit-hook-msg" role="status"></div>
737
+ </div>
738
+ <div class="card">
703
739
  <div class="field"><label for="sel-audit-project">Project</label>
704
740
  <select id="sel-audit-project"></select>
705
741
  <span class="hint" id="audit-hint"></span></div>
706
- <div class="actions"><button type="button" id="btn-audit-run">Run now</button></div>
742
+ <div class="actions"><button type="button" class="primary" id="btn-audit-run">Run now</button></div>
707
743
  <div class="msg" id="audit-msg" role="status"></div>
708
744
  <div id="audit-report"></div>
709
- </section>
710
-
711
- <section id="providers-section">
712
- <h2>Web search providers</h2>
713
- <p class="lede">All of them work without a key, on each provider's public free tier. Add your own key only if you need more volume: it is tested with a real search before being saved and is protected by DPAPI on this Windows machine.</p>
714
- <div class="field"><label for="contact-input">Your contact for public APIs (optional)</label>
715
- <input id="contact-input" autocomplete="off" spellcheck="false" placeholder="you@example.com or https://your.site">
716
- <span class="hint" id="contact-hint">Wikimedia asks tools to identify a contact in the User-Agent. It stays on this machine and is sent only to the search APIs.</span></div>
717
- <div class="actions"><button type="button" id="btn-save-contact">Save contact</button></div>
718
- <div class="msg" id="contact-msg" role="status"></div>
719
- <div class="field" style="margin-top:18px"><label for="provider-select">Provider</label>
720
- <select id="provider-select"></select>
721
- <span class="hint">Pick a provider to see its free tier and set or remove your key for it.</span></div>
722
- <div id="provider-panel"></div>
723
- </section>
724
- </div>
725
- </div>
726
- </main>
745
+ </div>
746
+ </section>
747
+
748
+ <section class="page" data-page="startup" aria-labelledby="h-startup" hidden>
749
+ <header class="page-head"><h2 id="h-startup" tabindex="-1">Startup</h2>
750
+ <p>The Smart Tool service runs in the background on this machine. Your agents talk to it at the address below.</p></header>
751
+ <div class="card">
752
+ <div class="card-head"><h3>Start with Windows</h3><span class="pill" id="autostart-pill" data-tone="busy">Checking</span></div>
753
+ <p class="lede">Starts Smart Tool when you sign in, so agents find it without you starting it by hand.</p>
754
+ <div class="actions"><button type="button" id="btn-autostart-toggle" disabled>Checking</button></div>
755
+ <div class="msg" id="autostart-msg" role="status"></div>
756
+ </div>
757
+ <div class="card">
758
+ <h3>This installation</h3>
759
+ <dl class="facts">
760
+ <div><dt>Version</dt><dd id="fact-version"></dd></div>
761
+ <div><dt>Service address</dt><dd class="mono">__SETUP_ORIGIN__</dd></div>
762
+ <div><dt>MCP endpoint</dt><dd class="mono">__SETUP_ORIGIN__/mcp</dd></div>
763
+ </dl>
764
+ </div>
765
+ </section>
766
+ </main>
767
+ </div>
727
768
  <script>
728
769
  const TOKEN = __SETUP_TOKEN__;
729
770
  let status = __STATUS_JSON__;
730
771
  const $ = (id) => document.getElementById(id);
772
+ const loaded = { integration: null, autostart: null, providers: null, audit: null };
773
+ const failed = {};
774
+ let serviceDown = false;
731
775
 
732
- function setMsg(id, kind, text) { const el = $(id); el.className = "msg" + (kind ? " " + kind : ""); el.textContent = text; }
733
-
776
+ function node(tag, className, text) {
777
+ const el = document.createElement(tag);
778
+ if (className) el.className = className;
779
+ if (text !== undefined) el.textContent = text;
780
+ return el;
781
+ }
782
+ function button(label, className, onClick) {
783
+ const el = node("button", className, label);
784
+ el.type = "button";
785
+ if (onClick) el.addEventListener("click", onClick);
786
+ return el;
787
+ }
788
+ function pill(tone, label) {
789
+ const el = node("span", "pill", label);
790
+ el.dataset.tone = tone;
791
+ return el;
792
+ }
793
+ function plural(n, word) { return n + " " + word + (n === 1 ? "" : "s"); }
794
+ function setPill(id, tone, label) { const el = $(id); el.dataset.tone = tone; el.textContent = label; }
795
+ function setMsg(target, kind, text) {
796
+ const el = typeof target === "string" ? $(target) : target;
797
+ el.className = (el.dataset.base || "msg") + (kind ? " " + kind : "");
798
+ el.textContent = text;
799
+ }
734
800
  async function post(path, body) {
735
801
  const resp = await fetch(path, { method: "POST", headers: { "X-Setup-Token": TOKEN, "Content-Type": "application/json" }, body: JSON.stringify(body) });
736
802
  const data = await resp.json().catch(() => ({}));
737
803
  if (!resp.ok || data.error) throw new Error(data.error || `HTTP error ${resp.status}.`);
738
804
  return data;
739
805
  }
806
+ async function getJSON(path) {
807
+ const resp = await fetch(path);
808
+ const data = await resp.json().catch(() => ({}));
809
+ if (!resp.ok || data.error) throw new Error(data.error || `HTTP error ${resp.status}.`);
810
+ return data;
811
+ }
740
812
 
741
- function station(id, state, live, broken) {
742
- const el = $(id);
743
- el.dataset.state = state;
744
- el.dataset.live = live ? "1" : "0";
745
- el.dataset.break = broken ? "1" : "0";
813
+ const PAGES = [...document.querySelectorAll("section.page")].map((section) => section.dataset.page);
814
+ function showPage(name, focus) {
815
+ if (!PAGES.includes(name)) name = "overview";
816
+ for (const section of document.querySelectorAll("section.page")) section.hidden = section.dataset.page !== name;
817
+ for (const link of document.querySelectorAll(".side a")) {
818
+ if (link.dataset.page === name) link.setAttribute("aria-current", "page"); else link.removeAttribute("aria-current");
819
+ }
820
+ if (focus) $("h-" + name).focus();
821
+ }
822
+ function go(page) {
823
+ if (location.hash === "#" + page) showPage(page, true); else location.hash = page;
824
+ }
825
+ window.addEventListener("hashchange", () => showPage(location.hash.slice(1), true));
826
+ showPage(location.hash.slice(1), false);
827
+ $("app-version").textContent = status.version;
828
+ $("fact-version").textContent = status.version;
829
+
830
+ function agentState(item) {
831
+ if (!item.mcp_url) return { tone: "bad", label: "Not connected", action: "Connect",
832
+ text: "The smart-tool MCP server is not registered in " + item.label + ", so it has no smart_search, web_search or web_fetch." };
833
+ if (item.hook_error) return { tone: "bad", label: "Hook unreadable", action: "Open",
834
+ text: "Could not read " + item.file + ": " + item.hook_error };
835
+ if (item.hook_state === "outdated") return { tone: "warn", label: "Hook outdated", action: "Update hook", hook: true,
836
+ text: "The redirect hook was written by an older Smart Tool. " + item.hook_changes.join(" ") };
837
+ if (item.hook_state === "missing") return { tone: "warn", label: "No hook", action: "Install hook", hook: true,
838
+ text: "Connected, but its folder searches and web lookups are not redirected to Smart Tool." };
839
+ return { tone: "ok", label: "Connected", action: "Open", text: "Connection and redirect hook are up to date." };
746
840
  }
747
841
 
748
- function renderPath() {
842
+ function overviewItems() {
843
+ const items = [];
749
844
  const gw = status.gateway;
750
- const gwReady = gw.status === "ready";
751
- const modelsReady = status.models_status === "ready";
752
- const source = gw.label || "Not configured";
753
- $("st-gateway-detail").textContent = gw.label || "no adapter";
754
- $("st-gateway-verdict").textContent = gwReady ? source : (gw.error || "Unavailable");
755
- $("st-models-detail").textContent = [status.embedding_model, status.rerank_model].filter(Boolean).join(" · ") || "none chosen";
756
- $("st-models-verdict").textContent = status.models_message || (modelsReady ? "Ready" : "Choose the models");
757
- station("st-agent", "ok", true, false);
758
- station("st-daemon", "ok", gwReady, !gwReady);
759
- station("st-gateway", gwReady ? "ok" : "bad", gwReady && modelsReady, gwReady && !modelsReady);
760
- station("st-models", gwReady ? (modelsReady ? "ok" : "warn") : "idle", false, false);
761
- ["st-agent", "st-daemon", "st-gateway"].forEach((id, i) => $(id).style.setProperty("--delay", (i * 0.35) + "s"));
845
+ items.push(serviceDown
846
+ ? { tone: "bad", label: "Not responding", title: "Smart Tool service", page: "startup", action: "Open", text: "The service stopped answering this page. Start Smart Tool again and reload." }
847
+ : { tone: "ok", label: "Running", title: "Smart Tool service", page: "startup", action: "Open",
848
+ text: "Answering at " + location.origin + "." + (loaded.autostart ? (loaded.autostart.installed ? " Starts with Windows." : " Not started with Windows.") : "") });
849
+ items.push(gw.status === "ready"
850
+ ? { tone: "ok", label: "Connected", title: "Model gateway", page: "models", action: "Open", text: "Model calls go through " + gw.label + "." }
851
+ : { tone: "bad", label: "Not connected", title: "Model gateway", page: "models", action: "Connect", text: (gw.error || "No gateway configured.") + " Code search and routing need it." });
852
+ if (gw.status === "ready") items.push(status.models_status === "ready"
853
+ ? { tone: "ok", label: "Ready", title: "Models", page: "models", action: "Open", text: [status.embedding_model, status.rerank_model].filter(Boolean).join(" · ") || "Ready." }
854
+ : { tone: "warn", label: "Choose models", title: "Models", page: "models", action: "Choose", text: status.models_message || "Some models are not chosen yet." });
855
+ const integration = loaded.integration;
856
+ if (failed.integration) items.push({ tone: "bad", label: "Unavailable", title: "Agents", page: "agents", action: "Open", text: failed.integration });
857
+ else if (!integration) items.push({ tone: "busy", label: "Checking", title: "Agents", page: "agents", action: "Open", text: "Reading Claude Code and Codex settings…" });
858
+ else {
859
+ for (const item of integration.clients) {
860
+ const state = agentState(item);
861
+ items.push({ ...state, title: item.label, page: "agents", run: state.hook ? () => { go("agents"); hookControls[item.client](); } : null });
862
+ }
863
+ for (const rule of RULES) {
864
+ if (integration[rule.key + "_error"]) items.push({ tone: "bad", label: "Unreadable", title: rule.title, page: "rules", action: "Open", text: integration[rule.key + "_error"] });
865
+ }
866
+ if (integration.hook_mode === "off") items.push({ tone: "warn", label: "Off", title: "Redirects", page: "rules", action: "Turn on", text: "The hook lets every native search run; agents are not sent to Smart Tool." });
867
+ const waiting = integration.block_patterns.proposals.length;
868
+ if (integration.block_patterns.error) items.push({ tone: "bad", label: "Unreadable", title: "Block patterns", page: "redirects", action: "Open", text: integration.block_patterns.error });
869
+ else if (waiting) items.push({ tone: "warn", label: waiting + " waiting", title: "Block patterns", page: "redirects", action: "Review", text: "A model proposed " + plural(waiting, "pattern") + " to block. Nothing blocks until you accept." });
870
+ }
871
+ if (failed.providers) items.push({ tone: "bad", label: "Unavailable", title: "Web search", page: "web", action: "Open", text: failed.providers });
872
+ else if (loaded.providers) {
873
+ const list = Object.values(loaded.providers.providers);
874
+ const unreadable = list.filter((info) => info.status === "unreadable");
875
+ const keyed = list.filter((info) => info.status === "configured").length;
876
+ items.push(unreadable.length
877
+ ? { tone: "bad", label: "Key unreadable", title: "Web search", page: "web", action: "Fix", text: unreadable.map((info) => info.label).join(", ") + ": the saved key cannot be opened in this Windows profile. Paste it again." }
878
+ : { tone: "ok", label: "Ready", title: "Web search", page: "web", action: "Open", text: plural(list.length, "provider") + " on their free tier" + (keyed ? ", " + keyed + " with your key." : "; no key needed.") });
879
+ }
880
+ if (failed.audit) items.push({ tone: "bad", label: "Unavailable", title: "Setup audit", page: "audit", action: "Open", text: failed.audit });
881
+ else if (loaded.audit && loaded.audit.projects.length) {
882
+ const errors = Object.values(loaded.audit.index).reduce((sum, entry) => sum + entry.summary.error, 0);
883
+ items.push(errors
884
+ ? { tone: "warn", label: plural(errors, "problem"), title: "Setup audit", page: "audit", action: "See report", text: "Hooks or MCP servers that collide or do not work in your registered projects." }
885
+ : { tone: "ok", label: "Clean", title: "Setup audit", page: "audit", action: "Open", text: "No collision or broken piece in the audited projects." });
886
+ }
887
+ const rank = { bad: 0, warn: 1, busy: 2, idle: 3, ok: 4 };
888
+ return items.map((item, index) => ({ ...item, index })).sort((a, b) => rank[a.tone] - rank[b.tone] || a.index - b.index);
889
+ }
890
+
891
+ function renderOverview() {
892
+ const items = overviewItems();
893
+ const list = $("overview-list");
894
+ list.replaceChildren();
895
+ for (const item of items) {
896
+ const row = node("li", "check");
897
+ const title = node("div", "check-title");
898
+ title.append(pill(item.tone, item.label), node("span", "", item.title));
899
+ const action = button(item.action, item.tone === "bad" || item.tone === "warn" ? "primary" : "", item.run || (() => go(item.page)));
900
+ action.setAttribute("aria-label", item.action + ": " + item.title);
901
+ const side = node("div", "check-action");
902
+ side.appendChild(action);
903
+ row.append(title, side, node("div", "check-text", item.text));
904
+ list.appendChild(row);
905
+ }
906
+ const problems = items.filter((item) => item.tone === "bad" || item.tone === "warn");
907
+ const pending = items.some((item) => item.tone === "busy");
908
+ const banner = $("overview-banner");
909
+ banner.dataset.tone = problems.some((item) => item.tone === "bad") ? "bad" : problems.length ? "warn" : pending ? "busy" : "ok";
910
+ banner.textContent = problems.length ? problems.length + (problems.length === 1 ? " thing needs" : " things need") + " your attention."
911
+ : pending ? "Checking…" : "Everything is working.";
912
+ const counts = {};
913
+ for (const item of problems) {
914
+ const entry = counts[item.page] || (counts[item.page] = { count: 0, bad: false });
915
+ entry.count += 1;
916
+ entry.bad = entry.bad || item.tone === "bad";
917
+ }
918
+ counts.overview = { count: problems.length, bad: problems.some((item) => item.tone === "bad") };
919
+ for (const badge of document.querySelectorAll(".side .count")) {
920
+ const entry = counts[badge.dataset.count];
921
+ badge.hidden = !entry;
922
+ badge.textContent = entry ? entry.count : "";
923
+ badge.dataset.tone = entry && entry.bad ? "bad" : "warn";
924
+ badge.title = entry ? plural(entry.count, "item") + (entry.count === 1 ? " needs" : " need") + " attention" : "";
925
+ }
762
926
  }
763
927
 
928
+ let gatewaySignature = null;
764
929
  function renderGateway() {
765
930
  const gw = status.gateway;
766
931
  const ready = gw.status === "ready";
767
- const el = $("gateway-state");
768
- el.dataset.state = ready ? "ok" : "bad";
769
- el.textContent = ready ? "Connected through " + gw.label : (gw.error || "Gateway unavailable");
932
+ setPill("gateway-pill", ready ? "ok" : "bad", ready ? "Connected through " + gw.label : "Not connected");
933
+ if (!ready) setMsg("gateway-msg", "error", gw.error || "Gateway unavailable.");
770
934
  $("gateway-dir").textContent = "Your adapters: " + gw.dir;
771
935
  $("gateway-errors").hidden = !gw.errors.length;
772
936
  $("gateway-errors").textContent = gw.errors.length ? "Adapters that failed to load: " + gw.errors.join(" · ") : "";
773
937
  const select = $("gateway-adapter");
774
- // Redraw only when the adapters or their stored state change: the 15 s refresh must not wipe what is being typed.
775
938
  const signature = JSON.stringify([gw.selected, gw.adapters]);
776
939
  if (signature !== gatewaySignature && document.activeElement !== select && !select.dataset.touched) {
777
940
  gatewaySignature = signature;
@@ -782,39 +945,40 @@ function renderGateway() {
782
945
  $("gateway-clear").disabled = !gw.selected;
783
946
  $("models-blocked").hidden = ready;
784
947
  $("models-form").hidden = !ready;
948
+ if (!ready) setPill("models-pill", "idle", "Waiting for the gateway");
949
+ else if (status.models_status === "ready") setPill("models-pill", "ok", "Ready");
950
+ else setPill("models-pill", "warn", "Choose models");
785
951
  }
786
-
787
- let gatewaySignature = null;
788
952
  function renderGatewayFields() {
789
953
  const adapter = status.gateway.adapters.find((a) => a.name === $("gateway-adapter").value);
790
954
  const box = $("gateway-fields");
791
955
  box.replaceChildren();
792
956
  for (const field of (adapter || { fields: [] }).fields) {
793
- const wrap = document.createElement("div");
794
- wrap.className = "field";
795
- wrap.innerHTML = `<label></label><input type="text" autocomplete="off" spellcheck="false"><span class="hint"></span>`;
796
- const input = wrap.querySelector("input");
957
+ const wrap = node("div", "field");
958
+ const input = node("input");
959
+ input.type = "text";
960
+ input.autocomplete = "off";
961
+ input.spellcheck = false;
797
962
  input.id = "gateway-field-" + field.name;
798
- wrap.querySelector("label").htmlFor = input.id;
799
- wrap.querySelector("label").textContent = field.label + (field.required ? "" : " (optional)");
963
+ const label = node("label", "", field.label + (field.required ? "" : " (optional)"));
964
+ label.htmlFor = input.id;
965
+ const hint = node("span", "hint");
800
966
  input.dataset.field = field.name;
801
967
  input.dataset.secret = field.secret ? "1" : "";
802
968
  if (field.secret) {
803
969
  input.type = "password";
804
970
  input.autocomplete = "new-password";
805
971
  input.placeholder = field.state === "configured" ? "Saved · paste another to replace" : "";
806
- const hint = field.state === "unreadable" ? "The saved value cannot be opened in this Windows profile; paste it again. " : "";
807
- wrap.querySelector(".hint").textContent = hint + (field.hint || "") + " Protected by DPAPI.";
808
- if (field.state === "configured") {
809
- const remove = document.createElement("button");
810
- remove.type = "button"; remove.className = "quiet"; remove.textContent = "Remove";
811
- remove.addEventListener("click", () => saveGateway({ adapter: adapter.name, remove_secret: field.name }));
812
- wrap.appendChild(remove);
813
- }
972
+ hint.textContent = (field.state === "unreadable" ? "The saved value cannot be opened in this Windows profile; paste it again. " : "")
973
+ + (field.hint || "") + " Protected by DPAPI.";
814
974
  } else {
815
975
  input.value = field.value || "";
816
976
  input.placeholder = field.placeholder || "";
817
- wrap.querySelector(".hint").textContent = field.hint || "";
977
+ hint.textContent = field.hint || "";
978
+ }
979
+ wrap.append(label, input, hint);
980
+ if (field.secret && field.state === "configured") {
981
+ wrap.appendChild(button("Remove saved value", "small", () => saveGateway({ adapter: adapter.name, remove_secret: field.name })));
818
982
  }
819
983
  box.appendChild(wrap);
820
984
  }
@@ -828,22 +992,18 @@ function gatewayValues() {
828
992
  return values;
829
993
  }
830
994
  $("gateway-adapter").addEventListener("change", () => { $("gateway-adapter").dataset.touched = "1"; renderGatewayFields(); });
831
-
832
- function render() { renderPath(); renderGateway(); }
833
- render();
834
- requestAnimationFrame(() => requestAnimationFrame(() => document.body.classList.add("ready")));
835
-
836
995
  async function saveGateway(body) {
837
996
  const buttons = [$("gateway-save"), $("gateway-clear")];
838
997
  buttons.forEach((b) => b.disabled = true);
839
- setMsg("gateway-msg", "", body.adapter ? "Testing…" : "Disconnecting…");
998
+ setMsg("gateway-msg", "", body.adapter ? "Testing the connection…" : "Disconnecting…");
840
999
  try {
841
1000
  const data = await post("/setup/gateway", body);
842
1001
  status.gateway = data.gateway;
843
1002
  delete $("gateway-adapter").dataset.touched;
844
1003
  gatewaySignature = null;
845
1004
  setMsg("gateway-msg", data.gateway.status === "ready" ? "ok" : "warn",
846
- body.adapter ? "Gateway saved and responding." : "Gateway disconnected.");
1005
+ body.adapter ? (data.gateway.status === "ready" ? "Saved. The gateway answered." : "Saved, but the gateway does not answer: " + (data.gateway.error || "no reason given."))
1006
+ : "Gateway disconnected.");
847
1007
  await refreshStatus(true);
848
1008
  } catch (error) {
849
1009
  setMsg("gateway-msg", "error", error.message);
@@ -855,44 +1015,7 @@ async function saveGateway(body) {
855
1015
  $("gateway-save").addEventListener("click", () => saveGateway({ adapter: $("gateway-adapter").value, values: gatewayValues() }));
856
1016
  $("gateway-clear").addEventListener("click", () => saveGateway({ adapter: "" }));
857
1017
 
858
- let autostartState = { installed: false, method: null };
859
- function renderAutostart() {
860
- const el = $("autostart-status");
861
- el.dataset.state = autostartState.installed ? "ok" : "warn";
862
- el.textContent = autostartState.installed ? `On via ${autostartState.method === "task" ? "Scheduled Task" : "Startup folder"}` : "Off";
863
- $("st-daemon-verdict").textContent = autostartState.installed ? "Responding · starts with Windows" : "Responding · manual start";
864
- const btn = $("btn-autostart-toggle");
865
- btn.disabled = false;
866
- btn.textContent = autostartState.installed ? "Turn off automatic start" : "Turn on automatic start";
867
- }
868
- async function loadAutostart() {
869
- try {
870
- const resp = await fetch("/setup/autostart");
871
- autostartState = await resp.json();
872
- renderAutostart();
873
- } catch (error) {
874
- $("autostart-status").dataset.state = "bad";
875
- $("autostart-status").textContent = "Status unavailable";
876
- }
877
- }
878
- loadAutostart();
879
- $("btn-autostart-toggle").addEventListener("click", async () => {
880
- const action = autostartState.installed ? "remove" : "install";
881
- $("btn-autostart-toggle").disabled = true;
882
- setMsg("autostart-msg", "", action === "install" ? "Turning on…" : "Turning off…");
883
- try {
884
- const data = await post("/setup/autostart", { action });
885
- setMsg("autostart-msg", "ok", action === "install"
886
- ? (data.method === "task" ? "Turned on via Scheduled Task." : `Turned on via the Startup folder; the Scheduled Task was refused: ${data.fallback_reason || "no reason given"}.`)
887
- : "Turned off.");
888
- await loadAutostart();
889
- } catch (error) {
890
- setMsg("autostart-msg", "error", error.message);
891
- $("btn-autostart-toggle").disabled = false;
892
- }
893
- });
894
-
895
- function fillSelect(input, options, current) {
1018
+ function fillSuggestions(input, options, current) {
896
1019
  $(input.getAttribute("list")).replaceChildren(...options.map((opt) => new Option(opt, opt)));
897
1020
  input.value = current || "";
898
1021
  }
@@ -905,14 +1028,12 @@ function fillNumber(id, hintId, range, current, recommended, unit) {
905
1028
  let modelsLoaded = false;
906
1029
  async function loadModels() {
907
1030
  try {
908
- const resp = await fetch("/setup/models");
909
- const data = await resp.json();
910
- if (!resp.ok || data.error) throw new Error(data.error || "The catalog did not respond.");
911
- fillSelect($("sel-router"), data.chat_lightweight.length ? data.chat_lightweight : data.chat, data.current.router_model);
912
- fillSelect($("sel-scope"), data.chat, data.current.scope_model);
913
- fillSelect($("sel-research"), data.chat, data.current.research_model);
914
- fillSelect($("sel-embedding"), data.embedding, data.current.embedding_model);
915
- fillSelect($("sel-rerank"), data.rerank, data.current.rerank_model);
1031
+ const data = await getJSON("/setup/models");
1032
+ fillSuggestions($("sel-router"), data.chat_lightweight.length ? data.chat_lightweight : data.chat, data.current.router_model);
1033
+ fillSuggestions($("sel-scope"), data.chat, data.current.scope_model);
1034
+ fillSuggestions($("sel-research"), data.chat, data.current.research_model);
1035
+ fillSuggestions($("sel-embedding"), data.embedding, data.current.embedding_model);
1036
+ fillSuggestions($("sel-rerank"), data.rerank, data.current.rerank_model);
916
1037
  fillNumber("num-research-iterations", "research-iterations-hint", data.ranges.research_max_iterations, data.current.research_max_iterations, data.recommended.research_max_iterations, "");
917
1038
  fillNumber("num-quick-timeout", "quick-timeout-hint", data.ranges.quick_search_timeout_s, data.current.quick_search_timeout_s, data.recommended.quick_search_timeout_s, " s");
918
1039
  fillNumber("num-site-memory-threshold", "site-memory-threshold-hint", data.ranges.site_memory_similarity_threshold, data.current.site_memory_similarity_threshold, data.recommended.site_memory_similarity_threshold, "");
@@ -922,8 +1043,6 @@ async function loadModels() {
922
1043
  setMsg("models-msg", "error", "Could not read the gateway catalog: " + error.message);
923
1044
  }
924
1045
  }
925
- if (status.gateway.status === "ready") loadModels();
926
-
927
1046
  $("btn-save-models").addEventListener("click", async () => {
928
1047
  if (!modelsLoaded) { setMsg("models-msg", "error", "The catalog has not loaded yet; nothing was saved."); return; }
929
1048
  setMsg("models-msg", "", "Saving…");
@@ -948,141 +1067,318 @@ async function refreshStatus(force) {
948
1067
  const next = await resp.json();
949
1068
  const reload = next.gateway.status === "ready" && (force || status.gateway.status !== "ready");
950
1069
  status = next;
951
- render();
1070
+ serviceDown = false;
1071
+ renderGateway();
952
1072
  if (reload && !modelsLoaded) loadModels();
953
1073
  } catch (error) {
954
- $("st-daemon-verdict").textContent = "No response from the daemon";
955
- station("st-daemon", "bad", false, true);
1074
+ serviceDown = true;
956
1075
  }
1076
+ renderOverview();
957
1077
  }
958
- setInterval(refreshStatus, 15000);
959
1078
 
960
- async function loadLocalModels() {
961
- try {
962
- const resp = await fetch("/setup/local-models");
963
- const data = await resp.json();
964
- if (!resp.ok || data.error) throw new Error(data.error);
965
- $("sel-local-models").value = data.mode;
966
- $("local-models-hint").textContent = !data.sidecar.configured ? "mcp-memory sidecar not configured on this machine."
967
- : data.sidecar.embedding_model ? "Sidecar responding: " + data.sidecar.embedding_model
968
- : "Sidecar configured (" + data.sidecar.url + ") but not responding right now.";
969
- } catch (error) {
970
- $("local-models-hint").textContent = "Status unavailable: " + error.message;
1079
+ function choiceGroup(fieldset, name, options, current, onPick) {
1080
+ for (const [value, title, text, recommended] of options) {
1081
+ const option = node("label", "option");
1082
+ const radio = node("input");
1083
+ radio.type = "radio";
1084
+ radio.name = name;
1085
+ radio.value = value;
1086
+ radio.checked = value === current;
1087
+ radio.addEventListener("change", () => { if (radio.checked) onPick(value); });
1088
+ const head = node("span", "option-title", title);
1089
+ if (recommended) head.appendChild(node("span", "tag", "Recommended"));
1090
+ option.append(radio, head, node("span", "option-text", text));
1091
+ fieldset.appendChild(option);
971
1092
  }
1093
+ const saved = node("div", "saved msg");
1094
+ saved.dataset.base = "saved msg";
1095
+ saved.setAttribute("role", "status");
1096
+ fieldset.appendChild(saved);
1097
+ return saved;
972
1098
  }
973
- loadLocalModels();
974
- $("btn-save-local-models").addEventListener("click", async () => {
975
- setMsg("local-models-msg", "", "Saving…");
1099
+ function checkRadio(name, value) {
1100
+ for (const radio of document.querySelectorAll(`input[name="${name}"]`)) radio.checked = radio.value === value;
1101
+ }
1102
+
1103
+ const LOCAL_OPTIONS = [
1104
+ ["fallback", "Only as a fallback", "Use the local model only when the gateway does not have the embedding model.", true],
1105
+ ["prefer", "Prefer local", "Use the local model even when the gateway has it; your code vectors stay on this machine."],
1106
+ ["off", "Never", "Always use the gateway."],
1107
+ ];
1108
+ let localMode = null;
1109
+ const localSaved = choiceGroup($("local-models-choice"), "local_models", LOCAL_OPTIONS, null, async (mode) => {
1110
+ setMsg(localSaved, "", "Saving…");
976
1111
  try {
977
- await post("/setup/local-models", { mode: $("sel-local-models").value });
978
- setMsg("local-models-msg", "ok", "Mode saved; the indexes adjust on the next search or check.");
979
- await loadLocalModels();
1112
+ await post("/setup/local-models", { mode });
1113
+ localMode = mode;
1114
+ setMsg(localSaved, "ok", "Saved. The indexes adjust on the next search or check.");
980
1115
  } catch (error) {
981
- setMsg("local-models-msg", "error", error.message);
1116
+ checkRadio("local_models", localMode);
1117
+ setMsg(localSaved, "error", error.message);
982
1118
  }
983
1119
  });
1120
+ async function loadLocalModels() {
1121
+ try {
1122
+ const data = await getJSON("/setup/local-models");
1123
+ localMode = data.mode;
1124
+ checkRadio("local_models", data.mode);
1125
+ if (!data.sidecar.configured) setPill("local-pill", "idle", "No sidecar on this machine");
1126
+ else if (data.sidecar.embedding_model) setPill("local-pill", "ok", "Sidecar answering: " + data.sidecar.embedding_model);
1127
+ else setPill("local-pill", "warn", "Sidecar not answering (" + data.sidecar.url + ")");
1128
+ } catch (error) {
1129
+ setPill("local-pill", "bad", "Status unavailable");
1130
+ setMsg(localSaved, "error", error.message);
1131
+ }
1132
+ }
1133
+
1134
+ const RULES = [
1135
+ { key: "hook_mode", title: "Redirect behavior", applies: "Applies on the next tool call.",
1136
+ intro: "What the hook does when an agent reaches for a native search or web tool that Smart Tool covers.",
1137
+ options: [["redirect", "Redirect", "Stop the native tool and tell the agent which Smart Tool call to make instead.", true],
1138
+ ["advise", "Advise only", "Let the native tool run and tell the agent what Smart Tool would have done."],
1139
+ ["off", "Off", "No routing; agents use their native tools as usual."]] },
1140
+ { key: "doc_mode", title: "Documentation on edit", applies: "Applies on the next edit.",
1141
+ intro: "Checks the public functions an edit touches. Private, nested and override functions are exempt, as in pydocstyle, eslint-plugin-jsdoc and Checkstyle. A documented function comes up again only when its signature changes.",
1142
+ options: [["remind", "Remind", "The edit runs; the agent is told which touched functions lack a docstring.", true],
1143
+ ["require", "Require", "An edit that leaves a touched function without a docstring is blocked until it adds one."],
1144
+ ["off", "Off", "No documentation checks."]] },
1145
+ { key: "duplicate_mode", title: "Duplicate functions on edit", applies: "Applies on the next edit.",
1146
+ intro: "Compares the functions an edit writes with the indexed code: identical bodies, and near-identical ones with only local names changed. It never blocks.",
1147
+ options: [["warn", "Warn", "The edit runs; the agent is told when a function copies one already in the project.", true],
1148
+ ["off", "Off", "No duplicate checks."]] },
1149
+ { key: "pattern_proposals", title: "Block patterns proposed by a model", applies: "Applies to the next review.",
1150
+ intro: "Afterwards, never delaying a call, the scope model (else the router model) reviews searches the fixed rule let through and may propose block patterns. Nothing blocks until you accept it on the Redirects page.",
1151
+ options: [["on", "On", "Review in the background and list proposals for you.", true],
1152
+ ["off", "Off", "No review and no proposals."]] },
1153
+ ];
1154
+ function renderRules() {
1155
+ const card = $("rules-card");
1156
+ if (card.dataset.built) {
1157
+ for (const rule of RULES) checkRadio(rule.key, loaded.integration[rule.key]);
1158
+ return;
1159
+ }
1160
+ card.dataset.built = "1";
1161
+ card.replaceChildren();
1162
+ for (const rule of RULES) {
1163
+ const fieldset = node("fieldset", "choice");
1164
+ fieldset.appendChild(node("legend", "", rule.title));
1165
+ fieldset.appendChild(node("p", "choice-intro", rule.intro));
1166
+ const saved = choiceGroup(fieldset, rule.key, rule.options, loaded.integration[rule.key], async (mode) => {
1167
+ setMsg(saved, "", "Saving…");
1168
+ try {
1169
+ await post("/setup/integration", { action: rule.key, mode });
1170
+ loaded.integration[rule.key] = mode;
1171
+ loaded.integration[rule.key + "_error"] = "";
1172
+ setMsg(saved, "ok", "Saved. " + rule.applies);
1173
+ renderOverview();
1174
+ } catch (error) {
1175
+ checkRadio(rule.key, loaded.integration[rule.key]);
1176
+ setMsg(saved, "error", error.message);
1177
+ }
1178
+ });
1179
+ if (loaded.integration[rule.key + "_error"]) setMsg(saved, "error", loaded.integration[rule.key + "_error"]);
1180
+ card.appendChild(fieldset);
1181
+ }
1182
+ }
984
1183
 
985
- function browserText(item) {
986
- if (item.browser_control_error) return "Browser control status unreadable: " + item.browser_control_error;
1184
+ function browserState(item) {
1185
+ if (item.browser_control_error) return ["bad", "Unreadable", "Browser control status unreadable: " + item.browser_control_error];
987
1186
  const state = item.browser_control || {};
988
- if (state.state === "registered") return "Browser control on: Playwright MCP drives an isolated, headless Chromium";
989
- if (state.state === "kept") return "Browser control: your own playwright MCP server is kept";
990
- if (state.state === "undenied") return "Browser control is registered without its safety rule: " + state.reason;
991
- if (state.state === "unavailable") return "Browser control unavailable on this machine (" + state.reason + "); pages are still read by web_fetch";
992
- return "Browser control is set up when the MCP is registered";
1187
+ if (state.state === "registered") return ["ok", "On", "Agents can open pages in an isolated, headless Chromium through the Playwright MCP server."];
1188
+ if (state.state === "kept") return ["ok", "Your own server", "Your own playwright MCP server is kept as it is."];
1189
+ if (state.state === "undenied") return ["bad", "Safety rule missing", "Browser control is registered without its safety rule: " + state.reason];
1190
+ if (state.state === "unavailable") return ["idle", "Unavailable", "Not available on this machine (" + state.reason + "). Pages are still read by web_fetch."];
1191
+ return ["idle", "Not set up", "Set up together with the connection."];
993
1192
  }
994
- async function loadAgents() {
995
- try {
996
- const resp = await fetch("/setup/integration");
997
- const data = await resp.json();
998
- if (!resp.ok || data.error) throw new Error(data.error);
999
- if (document.activeElement !== $("sel-hook-mode")) $("sel-hook-mode").value = data.hook_mode;
1000
- if (document.activeElement !== $("sel-doc-mode")) $("sel-doc-mode").value = data.doc_mode;
1001
- if (document.activeElement !== $("sel-duplicate-mode")) $("sel-duplicate-mode").value = data.duplicate_mode;
1002
- if (data.hook_mode_error) setMsg("agents-msg", "error", data.hook_mode_error);
1003
- if (data.doc_mode_error) setMsg("agents-msg", "error", data.doc_mode_error);
1004
- if (data.duplicate_mode_error) setMsg("agents-msg", "error", data.duplicate_mode_error);
1005
- if (document.activeElement !== $("sel-pattern-proposals")) $("sel-pattern-proposals").value = data.pattern_proposals;
1006
- if (data.pattern_proposals_error) setMsg("agents-msg", "error", data.pattern_proposals_error);
1007
- renderPatterns(data.block_patterns);
1008
- renderRedirects(data.redirects);
1009
- const list = $("agents-list");
1010
- list.textContent = "";
1011
- for (const item of data.clients) {
1012
- const row = document.createElement("div");
1013
- row.className = "provider";
1014
- const mcp = item.mcp_url ? "MCP registered: " + item.mcp_url : "smart-tool MCP not registered in this client";
1015
- const hook = item.hook_error ? "Hook unreadable: " + item.hook_error : item.hook ? "Hook installed and up to date" : "Hook missing or outdated";
1016
- row.innerHTML = `<div class="provider-head"><strong></strong><span class="state"></span></div><p class="hint mcp"></p><p class="hint browser"></p><p class="hint mono cmd"></p><p class="hint file"></p>
1017
- <div class="actions"><button type="button" class="register">Register MCP</button><button type="button" class="hook">Install or update hook</button><button type="button" class="quiet browser-retry">Set up browser control</button></div>
1018
- <div class="plan" hidden><span class="hint plan-file"></span><pre class="code-preview"></pre>
1019
- <div class="actions"><button type="button" class="confirm">Confirm and write</button><button type="button" class="quiet cancel">Cancel</button></div></div>`;
1020
- row.querySelector("strong").textContent = item.label;
1021
- row.querySelector(".state").textContent = hook;
1022
- row.querySelector(".mcp").textContent = mcp;
1023
- row.querySelector(".browser").textContent = browserText(item);
1024
- const retry = row.querySelector(".browser-retry");
1025
- retry.hidden = !item.mcp_url || ["registered", "kept"].includes((item.browser_control || {}).state);
1026
- retry.addEventListener("click", async () => {
1027
- retry.disabled = true;
1028
- setMsg("agents-msg", "", "Checking whether agents can drive a browser here…");
1029
- try {
1030
- const result = await post("/setup/integration", { client: item.client, action: "browser_control" });
1031
- setMsg("agents-msg", "ok", item.label + ": " + browserText({ browser_control: result.browser_control }));
1032
- await loadAgents();
1033
- } catch (error) {
1034
- setMsg("agents-msg", "error", error.message);
1035
- retry.disabled = false;
1036
- }
1037
- });
1038
- row.querySelector(".file").textContent = item.file;
1039
- row.querySelector(".cmd").textContent = item.mcp_url ? "" : "Or in a terminal: " + item.register_command;
1040
- const register = row.querySelector(".register");
1041
- register.hidden = Boolean(item.mcp_url);
1042
- register.addEventListener("click", async () => {
1043
- register.disabled = true;
1044
- setMsg("agents-msg", "", "Registering the MCP in " + item.label + "…");
1045
- try {
1046
- const result = await post("/setup/integration", { client: item.client, action: "register_mcp" });
1047
- setMsg("agents-msg", "ok", "MCP registered with: " + result.command + ". " + browserText({ browser_control: result.browser_control }) + ". Reconnect open sessions (/mcp).");
1048
- await loadAgents();
1049
- } catch (error) {
1050
- setMsg("agents-msg", "error", error.message);
1051
- register.disabled = false;
1052
- }
1053
- });
1054
- const button = row.querySelector(".hook");
1055
- const plan = row.querySelector(".plan");
1056
- button.hidden = Boolean(item.hook);
1057
- button.addEventListener("click", async () => {
1058
- setMsg("agents-msg", "", "Preparing the change…");
1193
+ const hookControls = {};
1194
+ function row(titleText, pillEl, text) {
1195
+ const el = node("div", "row");
1196
+ const title = node("div", "row-title");
1197
+ title.append(node("span", "", titleText), pillEl);
1198
+ const side = node("div", "row-side");
1199
+ const body = node("div", "row-text", text);
1200
+ el.append(title, side, body);
1201
+ return { el, side, body };
1202
+ }
1203
+ function agentCard(item) {
1204
+ const card = node("article", "card");
1205
+ const state = agentState(item);
1206
+ const head = node("div", "card-head");
1207
+ head.append(node("h3", "", item.label), pill(state.tone, state.label));
1208
+ const msg = node("div", "msg");
1209
+ msg.setAttribute("role", "status");
1210
+
1211
+ const mcp = row("Connection (MCP server)", item.mcp_url ? pill("ok", "Registered") : pill("bad", "Not registered"),
1212
+ item.mcp_url ? "Registered at " + item.mcp_url + ". Gives the agent smart_search, web_search and web_fetch."
1213
+ : "Not registered. Without it the agent has no smart_search, web_search or web_fetch.");
1214
+ if (!item.mcp_url) {
1215
+ const register = button("Connect", "primary", async () => {
1216
+ register.disabled = true;
1217
+ setMsg(msg, "", "Registering the MCP server in " + item.label + "…");
1218
+ try {
1219
+ const result = await post("/setup/integration", { client: item.client, action: "register_mcp" });
1220
+ await loadIntegration();
1221
+ setMsg(agentMsg(item.client), "ok", "Registered with: " + result.command + ". " + browserState({ browser_control: result.browser_control })[2]
1222
+ + " Reconnect open " + item.label + " sessions (/mcp) to see the tools.");
1223
+ } catch (error) {
1224
+ setMsg(msg, "error", error.message);
1225
+ register.disabled = false;
1226
+ }
1227
+ });
1228
+ mcp.side.appendChild(register);
1229
+ const manual = node("details", "more row-more");
1230
+ manual.append(node("summary", "", "Or run it yourself in a terminal"), node("pre", "code", item.register_command));
1231
+ mcp.el.appendChild(manual);
1232
+ }
1233
+
1234
+ const hookPill = item.hook_error ? pill("bad", "Unreadable") : item.hook_state === "current" ? pill("ok", "Up to date")
1235
+ : item.hook_state === "outdated" ? pill("warn", "Outdated") : pill("warn", "Not installed");
1236
+ const hook = row("Redirect hook", hookPill, item.hook_error ? "Could not read " + item.file + ": " + item.hook_error
1237
+ : "Runs before the agent's own search and web tools: folder searches go to smart_search, web lookups to web_search and web_fetch, so the agent reads less. It lives in " + item.file + ".");
1238
+ if (item.hook_state === "outdated") {
1239
+ const why = node("div", "callout");
1240
+ why.append(node("strong", "", "Why update: "), document.createTextNode("this entry was written by an older Smart Tool version."));
1241
+ const list = node("ul");
1242
+ for (const change of item.hook_changes) list.appendChild(node("li", "", change));
1243
+ why.append(list, node("div", "", "Updating rewrites only Smart Tool's entry. Your other hooks stay as they are, and the file is backed up first."));
1244
+ hook.body.appendChild(why);
1245
+ } else if (item.hook_state === "missing" && !item.hook_error) {
1246
+ hook.body.appendChild(node("div", "callout info", "Installing adds one entry to this file. Your other hooks stay as they are, and the file is backed up first."));
1247
+ }
1248
+ const docs = node("a", "", "How " + item.label + " hooks work");
1249
+ docs.href = item.docs;
1250
+ docs.target = "_blank";
1251
+ docs.rel = "noopener noreferrer";
1252
+ const docsLine = node("div", "hint");
1253
+ docsLine.style.marginTop = "6px";
1254
+ docsLine.appendChild(docs);
1255
+ hook.body.appendChild(docsLine);
1256
+
1257
+ const confirm = node("div", "confirm-box row-more");
1258
+ confirm.hidden = true;
1259
+ const confirmFile = node("p", "mono");
1260
+ const preview = node("pre", "code");
1261
+ const exact = node("details", "more");
1262
+ exact.append(node("summary", "", "Show the exact entry that will be written"), preview);
1263
+ const confirmMsg = node("div", "msg");
1264
+ confirmMsg.setAttribute("role", "status");
1265
+ const write = button("Confirm and write", "primary");
1266
+ const cancel = button("Cancel", "");
1267
+ const confirmActions = node("div", "actions");
1268
+ confirmActions.append(write, cancel);
1269
+ confirm.append(node("p", "", "Review the change, then confirm. The preview is valid for 10 minutes."), confirmFile, exact, confirmMsg, confirmActions);
1270
+ if (item.after_install) confirm.appendChild(node("p", "callout info", "After writing: " + item.after_install));
1271
+ hook.el.appendChild(confirm);
1272
+
1273
+ const hookLabel = item.hook_state === "outdated" ? "Update hook" : "Install hook";
1274
+ const start = button(hookLabel, "primary");
1275
+ start.hidden = item.hook_state === "current" || Boolean(item.hook_error) || item.hook_state === null;
1276
+ hook.side.appendChild(start);
1277
+ async function openPreview() {
1278
+ start.disabled = true;
1279
+ setMsg(msg, "", "Preparing the change…");
1280
+ try {
1281
+ const plan = await post("/setup/integration", { client: item.client, action: "preview" });
1282
+ setMsg(msg, "", "");
1283
+ if (plan.installed) { await loadIntegration(); return; }
1284
+ confirmFile.textContent = (item.hook_state === "outdated" ? "Replaces Smart Tool's entry with this one under " : "Adds this entry under ") + plan.event + " in " + plan.file;
1285
+ preview.textContent = JSON.stringify(plan.change, null, 2);
1286
+ confirm.hidden = false;
1287
+ start.hidden = true;
1288
+ setMsg(confirmMsg, "", "");
1289
+ write.disabled = false;
1290
+ write.onclick = async () => {
1291
+ write.disabled = true;
1292
+ setMsg(confirmMsg, "", "Writing…");
1059
1293
  try {
1060
- const preview = await post("/setup/integration", { client: item.client, action: "preview" });
1061
- row.querySelector(".plan-file").textContent = "Entry added to " + preview.file + " (the file is backed up first):";
1062
- row.querySelector(".code-preview").textContent = JSON.stringify(preview.change, null, 2);
1063
- plan.hidden = false;
1064
- button.hidden = true;
1065
- setMsg("agents-msg", "", "");
1066
- row.querySelector(".confirm").onclick = async () => {
1067
- try {
1068
- const result = await post("/setup/integration", { client: item.client, action: "install", token: preview.token });
1069
- setMsg("agents-msg", "ok", item.label + ": hook written. Backup: " + (result.backup || "new file") + (result.after_install ? ". " + result.after_install : ""));
1070
- await loadAgents();
1071
- } catch (error) {
1072
- setMsg("agents-msg", "error", error.message);
1073
- }
1074
- };
1294
+ const result = await post("/setup/integration", { client: item.client, action: "install", token: plan.token });
1295
+ await loadIntegration();
1296
+ setMsg(agentMsg(item.client), "ok", "Hook written. Backup: " + (result.backup || "none, the file was new") + "."
1297
+ + (result.after_install ? " " + result.after_install : ""));
1075
1298
  } catch (error) {
1076
- setMsg("agents-msg", "error", error.message);
1299
+ setMsg(confirmMsg, "error", error.message);
1300
+ write.disabled = false;
1077
1301
  }
1078
- });
1079
- row.querySelector(".cancel").addEventListener("click", () => { plan.hidden = true; button.hidden = false; });
1080
- list.appendChild(row);
1302
+ };
1303
+ write.focus();
1304
+ } catch (error) {
1305
+ setMsg(msg, "error", error.message);
1306
+ } finally {
1307
+ start.disabled = false;
1081
1308
  }
1082
- } catch (error) {
1083
- setMsg("agents-msg", "error", "Agent status unavailable: " + error.message);
1084
1309
  }
1310
+ start.addEventListener("click", openPreview);
1311
+ cancel.addEventListener("click", () => { confirm.hidden = true; start.hidden = false; start.focus(); });
1312
+ hookControls[item.client] = () => { card.scrollIntoView({ block: "start" }); if (!start.hidden) openPreview(); };
1313
+
1314
+ const [browserTone, browserLabel, browserText] = browserState(item);
1315
+ const browser = row("Browser control", pill(browserTone, browserLabel), browserText);
1316
+ if (item.mcp_url && !["registered", "kept"].includes((item.browser_control || {}).state)) {
1317
+ const retry = button("Set up", "", async () => {
1318
+ retry.disabled = true;
1319
+ setMsg(msg, "", "Checking whether agents can drive a browser here…");
1320
+ try {
1321
+ const result = await post("/setup/integration", { client: item.client, action: "browser_control" });
1322
+ await loadIntegration();
1323
+ setMsg(agentMsg(item.client), "ok", browserState({ browser_control: result.browser_control })[2]);
1324
+ } catch (error) {
1325
+ setMsg(msg, "error", error.message);
1326
+ retry.disabled = false;
1327
+ }
1328
+ });
1329
+ browser.side.appendChild(retry);
1330
+ }
1331
+ msg.dataset.client = item.client;
1332
+ card.append(head, msg, mcp.el, hook.el, browser.el);
1333
+ return card;
1085
1334
  }
1335
+ function agentMsg(client) { return document.querySelector(`#agents-list .msg[data-client="${client}"]`); }
1336
+
1337
+ function renderAgents() {
1338
+ const list = $("agents-list");
1339
+ list.replaceChildren(...loaded.integration.clients.map(agentCard));
1340
+ }
1341
+
1342
+ function bars(entries) {
1343
+ const list = node("ul", "bars");
1344
+ const top = Math.max(1, ...entries.map(([, count]) => count));
1345
+ for (const [name, count] of entries) {
1346
+ const item = node("li");
1347
+ const bar = node("span", "bar");
1348
+ const fill = node("span");
1349
+ fill.style.width = Math.round(count / top * 100) + "%";
1350
+ bar.appendChild(fill);
1351
+ item.append(node("span", "name", name), bar, node("span", "num", String(count)));
1352
+ list.appendChild(item);
1353
+ }
1354
+ return list;
1355
+ }
1356
+ function tile(value, label) {
1357
+ const el = node("div", "tile");
1358
+ el.append(node("div", "value", String(value)), node("div", "label", label));
1359
+ return el;
1360
+ }
1361
+ function renderRedirects(stats) {
1362
+ const card = $("redirects-card");
1363
+ card.replaceChildren(node("h3", "", "Native searches redirected"),
1364
+ node("p", "lede", "Last " + stats.days + " days. After each redirect, Smart Tool looks at the same session's next call to see whether the agent followed it."));
1365
+ if (!stats.total) { card.appendChild(node("p", "", "No native search was redirected in the last " + stats.days + " days.")); return; }
1366
+ const out = stats.outcomes, tokens = stats.tokens_per_call;
1367
+ const tiles = node("div", "tiles");
1368
+ tiles.append(tile(stats.total, "redirected"), tile(out.followed || 0, "then used smart_search"),
1369
+ tile(out.native || 0, "then ran an allowed native call"), tile(out.blocked_again || 0, "blocked again"),
1370
+ tile(out.no_other_call || 0, "no other call within 15 min"));
1371
+ card.appendChild(tiles);
1372
+ if (out.unknown) card.appendChild(node("p", "hint", plural(out.unknown, "redirect") + " had no session logged, so their next call is unknown."));
1373
+ const byTool = Object.entries(stats.by_tool).sort((a, b) => b[1] - a[1]);
1374
+ if (byTool.length) card.append(node("h4", "", "By tool"), bars(byTool));
1375
+ const byReason = Object.entries(stats.by_reason).sort((a, b) => b[1] - a[1]);
1376
+ if (byReason.length) card.append(node("h4", "", "By reason"), bars(byReason));
1377
+ card.appendChild(node("p", "hint", "Context per call, measured over " + plural(tokens.measured, "call") + ": a native call of the kinds redirected costs about "
1378
+ + tokens.native_redirected + " tokens; a smart_search round trip about " + tokens.smart_search
1379
+ + " tokens. A redirect saves context only when one smart_search replaces several native searches and reads; that part is not measured yet."));
1380
+ }
1381
+
1086
1382
  const PATTERN_PAGE_SIZE = 8;
1087
1383
  const patternView = { page: 0, filter: "", sort: "impact", selected: new Set(), open: false };
1088
1384
  let lastPatterns = null;
@@ -1099,26 +1395,22 @@ function patternPage(items, view) {
1099
1395
  matched: sorted.length, total: items.length,
1100
1396
  calls: items.reduce((sum, item) => sum + (item.history_matches || 0), 0) };
1101
1397
  }
1102
- function patternEl(tag, className, text) {
1103
- const el = document.createElement(tag);
1104
- if (className) el.className = className;
1105
- if (text !== undefined) el.textContent = text;
1106
- return el;
1107
- }
1108
1398
  async function decidePatterns(ids, decision, label) {
1109
1399
  try {
1110
1400
  const result = await post("/setup/integration", { action: "block_patterns", ids, decision });
1111
1401
  for (const id of ids) patternView.selected.delete(id);
1402
+ loaded.integration = result;
1112
1403
  renderPatterns(result.block_patterns);
1113
- setMsg("agents-msg", "ok", label + ": " + ids.length + " pattern(s).");
1404
+ renderOverview();
1405
+ setMsg("patterns-msg", "ok", label + ": " + plural(ids.length, "pattern") + ".");
1114
1406
  } catch (error) {
1115
- setMsg("agents-msg", "error", error.message);
1407
+ setMsg("patterns-msg", "error", error.message);
1116
1408
  }
1117
1409
  }
1118
1410
  function patternRow(item, actions, selectable) {
1119
- const row = patternEl("li", "pattern-row");
1411
+ const entry = node("li", "pattern-row" + (selectable ? "" : " plain"));
1120
1412
  if (selectable) {
1121
- const check = patternEl("input");
1413
+ const check = node("input");
1122
1414
  check.type = "checkbox";
1123
1415
  check.checked = patternView.selected.has(item.id);
1124
1416
  check.setAttribute("aria-label", "Select " + item.pattern);
@@ -1126,67 +1418,42 @@ function patternRow(item, actions, selectable) {
1126
1418
  if (check.checked) patternView.selected.add(item.id); else patternView.selected.delete(item.id);
1127
1419
  renderPatterns(lastPatterns);
1128
1420
  });
1129
- row.appendChild(check);
1421
+ entry.appendChild(check);
1130
1422
  }
1131
- const body = patternEl("details", "pattern-body");
1132
- const summary = patternEl("summary");
1133
- const code = patternEl("code", "pattern-code", item.pattern);
1423
+ const body = node("details", "pattern-body");
1424
+ const summary = node("summary");
1425
+ const code = node("code", "pattern-code", item.pattern);
1134
1426
  code.title = item.pattern;
1135
- summary.append(patternEl("span", "pattern-tool", item.tool), code);
1136
- const detail = patternEl("div", "pattern-detail");
1137
- detail.append(patternEl("p", "", item.reason), patternEl("p", "hint mono", "Example: " + item.example),
1138
- patternEl("p", "hint mono", item.pattern));
1427
+ summary.append(node("span", "pattern-tool", item.tool), code);
1428
+ const detail = node("div", "pattern-detail");
1429
+ detail.append(node("p", "", item.reason), node("p", "hint mono", "Example: " + item.example), node("p", "hint mono", item.pattern));
1139
1430
  body.append(summary, detail);
1140
- const reach = patternEl("span", "pattern-reach", item.history_total ? item.history_matches + " / " + item.history_total : "–");
1141
- reach.title = item.history_total ? "Would have blocked " + item.history_matches + " of " + item.history_total + " logged " + item.tool + " calls" : "No logged calls to compare";
1142
- const buttons = patternEl("span", "pattern-actions");
1143
- for (const [decision, label] of actions) {
1144
- const button = patternEl("button", "quiet", label);
1145
- button.type = "button";
1146
- button.addEventListener("click", () => decidePatterns([item.id], decision, label));
1147
- buttons.appendChild(button);
1148
- }
1149
- const meta = patternEl("div", "pattern-meta");
1431
+ const reach = node("span", "pattern-reach", item.history_total ? "would block " + item.history_matches + " of " + item.history_total + " logged " + item.tool + " calls" : "no logged calls to compare");
1432
+ const buttons = node("span", "actions");
1433
+ buttons.style.marginTop = "0";
1434
+ for (const [decision, label] of actions) buttons.appendChild(button(label, "small", () => decidePatterns([item.id], decision, label)));
1435
+ const meta = node("div", "pattern-meta");
1150
1436
  meta.append(reach, buttons);
1151
- const main = patternEl("div", "pattern-main");
1437
+ const main = node("div");
1152
1438
  main.append(body, meta);
1153
- row.appendChild(main);
1154
- return row;
1155
- }
1156
- function renderRedirects(stats) {
1157
- const panel = $("redirects-panel");
1158
- panel.textContent = "";
1159
- panel.append(patternEl("h3", "", "Native searches redirected (last " + stats.days + " days): " + stats.total));
1160
- const out = stats.outcomes, tokens = stats.tokens_per_call;
1161
- const lines = [
1162
- "By tool: " + (Object.entries(stats.by_tool).map(([k, v]) => k + " " + v).join(", ") || "none"),
1163
- "Next call of the same session: smart_search " + (out.followed || 0) + ", allowed native call " + (out.native || 0)
1164
- + ", blocked again " + (out.blocked_again || 0) + ", none within 15 min " + (out.no_other_call || 0)
1165
- + ", unknown (no session logged) " + (out.unknown || 0),
1166
- "Context per call (measured " + tokens.measured + "): a native call of the kinds redirected ~" + tokens.native_redirected
1167
- + " tokens; a smart_search round trip ~" + tokens.smart_search + " tokens. A redirect saves context only when one"
1168
- + " smart_search replaces several native searches and reads; that part is not measured yet.",
1169
- ];
1170
- for (const line of lines) panel.append(patternEl("p", "hint", line));
1171
- for (const [reason, count] of Object.entries(stats.by_reason)) panel.append(patternEl("p", "hint mono", count + " × " + reason));
1439
+ entry.appendChild(main);
1440
+ return entry;
1172
1441
  }
1173
1442
  function renderPatterns(patterns) {
1174
1443
  lastPatterns = patterns;
1175
1444
  const box = $("patterns-list");
1176
- box.textContent = "";
1177
- if (patterns.error) { box.appendChild(patternEl("p", "msg error", patterns.error)); return; }
1445
+ box.replaceChildren();
1446
+ if (patterns.error) { box.appendChild(node("p", "msg error", patterns.error)); return; }
1178
1447
  const proposals = patterns.proposals;
1179
1448
  const live = new Set(proposals.map((item) => item.id));
1180
1449
  for (const id of [...patternView.selected]) if (!live.has(id)) patternView.selected.delete(id);
1181
- if (proposals.length) {
1450
+ if (!proposals.length) box.appendChild(node("p", "", "No proposal waiting for you."));
1451
+ else {
1182
1452
  const view = patternPage(proposals, patternView);
1183
1453
  patternView.page = view.page;
1184
- const panel = patternEl("div", "pattern-panel");
1185
- const head = patternEl("div", "pattern-head");
1186
- head.append(patternEl("strong", "", proposals.length + " proposed pattern(s) waiting"),
1187
- patternEl("span", "hint", "Together they would have blocked " + view.calls + " logged call(s). Open a row for its reason and example."));
1188
- const tools = patternEl("div", "pattern-tools");
1189
- const filter = patternEl("input");
1454
+ box.appendChild(node("p", "", plural(proposals.length, "proposal") + " waiting. Together they would have blocked " + plural(view.calls, "logged call") + ". Open a row for its reason and an example."));
1455
+ const tools = node("div", "pattern-tools");
1456
+ const filter = node("input");
1190
1457
  filter.type = "text";
1191
1458
  filter.placeholder = "Filter by pattern, reason or example";
1192
1459
  filter.value = patternView.filter;
@@ -1198,103 +1465,189 @@ function renderPatterns(patterns) {
1198
1465
  const again = document.querySelector(".pattern-tools input[type=text]");
1199
1466
  if (again) { again.focus(); again.setSelectionRange(again.value.length, again.value.length); }
1200
1467
  });
1201
- const sort = patternEl("select");
1468
+ const sort = node("select");
1202
1469
  sort.setAttribute("aria-label", "Order of proposed patterns");
1203
- for (const [value, label] of [["impact", "Most blocked calls first"], ["newest", "Newest first"]]) {
1204
- const option = patternEl("option", "", label);
1205
- option.value = value;
1206
- sort.appendChild(option);
1207
- }
1470
+ for (const [value, label] of [["impact", "Most blocked calls first"], ["newest", "Newest first"]]) sort.appendChild(new Option(label, value));
1208
1471
  sort.value = patternView.sort;
1209
1472
  sort.addEventListener("change", () => { patternView.sort = sort.value; patternView.page = 0; renderPatterns(lastPatterns); });
1210
1473
  tools.append(filter, sort);
1211
- const bulk = patternEl("div", "actions pattern-bulk");
1474
+ const bulk = node("div", "actions");
1212
1475
  const pageIds = view.rows.map((item) => item.id);
1213
1476
  const allOnPage = pageIds.length > 0 && pageIds.every((id) => patternView.selected.has(id));
1214
- const selectPage = patternEl("button", "quiet", allOnPage ? "Clear this page" : "Select this page");
1215
- selectPage.type = "button";
1216
- selectPage.disabled = !pageIds.length;
1217
- selectPage.addEventListener("click", () => {
1477
+ const selectPage = button(allOnPage ? "Clear this page" : "Select this page", "", () => {
1218
1478
  for (const id of pageIds) if (allOnPage) patternView.selected.delete(id); else patternView.selected.add(id);
1219
1479
  renderPatterns(lastPatterns);
1220
1480
  });
1481
+ selectPage.disabled = !pageIds.length;
1221
1482
  const count = patternView.selected.size;
1222
- const accept = patternEl("button", "", "Accept selected (" + count + ")");
1223
- const reject = patternEl("button", "quiet", "Reject selected (" + count + ")");
1224
- for (const [button, decision, label] of [[accept, "accept", "Accepted"], [reject, "reject", "Rejected"]]) {
1225
- button.type = "button";
1226
- button.disabled = !count;
1227
- button.addEventListener("click", () => decidePatterns([...patternView.selected], decision, label));
1228
- }
1483
+ const accept = button("Accept selected (" + count + ")", "primary", () => decidePatterns([...patternView.selected], "accept", "Accepted"));
1484
+ const reject = button("Reject selected (" + count + ")", "", () => decidePatterns([...patternView.selected], "reject", "Rejected"));
1485
+ accept.disabled = reject.disabled = !count;
1229
1486
  bulk.append(selectPage, accept, reject);
1230
- const list = patternEl("ul", "pattern-list");
1487
+ const list = node("ul", "pattern-list");
1231
1488
  for (const item of view.rows) list.appendChild(patternRow(item, [["accept", "Accept"], ["reject", "Reject"]], true));
1232
- if (!view.rows.length) list.appendChild(patternEl("li", "hint", "No proposal matches the filter."));
1233
- const pager = patternEl("div", "actions pattern-pager");
1234
- const prev = patternEl("button", "quiet", "Previous");
1235
- const next = patternEl("button", "quiet", "Next");
1236
- prev.type = "button";
1237
- next.type = "button";
1489
+ if (!view.rows.length) list.appendChild(node("li", "hint", "No proposal matches the filter."));
1490
+ const pager = node("div", "actions pager");
1491
+ const prev = button("Previous", "", () => { patternView.page -= 1; renderPatterns(lastPatterns); });
1492
+ const next = button("Next", "", () => { patternView.page += 1; renderPatterns(lastPatterns); });
1238
1493
  prev.disabled = view.page === 0;
1239
1494
  next.disabled = view.page >= view.pages - 1;
1240
- prev.addEventListener("click", () => { patternView.page -= 1; renderPatterns(lastPatterns); });
1241
- next.addEventListener("click", () => { patternView.page += 1; renderPatterns(lastPatterns); });
1242
1495
  const first = view.page * PATTERN_PAGE_SIZE;
1243
1496
  const shown = view.matched ? (first + 1) + "–" + (first + view.rows.length) : "0";
1244
1497
  const filtered = view.matched < view.total ? " (filtered from " + view.total + ")" : "";
1245
- pager.append(prev, patternEl("span", "hint", shown + " of " + view.matched + filtered + " · page " + (view.page + 1) + " of " + view.pages), next);
1246
- panel.append(head, tools, bulk, list, pager);
1247
- box.appendChild(panel);
1498
+ pager.append(prev, node("span", "hint", shown + " of " + view.matched + filtered + " · page " + (view.page + 1) + " of " + view.pages), next);
1499
+ box.append(tools, bulk, list, pager);
1248
1500
  }
1249
1501
  if (patterns.accepted.length) {
1250
- const blocking = patternEl("details", "pattern-blocking");
1502
+ const blocking = node("details", "more");
1251
1503
  blocking.open = patternView.open;
1252
1504
  blocking.addEventListener("toggle", () => { patternView.open = blocking.open; });
1253
- blocking.appendChild(patternEl("summary", "", "Blocking patterns (" + patterns.accepted.length + ")"));
1254
- const list = patternEl("ul", "pattern-list");
1505
+ blocking.appendChild(node("summary", "", "Patterns you accepted, blocking now (" + patterns.accepted.length + ")"));
1506
+ const list = node("ul", "pattern-list");
1255
1507
  for (const item of patterns.accepted) list.appendChild(patternRow(item, [["remove", "Remove"]], false));
1256
1508
  blocking.appendChild(list);
1257
1509
  box.appendChild(blocking);
1258
1510
  }
1259
- if (patterns.rejected) box.appendChild(patternEl("p", "hint", patterns.rejected + " rejected proposal(s) are not offered again."));
1511
+ if (patterns.rejected) box.appendChild(node("p", "hint", plural(patterns.rejected, "rejected proposal") + " not offered again."));
1260
1512
  }
1261
- loadAgents();
1262
- $("btn-save-pattern-proposals").addEventListener("click", async () => {
1513
+
1514
+ async function loadIntegration() {
1263
1515
  try {
1264
- await post("/setup/integration", { action: "pattern_proposals", mode: $("sel-pattern-proposals").value });
1265
- setMsg("agents-msg", "ok", "Proposals setting saved.");
1516
+ loaded.integration = await getJSON("/setup/integration");
1517
+ delete failed.integration;
1518
+ renderAgents();
1519
+ renderRules();
1520
+ renderRedirects(loaded.integration.redirects);
1521
+ renderPatterns(loaded.integration.block_patterns);
1266
1522
  } catch (error) {
1267
- setMsg("agents-msg", "error", error.message);
1523
+ failed.integration = "Agent status unavailable: " + error.message;
1524
+ setMsg("agents-msg", "error", failed.integration);
1525
+ $("rules-card").replaceChildren(node("p", "msg error", failed.integration));
1526
+ $("redirects-card").replaceChildren(node("p", "msg error", failed.integration));
1268
1527
  }
1269
- });
1270
- $("btn-save-doc-mode").addEventListener("click", async () => {
1528
+ renderOverview();
1529
+ }
1530
+
1531
+ async function loadAutostart() {
1271
1532
  try {
1272
- await post("/setup/integration", { action: "doc_mode", mode: $("sel-doc-mode").value });
1273
- setMsg("agents-msg", "ok", "Documentation setting saved; it applies on the next edit.");
1533
+ loaded.autostart = await getJSON("/setup/autostart");
1534
+ const on = loaded.autostart.installed;
1535
+ setPill("autostart-pill", on ? "ok" : "idle", on ? "On, via " + (loaded.autostart.method === "task" ? "Scheduled Task" : "Startup folder") : "Off");
1536
+ const toggle = $("btn-autostart-toggle");
1537
+ toggle.disabled = false;
1538
+ toggle.className = on ? "" : "primary";
1539
+ toggle.textContent = on ? "Turn off" : "Turn on";
1274
1540
  } catch (error) {
1275
- setMsg("agents-msg", "error", error.message);
1541
+ setPill("autostart-pill", "bad", "Status unavailable");
1542
+ setMsg("autostart-msg", "error", error.message);
1276
1543
  }
1277
- });
1278
- $("btn-save-duplicate-mode").addEventListener("click", async () => {
1544
+ renderOverview();
1545
+ }
1546
+ $("btn-autostart-toggle").addEventListener("click", async () => {
1547
+ const action = loaded.autostart.installed ? "remove" : "install";
1548
+ $("btn-autostart-toggle").disabled = true;
1549
+ setMsg("autostart-msg", "", action === "install" ? "Turning on…" : "Turning off…");
1279
1550
  try {
1280
- await post("/setup/integration", { action: "duplicate_mode", mode: $("sel-duplicate-mode").value });
1281
- setMsg("agents-msg", "ok", "Duplicate setting saved; it applies on the next edit.");
1551
+ const data = await post("/setup/autostart", { action });
1552
+ setMsg("autostart-msg", "ok", action === "install"
1553
+ ? (data.method === "task" ? "Turned on via Scheduled Task." : `Turned on via the Startup folder; the Scheduled Task was refused: ${data.fallback_reason || "no reason given"}.`)
1554
+ : "Turned off.");
1555
+ await loadAutostart();
1282
1556
  } catch (error) {
1283
- setMsg("agents-msg", "error", error.message);
1557
+ setMsg("autostart-msg", "error", error.message);
1558
+ $("btn-autostart-toggle").disabled = false;
1284
1559
  }
1285
1560
  });
1286
- $("btn-save-hook-mode").addEventListener("click", async () => {
1561
+
1562
+ const PROVIDER_STATES = { keyless: ["ok", "Free tier, no key"], configured: ["ok", "Your key"], unreadable: ["bad", "Key unreadable"] };
1563
+ function providerRow(name, info) {
1564
+ const entry = node("div", "provider-row");
1565
+ const [tone, label] = PROVIDER_STATES[info.status] || ["bad", info.status];
1566
+ const title = node("div", "row-title");
1567
+ title.append(node("span", "", info.label), pill(tone, label));
1568
+ const text = node("div", "row-text");
1569
+ text.append(node("div", "", "Without a key: " + info.free), node("div", "", "With your key: " + info.keyed));
1570
+ if (info.status === "unreadable") text.appendChild(node("div", "msg error", "The saved key cannot be opened in this Windows profile; paste it again."));
1571
+ const side = node("div", "row-side");
1572
+ const form = node("div", "key-form");
1573
+ form.hidden = true;
1574
+ const field = node("div", "field");
1575
+ const input = node("input");
1576
+ input.type = "password";
1577
+ input.autocomplete = "new-password";
1578
+ input.id = name + "-key";
1579
+ input.placeholder = info.key_prefix ? `Paste the key (starts with ${info.key_prefix})` : "Paste the key from your account";
1580
+ const fieldLabel = node("label", "", info.label + " API key");
1581
+ fieldLabel.htmlFor = input.id;
1582
+ const signup = node("a", "", "Create a key in your " + info.label + " account");
1583
+ signup.href = info.signup;
1584
+ signup.target = "_blank";
1585
+ signup.rel = "noopener noreferrer";
1586
+ const hint = node("span", "hint");
1587
+ hint.appendChild(signup);
1588
+ field.append(fieldLabel, input, hint);
1589
+ const msg = node("div", "msg");
1590
+ msg.setAttribute("role", "status");
1591
+ const save = button("Test and save", "primary", async () => {
1592
+ if (!input.value.trim()) { setMsg(msg, "error", "Paste the API key before saving."); return; }
1593
+ save.disabled = true;
1594
+ setMsg(msg, "", "Testing the key with a real search…");
1595
+ try {
1596
+ const data = await post("/setup/providers", { provider: name, action: "save", api_key: input.value.trim() });
1597
+ await loadProviders(name, `Key accepted (${plural(data.validated_results, "result")} in the test) and protected on this Windows machine.`);
1598
+ } catch (error) {
1599
+ setMsg(msg, "error", error.message);
1600
+ save.disabled = false;
1601
+ }
1602
+ });
1603
+ const formActions = node("div", "actions");
1604
+ formActions.append(save, button("Cancel", "", () => { form.hidden = true; open.hidden = false; }));
1605
+ form.append(field, formActions);
1606
+ const open = button(info.status === "keyless" ? "Add key" : "Replace key", "", () => { form.hidden = false; open.hidden = true; input.focus(); });
1607
+ side.appendChild(open);
1608
+ if (info.status !== "keyless") {
1609
+ const remove = button("Remove key", "", async () => {
1610
+ remove.disabled = true;
1611
+ setMsg(msg, "", "Removing…");
1612
+ try {
1613
+ await post("/setup/providers", { provider: name, action: "remove" });
1614
+ await loadProviders(name, "Key removed; the free tier is active.");
1615
+ } catch (error) {
1616
+ setMsg(msg, "error", error.message);
1617
+ remove.disabled = false;
1618
+ }
1619
+ });
1620
+ side.appendChild(remove);
1621
+ }
1622
+ msg.dataset.provider = name;
1623
+ entry.append(title, side, text, form, msg);
1624
+ return entry;
1625
+ }
1626
+ async function loadProviders(provider, message) {
1287
1627
  try {
1288
- await post("/setup/integration", { action: "hook_mode", mode: $("sel-hook-mode").value });
1289
- setMsg("agents-msg", "ok", "Hook behavior saved; it applies on the next tool call.");
1290
- await loadAgents();
1628
+ loaded.providers = await getJSON("/setup/providers");
1629
+ delete failed.providers;
1630
+ $("provider-list").replaceChildren(...Object.entries(loaded.providers.providers).map(([name, info]) => providerRow(name, info)));
1631
+ if (provider) setMsg(document.querySelector(`#provider-list .msg[data-provider="${provider}"]`), "ok", message);
1632
+ if (document.activeElement !== $("contact-input")) $("contact-input").value = loaded.providers.contact;
1633
+ $("contact-hint").textContent = "Sent as: " + loaded.providers.user_agent;
1291
1634
  } catch (error) {
1292
- setMsg("agents-msg", "error", error.message);
1635
+ failed.providers = "Provider status unavailable: " + error.message;
1636
+ $("provider-list").replaceChildren(node("p", "msg error", failed.providers));
1637
+ }
1638
+ renderOverview();
1639
+ }
1640
+ $("btn-save-contact").addEventListener("click", async () => {
1641
+ try {
1642
+ const data = await post("/setup/contact", { contact: $("contact-input").value.trim() });
1643
+ $("contact-hint").textContent = "Sent as: " + data.user_agent;
1644
+ setMsg("contact-msg", "ok", "Contact saved.");
1645
+ } catch (error) {
1646
+ setMsg("contact-msg", "error", error.message);
1293
1647
  }
1294
1648
  });
1295
1649
 
1296
- const AUDIT_SEVERITY = { error: "Error", warn: "Warning", info: "Note" };
1297
- let auditProjects = [];
1650
+ const AUDIT_SEVERITY = { error: ["bad", "Error"], warn: ["warn", "Warning"], info: ["idle", "Note"] };
1298
1651
  function auditWhen(seconds) {
1299
1652
  return seconds ? new Date(seconds * 1000).toLocaleString() : "never";
1300
1653
  }
@@ -1302,40 +1655,40 @@ function renderAudit(report) {
1302
1655
  const box = $("audit-report");
1303
1656
  box.replaceChildren();
1304
1657
  if (!report) {
1305
- box.appendChild(patternEl("p", "hint", "Not audited yet: the next scheduled run covers it, or press Run now."));
1658
+ box.appendChild(node("p", "hint", "Not audited yet: the next scheduled run covers it, or press Run now."));
1306
1659
  return;
1307
1660
  }
1308
1661
  const s = report.summary;
1309
- box.appendChild(patternEl("p", "", s.error + " error(s), " + s.warn + " warning(s), " + s.info + " note(s) · "
1662
+ box.appendChild(node("p", "", plural(s.error, "error") + ", " + plural(s.warn, "warning") + ", " + plural(s.info, "note") + " · "
1310
1663
  + (report.trigger === "schedule" ? "scheduled run" : "run on request") + " at " + auditWhen(report.checked_at)));
1311
1664
  const changes = report.changes;
1312
- if (changes) box.appendChild(patternEl("p", "hint", "Since the previous run: " + changes.new.length + " new, "
1665
+ if (changes) box.appendChild(node("p", "hint", "Since the previous run: " + changes.new.length + " new, "
1313
1666
  + changes.resolved.length + " resolved" + (changes.snapshot_changed ? " (configuration changed)." : ".")));
1314
- const list = patternEl("ul", "audit-list");
1667
+ const list = node("ul", "audit-list");
1315
1668
  for (const finding of report.findings) {
1316
- const row = patternEl("li", "audit-row");
1317
- const head = patternEl("div", "audit-head");
1318
- head.append(patternEl("span", "audit-sev audit-" + finding.severity, AUDIT_SEVERITY[finding.severity] || finding.severity),
1319
- patternEl("span", "pattern-tool", finding.harness), patternEl("strong", "", finding.subject));
1320
- if (finding.new) head.appendChild(patternEl("span", "audit-new", "new"));
1321
- const detail = patternEl("p", "audit-detail", finding.detail + " ");
1669
+ const entry = node("li", "audit-row");
1670
+ const head = node("div", "audit-head");
1671
+ const [tone, label] = AUDIT_SEVERITY[finding.severity] || ["idle", finding.severity];
1672
+ head.append(pill(tone, label), node("span", "pattern-tool", finding.harness), node("strong", "", finding.subject));
1673
+ if (finding.new) head.appendChild(node("span", "new-tag", "new"));
1674
+ const detail = node("p", "audit-detail", finding.detail + " ");
1322
1675
  if ((finding.source || "").startsWith("https://")) {
1323
- const link = patternEl("a", "", "documentation");
1676
+ const link = node("a", "", "documentation");
1324
1677
  link.setAttribute("href", finding.source);
1325
1678
  link.setAttribute("target", "_blank");
1326
1679
  link.setAttribute("rel", "noopener noreferrer");
1327
1680
  detail.appendChild(link);
1328
1681
  }
1329
- row.append(head, detail);
1330
- list.appendChild(row);
1682
+ entry.append(head, detail);
1683
+ list.appendChild(entry);
1331
1684
  }
1332
1685
  if (report.findings.length) box.appendChild(list);
1333
- else box.appendChild(patternEl("p", "msg ok", "No collision or broken piece found."));
1686
+ else box.appendChild(node("p", "msg ok", "No collision or broken piece found."));
1334
1687
  if (changes && changes.resolved.length) {
1335
- const resolved = patternEl("details", "");
1336
- resolved.appendChild(patternEl("summary", "", "Resolved since the previous run (" + changes.resolved.length + ")"));
1337
- const items = patternEl("ul", "audit-list");
1338
- for (const finding of changes.resolved) items.appendChild(patternEl("li", "audit-detail", finding.subject + ": " + finding.detail));
1688
+ const resolved = node("details", "more");
1689
+ resolved.appendChild(node("summary", "", "Resolved since the previous run (" + changes.resolved.length + ")"));
1690
+ const items = node("ul", "audit-list");
1691
+ for (const finding of changes.resolved) items.appendChild(node("li", "audit-detail", finding.subject + ": " + finding.detail));
1339
1692
  resolved.appendChild(items);
1340
1693
  box.appendChild(resolved);
1341
1694
  }
@@ -1345,11 +1698,11 @@ function renderAudit(report) {
1345
1698
  if (servers.length) costs.push(side + ": " + servers.map((m) => m.name + " " + m.tools + " tools (~"
1346
1699
  + Math.round(m.tool_chars / 4).toLocaleString() + " tokens)").join(", "));
1347
1700
  }
1348
- if (costs.length) box.appendChild(patternEl("p", "hint", "MCP tools offered — " + costs.join(" · ")));
1349
- const unverified = patternEl("details", "");
1350
- unverified.appendChild(patternEl("summary", "", "Not verified (" + report.unverified.length + ")"));
1351
- const items = patternEl("ul", "audit-list");
1352
- for (const item of report.unverified) items.appendChild(patternEl("li", "audit-detail", item));
1701
+ if (costs.length) box.appendChild(node("p", "hint", "MCP tools offered — " + costs.join(" · ")));
1702
+ const unverified = node("details", "more");
1703
+ unverified.appendChild(node("summary", "", "Not verified (" + report.unverified.length + ")"));
1704
+ const items = node("ul", "audit-list");
1705
+ for (const item of report.unverified) items.appendChild(node("li", "audit-detail", item));
1353
1706
  unverified.appendChild(items);
1354
1707
  box.appendChild(unverified);
1355
1708
  }
@@ -1363,126 +1716,102 @@ async function showAudit(root) {
1363
1716
  async function loadAudit() {
1364
1717
  try {
1365
1718
  const data = await post("/setup/audit", { action: "index" });
1366
- auditProjects = data.projects;
1719
+ loaded.audit = data;
1720
+ delete failed.audit;
1367
1721
  const select = $("sel-audit-project");
1368
- select.replaceChildren();
1369
- for (const root of data.projects) {
1722
+ select.replaceChildren(...data.projects.map((root) => {
1370
1723
  const entry = data.index[root];
1371
- const label = root + (entry ? " — " + entry.summary.error + " error(s), " + entry.summary.warn + " warning(s)" : " — not audited yet");
1372
- const option = patternEl("option", "", label);
1373
- option.value = root;
1374
- select.appendChild(option);
1375
- }
1376
- $("audit-hint").textContent = data.projects.length ? "Runs every " + Math.round(data.schedule_s / 60) + " minutes." : "Register a project to audit it.";
1724
+ return new Option(root + (entry ? " — " + plural(entry.summary.error, "error") + ", " + plural(entry.summary.warn, "warning") : " — not audited yet"), root);
1725
+ }));
1726
+ $("audit-hint").textContent = data.projects.length ? "Runs on its own every " + Math.round(data.schedule_s / 60) + " minutes." : "Register a project on the Projects page to audit it.";
1377
1727
  $("btn-audit-run").disabled = !data.projects.length;
1378
1728
  if (data.projects.length) {
1379
- const worst = data.projects.slice().sort((a, b) => ((data.index[b] || {summary: {error: -1}}).summary.error)
1380
- - ((data.index[a] || {summary: {error: -1}}).summary.error))[0];
1729
+ const worst = data.projects.slice().sort((a, b) => ((data.index[b] || { summary: { error: -1 } }).summary.error)
1730
+ - ((data.index[a] || { summary: { error: -1 } }).summary.error))[0];
1381
1731
  select.value = worst;
1382
1732
  await showAudit(worst);
1383
1733
  }
1384
1734
  } catch (error) {
1385
- setMsg("audit-msg", "error", "Setup audit unavailable: " + error.message);
1735
+ failed.audit = "Setup audit unavailable: " + error.message;
1736
+ setMsg("audit-msg", "error", failed.audit);
1386
1737
  }
1738
+ renderOverview();
1387
1739
  }
1388
- $("sel-audit-project").addEventListener("change", () => showAudit($("sel-audit-project").value));
1389
- $("btn-audit-run").addEventListener("click", async () => {
1390
- const button = $("btn-audit-run");
1391
- button.disabled = true;
1392
- setMsg("audit-msg", "", "Auditing; MCP servers are being contacted…");
1740
+ async function loadAuditHook() {
1393
1741
  try {
1394
- renderAudit((await post("/setup/audit", { action: "run", project_root: $("sel-audit-project").value })).report);
1395
- setMsg("audit-msg", "ok", "Audit finished.");
1742
+ const hook = await post("/setup/audit", { action: "hook_state" });
1743
+ $("audit-hook-file").textContent = hook.file;
1744
+ const on = hook.state === "current";
1745
+ const pillEl = $("audit-hook-pill");
1746
+ pillEl.textContent = on ? "On" : hook.state === "outdated" ? "Outdated" : "Off";
1747
+ pillEl.dataset.tone = on ? "ok" : hook.state === "outdated" ? "warn" : "idle";
1748
+ $("btn-audit-hook-on").hidden = on;
1749
+ $("btn-audit-hook-on").textContent = hook.state === "outdated" ? "Update" : "Turn on";
1750
+ $("btn-audit-hook-off").hidden = hook.state === "missing";
1396
1751
  } catch (error) {
1397
- setMsg("audit-msg", "error", error.message);
1398
- } finally {
1399
- button.disabled = false;
1752
+ setMsg("audit-hook-msg", "error", "Session-start report state unavailable: " + error.message);
1400
1753
  }
1401
- });
1402
- loadAudit();
1403
-
1404
- const providerLabels = { keyless: ["warn", "No key · free tier"], configured: ["ok", "Key configured"], unreadable: ["bad", "Key unreadable in this Windows profile"] };
1405
- function providerCard(name, info) {
1406
- const card = document.createElement("div");
1407
- card.className = "provider";
1408
- card.innerHTML = `
1409
- <div class="provider-head"><strong></strong><span class="state" aria-live="polite"></span></div>
1410
- <p class="hint free"></p><p class="hint keyed"></p>
1411
- <p class="hint"><a target="_blank" rel="noopener noreferrer">Create a key in your provider account</a></p>
1412
- <label>API key</label>
1413
- <input type="password" autocomplete="new-password">
1414
- <div class="actions"><button type="button" data-action="save">Validate and save</button><button type="button" class="quiet" data-action="remove">Remove key</button></div>
1415
- <div class="msg" role="status"></div>`;
1416
- card.querySelector("strong").textContent = info.label;
1417
- card.querySelector(".free").textContent = info.free;
1418
- card.querySelector(".keyed").textContent = info.keyed;
1419
- const link = card.querySelector("a");
1420
- link.href = info.signup;
1421
- const input = card.querySelector("input");
1422
- input.id = name + "-key";
1423
- card.querySelector("label").htmlFor = input.id;
1424
- input.placeholder = info.key_prefix ? `Paste the key (starts with ${info.key_prefix})` : "Paste the key from your account";
1425
- const [kind, label] = providerLabels[info.status] || ["bad", info.status];
1426
- Object.assign(card.querySelector(".state"), { textContent: label }).dataset.state = kind;
1427
- const msg = card.querySelector(".msg");
1428
- msg.id = name + "-msg";
1429
- card.querySelector('[data-action="remove"]').disabled = info.status === "keyless";
1430
- for (const button of card.querySelectorAll("button")) {
1431
- button.addEventListener("click", async () => {
1432
- const action = button.dataset.action;
1433
- if (action === "save" && !input.value.trim()) { setMsg(msg.id, "error", "Paste the API key before saving."); return; }
1434
- button.disabled = true;
1435
- setMsg(msg.id, "", action === "save" ? "Testing the key with a real search…" : "Removing…");
1754
+ }
1755
+ $("btn-audit-hook-on").addEventListener("click", async () => {
1756
+ setMsg("audit-hook-msg", "", "Preparing the change…");
1757
+ try {
1758
+ const plan = await post("/setup/audit", { action: "hook_preview" });
1759
+ setMsg("audit-hook-msg", "", "");
1760
+ $("audit-hook-where").textContent = "Adds this entry under " + plan.event + " in " + plan.file + ".";
1761
+ $("audit-hook-preview").textContent = JSON.stringify(plan.change, null, 2);
1762
+ $("audit-hook-confirm").hidden = false;
1763
+ $("btn-audit-hook-write").onclick = async () => {
1764
+ $("btn-audit-hook-write").disabled = true;
1436
1765
  try {
1437
- const data = await post("/setup/providers", { provider: name, action, ...(action === "save" ? { api_key: input.value.trim() } : {}) });
1438
- input.value = "";
1439
- await loadProviders(action === "save" ? `Key accepted by the provider (${data.validated_results} result(s) in the test) and protected on this Windows machine.` : "Key removed; free tier active.");
1766
+ const result = await post("/setup/audit", { action: "hook_install", token: plan.token });
1767
+ $("audit-hook-confirm").hidden = true;
1768
+ await loadAuditHook();
1769
+ setMsg("audit-hook-msg", "ok", "Turned on. Backup: " + (result.backup || "none, the file was new") + ".");
1440
1770
  } catch (error) {
1441
- setMsg(msg.id, "error", error.message);
1442
- button.disabled = false;
1771
+ setMsg("audit-hook-msg", "error", error.message);
1772
+ } finally {
1773
+ $("btn-audit-hook-write").disabled = false;
1443
1774
  }
1444
- });
1775
+ };
1776
+ } catch (error) {
1777
+ setMsg("audit-hook-msg", "error", error.message);
1445
1778
  }
1446
- return card;
1447
- }
1448
- $("btn-save-contact").addEventListener("click", async () => {
1779
+ });
1780
+ $("btn-audit-hook-cancel").addEventListener("click", () => { $("audit-hook-confirm").hidden = true; });
1781
+ $("btn-audit-hook-off").addEventListener("click", async () => {
1449
1782
  try {
1450
- const data = await post("/setup/contact", { contact: $("contact-input").value.trim() });
1451
- $("contact-hint").textContent = "Sent as: " + data.user_agent;
1452
- setMsg("contact-msg", "ok", "Contact saved.");
1783
+ const result = await post("/setup/audit", { action: "hook_remove" });
1784
+ await loadAuditHook();
1785
+ setMsg("audit-hook-msg", "ok", "Turned off. Backup: " + (result.backup || "none") + ".");
1453
1786
  } catch (error) {
1454
- setMsg("contact-msg", "error", error.message);
1787
+ setMsg("audit-hook-msg", "error", error.message);
1455
1788
  }
1456
1789
  });
1457
-
1458
- let providers = {};
1459
- function showProvider(message) {
1460
- const name = $("provider-select").value;
1461
- $("provider-panel").replaceChildren(...(providers[name] ? [providerCard(name, providers[name])] : []));
1462
- if (message) setMsg(name + "-msg", "ok", message);
1463
- }
1464
- $("provider-select").addEventListener("change", () => showProvider());
1465
-
1466
- async function loadProviders(message) {
1467
- const list = $("provider-panel");
1790
+ $("sel-audit-project").addEventListener("change", () => showAudit($("sel-audit-project").value));
1791
+ $("btn-audit-run").addEventListener("click", async () => {
1792
+ const run = $("btn-audit-run");
1793
+ run.disabled = true;
1794
+ setMsg("audit-msg", "", "Auditing; MCP servers are being contacted…");
1468
1795
  try {
1469
- const resp = await fetch("/setup/providers");
1470
- const data = await resp.json();
1471
- if (!resp.ok || data.error) throw new Error(data.error);
1472
- providers = data.providers;
1473
- const select = $("provider-select");
1474
- const chosen = select.value;
1475
- select.replaceChildren(...Object.entries(providers).map(([name, info]) =>
1476
- new Option(info.label + " · " + ((providerLabels[info.status] || [null, info.status])[1]), name)));
1477
- if (chosen && providers[chosen]) select.value = chosen;
1478
- showProvider(message);
1479
- if (document.activeElement !== $("contact-input")) $("contact-input").value = data.contact;
1480
- $("contact-hint").textContent = "Sent as: " + data.user_agent;
1796
+ renderAudit((await post("/setup/audit", { action: "run", project_root: $("sel-audit-project").value })).report);
1797
+ setMsg("audit-msg", "ok", "Audit finished.");
1481
1798
  } catch (error) {
1482
- list.replaceChildren(Object.assign(document.createElement("p"), { className: "msg error", textContent: "Provider status unavailable: " + error.message }));
1799
+ setMsg("audit-msg", "error", error.message);
1800
+ } finally {
1801
+ run.disabled = false;
1483
1802
  }
1484
- }
1803
+ });
1804
+
1805
+ renderGateway();
1806
+ renderOverview();
1807
+ if (status.gateway.status === "ready") loadModels();
1808
+ loadLocalModels();
1809
+ loadIntegration();
1810
+ loadAutostart();
1485
1811
  loadProviders();
1812
+ loadAudit();
1813
+ loadAuditHook();
1814
+ setInterval(refreshStatus, 15000);
1486
1815
  </script>
1487
1816
  </body>
1488
1817
  </html>