@allansantos-dev/smart-tool 0.9.73 → 0.9.75
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/CHANGELOG.md +19 -0
- package/README.md +3 -3
- package/browser_control.py +30 -20
- package/locales/pt-BR.json +6 -1
- package/package.json +1 -1
- package/project_insights_ui.py +2 -2
- package/project_storage.py +19 -6
- package/smart_tool_daemon.py +3 -3
- package/version.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.75 - beta
|
|
4
|
+
|
|
5
|
+
- The disk space card of each project marks the stale views itself: a view that is not pinned or active and was not
|
|
6
|
+
updated for 30 days shows "Stale" in its Protection column, and a "Stale views" total gives their size and count. The
|
|
7
|
+
inventory (`project_manage action=storage`) carries `stale` per view plus `stale_bytes` and `stale_after_days`, using the
|
|
8
|
+
same test as the daily cleanup (`project_storage.stale_view_ids`). The card's note now says the daily cleanup removes
|
|
9
|
+
stale views instead of "Cleanup is manual". No notification is sent for it. Tests: `tests/test_storage_auto_cleanup.py`.
|
|
10
|
+
|
|
11
|
+
## 0.9.74 - beta
|
|
12
|
+
|
|
13
|
+
- The agent's browser (the Playwright MCP server Smart Tool registers) is marked by its User-Agent, which ends with
|
|
14
|
+
`SmartToolAgentBrowser`, instead of the `X-Smart-Tool-Agent-Browser` header. Any header added to every request made
|
|
15
|
+
each cross-origin `fetch` and every web font from another origin send a CORS preflight, and servers that do not allow
|
|
16
|
+
that header refused it: the product page showed 8 console errors in the agent's browser and lost its fonts. The browser
|
|
17
|
+
sets the User-Agent itself, so it reaches navigations, redirects and subresources without a preflight, and the daemon
|
|
18
|
+
still refuses the agent's browser on every path, `/setup` included. `--blocked-origins` was not used: Playwright MCP
|
|
19
|
+
documents that it does not apply to redirects. Test: `tests/test_browser_control.py` (a redirecting page that fetches
|
|
20
|
+
from another origin answered like a font CDN).
|
|
21
|
+
|
|
3
22
|
## 0.9.73 - beta
|
|
4
23
|
|
|
5
24
|
- Once a day (first pass 10 minutes after the daemon starts) the daemon removes, in each registered project without a
|
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ registered as the `playwright` server where this machine lets a browser be drive
|
|
|
17
17
|
An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
|
|
18
18
|
are cheaper, or just tells the agent what Smart Tool would do.
|
|
19
19
|
|
|
20
|
-
**Status:** 0.9.
|
|
20
|
+
**Status:** 0.9.75 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
|
|
21
21
|
|
|
22
22
|
## How it works
|
|
23
23
|
|
|
@@ -83,7 +83,7 @@ gateway such as Ollama, nothing about your code leaves the machine.
|
|
|
83
83
|
## Install
|
|
84
84
|
|
|
85
85
|
```powershell
|
|
86
|
-
npx @allansantos-dev/smart-tool@0.9.
|
|
86
|
+
npx @allansantos-dev/smart-tool@0.9.75 install
|
|
87
87
|
```
|
|
88
88
|
|
|
89
89
|
Updates install themselves, on by default: the tray checks npm when it starts (at logon) and every 24 h, and when there
|
|
@@ -382,7 +382,7 @@ fails to load is listed in the setup screen with its error and does not affect t
|
|
|
382
382
|
## Uninstall
|
|
383
383
|
|
|
384
384
|
```powershell
|
|
385
|
-
npx @allansantos-dev/smart-tool@0.9.
|
|
385
|
+
npx @allansantos-dev/smart-tool@0.9.75 uninstall [--target DIR] [--keep-data]
|
|
386
386
|
```
|
|
387
387
|
|
|
388
388
|
It asks nothing and opens no window. It stops the tray and the daemon, removes the logon task, the hook entries of Smart
|
package/browser_control.py
CHANGED
|
@@ -11,11 +11,11 @@ The registered command is lazy_mcp_proxy.py around the real server: every sessio
|
|
|
11
11
|
a Node process kept idle in each session that never opens a browser cost about 97 MB of commit each. The proxy answers
|
|
12
12
|
the handshake from the cache the probe writes (HANDSHAKE_PATH) and starts the real server on the first tool call.
|
|
13
13
|
|
|
14
|
-
Pages the agent opens are untrusted input. The server never exposes tools a page registers (WebMCP);
|
|
15
|
-
the browser makes
|
|
16
|
-
own setup page and its token (redirects included); `browser_run_code_unsafe` (arbitrary JavaScript
|
|
17
|
-
process, outside any client sandbox) is denied in the client: Playwright MCP itself is not a security
|
|
18
|
-
its documentation points to client-level permissions.
|
|
14
|
+
Pages the agent opens are untrusted input. The server never exposes tools a page registers (WebMCP); the User-Agent of
|
|
15
|
+
every request the browser makes ends with AGENT_UA_MARK, which the daemon refuses, so a page cannot steer the agent
|
|
16
|
+
into Smart Tool's own setup page and its token (redirects included); `browser_run_code_unsafe` (arbitrary JavaScript
|
|
17
|
+
in the server process, outside any client sandbox) is denied in the client: Playwright MCP itself is not a security
|
|
18
|
+
boundary and its documentation points to client-level permissions.
|
|
19
19
|
"""
|
|
20
20
|
import json
|
|
21
21
|
import os
|
|
@@ -43,26 +43,29 @@ OUTPUT_DIR = os.path.join(paths.DATA_DIR, "playwright-mcp")
|
|
|
43
43
|
CONFIG_PATH = os.path.join(paths.DATA_DIR, "playwright-mcp.json")
|
|
44
44
|
HANDSHAKE_PATH = os.path.join(paths.DATA_DIR, "playwright-mcp-handshake.json")
|
|
45
45
|
PROXY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "lazy_mcp_proxy.py")
|
|
46
|
-
|
|
46
|
+
AGENT_UA_MARK = "SmartToolAgentBrowser"
|
|
47
47
|
OUTPUT_MAX_BYTES = 100 * 1024 * 1024
|
|
48
48
|
PROBE_TIMEOUT_S = 60
|
|
49
49
|
DENIED_TOOLS = ("browser_run_code_unsafe",)
|
|
50
50
|
_CODEX_TABLE_RE = re.compile(rf"^\[mcp_servers\.{SERVER}\][ \t]*\r?\n", re.M)
|
|
51
51
|
_CHROMIUM_PROBE = ("from playwright.sync_api import sync_playwright\n"
|
|
52
|
-
"with sync_playwright() as p
|
|
52
|
+
"with sync_playwright() as p:\n"
|
|
53
|
+
" print(p.chromium.executable_path)\n"
|
|
54
|
+
" b = p.chromium.launch(headless=True); print(b.new_page().evaluate('navigator.userAgent')); b.close()")
|
|
53
55
|
|
|
54
56
|
|
|
55
|
-
def
|
|
56
|
-
"""The Chromium that `playwright install chromium` put in place for the browser venv
|
|
57
|
+
def chromium():
|
|
58
|
+
"""The Chromium that `playwright install chromium` put in place for the browser venv and the User-Agent it sends
|
|
59
|
+
headless, as (path, user_agent); RuntimeError when absent or when it does not start."""
|
|
57
60
|
if not install_runtime.BROWSER_PYTHON.is_file():
|
|
58
61
|
raise RuntimeError(f"Browser runtime missing ({install_runtime.BROWSER_PYTHON}).")
|
|
59
62
|
done = subprocess.run([str(install_runtime.BROWSER_PYTHON), "-c", _CHROMIUM_PROBE], capture_output=True,
|
|
60
63
|
text=True, encoding="utf-8", errors="replace", timeout=60,
|
|
61
64
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
|
62
|
-
|
|
63
|
-
if done.returncode or not os.path.isfile(
|
|
64
|
-
raise RuntimeError(f"Chromium not found: {(done.stderr or done.stdout).strip()[-300:]
|
|
65
|
-
return
|
|
65
|
+
lines = done.stdout.strip().splitlines()
|
|
66
|
+
if done.returncode or len(lines) < 2 or not os.path.isfile(lines[-2]):
|
|
67
|
+
raise RuntimeError(f"Chromium not found or not starting: {(done.stderr or done.stdout).strip()[-300:]}")
|
|
68
|
+
return lines[-2], lines[-1]
|
|
66
69
|
|
|
67
70
|
|
|
68
71
|
def server_command():
|
|
@@ -72,9 +75,9 @@ def server_command():
|
|
|
72
75
|
raise RuntimeError("Supported Node.js not found for Playwright MCP.")
|
|
73
76
|
if not CLI.is_file():
|
|
74
77
|
raise RuntimeError(f"Playwright MCP is not installed ({CLI}); reinstall Smart Tool.")
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
"--output-max-size", str(OUTPUT_MAX_BYTES)]
|
|
78
|
+
executable, user_agent = chromium()
|
|
79
|
+
return [node, str(CLI), "--isolated", "--headless", "--no-webmcp", "--caps=", "--config", write_config(user_agent),
|
|
80
|
+
"--executable-path", executable, "--output-dir", OUTPUT_DIR, "--output-max-size", str(OUTPUT_MAX_BYTES)]
|
|
78
81
|
|
|
79
82
|
|
|
80
83
|
def lazy_command(command):
|
|
@@ -86,11 +89,18 @@ def lazy_command(command):
|
|
|
86
89
|
return [python, PROXY, "--handshake", HANDSHAKE_PATH, "--", *command]
|
|
87
90
|
|
|
88
91
|
|
|
89
|
-
def
|
|
90
|
-
"""
|
|
91
|
-
|
|
92
|
+
def is_agent_browser(headers):
|
|
93
|
+
"""True when the request headers come from the agent's browser: its User-Agent carries AGENT_UA_MARK."""
|
|
94
|
+
return AGENT_UA_MARK in (headers.get("User-Agent") or "").split()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def write_config(user_agent):
|
|
98
|
+
"""Writes the Playwright MCP config file that sends user_agent followed by AGENT_UA_MARK on every request of the
|
|
99
|
+
browser and returns its path. The browser sets User-Agent itself, on navigations, redirects and subresources, and
|
|
100
|
+
a CORS request does not count it as an author header, so no preflight is added; a header in extraHTTPHeaders
|
|
101
|
+
forced one on every cross-origin fetch and font."""
|
|
92
102
|
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
|
|
93
|
-
config = {"browser": {"contextOptions": {"
|
|
103
|
+
config = {"browser": {"contextOptions": {"userAgent": f"{user_agent} {AGENT_UA_MARK}"}}}
|
|
94
104
|
atomic_io.write_secret_text(CONFIG_PATH, json.dumps(config, indent=1))
|
|
95
105
|
return CONFIG_PATH
|
|
96
106
|
|
package/locales/pt-BR.json
CHANGED
|
@@ -433,7 +433,12 @@
|
|
|
433
433
|
"Local counts and usage reported by the gateway. No query text is saved in this telemetry.": "Contagens locais e uso informado pelo gateway. Nenhum texto de consulta é salvo nesta telemetria.",
|
|
434
434
|
"Disk space and view cleanup": "Espaço em disco e limpeza de visões",
|
|
435
435
|
"Refresh inventory": "Atualizar inventário",
|
|
436
|
-
"The active view
|
|
436
|
+
"The active view, pinned views and the last available view are protected. Stale views are removed by a daily cleanup; you can also remove views here. Only Smart Tool indexes and cache are removed.": "A visão ativa, as fixadas e a última disponível são protegidas. As visões obsoletas são removidas por uma limpeza diária; você também pode removê-las aqui. Só índices e cache do Smart Tool são removidos.",
|
|
437
|
+
"Stale views": "Visões obsoletas",
|
|
438
|
+
"not updated for": "sem atualização há",
|
|
439
|
+
"Stale: not updated for": "Obsoleta: sem atualização há",
|
|
440
|
+
"{0} not updated for {1} days": "{0} sem atualização há {1} dias",
|
|
441
|
+
"Stale: not updated for {0} days": "Obsoleta: sem atualização há {0} dias",
|
|
437
442
|
"Also clear vectors no longer used by the stored generations": "Limpar também os vetores que as gerações guardadas não usam mais",
|
|
438
443
|
"Preview selected cleanup": "Pré-visualizar a limpeza selecionada",
|
|
439
444
|
"Confirm removal of this preview": "Confirmar a remoção desta pré-visualização",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@allansantos-dev/smart-tool",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.75",
|
|
4
4
|
"description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Smart Tool contributors",
|
package/project_insights_ui.py
CHANGED
|
@@ -6,7 +6,7 @@ STYLE=r'''
|
|
|
6
6
|
HTML=r'''
|
|
7
7
|
<details class="insights-panel" id="usage-panel"><summary>Usage and reuse by project and view</summary>
|
|
8
8
|
<div class="insights-controls"><div><label for="usage-days">Period</label><select id="usage-days"><option value="7">7 days</option><option value="30" selected>30 days</option><option value="90">90 days</option><option value="366">1 year</option></select></div><div><label for="usage-view">View</label><select id="usage-view"><option value="">All</option></select></div><button id="usage-load">Refresh usage</button></div><p id="usage-message" class="insights-note">Local counts and usage reported by the gateway. No query text is saved in this telemetry.</p><div id="usage-summary" class="insights-summary"></div><div id="usage-table" class="insights-table-wrap"></div><div id="usage-indexing" class="insights-table-wrap"></div></details>
|
|
9
|
-
<details class="insights-panel" id="storage-panel"><summary>Disk space and view cleanup</summary><div class="insights-controls"><button id="storage-load">Refresh inventory</button></div><p class="insights-note">The active view
|
|
9
|
+
<details class="insights-panel" id="storage-panel"><summary>Disk space and view cleanup</summary><div class="insights-controls"><button id="storage-load">Refresh inventory</button></div><p class="insights-note">The active view, pinned views and the last available view are protected. Stale views are removed by a daily cleanup; you can also remove views here. Only Smart Tool indexes and cache are removed.</p><div id="storage-summary" class="insights-summary"></div><div id="storage-table" class="insights-table-wrap"></div><label class="check-label"><input id="cleanup-cache" type="checkbox" checked>Also clear vectors no longer used by the stored generations</label><div class="actions"><button id="cleanup-preview" disabled>Preview selected cleanup</button></div><div id="cleanup-plan" class="cleanup-preview" hidden></div><button id="cleanup-apply" class="danger" hidden>Confirm removal of this preview</button><p id="storage-message" class="insights-note"></p></details>
|
|
10
10
|
<details class="insights-panel" id="compare-panel"><summary>Compare two stored views</summary><p class="insights-note">The comparison uses the index content, with no checkout and no new embeddings. Scope differences can also show up as added or removed files.</p><button id="compare-load-views">Load views</button><div class="insights-views"><div><label for="compare-left">View A · base</label><select id="compare-left"></select></div><div><label for="compare-right">View B · compare with A</label><select id="compare-right"></select></div></div><label class="check-label"><input id="compare-relations" type="checkbox" checked>Also compare resolved references and static calls</label><div class="actions"><button id="compare-run" disabled>Compare A → B</button></div><p id="compare-message" class="insights-note"></p><div id="compare-summary" class="insights-summary"></div><div id="compare-files" class="insights-table-wrap"></div><div id="compare-graph"></div><h3 id="compare-file-title"></h3><pre id="compare-diff" class="comparison-diff"></pre></details>
|
|
11
11
|
'''
|
|
12
12
|
SCRIPT=r'''
|
|
@@ -20,7 +20,7 @@ window.SmartInsights=(()=>{
|
|
|
20
20
|
function clearPlan(){plan=null;$i('cleanup-plan').hidden=true;$i('cleanup-apply').hidden=true;$i('cleanup-preview').disabled=!document.querySelector('#storage-table input[data-storage]:checked')}
|
|
21
21
|
function reset(){sequence++;storage=null;comparison=null;plan=null;for(const id of ['usage-summary','usage-table','usage-indexing','storage-summary','storage-table','storage-message','compare-summary','compare-files','compare-graph','compare-file-title','compare-diff','compare-message'])$i(id).replaceChildren();$i('usage-view').replaceChildren(new Option('All',''));$i('compare-left').replaceChildren();$i('compare-right').replaceChildren();$i('compare-run').disabled=true;clearPlan();for(const id of ['usage-load','storage-load','compare-load-views'])$i(id).disabled=false;$i('usage-message').textContent='Refresh the usage of this project. The telemetry stores only counts and metadata.'}
|
|
22
22
|
async function loadUsage(key,valid){const requestedDays=$i('usage-days').value,requestedView=$i('usage-view').value;const data=await api({action:'usage',project_id:key,days:Number($i('usage-days').value),...($i('usage-view').value?{view_id:$i('usage-view').value}:{})});if(!valid()||requestedDays!==$i('usage-days').value||requestedView!==$i('usage-view').value)return;const t=data.totals,old=$i('usage-view').value,views=new Map();for(const row of [...data.daily,...data.indexing])views.set(row.view_id,row.view_label);if(!old)$i('usage-view').replaceChildren(new Option('All',''),...Array.from(views,([id,label])=>new Option(label||id,id)));summary($i('usage-summary'),[['Call attempts',count(t.attempts),count(t.errors)+' with errors'],['Reported tokens',t.token_reports?count((t.prompt_tokens||0)+(t.output_tokens||0)):'Not reported',count(t.token_reports)+' of '+count(t.attempts)+' calls with data'],['Cost reported by the gateway',t.reported_usd==null?'Not reported':new Intl.NumberFormat('en-US',{style:'currency',currency:'USD',maximumFractionDigits:6}).format(t.reported_usd),count(t.price_reports)+' calls with a cost; not the full bill'],['Chunks sent / cache',count(data.indexing.reduce((s,r)=>s+r.embedded_chunks,0))+' / '+count(data.indexing.reduce((s,r)=>s+r.reused_chunks,0)),'Unchanged files are counted separately']]);$i('usage-message').textContent='Loaded period: '+data.days+' days (UTC). '+data.notes.join(' ');$i('usage-table').innerHTML=table(['Date UTC','View / step','Model','Attempts','Reported tokens','Measured characters'],data.daily.slice(0,200).map(r=>[esc(r.day),esc(r.view_label)+'<br>'+esc(phaseNames[r.purpose]||r.purpose),esc(r.model),count(r.attempts),r.token_reports?count(r.prompt_tokens+r.output_tokens):'Not reported',count(r.input_characters)]));$i('usage-indexing').innerHTML=table(['View','Indexing jobs','Chunks sent','Cache reuse','Unchanged files'],data.indexing.map(r=>[esc(r.view_label),count(r.jobs),count(r.embedded_chunks),count(r.reused_chunks),count(r.unchanged_files)]))}
|
|
23
|
-
function renderStorage(data){storage=data;clearPlan();summary($i('storage-summary'),[['SQLite indexes',size(data.total_bytes)],['Vector cache',size(data.cache_bytes)],['Auxiliary generations',size(data.auxiliary_bytes)],['Stored views',count(data.views.length),'Active and pinned views are protected']]);$i('storage-table').innerHTML=table(['Clear','View','Space','Protection'],data.views.map(v=>[`<input type="checkbox" data-storage="${esc(v.storage_id)}" aria-label="Select ${esc(v.label)} for cleanup" ${v.protected?'disabled':''}>`,esc(v.label)+'<br><small>'+esc(v.commit?.slice(0,10)||'Commit not recorded')+'</small>',size(v.bytes),esc(v.protected_reason||'Can be selected')+`<br><button data-pin="${esc(v.storage_id)}" data-pinned="${v.pinned?'1':'0'}">${v.pinned?'Unpin':'Pin'}</button>`]));$i('storage-message').textContent=data.views.length?'Choose the old views and check the preview before removing.':'No stored views in this project.';clearPlan()}
|
|
23
|
+
function renderStorage(data){storage=data;clearPlan();summary($i('storage-summary'),[['SQLite indexes',size(data.total_bytes)],['Vector cache',size(data.cache_bytes)],['Auxiliary generations',size(data.auxiliary_bytes)],['Stored views',count(data.views.length),'Active and pinned views are protected'],['Stale views',size(data.stale_bytes),count(data.views.filter(v=>v.stale).length)+' not updated for '+data.stale_after_days+' days']]);$i('storage-table').innerHTML=table(['Clear','View','Space','Protection'],data.views.map(v=>[`<input type="checkbox" data-storage="${esc(v.storage_id)}" aria-label="Select ${esc(v.label)} for cleanup" ${v.protected?'disabled':''}>`,esc(v.label)+'<br><small>'+esc(v.commit?.slice(0,10)||'Commit not recorded')+'</small>',size(v.bytes),esc(v.protected_reason||(v.stale?'Stale: not updated for '+data.stale_after_days+' days':'Can be selected'))+`<br><button data-pin="${esc(v.storage_id)}" data-pinned="${v.pinned?'1':'0'}">${v.pinned?'Unpin':'Pin'}</button>`]));$i('storage-message').textContent=data.views.length?'Choose the old views and check the preview before removing.':'No stored views in this project.';clearPlan()}
|
|
24
24
|
async function loadStorage(key,valid){const data=await api({action:'storage',project_id:key});if(valid())renderStorage(data)}
|
|
25
25
|
$i('usage-load').onclick=()=>run($i('usage-load'),loadUsage);$i('usage-days').onchange=()=>run($i('usage-load'),loadUsage);$i('usage-view').onchange=()=>run($i('usage-load'),loadUsage);$i('storage-load').onclick=()=>run($i('storage-load'),loadStorage);
|
|
26
26
|
$i('storage-table').onchange=clearPlan;$i('cleanup-cache').onchange=clearPlan;
|
package/project_storage.py
CHANGED
|
@@ -36,7 +36,20 @@ def _stamp(path):
|
|
|
36
36
|
stat=os.stat(path);return [stat.st_size,stat.st_mtime_ns,stat.st_ino]
|
|
37
37
|
|
|
38
38
|
|
|
39
|
-
def
|
|
39
|
+
def _is_stale(row,now):
|
|
40
|
+
return not row['protected'] and bool(row.get('updated_at')) and now-row['updated_at']>STALE_VIEW_S
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _view_files(storage_id,assets):
|
|
44
|
+
"""Paths of a view's database and its `.previous` and `.building-*` generations."""
|
|
45
|
+
stem=storage_id[:-8]
|
|
46
|
+
return [path for name,path in assets.items() if name==storage_id or re.fullmatch(re.escape(stem)+r'(?:\.previous|\.building-[a-f0-9]+)\.sqlite3',name)]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def inventory(project,now=None):
|
|
50
|
+
"""Disk use of the project's indexes and vector cache, one row per stored view; `stale` marks the unprotected
|
|
51
|
+
views the daily cleanup removes."""
|
|
52
|
+
now=time.time() if now is None else now
|
|
40
53
|
root=project['root'];views=index_inventory.views(root);assets=_assets(root)
|
|
41
54
|
active=indexer.existing_db_path(root)
|
|
42
55
|
for view in views:view['current']=bool(active and os.path.normcase(view['path'])==os.path.normcase(active))
|
|
@@ -46,12 +59,13 @@ def inventory(project):
|
|
|
46
59
|
for view in views:
|
|
47
60
|
row={**view,'storage_id':Path(view['path']).name,'pinned':view['view_id'] in pins}
|
|
48
61
|
row['protected_reason']='Active view' if view['current'] else 'Pinned view' if row['pinned'] else 'Last available view; the active branch has no index' if view['path']==fallback else ''
|
|
49
|
-
row['protected']=bool(row['protected_reason']);rows.append(row)
|
|
62
|
+
row['protected']=bool(row['protected_reason']);row['stale']=_is_stale(row,now);rows.append(row)
|
|
50
63
|
total=sum(os.path.getsize(path) for path in assets.values())
|
|
51
64
|
cache_path=Path(indexer.INDEX_DIR)/(project_identity.project_id(root)+'.vectors.sqlite3')
|
|
52
65
|
return {'views':rows,'total_bytes':total,'cache_bytes':cache_path.stat().st_size if cache_path.exists() else 0,
|
|
53
66
|
'auxiliary_bytes':max(0,total-sum(v['bytes'] for v in rows)-(cache_path.stat().st_size if cache_path.exists() else 0)),
|
|
54
|
-
'
|
|
67
|
+
'stale_bytes':sum(os.path.getsize(path) for v in rows if v['stale'] for path in _view_files(v['storage_id'],assets)),'stale_after_days':STALE_VIEW_S//86400,
|
|
68
|
+
'source_files_untouched':True}
|
|
55
69
|
|
|
56
70
|
|
|
57
71
|
def pin(project,storage_id,pinned):
|
|
@@ -98,7 +112,7 @@ def preview(project,storage_ids,clear_cache=True):
|
|
|
98
112
|
if row['protected']:raise ValueError(row['label']+': '+row['protected_reason']+'.')
|
|
99
113
|
selected.append(row)
|
|
100
114
|
stem=storage_id[:-8]
|
|
101
|
-
removed.extend(
|
|
115
|
+
removed.extend(_view_files(storage_id,assets))
|
|
102
116
|
if '.v-' in stem:
|
|
103
117
|
scope=Path(index_scope.SCOPE_DIR)/(stem+'.scope.json')
|
|
104
118
|
if scope.is_file():removed.append(str(scope))
|
|
@@ -121,8 +135,7 @@ def preview(project,storage_ids,clear_cache=True):
|
|
|
121
135
|
def stale_view_ids(project,now=None):
|
|
122
136
|
"""Storage ids of the views of `project` that are not protected and were last updated over STALE_VIEW_S ago."""
|
|
123
137
|
now=time.time() if now is None else now
|
|
124
|
-
return [v['storage_id'] for v in inventory(project)['views']
|
|
125
|
-
if not v['protected'] and v.get('updated_at') and now-v['updated_at']>STALE_VIEW_S]
|
|
138
|
+
return [v['storage_id'] for v in inventory(project,now)['views'] if v['stale']]
|
|
126
139
|
|
|
127
140
|
|
|
128
141
|
def auto_cleanup(project,now=None):
|
package/smart_tool_daemon.py
CHANGED
|
@@ -372,7 +372,7 @@ SERVER_INSTRUCTIONS = (
|
|
|
372
372
|
TOOLS = [
|
|
373
373
|
{
|
|
374
374
|
"name": "project_manage",
|
|
375
|
-
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project (a project whose folder is gone shows as unavailable with the reason); status shows storage, scope and jobs, and with a path inside a registered project answers for the deepest one that holds it (resolved_from). graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. pr_impact (base, default HEAD; main or origin/main for a branch) returns a Markdown report of the change for a pull request: the functions the diff touches with their callers, the documentation entries it leaves out of date and the tests to run with their command; it publishes nothing. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python, Go and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc, Go doc comment starting with the name; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; docs generate=true writes the documentation scope to docs/scope in the project in three levels tied to the code: technical pages by folder (an entry per public function anchored on path::name with signature, first doc line, layer, callers, calls and tests, plus a Mermaid flow by layer), functional.md (each entry point and the functions its flow reaches, by layer) and simple.md; the prose between the prose markers is kept by regeneration; docs write_prose=true writes the empty prose blocks with the Docs model of the setup (each paragraph checked against the code first) within about 40 s and says how many are left, call it again until none is; docs check=true reports anchors whose function changed signature or is gone and broken links; docs validate=true checks every claim of docs/scope against the code (anchors, links, line numbers, callers and tests, coverage, entry points, command-line options, prose names, counts, glossary, navigation, versions) and writes docs/scope/validation.md with pass/fail per check, the evidence, a score and the verdict (generate runs it too); docs with symbol lists where that function is documented; layers declares the project's layers (ordered highest first, each with path globs and annotations): without layers it returns the saved rule or a suggestion read from folder names and annotations, with files, symbols and calls between layers (direction down or up); pass layers to preview a rule and the same layers with confirm=true to save it in the project (.smart-tool/layers.json); duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified; each finding carries its fix (the file to edit or the command to run), applied by the agent when the user agrees, never by Smart Tool; mode=last returns the stored report instead of auditing again. redirect_proposals (no project_root) lists the redirect patterns proposed from allowed searches, most matched first, with a guide; redirect_decide decides them by ids: accept, instruct (tip without blocking), reject, or remove an accepted one. Jobs via smart_search_result.",
|
|
375
|
+
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project (a project whose folder is gone shows as unavailable with the reason); status shows storage, scope and jobs, and with a path inside a registered project answers for the deepest one that holds it (resolved_from). graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. pr_impact (base, default HEAD; main or origin/main for a branch) returns a Markdown report of the change for a pull request: the functions the diff touches with their callers, the documentation entries it leaves out of date and the tests to run with their command; it publishes nothing. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python, Go and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc, Go doc comment starting with the name; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; docs generate=true writes the documentation scope to docs/scope in the project in three levels tied to the code: technical pages by folder (an entry per public function anchored on path::name with signature, first doc line, layer, callers, calls and tests, plus a Mermaid flow by layer), functional.md (each entry point and the functions its flow reaches, by layer) and simple.md; the prose between the prose markers is kept by regeneration; docs write_prose=true writes the empty prose blocks with the Docs model of the setup (each paragraph checked against the code first) within about 40 s and says how many are left, call it again until none is; docs check=true reports anchors whose function changed signature or is gone and broken links; docs validate=true checks every claim of docs/scope against the code (anchors, links, line numbers, callers and tests, coverage, entry points, command-line options, prose names, counts, glossary, navigation, versions) and writes docs/scope/validation.md with pass/fail per check, the evidence, a score and the verdict (generate runs it too); docs with symbol lists where that function is documented; layers declares the project's layers (ordered highest first, each with path globs and annotations): without layers it returns the saved rule or a suggestion read from folder names and annotations, with files, symbols and calls between layers (direction down or up); pass layers to preview a rule and the same layers with confirm=true to save it in the project (.smart-tool/layers.json); duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; each view carries stale (not updated for 30 days, the test of the daily cleanup that removes them) and stale_bytes sums them; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified; each finding carries its fix (the file to edit or the command to run), applied by the agent when the user agrees, never by Smart Tool; mode=last returns the stored report instead of auditing again. redirect_proposals (no project_root) lists the redirect patterns proposed from allowed searches, most matched first, with a guide; redirect_decide decides them by ids: accept, instruct (tip without blocking), reject, or remove an accepted one. Jobs via smart_search_result.",
|
|
376
376
|
"inputSchema": {
|
|
377
377
|
"type": "object", "properties": {
|
|
378
378
|
"action": {"type": "string", "enum": ["list", "status", "register", "preview", "index", "rebuild", "pause", "cancel", "resume", "watch", "scope", "remove", "relocate", "probe", "policy", "inspect", "graph", "usage", "storage", "pin_view", "cleanup_preview", "cleanup_commit", "compare", "search_limits", "integration", "install_hook_preview", "install_hook", "duplicates", "duplicates_dismiss", "duplicates_restore", "docs", "layers", "affected_tests", "pr_impact", "setup_audit", "redirect_proposals", "redirect_decide"]},
|
|
@@ -4409,9 +4409,9 @@ class MCPHandler(BaseHTTPRequestHandler):
|
|
|
4409
4409
|
return origin is None or _loopback_host(origin, require_port=True)
|
|
4410
4410
|
|
|
4411
4411
|
def _reject_foreign_origin(self):
|
|
4412
|
-
"""The agent's browser (Playwright MCP marks every request
|
|
4412
|
+
"""The agent's browser (Playwright MCP marks the User-Agent of every request) never reaches the daemon: a page
|
|
4413
4413
|
it opens could otherwise steer the agent into /setup, whose token unlocks every setting."""
|
|
4414
|
-
if self.headers
|
|
4414
|
+
if browser_control.is_agent_browser(self.headers):
|
|
4415
4415
|
self._write_json(403, {"error": "Smart Tool's pages are not available to the agent's browser"})
|
|
4416
4416
|
return True
|
|
4417
4417
|
if self._origin_allowed():
|
package/version.py
CHANGED