@allansantos-dev/smart-tool 0.0.0-stage → 0.9.0
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 +23 -0
- package/LICENSE +202 -0
- package/NOTICE +32 -0
- package/README.md +116 -3
- package/atomic_io.py +94 -0
- package/autostart.py +199 -0
- package/bin/smart-tool.mjs +82 -0
- package/browser_service_client.py +232 -0
- package/capabilities.py +63 -0
- package/client_hooks.py +192 -0
- package/code_graph.py +403 -0
- package/code_graph_java.mjs +49 -0
- package/code_graph_js.cjs +135 -0
- package/config.py +241 -0
- package/daemon_launcher.py +165 -0
- package/directory_watch.py +131 -0
- package/document_text.py +69 -0
- package/duplicates.py +313 -0
- package/embedding_cache.py +99 -0
- package/endpoint_sync.py +179 -0
- package/folder_picker.py +73 -0
- package/freshness.py +278 -0
- package/gateway.py +220 -0
- package/hook_decision.py +96 -0
- package/hooks/pretool_router.py +45 -0
- package/index_inventory.py +75 -0
- package/index_profile.py +167 -0
- package/index_scope.py +458 -0
- package/index_views.py +121 -0
- package/indexer.py +878 -0
- package/install.py +251 -0
- package/install_runtime.py +249 -0
- package/integration_metrics.py +82 -0
- package/local_embedder.py +172 -0
- package/model_adapters/__init__.py +0 -0
- package/model_adapters/openai_compatible.py +57 -0
- package/model_catalog.py +74 -0
- package/model_client.py +38 -0
- package/model_defaults.py +70 -0
- package/package.json +35 -6
- package/paths.py +6 -0
- package/project_identity.py +42 -0
- package/project_insights_ui.py +38 -0
- package/project_maps_ui.py +96 -0
- package/project_monitor.py +204 -0
- package/project_scheduler.py +61 -0
- package/project_storage.py +165 -0
- package/project_store.py +220 -0
- package/projects_ui.py +146 -0
- package/requirements.txt +8 -0
- package/research_cache.py +171 -0
- package/research_metrics.py +110 -0
- package/router.py +582 -0
- package/secret_store.py +121 -0
- package/setup_ui.py +986 -0
- package/site_memory.py +53 -0
- package/smart_tool_daemon.py +3604 -0
- package/tray.py +245 -0
- package/update_check.py +22 -0
- package/usage_meter.py +124 -0
- package/version.py +18 -0
- package/view_compare.py +68 -0
- package/web_adapters/browser/browser_service.py +302 -0
- package/web_adapters/browser/crawl4ai_search.py +236 -0
- package/web_adapters/browser/requirements.txt +2 -0
- package/web_adapters/node/adapter-common.mjs +40 -0
- package/web_adapters/node/ddg-search.mjs +89 -0
- package/web_adapters/node/open-websearch-adapter.mjs +77 -0
- package/web_adapters/node/package-lock.json +2720 -0
- package/web_adapters/node/package.json +12 -0
- package/web_adapters/node/wikipedia-search.mjs +44 -0
- package/web_document_graph.py +71 -0
- package/web_fetch.py +242 -0
- package/web_search_adapters.py +193 -0
- package/web_search_ddgs.py +42 -0
- package/web_search_external.py +288 -0
- package/web_search_health.py +88 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.9.0 - beta
|
|
4
|
+
|
|
5
|
+
First release for beta testers. Windows only.
|
|
6
|
+
|
|
7
|
+
- `smart_search`: semantic + lexical search (Weaviate-style relative score fusion), results split into code, tests and
|
|
8
|
+
docs, likeliest functions per chunk, per-project language profile; asks the calling agent to define the scope when no
|
|
9
|
+
scope model is configured.
|
|
10
|
+
- `web_search`: parallel sources (DuckDuckGo, Yahoo, Wikipedia, Exa, Parallel, Keenable, Google and Startpage through a
|
|
11
|
+
resident browser), bilingual queries, cache shared across sessions with volatility checks, research mode.
|
|
12
|
+
- `web_fetch`: reads a known URL and returns only the answer to the prompt, 24 h page cache, browser rendering for
|
|
13
|
+
JavaScript pages.
|
|
14
|
+
- Model gateway through adapters: built-in OpenAI-compatible adapter; user adapters as Python files in
|
|
15
|
+
`~/.smart-tool/adapters`.
|
|
16
|
+
- Optional local embedder through the mcp-memory sidecar when the gateway has no embedding model.
|
|
17
|
+
- PreToolUse hook for Claude Code (HTTP to the daemon) and Codex (thin command), with Redirect, Advise only and Off modes.
|
|
18
|
+
- Setup screen: model gateway, models, agents (MCP registration, hook install, hook behavior), web provider keys,
|
|
19
|
+
contact for public APIs, local models, start at logon.
|
|
20
|
+
- The daemon owns its port: falls back to a free port and rewrites the smart-tool URLs the clients keep.
|
|
21
|
+
- Install and update with `npx @allansantos-dev/smart-tool@latest install`: the package brings uv (checksum verified)
|
|
22
|
+
and a private Python 3.12 in `~/.smart-tool/runtime`, so only Node.js is required. The tray offers the update command
|
|
23
|
+
when npm has a newer version. Product page on GitHub Pages.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Smart Tool
|
|
2
|
+
Copyright 2026 Allan Santos
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (see LICENSE).
|
|
5
|
+
|
|
6
|
+
Smart Tool does not bundle third-party code. The installer downloads the components below from their official
|
|
7
|
+
sources into the installation folder or the user's profile; each keeps its own license.
|
|
8
|
+
|
|
9
|
+
Python packages (installation venv, from PyPI)
|
|
10
|
+
- ddgs (MIT)
|
|
11
|
+
- trafilatura (Apache-2.0)
|
|
12
|
+
- pystray (LGPL-3.0; used unmodified as a library)
|
|
13
|
+
- Pillow (MIT-CMU)
|
|
14
|
+
- PyYAML (MIT)
|
|
15
|
+
|
|
16
|
+
Browser runtime (web_adapters/browser/.venv, from PyPI and the projects' download servers)
|
|
17
|
+
- camoufox Python package (MIT) and the Camoufox browser, a Firefox fork (MPL-2.0), fetched by `camoufox fetch`
|
|
18
|
+
- crawl4ai (Apache-2.0), https://github.com/unclecode/crawl4ai: page rendering is powered by Crawl4AI
|
|
19
|
+
- Playwright (Apache-2.0) and the Chromium build it installs (BSD-style, see https://www.chromium.org)
|
|
20
|
+
|
|
21
|
+
Node runtime and packages (web_adapters/node, from nodejs.org and npm)
|
|
22
|
+
- Node.js, downloaded only when no supported Node is installed (MIT and bundled licenses)
|
|
23
|
+
- open-websearch (Apache-2.0)
|
|
24
|
+
- typescript (Apache-2.0)
|
|
25
|
+
- java-parser (Apache-2.0)
|
|
26
|
+
- @angular/compiler (MIT)
|
|
27
|
+
- their dependencies as pinned in web_adapters/node/package-lock.json (MIT, ISC, BSD and Apache-2.0)
|
|
28
|
+
|
|
29
|
+
Web search sources
|
|
30
|
+
Smart Tool queries public search engines and APIs (DuckDuckGo, Yahoo, Wikipedia, Exa, Parallel, Keenable, Google and
|
|
31
|
+
Startpage through a local browser, and optionally Tavily and Firecrawl with your own key). Using them is subject to
|
|
32
|
+
each service's terms of use; free tiers are rate limited per IP address.
|
package/README.md
CHANGED
|
@@ -1,3 +1,116 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# Smart Tool
|
|
2
|
+
|
|
3
|
+
A local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search:
|
|
4
|
+
|
|
5
|
+
| Tool | What it does |
|
|
6
|
+
|---|---|
|
|
7
|
+
| `smart_search` / `smart_search_result` | Semantic + lexical search over an indexed project, results split into code, tests and docs, with the likeliest functions per chunk |
|
|
8
|
+
| `web_search` / `web_search_result` | Web search across several sources in parallel, in the query language and in English, with a cache shared across sessions; `depth="research"` runs a multi-round research loop |
|
|
9
|
+
| `web_fetch` | Reads a known URL and returns only the answer to your prompt, written by a small model; pages are cached for 24 h |
|
|
10
|
+
| `project_manage` | Registers and indexes projects, shows coverage, code maps, duplicated functions and index storage |
|
|
11
|
+
|
|
12
|
+
An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
|
|
13
|
+
are cheaper, or just tells the agent what Smart Tool would do.
|
|
14
|
+
|
|
15
|
+
**Status:** 0.9.0 beta. Windows only.
|
|
16
|
+
|
|
17
|
+
## Requirements
|
|
18
|
+
|
|
19
|
+
- Windows 10 or 11 (x64) and Node.js 18 or newer for `npx`. Python is not needed: the installer brings its own.
|
|
20
|
+
- About 1 GB of downloads on first install (Python 3.12 and its packages, Node.js when no supported version is
|
|
21
|
+
installed, the Camoufox and Chromium browsers used for pages that need JavaScript).
|
|
22
|
+
- An OpenAI-compatible model API for embeddings and small chat calls (OpenAI, OpenRouter, a LiteLLM proxy, Ollama...).
|
|
23
|
+
Web search works without it; smart_search falls back to lexical search.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```powershell
|
|
28
|
+
npx @allansantos-dev/smart-tool@latest install
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Run the same command to update; `~/.smart-tool` is kept. It downloads [uv](https://docs.astral.sh/uv/) (checksum
|
|
32
|
+
verified) and a private Python 3.12 into `~/.smart-tool/runtime`, with nothing added to `PATH` or the registry, then
|
|
33
|
+
copies Smart Tool to `%LOCALAPPDATA%\Programs\SmartTool` with its own virtual environment,
|
|
34
|
+
installs the web runtime, registers a per-user Scheduled Task that starts the tray at logon and starts the daemon on
|
|
35
|
+
`http://127.0.0.1:8765` (another free port is used, and announced, if 8765 is taken).
|
|
36
|
+
|
|
37
|
+
State lives in `~/.smart-tool`: `config.json`, your model adapters in `adapters/` and indexes, caches and logs in
|
|
38
|
+
`data/`. Secrets (API keys) are encrypted with Windows DPAPI for your user.
|
|
39
|
+
|
|
40
|
+
## Set up
|
|
41
|
+
|
|
42
|
+
Open the setup screen from the tray icon ("Open settings") or at `http://127.0.0.1:8765/setup`.
|
|
43
|
+
|
|
44
|
+
1. **Model gateway**: pick an adapter and fill its fields. The built-in **OpenAI-compatible** adapter takes a base
|
|
45
|
+
URL ending where the API starts, like the OpenAI SDK `base_url` (`https://api.openai.com/v1`,
|
|
46
|
+
`https://openrouter.ai/api/v1`, `http://localhost:11434/v1`), and an optional API key. Saving tests `/models` first.
|
|
47
|
+
2. **Models**: embedding, rerank (optional; without it results use the hybrid order), the router model (small, no
|
|
48
|
+
reasoning: it decides before tool calls), the index classification model and the research model. Any id the gateway
|
|
49
|
+
accepts works; the catalog is shown as suggestions.
|
|
50
|
+
3. **Agents**: register the MCP server in Claude Code or Codex (runs their official `mcp add` command), install the
|
|
51
|
+
hook and choose its behavior:
|
|
52
|
+
- **Redirect** (default): the native tool is denied with the reason and the Smart Tool tool to use.
|
|
53
|
+
- **Advise only**: the native tool runs; the agent receives the same advice next to the result and decides.
|
|
54
|
+
- **Off**: no routing.
|
|
55
|
+
4. **Local models** (optional): if the mcp-memory embedding sidecar is installed on the machine, its local embedder
|
|
56
|
+
can serve as a fallback (or preferred) embedding model.
|
|
57
|
+
5. **Web search providers** work without keys on their free public tiers; add your own key for more volume. Set your
|
|
58
|
+
own contact (e-mail or URL) if you want public APIs such as Wikimedia to see it in the User-Agent.
|
|
59
|
+
|
|
60
|
+
## Writing a model adapter
|
|
61
|
+
|
|
62
|
+
An adapter is a Python file in `~/.smart-tool/adapters/`. It appears in the setup screen next to the built-in one.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import json
|
|
66
|
+
import urllib.request
|
|
67
|
+
|
|
68
|
+
NAME = "my_gateway" # unique id
|
|
69
|
+
LABEL = "My gateway" # shown in the setup screen
|
|
70
|
+
FIELDS = ( # rendered as inputs; secret values are stored with DPAPI
|
|
71
|
+
{"name": "url", "label": "Address", "required": True, "placeholder": "http://10.0.0.5"},
|
|
72
|
+
{"name": "token", "label": "Token", "secret": True},
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def request(options, route, body=None, timeout=15):
|
|
77
|
+
"""route is OpenAI-style: models, model/info, embeddings, chat/completions, rerank. body None means GET.
|
|
78
|
+
Return (parsed JSON, response headers); let urllib.error.HTTPError propagate."""
|
|
79
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
80
|
+
headers = {"Content-Type": "application/json"}
|
|
81
|
+
if options.get("token"):
|
|
82
|
+
headers["Authorization"] = "Bearer " + options["token"]
|
|
83
|
+
req = urllib.request.Request(f"{options['url']}/v1/{route}", data=data, headers=headers)
|
|
84
|
+
with urllib.request.urlopen(req, timeout=timeout) as response:
|
|
85
|
+
return json.load(response), response.headers
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def verify(options):
|
|
89
|
+
"""Raise RuntimeError with a reason a person can act on."""
|
|
90
|
+
request(options, "models", timeout=10)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Embeddings and chat use the OpenAI request and response formats; rerank uses the Cohere/Jina format served by
|
|
94
|
+
LiteLLM (`{"model", "query", "documents", "top_n"}` returning `results[].index` and `relevance_score`). A file that
|
|
95
|
+
fails to load is listed in the setup screen with its error and does not affect the others.
|
|
96
|
+
|
|
97
|
+
## Data and privacy
|
|
98
|
+
|
|
99
|
+
- Indexed code stays on your machine. Chunks are sent to your model gateway to compute embeddings, and small excerpts
|
|
100
|
+
go to its chat models (scope, profile, routing, web_fetch answers). Use a local gateway (Ollama, LiteLLM) to keep
|
|
101
|
+
everything local.
|
|
102
|
+
- Web queries go to the search sources listed in `NOTICE`. Their free tiers are rate limited per IP address; respect
|
|
103
|
+
each service's terms of use.
|
|
104
|
+
- Logs and metrics are written to `~/.smart-tool/data` and never leave the machine.
|
|
105
|
+
|
|
106
|
+
## Uninstall
|
|
107
|
+
|
|
108
|
+
Turn off "Start automatically" in the setup screen, quit from the tray, remove the hook entries from
|
|
109
|
+
`~/.claude/settings.json` / `~/.codex/hooks.json` (the setup screen shows them), run `claude mcp remove smart-tool -s
|
|
110
|
+
user` / `codex mcp remove smart-tool`, then delete `%LOCALAPPDATA%\Programs\SmartTool` and `~/.smart-tool`.
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
Apache License 2.0. See `LICENSE` and `NOTICE` for third-party components.
|
|
115
|
+
|
|
116
|
+
Page rendering is powered by [Crawl4AI](https://github.com/unclecode/crawl4ai) (Apache-2.0).
|
package/atomic_io.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Gravação atômica de arquivo pequeno de estado/credencial, compartilhada pelos módulos
|
|
3
|
+
do Smart Tool."""
|
|
4
|
+
import glob
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
|
|
9
|
+
_REPLACE_ATTEMPTS = 4
|
|
10
|
+
_REPLACE_BACKOFF_S = 0.05
|
|
11
|
+
TMP_SUFFIX = ".tmp."
|
|
12
|
+
ORPHAN_AGE_S = 300
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def rotate(path, max_bytes):
|
|
16
|
+
"""Keeps one previous generation (`path.1`) once an append-only log reaches max_bytes. Best effort: a log
|
|
17
|
+
locked by another process is rotated on a later append, and the append itself still happens."""
|
|
18
|
+
try:
|
|
19
|
+
if os.path.getsize(path) >= max_bytes:
|
|
20
|
+
os.replace(path, path + ".1")
|
|
21
|
+
except OSError:
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def atomic_replace(tmp_path, final_path):
|
|
26
|
+
"""`os.replace` com retry curto: no Windows, `MoveFileEx` falha com `PermissionError`
|
|
27
|
+
enquanto outro processo mantém o destino aberto — e estes arquivos têm vários leitores
|
|
28
|
+
concorrentes (hook do router, tray, configure.py). A janela é de
|
|
29
|
+
milissegundos, então insistir resolve; a exceção só sobe na última tentativa."""
|
|
30
|
+
for attempt in range(_REPLACE_ATTEMPTS):
|
|
31
|
+
try:
|
|
32
|
+
os.replace(tmp_path, final_path)
|
|
33
|
+
return
|
|
34
|
+
except PermissionError:
|
|
35
|
+
if attempt == _REPLACE_ATTEMPTS - 1:
|
|
36
|
+
raise
|
|
37
|
+
time.sleep(_REPLACE_BACKOFF_S)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def tmp_path_for(final_path):
|
|
41
|
+
"""Sufixo único por chamada (não por pid): duas threads/processos podem gravar o mesmo
|
|
42
|
+
arquivo quase ao mesmo tempo."""
|
|
43
|
+
return final_path + TMP_SUFFIX + uuid.uuid4().hex
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def sweep_orphans(final_path, max_age_s=ORPHAN_AGE_S):
|
|
47
|
+
"""Remove tmp de gravação interrompida (kill -9, queda de energia) do mesmo arquivo.
|
|
48
|
+
Esses tmp carregam o mesmo conteúdo do destino — credencial, no caso — com nome
|
|
49
|
+
aleatório e ninguém mais os apagaria. Best-effort: nunca impede a gravação em curso."""
|
|
50
|
+
limite = time.time() - max_age_s
|
|
51
|
+
for candidate in glob.glob(glob.escape(final_path) + TMP_SUFFIX + "*"):
|
|
52
|
+
try:
|
|
53
|
+
if os.path.getmtime(candidate) < limite:
|
|
54
|
+
os.remove(candidate)
|
|
55
|
+
except OSError:
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _write_and_replace(final_path, data, encoding=None):
|
|
60
|
+
sweep_orphans(final_path)
|
|
61
|
+
tmp_path = tmp_path_for(final_path)
|
|
62
|
+
try:
|
|
63
|
+
# `O_EXCL` garante tmp novo (nunca aproveita um abandonado, que pode ser de outro
|
|
64
|
+
# conteúdo); `0o600` é o pedido de permissão restrita onde o SO honra (no Windows
|
|
65
|
+
# só liga o atributo read-only — lá a confidencialidade vem da ACL do diretório).
|
|
66
|
+
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0)
|
|
67
|
+
fd = os.open(tmp_path, flags, 0o600)
|
|
68
|
+
mode = "wb" if encoding is None else "w"
|
|
69
|
+
extra = {} if encoding is None else {"encoding": encoding, "newline": ""}
|
|
70
|
+
with os.fdopen(fd, mode, **extra) as f:
|
|
71
|
+
f.write(data)
|
|
72
|
+
# `os.replace` só garante que o nome aparece inteiro; sem o flush+fsync uma
|
|
73
|
+
# queda de energia pode persistir o rename sem os dados e deixar o destino —
|
|
74
|
+
# que era o único lugar com o conteúdo anterior — vazio ou com lixo.
|
|
75
|
+
f.flush()
|
|
76
|
+
os.fsync(f.fileno())
|
|
77
|
+
atomic_replace(tmp_path, final_path)
|
|
78
|
+
except Exception:
|
|
79
|
+
try:
|
|
80
|
+
os.remove(tmp_path)
|
|
81
|
+
except OSError:
|
|
82
|
+
pass
|
|
83
|
+
raise
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def write_secret_bytes(final_path, data):
|
|
87
|
+
"""Grava bytes em `final_path` com o tmp restrito, `fsync` dos dados antes do rename
|
|
88
|
+
(a durabilidade da entrada de diretório fica com o SO) e replace atômico."""
|
|
89
|
+
_write_and_replace(final_path, data)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def write_secret_text(final_path, text, encoding="utf-8"):
|
|
93
|
+
"""Mesmo contrato de `write_secret_bytes`, para conteúdo textual (JSON de token)."""
|
|
94
|
+
_write_and_replace(final_path, text, encoding=encoding)
|
package/autostart.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Autostart do Smart Tool no logon do Windows — Tarefa Agendada por usuário (sem
|
|
3
|
+
admin), com política `RestartOnFailure` cobrindo o SO reiniciar o processo se ele
|
|
4
|
+
morrer. `schtasks /Create` pode ser bloqueado por política de grupo corporativa
|
|
5
|
+
(máquina AD-joined); nesse caso cai automaticamente para um atalho na pasta Startup
|
|
6
|
+
do usuário — sem a política de restart do Task Scheduler, mas o loop de polling do
|
|
7
|
+
próprio `tray.py` já cobre "se cair, sobe de novo" independente do mecanismo de boot.
|
|
8
|
+
"""
|
|
9
|
+
import os
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
|
|
14
|
+
TASK_NAME = os.environ.get("SMART_TOOL_TASK_NAME", "SmartTool-Tray")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AutostartError(Exception):
|
|
18
|
+
"""Mensagem já pronta pra exibir ao usuário — sem stack trace nem caminho interno."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _xml_escape(text):
|
|
22
|
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _tool_dir():
|
|
26
|
+
return os.path.dirname(os.path.abspath(__file__))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _tray_path():
|
|
30
|
+
return os.path.join(_tool_dir(), "tray.py")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _pythonw_path():
|
|
34
|
+
exe = sys.executable
|
|
35
|
+
base, name = os.path.split(exe)
|
|
36
|
+
if name.lower() == "python.exe":
|
|
37
|
+
candidate = os.path.join(base, "pythonw.exe")
|
|
38
|
+
if os.path.isfile(candidate):
|
|
39
|
+
return candidate
|
|
40
|
+
return exe
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _current_user_id():
|
|
44
|
+
domain = os.environ.get("USERDOMAIN", "")
|
|
45
|
+
user = os.environ.get("USERNAME", "")
|
|
46
|
+
return f"{domain}\\{user}" if domain else user
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _task_xml():
|
|
50
|
+
user_id = _xml_escape(_current_user_id())
|
|
51
|
+
pythonw = _xml_escape(_pythonw_path())
|
|
52
|
+
tray = _xml_escape(_tray_path())
|
|
53
|
+
workdir = _xml_escape(_tool_dir())
|
|
54
|
+
return (
|
|
55
|
+
'<?xml version="1.0" encoding="UTF-16"?>\r\n'
|
|
56
|
+
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">\r\n'
|
|
57
|
+
' <RegistrationInfo>\r\n'
|
|
58
|
+
' <Description>Smart Tool - MCP daemon + tray icon, starts at user sign-in.</Description>\r\n'
|
|
59
|
+
' </RegistrationInfo>\r\n'
|
|
60
|
+
' <Triggers>\r\n'
|
|
61
|
+
' <LogonTrigger>\r\n'
|
|
62
|
+
' <Enabled>true</Enabled>\r\n'
|
|
63
|
+
f' <UserId>{user_id}</UserId>\r\n'
|
|
64
|
+
' </LogonTrigger>\r\n'
|
|
65
|
+
' </Triggers>\r\n'
|
|
66
|
+
' <Principals>\r\n'
|
|
67
|
+
' <Principal id="Author">\r\n'
|
|
68
|
+
f' <UserId>{user_id}</UserId>\r\n'
|
|
69
|
+
' <LogonType>InteractiveToken</LogonType>\r\n'
|
|
70
|
+
' <RunLevel>LeastPrivilege</RunLevel>\r\n'
|
|
71
|
+
' </Principal>\r\n'
|
|
72
|
+
' </Principals>\r\n'
|
|
73
|
+
' <Settings>\r\n'
|
|
74
|
+
' <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\r\n'
|
|
75
|
+
' <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\r\n'
|
|
76
|
+
' <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\r\n'
|
|
77
|
+
' <AllowHardTerminate>true</AllowHardTerminate>\r\n'
|
|
78
|
+
' <StartWhenAvailable>true</StartWhenAvailable>\r\n'
|
|
79
|
+
' <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\r\n'
|
|
80
|
+
' <Enabled>true</Enabled>\r\n'
|
|
81
|
+
' <Hidden>false</Hidden>\r\n'
|
|
82
|
+
' <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\r\n'
|
|
83
|
+
' <RestartOnFailure>\r\n'
|
|
84
|
+
' <Interval>PT1M</Interval>\r\n'
|
|
85
|
+
' <Count>999</Count>\r\n'
|
|
86
|
+
' </RestartOnFailure>\r\n'
|
|
87
|
+
' </Settings>\r\n'
|
|
88
|
+
' <Actions Context="Author">\r\n'
|
|
89
|
+
' <Exec>\r\n'
|
|
90
|
+
f' <Command>{pythonw}</Command>\r\n'
|
|
91
|
+
f' <Arguments>"{tray}"</Arguments>\r\n'
|
|
92
|
+
f' <WorkingDirectory>{workdir}</WorkingDirectory>\r\n'
|
|
93
|
+
' </Exec>\r\n'
|
|
94
|
+
' </Actions>\r\n'
|
|
95
|
+
'</Task>\r\n'
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _startup_dir():
|
|
100
|
+
appdata = os.environ.get("APPDATA", "")
|
|
101
|
+
if not appdata:
|
|
102
|
+
raise AutostartError("APPDATA environment variable not set; could not find the user Startup folder.")
|
|
103
|
+
return os.path.join(appdata, "Microsoft", "Windows", "Start Menu", "Programs", "Startup")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _startup_script_path():
|
|
107
|
+
return os.path.join(_startup_dir(), "SmartTool-Tray.vbs")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _vbs_quoted_run(pythonw, tray):
|
|
111
|
+
# WshShell.Run monta a linha de comando com Chr(34) em vez de aspas literais —
|
|
112
|
+
# evita ter que escapar aspas dentro de aspas tanto em Python quanto em VBScript.
|
|
113
|
+
return f'Chr(34) & "{pythonw}" & Chr(34) & " " & Chr(34) & "{tray}" & Chr(34)'
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _install_startup_shortcut():
|
|
117
|
+
os.makedirs(_startup_dir(), exist_ok=True)
|
|
118
|
+
vbs = (
|
|
119
|
+
'Set shell = CreateObject("WScript.Shell")\r\n'
|
|
120
|
+
f'shell.Run {_vbs_quoted_run(_pythonw_path(), _tray_path())}, 0, False\r\n'
|
|
121
|
+
)
|
|
122
|
+
with open(_startup_script_path(), "w", encoding="utf-8") as f:
|
|
123
|
+
f.write(vbs)
|
|
124
|
+
return {"ok": True, "method": "startup_folder"}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _remove_startup_shortcut():
|
|
128
|
+
try:
|
|
129
|
+
os.remove(_startup_script_path())
|
|
130
|
+
return True
|
|
131
|
+
except OSError:
|
|
132
|
+
return False
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _task_installed():
|
|
136
|
+
try:
|
|
137
|
+
result = subprocess.run(
|
|
138
|
+
["schtasks", "/Query", "/TN", TASK_NAME],
|
|
139
|
+
capture_output=True, text=True, timeout=20,
|
|
140
|
+
)
|
|
141
|
+
except (OSError, subprocess.SubprocessError):
|
|
142
|
+
return False
|
|
143
|
+
return result.returncode == 0
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def install():
|
|
147
|
+
"""Tenta a Tarefa Agendada primeiro (cobre restart automático pelo SO); se
|
|
148
|
+
`schtasks /Create` falhar por qualquer motivo (ex.: bloqueado por politica de
|
|
149
|
+
grupo corporativa, `schtasks` fora do PATH, timeout), cai para o atalho de
|
|
150
|
+
Startup em vez de propagar o erro."""
|
|
151
|
+
fallback_reason = None
|
|
152
|
+
try:
|
|
153
|
+
xml = _task_xml()
|
|
154
|
+
fd, tmp_path = tempfile.mkstemp(suffix=".xml")
|
|
155
|
+
try:
|
|
156
|
+
with os.fdopen(fd, "wb") as f:
|
|
157
|
+
f.write(xml.encode("utf-16"))
|
|
158
|
+
result = subprocess.run(
|
|
159
|
+
["schtasks", "/Create", "/TN", TASK_NAME, "/XML", tmp_path, "/F"],
|
|
160
|
+
capture_output=True, text=True, timeout=20,
|
|
161
|
+
)
|
|
162
|
+
finally:
|
|
163
|
+
try:
|
|
164
|
+
os.remove(tmp_path)
|
|
165
|
+
except OSError:
|
|
166
|
+
pass
|
|
167
|
+
if result.returncode == 0:
|
|
168
|
+
return {"ok": True, "method": "task"}
|
|
169
|
+
fallback_reason = (result.stderr or result.stdout or "").strip()
|
|
170
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
171
|
+
fallback_reason = str(exc)
|
|
172
|
+
|
|
173
|
+
fallback = _install_startup_shortcut()
|
|
174
|
+
fallback["fallback_reason"] = fallback_reason
|
|
175
|
+
return fallback
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def remove():
|
|
179
|
+
removed = []
|
|
180
|
+
try:
|
|
181
|
+
result = subprocess.run(
|
|
182
|
+
["schtasks", "/Delete", "/TN", TASK_NAME, "/F"],
|
|
183
|
+
capture_output=True, text=True, timeout=20,
|
|
184
|
+
)
|
|
185
|
+
if result.returncode == 0:
|
|
186
|
+
removed.append("task")
|
|
187
|
+
except (OSError, subprocess.SubprocessError):
|
|
188
|
+
pass
|
|
189
|
+
if _remove_startup_shortcut():
|
|
190
|
+
removed.append("startup_folder")
|
|
191
|
+
return {"ok": True, "removed": removed}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def status():
|
|
195
|
+
if _task_installed():
|
|
196
|
+
return {"installed": True, "method": "task"}
|
|
197
|
+
if os.path.isfile(_startup_script_path()):
|
|
198
|
+
return {"installed": True, "method": "startup_folder"}
|
|
199
|
+
return {"installed": False, "method": None}
|