tokensafe 4.6.3 → 4.7.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.
Files changed (47) hide show
  1. package/.codex-plugin/plugin.json +2 -2
  2. package/LICENSE +202 -21
  3. package/README.md +44 -7
  4. package/hooks/claude_code_hook.py +24 -2
  5. package/hooks/kimi_hook.py +20 -0
  6. package/hooks/pre_invocation.py +7 -12
  7. package/hooks/session_start.py +8 -0
  8. package/kimi.plugin.json +2 -2
  9. package/package.json +2 -2
  10. package/plugin.json +2 -1
  11. package/server.json +3 -3
  12. package/src/acp/__init__.py +15 -0
  13. package/src/acp/server.py +328 -0
  14. package/src/adapter_core.py +22 -3
  15. package/src/agent/__init__.py +11 -0
  16. package/src/agent/context.py +99 -0
  17. package/src/agent/loop.py +385 -0
  18. package/src/agent/pricing.py +77 -0
  19. package/src/agent/providers.py +486 -0
  20. package/src/agent/tools.py +98 -0
  21. package/src/auto_inject.py +517 -0
  22. package/src/bench/__init__.py +1 -0
  23. package/src/bench/driver.py +219 -0
  24. package/src/bench/go_target.py +360 -0
  25. package/src/bench/react_target.py +234 -0
  26. package/src/bench/runner.py +247 -0
  27. package/src/cli.py +244 -5
  28. package/src/command_sanitizer.py +54 -0
  29. package/src/guard.py +63 -10
  30. package/src/history_compactor.py +200 -2
  31. package/src/mcp_server.py +65 -13
  32. package/src/paths.py +99 -2
  33. package/src/retrofit.py +91 -4
  34. package/src/savings.py +81 -0
  35. package/src/scaffold.py +190 -8
  36. package/src/session_brief.py +154 -0
  37. package/src/session_context.py +124 -0
  38. package/src/telemetry_sync.py +93 -25
  39. package/src/version_checker.py +1 -1
  40. package/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
  41. package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
  42. package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
  43. package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
  44. package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
  45. package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
  46. package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
  47. package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.6.3",
2
+ "version": "4.7.0",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "homepage": "https://tokensafe.dev",
10
10
  "repository": "https://github.com/tokensafe-dev/tokensafe",
11
- "license": "MIT",
11
+ "license": "Apache-2.0",
12
12
  "keywords": [
13
13
  "tokensafe",
14
14
  "token-optimizer",
package/LICENSE CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Oleg Savelev
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
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/README.md CHANGED
@@ -18,7 +18,7 @@
18
18
  <a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/dw/tokensafe.svg?color=10B981&label=npm%20downloads&style=flat-square" alt="npm downloads"></a>
19
19
  <a href="https://pypi.org/project/tokensafe/"><img src="https://img.shields.io/pypi/v/tokensafe.svg?color=38BDF8&style=flat-square" alt="PyPI"></a>
20
20
  <a href="https://github.com/tokensafe-dev/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/tokensafe-dev/tokensafe?style=flat-square&color=334155" alt="Stars"></a>
21
- <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-0F766E?style=flat-square" alt="License"></a>
21
+ <a href="https://github.com/tokensafe-dev/tokensafe/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-Apache_2.0-0F766E?style=flat-square" alt="License"></a>
22
22
  <a href="https://tokensafe.dev#pricing"><img src="https://img.shields.io/badge/Team_Trial-7_Days_Free-10B981?style=flat-square" alt="Trial"></a>
23
23
  </p>
24
24
 
@@ -204,10 +204,42 @@ Why TokenSafe agents ship working code on the first pass without burning quotas
204
204
 
205
205
  Deeper mechanics (language matrix, AST syntax trees, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
206
206
 
207
+ ## What happens on the first prompt
208
+
209
+ You install TokenSafe, open a project in your agent, and the first turn does the wiring:
210
+
211
+ 1. **Detect** the stack (React/Vue + Vite, FastAPI, Go/Gin|Chi, or nothing supported).
212
+ 2. **Activate** the adapters:
213
+ * frontend — `tokensafe dev` serves OUMV from an inline Vite config; **no file in the
214
+ repository changes**;
215
+ * FastAPI — a global `~/.tokensafe/pyhooks/sitecustomize.py` mounts `mount_tokensafe(app)`
216
+ when the server runs through `tokensafe run-backend uvicorn ...`;
217
+ * Go — one `AutoMount()` line between `tokensafe:oumv` markers, byte-exact backup in
218
+ `~/.tokensafe/inject/`, `go build` validated, `tokensafe inject --revert` restores it.
219
+ 3. **Brief the agent** — a short routing block (hook context and MCP `instructions`) says which
220
+ stack is worked through OUMV and which through the TokenSafe tools. Nothing is written into
221
+ the repository by the brief.
222
+
223
+ ```bash
224
+ tokensafe inject --status # what would be wired, and where
225
+ tokensafe inject --dry-run # same, but explicit
226
+ tokensafe inject # apply the safe parts (config + Python autoload + Go line)
227
+ tokensafe inject --revert # restore the Go entrypoint byte-for-byte
228
+ tokensafe create shop --template react-fastapi # greenfield with everything pre-wired
229
+ tokensafe oumv doctor # readiness: adapter installed? runtime live? blocking reasons
230
+ ```
231
+
232
+ Full matrix and details: [docs/OUMV.md](docs/OUMV.md).
233
+
207
234
  ## Benchmarks
208
235
 
209
236
  ### Agent Usability Benchmarks (AUB) — Full-Stack Agent Velocity
210
237
 
238
+ > ⚠️ **Simulated, not measured.** These AER figures are computed from fixture traces in the
239
+ > benchmark harnesses (the 12-assertion oracles are real; the agent turns/tokens are not).
240
+ > A measured run is the next benchmark milestone — until it lands, treat this table as a
241
+ > model, not as a product claim.
242
+
211
243
  Beyond file slicing, TokenSafe's agent-native ecosystem eliminates architectural friction, state pollution, and compiler loops for autonomous coding agents across frontend and backend:
212
244
 
213
245
  | Ecosystem Stack | Target Package | Baseline vs. TokenSafe | Autonomous Efficiency Ratio (AER) | Token Savings | Turns to Green | State Safety |
@@ -438,7 +470,7 @@ All hook adapters fail open: an internal error never stalls your agent. Failures
438
470
  | `oumv_status` | Status, capabilities, and connection health of frontend/backend OUMV runtimes with hybrid fallback mode |
439
471
  | `oumv_observe` | Progressive runtime observation (L0 pulse, L1 surface, L2 detail) with out-of-the-box static AST fallback |
440
472
  | `oumv_understand` | Query runtime causality, state dependencies, and backend route mappings |
441
- | `oumv_mutate` | Controlled mutations with optimistic concurrency control (safe-by-default, requires workspace permissions) |
473
+ | `oumv_mutate` | OCC-guarded source edits (mandatory `expectedVersion`, path jail, syntax pre-flight, backup) |
442
474
  | `oumv_verify` | Transactional verification and state invariant assertions |
443
475
  </details>
444
476
 
@@ -541,12 +573,13 @@ TokenSafe integrates with the [OUMV Protocol](https://github.com/tokensafe-dev/o
541
573
  - **Out-of-the-Box Stack Detection**: TokenSafe automatically detects your application stack (`package.json`, `go.mod`, `pyproject.toml`, Vite, Next.js, FastAPI, Gin) and configures agent tooling dynamically.
542
574
  - **Level 1 Static AST Fallback**: When live dev-servers are offline, `oumv_observe` and `oumv_understand` gracefully fall back to zero-config static AST component trees and route maps with evidence tracking.
543
575
  - **Consolidated Adapters**:
544
- - **Frontend**: `@tokensafe-ui/oumv/react`, `@tokensafe-ui/oumv/vue`, and `@tokensafe-ui/vite` with secure `.tokensafe/runtime.json` session authentication.
576
+ - **Frontend**: `tokensafe-ui/react`, `tokensafe-ui/vue`, and the zero-footprint Vite bridge (`tokensafe-ui/vite`) with a session token stored in the per-workspace descriptor (`~/.tokensafe/runtimes/<hash>.json`, mode 0600).
545
577
  - **Backend**: Go (`gin`, `chi`, `stdhttp`) and Python (`fastapi`, `sqlalchemy`) in [`tokensafe-backend`](https://github.com/tokensafe-dev/tokensafe-backend).
546
- - **Safe-by-Default Mutations**: Mutation tools (`oumv_mutate`) require explicit permission in `.tokensafe/oumv.json` (`mutate: false` by default) and enforce optimistic concurrency control to prevent agent code drifts.
547
- - **Doctor & Integration CLI**: Run `tokensafe integrate` to scaffold project configs or `tokensafe oumv doctor` to verify dev-server connectivity and capabilities.
578
+ - **Guarded Mutations, Enabled by Default**: `oumv_mutate` works out of the box and guards every write — mandatory OCC `expectedVersion`, workspace path jail, syntax pre-flight, backup of previous bytes. Opt out with `permissions.mutate: false` in `.tokensafe/oumv.json`.
579
+ - **Automatic Wiring CLI**: `tokensafe inject` activates adapters with zero repository footprint (Vite wrapper, Python autoload, one marker-delimited Go line), `tokensafe inject --revert` restores it, and `tokensafe oumv doctor` reports readiness with blocking reasons.
580
+ - **Greenfield Recipes**: `tokensafe create <name> --template react-fastapi|react-go|vue-gin|fastapi|gin` generates a normal project in your stack with OUMV already wired.
548
581
 
549
- More documentation: [docs/AGENT_SETUP.md](docs/AGENT_SETUP.md) · [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) · [docs/API.md](docs/API.md) · [METRICS.md](METRICS.md) · [BENCHMARK_REPORT.md](BENCHMARK_REPORT.md)
582
+ More documentation: [docs/OUMV.md](docs/OUMV.md) · [docs/AGENT_SETUP.md](docs/AGENT_SETUP.md) · [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) · [docs/API.md](docs/API.md) · [METRICS.md](METRICS.md)
550
583
 
551
584
  ## Development and License
552
585
 
@@ -561,4 +594,8 @@ tokensafe tests
561
594
  - Security policy and vulnerability reporting: [SECURITY.md](SECURITY.md)
562
595
  - Metrics and honesty contract: [METRICS.md](METRICS.md)
563
596
 
564
- MIT License. Commercial licenses are available for self-hosted B2B and enterprise VPC deployments. Questions: [corp@tokensafe.dev](mailto:corp@tokensafe.dev) · [tokensafe.dev](https://tokensafe.dev)
597
+ Apache-2.0 for versions 4.7.0 and newer. Versions up to and including 4.6.4 were released under MIT and remain MIT forever — that grant cannot be withdrawn, and those tags stay forkable.
598
+
599
+ Commercial licenses are available for self-hosted B2B and enterprise VPC deployments, support and indemnity. Questions: [corp@tokensafe.dev](mailto:corp@tokensafe.dev) · [tokensafe.dev](https://tokensafe.dev)
600
+
601
+ "TokenSafe" and "OUMV Certified" are trademarks of Oleg Savelev. Apache-2.0 section 6 excludes trademark rights: the code is open, the names are not.
@@ -73,6 +73,17 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
73
73
  )
74
74
  except Exception:
75
75
  pass
76
+ # Routing brief: which stack is worked through OUMV vs TokenSafe tools.
77
+ try:
78
+ from src.paths import is_project_root as _is_project_root
79
+ from src.session_brief import build_workspace_brief
80
+ cwd_for_brief = str(payload.get("cwd") or os.getcwd())
81
+ if _is_project_root(cwd_for_brief):
82
+ routing = build_workspace_brief(cwd_for_brief, include_live=True)
83
+ if routing:
84
+ extra = f"{extra}\n\n{routing}"
85
+ except Exception:
86
+ pass
76
87
  try:
77
88
  from src.burn_monitor import get_burn_warnings
78
89
  burn_warn = get_burn_warnings(
@@ -136,6 +147,17 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
136
147
  )
137
148
 
138
149
  transcript_path = str(payload.get("transcript_path") or "")
150
+ # Routing brief: which stack is worked through OUMV vs TokenSafe tools.
151
+ try:
152
+ from src.paths import is_project_root as _is_project_root
153
+ from src.session_brief import build_workspace_brief
154
+ cwd_for_brief = str(payload.get("cwd") or os.getcwd())
155
+ if _is_project_root(cwd_for_brief):
156
+ routing = build_workspace_brief(cwd_for_brief, include_live=True)
157
+ if routing:
158
+ extra = f"{extra}\n\n{routing}"
159
+ except Exception:
160
+ pass
139
161
  try:
140
162
  from src.burn_monitor import get_burn_warnings
141
163
  burn_warn = get_burn_warnings(
@@ -149,13 +171,13 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
149
171
  pass
150
172
  if transcript_path:
151
173
  try:
152
- from src.history_compactor import HistoryCompactor
174
+ from src.agent import context as kernel
153
175
  from src.metrics import MetricsTracker
154
176
  turn = 0
155
177
  with open(transcript_path, "r", encoding="utf-8", errors="replace") as tf:
156
178
  turn = sum(1 for ln in tf if ln.strip())
157
179
  if turn >= 3:
158
- folded, orig_hist, folded_tok, stats = HistoryCompactor.fold_transcript(
180
+ folded, orig_hist, folded_tok, stats = kernel.fold_history(
159
181
  transcript_path, turn
160
182
  )
161
183
  if folded and stats.get("saved_tokens", 0) > 0:
@@ -55,6 +55,16 @@ def handle(event: str, payload: dict) -> dict:
55
55
  extra = f"{extra}\n\n{guard}"
56
56
  except Exception:
57
57
  pass
58
+ try:
59
+ from src.paths import is_project_root as _is_project_root
60
+ from src.session_brief import build_workspace_brief
61
+ kimi_cwd = str(payload.get("cwd") or os.getcwd())
62
+ if _is_project_root(kimi_cwd):
63
+ routing = build_workspace_brief(kimi_cwd, include_live=True)
64
+ if routing:
65
+ extra = f"{extra}\n\n{routing}"
66
+ except Exception:
67
+ pass
58
68
  try:
59
69
  from src.burn_monitor import get_burn_warnings
60
70
  burn_warn = get_burn_warnings(
@@ -116,6 +126,16 @@ def handle(event: str, payload: dict) -> dict:
116
126
  f"(TokenSafe: compacted ~{meta['saved_tokens']} prompt tokens, "
117
127
  f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
118
128
  )
129
+ try:
130
+ from src.paths import is_project_root as _is_project_root
131
+ from src.session_brief import build_workspace_brief
132
+ kimi_cwd = str(payload.get("cwd") or os.getcwd())
133
+ if _is_project_root(kimi_cwd):
134
+ routing = build_workspace_brief(kimi_cwd, include_live=True)
135
+ if routing:
136
+ extra = f"{extra}\n\n{routing}"
137
+ except Exception:
138
+ pass
119
139
  try:
120
140
  from src.burn_monitor import get_burn_warnings
121
141
  burn_warn = get_burn_warnings(
@@ -21,12 +21,10 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
21
21
  if PROJECT_ROOT not in sys.path:
22
22
  sys.path.insert(0, PROJECT_ROOT)
23
23
 
24
- from src.compactor import PromptCompactor
25
- from src.history_compactor import HistoryCompactor
26
- from src.metrics import MetricsTracker
27
- from src.governor import ContextBudget
28
- from src.license_manager import LicenseManager
24
+ from src.agent import context as kernel
29
25
  from src.adapter_core import TOKENSAFE_DIRECTIVES as PROTOCOL_DIRECTIVES, resolve_event_model
26
+ from src.license_manager import LicenseManager
27
+ from src.metrics import MetricsTracker
30
28
  from src.paths import resolve_data_dir
31
29
 
32
30
  def _model_name(payload: dict) -> str:
@@ -102,7 +100,7 @@ def _handle(payload: dict) -> dict:
102
100
  }
103
101
  })
104
102
  elif last_user_input and len(last_user_input.strip()) >= 5 and not _proxy_is_active():
105
- compaction = PromptCompactor.compact(last_user_input, enable_distill=True)
103
+ compaction = kernel.compact_prompt(last_user_input)
106
104
  saved_tokens = compaction["saved_tokens"]
107
105
  reduction_pct = compaction["reduction_pct"]
108
106
 
@@ -160,7 +158,7 @@ def _handle(payload: dict) -> dict:
160
158
  fresh_fold = False
161
159
  orig_hist_tokens = 0
162
160
  if not is_quota_exceeded and invocation_num >= 3 and transcript_path:
163
- folded_text, orig_hist_tokens, folded_tokens, stats = HistoryCompactor.fold_transcript(
161
+ folded_text, orig_hist_tokens, folded_tokens, stats = kernel.fold_history(
164
162
  transcript_path, invocation_num
165
163
  )
166
164
  if folded_text and stats.get("saved_tokens", 0) > 0:
@@ -207,10 +205,7 @@ def _handle(payload: dict) -> dict:
207
205
  if folded_text is not None:
208
206
  history_mass = orig_hist_tokens
209
207
  elif transcript_path:
210
- try:
211
- history_mass = HistoryCompactor.measure_transcript(transcript_path)
212
- except Exception:
213
- history_mass = 0
208
+ history_mass = kernel.measure_transcript(transcript_path)
214
209
 
215
210
  # 4. Adaptive Protocol Enforcement Reminder (Guard-triggered or fresh fold only)
216
211
  recent_guard = tracker.get_last_event(conversation_id, "GUARD_RAW_CODE_SEARCH")
@@ -251,7 +246,7 @@ def _handle(payload: dict) -> dict:
251
246
 
252
247
  # 5. Context Budget HUD warning
253
248
  try:
254
- budget = ContextBudget.estimate(
249
+ budget = kernel.estimate_budget(
255
250
  tracker, session_id=conversation_id,
256
251
  model=_model_name(payload),
257
252
  history_tokens=history_mass,
@@ -122,6 +122,14 @@ def main():
122
122
  extra.append(oumv_brief)
123
123
  except Exception:
124
124
  pass
125
+ # Routing brief: what goes through OUMV, what goes through TokenSafe tools.
126
+ try:
127
+ from src.session_brief import build_workspace_brief
128
+ routing = build_workspace_brief(workspace_root, include_live=True)
129
+ if routing:
130
+ extra.append(routing)
131
+ except Exception:
132
+ pass
125
133
  if extra:
126
134
  directives = f"{directives}\n\n" + "\n".join(extra)
127
135
  except Exception:
package/kimi.plugin.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.6.3",
3
+ "version": "4.7.0",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
- "license": "MIT",
6
+ "license": "Apache-2.0",
7
7
  "logo": "https://tokensafe.dev/ts-logo-black-256.png",
8
8
  "icon": "https://tokensafe.dev/ts-logo-black-256.png",
9
9
  "iconUrl": "https://tokensafe.dev/ts-logo-black-256.png",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.6.3",
4
+ "version": "4.7.0",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
@@ -55,7 +55,7 @@
55
55
  "zero-trust"
56
56
  ],
57
57
  "author": "TokenSafe",
58
- "license": "MIT",
58
+ "license": "Apache-2.0",
59
59
  "repository": {
60
60
  "type": "git",
61
61
  "url": "git+https://github.com/tokensafe-dev/tokensafe.git"
package/plugin.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.6.3",
4
+ "version": "4.7.0",
5
+ "license": "Apache-2.0",
5
6
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
7
  "logo": "assets/logo.png",
7
8
  "developerName": "TokenSafe",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.6.3",
6
+ "version": "4.7.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.6.3",
26
+ "version": "4.7.0",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.6.3",
42
+ "version": "4.7.0",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -0,0 +1,15 @@
1
+ """Agent Client Protocol adapter: JSON-RPC 2.0 over stdio for editors.
2
+
3
+ The server module is imported lazily: importing it here would execute the
4
+ module twice under ``python -m src.acp.server`` and confuse the stdio loop.
5
+ """
6
+
7
+ __all__ = ["AcpServer", "run_acp_server"]
8
+
9
+
10
+ def __getattr__(name):
11
+ if name in __all__:
12
+ from src.acp import server as _server
13
+
14
+ return getattr(_server, name)
15
+ raise AttributeError(name)