tokensafe 4.2.7 → 4.2.9

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.2.7",
2
+ "version": "4.2.9",
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": {
@@ -31,6 +31,6 @@
31
31
  ],
32
32
  "websiteURL": "https://tokensafe.dev",
33
33
  "brandColor": "#10B981",
34
- "logo": "https://tokensafe.dev/logo.png"
34
+ "logo": "https://tokensafe.dev/ts-logo-black-256.png"
35
35
  }
36
36
  }
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <img src="assets/logo.svg" alt="TokenSafe Logo" width="88" height="88" />
2
+ <img src="https://www.tokensafe.dev/ts-logo-transp-big.png" alt="TokenSafe Logo" width="88" height="88" />
3
3
  </p>
4
4
 
5
5
  <h1 align="center">TokenSafe</h1>
@@ -67,28 +67,25 @@ def main():
67
67
  except Exception:
68
68
  pass
69
69
 
70
- inject_steps = [
71
- {"systemMessage": {"systemMessage": PROTOCOL_DIRECTIVES, "metadata": {}}}
72
- ]
73
-
70
+ directives = PROTOCOL_DIRECTIVES
74
71
  try:
75
72
  from src.graph_engine import GraphEngine
76
73
  graph = GraphEngine.get_instance(workspace_root)
77
74
  banner = graph.format_topology_banner()
78
75
  if banner:
79
- inject_steps.append({
80
- "systemMessage": {
81
- "systemMessage": (
82
- f"{banner}\n"
83
- "⚡ Core God Nodes and dependency hubs mapped above. "
84
- "Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
85
- ),
86
- "metadata": {},
87
- }
88
- })
76
+ directives = (
77
+ f"{directives}\n\n"
78
+ f"{banner}\n"
79
+ "⚡ Core God Nodes and dependency hubs mapped above. "
80
+ "Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
81
+ )
89
82
  except Exception:
90
83
  pass
91
84
 
85
+ inject_steps = [
86
+ {"systemMessage": {"systemMessage": directives, "metadata": {}}}
87
+ ]
88
+
92
89
  try:
93
90
  tracker = MetricsTracker()
94
91
  quota = LicenseManager.check_quota(tracker)
package/kimi.plugin.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.2.7",
3
+ "version": "4.2.9",
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
6
  "license": "MIT",
7
- "logo": "https://tokensafe.dev/logo.png",
8
- "icon": "https://tokensafe.dev/logo.png",
9
- "iconUrl": "https://tokensafe.dev/logo.png",
7
+ "logo": "https://tokensafe.dev/ts-logo-black-256.png",
8
+ "icon": "https://tokensafe.dev/ts-logo-black-256.png",
9
+ "iconUrl": "https://tokensafe.dev/ts-logo-black-256.png",
10
10
  "author": {
11
11
  "name": "TokenSafe"
12
12
  },
@@ -15,8 +15,8 @@
15
15
  "shortDescription": "Stop coding agent context rot, destructive rewrites & secret leaks",
16
16
  "developerName": "TokenSafe",
17
17
  "websiteURL": "https://tokensafe.dev",
18
- "logo": "https://tokensafe.dev/logo.png",
19
- "iconUrl": "https://tokensafe.dev/logo.png"
18
+ "logo": "https://tokensafe.dev/ts-logo-black-256.png",
19
+ "iconUrl": "https://tokensafe.dev/ts-logo-black-256.png"
20
20
  },
21
21
  "skills": [
22
22
  "skills/token-optimizer"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.2.7",
4
+ "version": "4.2.9",
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": {
package/plugin.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.2.7",
4
+ "version": "4.2.9",
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
- "logo": "https://tokensafe.dev/logo.png",
6
+ "logo": "https://tokensafe.dev/ts-logo-black-256.png",
7
7
  "developerName": "TokenSafe",
8
8
  "author": {
9
9
  "name": "TokenSafe",
package/rules/AGENTS.md CHANGED
@@ -32,8 +32,8 @@ Execute the specified action directly based on these extracted parameters.
32
32
  2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `"src/service.ts"` or absolute) and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview). Lockfiles (`package-lock.json`, `Cargo.lock`) and tabular data (`.csv`, `.tsv`, `.sql`, `.har`) auto-reduce to compact schemas with reversible hash anchors.
33
33
  3. **Reversible Hash Stashing (`expand_ref`)**: Whenever TokenSafe folds a long command output, test log, file, or MCP payload, it tags it with an 8-character hash `[TokenSafe folded: #a1b2c3d4 ...]`. If full raw content is ever needed, ALWAYS call `tokensafe:expand_ref(hash="a1b2c3d4")` or run `tokensafe expand-ref a1b2c3d4` to retrieve the exact original bytes without re-running.
34
34
  4. **Web & Documentation Reading (`read_web_page`)**: To read web pages, documentation, or API references, ALWAYS call `tokensafe:read_web_page(url)` or run `tokensafe web <url>` instead of raw HTML fetches — it strips scripts, styles, navbars, and cookie banners (-80-95% tokens).
35
- 5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path=".")` to locate God Nodes and dependency topology in < 250 tokens before reading individual files or searching (`project_path` defaults to active workspace).
36
- 6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path=".")` to get all exported classes, types, and interfaces in a single markdown map without crawling files.
35
+ 5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` to locate God Nodes and dependency topology in < 250 tokens before reading individual files or searching (pass the target project's absolute path when working across multiple workspaces or outside CWD).
36
+ 6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map without crawling files (pass the target project's absolute path when working across multiple workspaces or outside CWD).
37
37
  7. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
38
38
  8. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path=".", depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
39
39
  9. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
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.2.7",
6
+ "version": "4.2.9",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -16,13 +16,6 @@
16
16
  "sizes": [
17
17
  "96x96"
18
18
  ]
19
- },
20
- {
21
- "src": "https://tokensafe.dev/logo.svg",
22
- "mimeType": "image/svg+xml",
23
- "sizes": [
24
- "any"
25
- ]
26
19
  }
27
20
  ],
28
21
  "packages": [
@@ -30,7 +23,7 @@
30
23
  "registryType": "npm",
31
24
  "registryBaseUrl": "https://registry.npmjs.org",
32
25
  "identifier": "tokensafe",
33
- "version": "4.2.7",
26
+ "version": "4.2.9",
34
27
  "runtimeHint": "npx",
35
28
  "transport": {
36
29
  "type": "stdio"
@@ -46,7 +39,7 @@
46
39
  "registryType": "pypi",
47
40
  "registryBaseUrl": "https://pypi.org",
48
41
  "identifier": "tokensafe",
49
- "version": "4.2.7",
42
+ "version": "4.2.9",
50
43
  "runtimeHint": "uvx",
51
44
  "transport": {
52
45
  "type": "stdio"
@@ -32,7 +32,7 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
32
32
  - **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -98% tokens).
33
33
 
34
34
  3. **MANDATORY ARCHITECTURE GRAPH & GOD NODES FIRST (`get_architecture_graph`)**:
35
- - For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path=".")` (`project_path` defaults to active workspace) before diving into individual files or running searches.
35
+ - For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` before diving into individual files or running searches. Always pass the target project's absolute path (e.g. `"/path/to/repo"`) when working across multiple workspaces or outside CWD.
36
36
  - **Result**: Returns top architectural God Nodes, dependency hubs, and centrality rankings in < 250 tokens without file crawling.
37
37
 
38
38
  4. **API SURFACE INSPECTION (`get_api_surface`)**:
@@ -38,7 +38,7 @@ TOKENSAFE_DIRECTIVES = (
38
38
  "• Zero-Fluff Egress: Omit conversational filler, courtesy preambles, and wrap-ups. Format responses in dense, technical prose.\n"
39
39
  "• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.\n"
40
40
  "• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
41
- "• Mandatory Architecture Graph & God Nodes: For any codebase navigation, feature design, or multi-component investigation, ALWAYS inspect God Nodes via 'tokensafe:get_architecture_graph(project_path)' first before diving into individual files.\n"
41
+ "• Mandatory Architecture Graph & God Nodes: For any codebase inquiry, navigation, or multi-component work, ALWAYS inspect God Nodes via 'tokensafe:get_architecture_graph(project_path)' first before diving into files (pass target project's absolute path in multi-repo setups).\n"
42
42
  "• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
43
43
  "• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check context headroom and Quality Score (Grade S-F).\n"
44
44
  "• When context_budget reports warning/critical or Grade C/F: call 'tokensafe:compact_conversation(transcript_path=...)' to fold history before continuing.\n"
@@ -134,6 +134,22 @@ def _is_test_file(rel_path: str) -> bool:
134
134
  or base.endswith(("_test.py", "_test.go", ".test.ts", ".test.tsx", ".test.js", ".test.jsx", ".spec.ts", ".spec.tsx", ".spec.js"))
135
135
  )
136
136
 
137
+
138
+ def _is_generated_file(rel_path: str) -> bool:
139
+ norm = rel_path.replace("\\", "/").lower()
140
+ base = os.path.basename(norm)
141
+ parts = norm.split("/")
142
+ if any(p in ("generated", "__generated__", ".gen", "gen", "swagger", "openapi") for p in parts[:-1]):
143
+ return True
144
+ if any(p.endswith((".gen", "__generated__")) for p in parts[:-1]):
145
+ return True
146
+ return (
147
+ base.startswith(("swagger", "openapi", "generated"))
148
+ or base.endswith((".swagger.ts", ".swagger.js", ".gen.ts", ".gen.js", ".gen.go", ".pb.go", "_pb2.py"))
149
+ or "swaggerapi" in base
150
+ or "openapi" in base
151
+ )
152
+
137
153
  class CodeSymbol:
138
154
  """Represents a structural code entity (file, class, or function)."""
139
155
  __slots__ = ("name", "kind", "file_path", "line_start", "line_end", "signature", "body")
@@ -1090,7 +1106,7 @@ class CodeGraph:
1090
1106
  Prioritizes resolved file-to-file imports and import-verified symbol calls,
1091
1107
  and downweights test files when production files are present.
1092
1108
  """
1093
- has_prod_files = any(not _is_test_file(p) for p in self.file_symbols.keys())
1109
+ has_prod_files = any(not _is_test_file(p) and not _is_generated_file(p) for p in self.file_symbols.keys())
1094
1110
  has_resolved_imports = any(
1095
1111
  t.startswith("file:")
1096
1112
  for src, targets in self.edges.items()
@@ -1120,7 +1136,14 @@ class CodeGraph:
1120
1136
  in_degree += 1
1121
1137
 
1122
1138
  raw_centrality = in_degree * 2 + out_degree
1123
- rank_score = raw_centrality * 0.2 if (has_prod_files and _is_test_file(rel_path)) else float(raw_centrality)
1139
+ if has_prod_files and _is_test_file(rel_path):
1140
+ rank_score = raw_centrality * 0.1
1141
+ elif has_prod_files and _is_generated_file(rel_path):
1142
+ rank_score = raw_centrality * 0.01
1143
+ elif has_prod_files and in_degree == 0:
1144
+ rank_score = raw_centrality * 0.15
1145
+ else:
1146
+ rank_score = float(in_degree * 3 + out_degree)
1124
1147
  scores[rel_path] = {
1125
1148
  "file": rel_path,
1126
1149
  "centrality": raw_centrality,
@@ -1443,10 +1466,13 @@ class CodeGraph:
1443
1466
 
1444
1467
  def format_topology_banner(self) -> str:
1445
1468
  """Creates a compact 1-line prompt injection banner for coding agents."""
1446
- god_nodes = self.get_god_nodes(top_n=4)
1469
+ god_nodes = self.get_god_nodes(top_n=6)
1447
1470
  if not god_nodes:
1448
1471
  return ""
1449
- items = [f"{g['file']} ({g['dependents']} deps)" for g in god_nodes]
1472
+ # In multi-file projects, Core Hubs must have incoming dependents (dependents > 0)
1473
+ hubs = [g for g in god_nodes if g.get("dependents", 0) > 0]
1474
+ nodes_to_show = hubs[:4] if hubs else god_nodes[:4]
1475
+ items = [f"{g['file']} ({g['dependents']} deps)" for g in nodes_to_show]
1450
1476
  return f"[TokenSafe Architecture Map | Core Hubs: {', '.join(items)}]"
1451
1477
 
1452
1478
 
package/src/installer.py CHANGED
@@ -51,8 +51,8 @@ UNIFIED_TOKENSAFE_RULE = (
51
51
  "2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `'src/service.ts'` or absolute) and `symbol`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).\n"
52
52
  "3. **Repeat Read Deduplication**: Never repeatedly re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`); pass `force_full=true` only if context was compacted or you are a fresh subagent.\n"
53
53
  "4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler, courtesy preambles, and sign-offs. Provide concise bullet prose. Never reprint full unmodified files or lengthy boilerplate; link to file line ranges (`file.ts#L10-L25`) and output surgical diffs.\n"
54
- "5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path='.')` to inspect project God Nodes and key dependency hubs in < 250 tokens before reading individual files or searching.\n"
55
- "6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path='.')` to get all exported classes, types, and interfaces in a single markdown map without crawling files.\n"
54
+ "5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` to inspect project God Nodes and key dependency hubs in < 250 tokens before reading individual files or searching (pass target project's absolute path in multi-repo setups).\n"
55
+ "6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map without crawling files (pass target project's absolute path in multi-repo setups).\n"
56
56
  "7. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path='.', depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path='src'`).\n"
57
57
  "8. **Command Sanitization, Build Compaction & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `git push` --no-progress, `git commit` hook protection, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`, and build/typecheck commands like `npm run build`, `vite build`, `next build`, `cargo build`, `tsc`, `tsc --noEmit`, `npm run typecheck`, `npx eslint`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, `go test`) via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 1-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest`/`bun` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
58
58
  "9. **Styles & Design Token Preservation**: When inspecting CSS, SCSS, LESS, or Tailwind, `smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors to protect project design integrity.\n"
@@ -72,8 +72,8 @@ POINTER_RULE = (
72
72
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
73
73
  "The full 12-point protocol is installed globally in the agent-level instructions "
74
74
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
75
- "Core rules: never raw grep/find or `ls -la` — use `tokensafe:scoped_search`, "
76
- "`tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
75
+ "Core rules: never raw grep/find or `ls -la` — use `tokensafe:get_architecture_graph(project_path)` first for God Nodes, "
76
+ "`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
77
77
  "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
78
78
  "before large tasks and compact via `tokensafe:compact_conversation` (orientation digest active); never hardcode secret "
79
79
  "fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
@@ -1427,8 +1427,8 @@ WantedBy=default.target
1427
1427
  p["enabled"] = True
1428
1428
  p["updatedAt"] = iso_now
1429
1429
  p["originalSource"] = PROJECT_ROOT
1430
- p["iconUrl"] = "https://tokensafe.dev/logo.png"
1431
- p["logo"] = "https://tokensafe.dev/logo.png"
1430
+ p["iconUrl"] = "https://tokensafe.dev/ts-logo-black-256.png"
1431
+ p["logo"] = "https://tokensafe.dev/ts-logo-black-256.png"
1432
1432
  entry_found = True
1433
1433
  break
1434
1434
  if not entry_found:
@@ -1440,8 +1440,8 @@ WantedBy=default.target
1440
1440
  "updatedAt": iso_now,
1441
1441
  "originalSource": PROJECT_ROOT,
1442
1442
  "origin": "custom",
1443
- "iconUrl": "https://tokensafe.dev/logo.png",
1444
- "logo": "https://tokensafe.dev/logo.png"
1443
+ "iconUrl": "https://tokensafe.dev/ts-logo-black-256.png",
1444
+ "logo": "https://tokensafe.dev/ts-logo-black-256.png"
1445
1445
  })
1446
1446
  cls._atomic_write_json(installed_json, inst_data)
1447
1447
 
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.2.7"
45
+ "version": "4.2.9"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -127,7 +127,7 @@ TOOLS = [
127
127
  "inputSchema": {
128
128
  "type": "object",
129
129
  "properties": {
130
- "project_path": {"type": "string", "description": "Optional root path of the project (defaults to active workspace, or pass '.' or absolute path)"}
130
+ "project_path": {"type": "string", "description": "Target project root directory. IMPORTANT: Always pass the absolute directory path (e.g. '/path/to/repo') when working in multi-workspace setups or repositories outside CWD."}
131
131
  }
132
132
  }
133
133
  },
@@ -137,7 +137,7 @@ TOOLS = [
137
137
  "inputSchema": {
138
138
  "type": "object",
139
139
  "properties": {
140
- "project_path": {"type": "string", "description": "Optional root path of the project (defaults to active workspace, or pass '.' or absolute path)"}
140
+ "project_path": {"type": "string", "description": "Target project root directory. IMPORTANT: Always pass the absolute directory path (e.g. '/path/to/repo') when working in multi-workspace setups or repositories outside CWD."}
141
141
  }
142
142
  }
143
143
  },
package/src/proxy.py CHANGED
@@ -110,7 +110,9 @@ def _blocks_from_content(content: Any, role: str = "user") -> List[Dict[str, Any
110
110
  if not isinstance(blk, dict):
111
111
  continue
112
112
  btype = blk.get("type")
113
- if btype == "text" and isinstance(blk.get("text"), str):
113
+ # Empty text blocks are rejected by strict Anthropic mirrors (z.ai 1214)
114
+ # and carry no information — drop them at the source.
115
+ if btype == "text" and isinstance(blk.get("text"), str) and blk["text"]:
114
116
  nb = {"type": "text", "text": blk["text"]}
115
117
  if isinstance(blk.get("cache_control"), dict):
116
118
  nb["cache_control"] = blk["cache_control"]
@@ -169,9 +171,12 @@ def _translate_openai_payload_to_anthropic(payload: Dict[str, Any]) -> Dict[str,
169
171
 
170
172
  if role == "assistant":
171
173
  blocks: List[Dict[str, Any]] = _blocks_from_content(msg.get("content"), "assistant")
174
+ thinking = msg.get("_tokensafe_thinking") if isinstance(msg.get("_tokensafe_thinking"), list) else []
175
+ has_tool_use = False
172
176
  for tc in (msg.get("tool_calls") or []):
173
177
  if not isinstance(tc, dict):
174
178
  continue
179
+ has_tool_use = True
175
180
  fn = tc.get("function") or {}
176
181
  try:
177
182
  tool_input = json.loads(fn.get("arguments") or "{}")
@@ -188,9 +193,21 @@ def _translate_openai_payload_to_anthropic(payload: Dict[str, Any]) -> Dict[str,
188
193
  "name": fn.get("name") or "unknown",
189
194
  "input": tool_input,
190
195
  })
191
- if not blocks:
192
- blocks = [{"type": "text", "text": ""}]
193
- out_messages.append({"role": "assistant", "content": _collapse_plain_text(blocks) if len(blocks) == 1 and blocks[0].get("type") == "text" else blocks})
196
+ if not blocks and not thinking:
197
+ # An assistant turn with neither text, tool_use, nor thinking is
198
+ # illegal upstream (z.ai answers 1214 "messages parameter illegal").
199
+ continue
200
+ if thinking:
201
+ # Extended-thinking models (GLM via z.ai, Claude): assistant
202
+ # history must carry its thinking blocks back, signature included —
203
+ # thinking first, then text/tool_use. Dropping them (the old
204
+ # ingest behavior) trips strict mirrors with 1214.
205
+ content: Any = thinking + blocks if blocks else list(thinking)
206
+ elif len(blocks) == 1 and blocks[0].get("type") == "text":
207
+ content = _collapse_plain_text(blocks)
208
+ else:
209
+ content = blocks
210
+ out_messages.append({"role": "assistant", "content": content})
194
211
  elif role == "tool":
195
212
  tc_content = msg.get("content")
196
213
  text = tc_content if isinstance(tc_content, str) else json.dumps(tc_content, ensure_ascii=False)
@@ -203,7 +220,13 @@ def _translate_openai_payload_to_anthropic(payload: Dict[str, Any]) -> Dict[str,
203
220
  "content": [{"type": "tool_result", "tool_use_id": msg.get("tool_call_id") or "toolu_call", "content": text}],
204
221
  })
205
222
  elif role == "user":
206
- out_messages.append({"role": "user", "content": _collapse_plain_text(_blocks_from_content(msg.get("content"), "user")) or [{"type": "text", "text": ""}]})
223
+ blocks = _blocks_from_content(msg.get("content"), "user")
224
+ if not blocks:
225
+ # Empty user turns are rejected by strict mirrors — drop instead
226
+ # of emitting {"type":"text","text":""}; adjacent same-role
227
+ # messages are re-merged below, so alternation stays valid.
228
+ continue
229
+ out_messages.append({"role": "user", "content": _collapse_plain_text(blocks)})
207
230
 
208
231
  out: Dict[str, Any] = {
209
232
  "model": payload.get("model") or "claude-3-5-sonnet-latest",
@@ -366,12 +389,20 @@ def _translate_anthropic_payload_to_openai(payload: Dict[str, Any]) -> Dict[str,
366
389
  if role == "assistant":
367
390
  text_parts: List[str] = []
368
391
  tool_calls = []
392
+ thinking_blocks: List[Dict[str, Any]] = []
369
393
  blocks = content if isinstance(content, list) else ([{"type": "text", "text": content}] if isinstance(content, str) else [])
370
394
  for blk in blocks:
371
395
  if not isinstance(blk, dict):
372
396
  continue
373
397
  if blk.get("type") == "text" and isinstance(blk.get("text"), str):
374
398
  text_parts.append(blk["text"])
399
+ elif blk.get("type") in ("thinking", "redacted_thinking"):
400
+ # Side-channel: extended-thinking blocks must survive the
401
+ # OpenAI-form pipeline untouched so the outbound Anthropic
402
+ # translation can restore them (strict mirrors reject
403
+ # assistant history whose tool_use turns lost their thinking
404
+ # prefix — z.ai 1214 "messages parameter is illegal").
405
+ thinking_blocks.append(blk)
375
406
  elif blk.get("type") == "tool_use":
376
407
  tool_calls.append({
377
408
  "id": blk.get("id") or f"call_{blk.get('name', 'tool')}",
@@ -384,6 +415,8 @@ def _translate_anthropic_payload_to_openai(payload: Dict[str, Any]) -> Dict[str,
384
415
  m: Dict[str, Any] = {"role": "assistant", "content": "\n\n".join(text_parts) if text_parts else None}
385
416
  if tool_calls:
386
417
  m["tool_calls"] = tool_calls
418
+ if thinking_blocks:
419
+ m["_tokensafe_thinking"] = thinking_blocks
387
420
  out_messages.append(m)
388
421
  elif role == "user":
389
422
  blocks = content if isinstance(content, list) else ([{"type": "text", "text": content}] if isinstance(content, str) else [])
@@ -1091,6 +1124,12 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1091
1124
  # itself speaks Anthropic (ingest): the pipeline ran on the internal
1092
1125
  # OpenAI form, and this puts it back into Anthropic shape for upstream.
1093
1126
  payload = _translate_openai_payload_to_anthropic(payload)
1127
+ else:
1128
+ # The ingest thinking side-channel is Anthropic-only — never leak it
1129
+ # into an OpenAI-dialect upstream request.
1130
+ for _m in payload.get("messages") or []:
1131
+ if isinstance(_m, dict):
1132
+ _m.pop("_tokensafe_thinking", None)
1094
1133
 
1095
1134
  headers = {"Content-Type": "application/json"}
1096
1135
  if provider == "anthropic":
@@ -1245,6 +1284,22 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1245
1284
  with e:
1246
1285
  err_body = e.read()
1247
1286
  ctype = e.headers.get("Content-Type", "application/json") if e.headers else "application/json"
1287
+ # Permanent diagnostics: upstream rejections were previously forwarded
1288
+ # to the client without any server-side trace, making incidents like
1289
+ # z.ai 1214 undiagnosable from proxy.log alone.
1290
+ try:
1291
+ sys.stderr.write(
1292
+ f"[TokenSafe] {self.command} {self.path} -> upstream {e.code}: "
1293
+ f"{err_body[:400].decode('utf-8', 'replace')}\n"
1294
+ )
1295
+ if e.code == 400:
1296
+ sys.stderr.write(
1297
+ "[TokenSafe][debug] upstream-400 payload preview: "
1298
+ f"model={payload.get('model')!r} msgs={len(payload.get('messages') or [])} "
1299
+ f"body[:1200]={json.dumps(payload, ensure_ascii=False)[:1200]}\n"
1300
+ )
1301
+ except Exception:
1302
+ pass
1248
1303
  if provider == "anthropic" and not client_anthropic:
1249
1304
  err_body = _translate_anthropic_error_body(err_body)
1250
1305
  elif client_anthropic and provider != "anthropic":
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.2.7"
244
+ "User-Agent": "TokenSafe-Sync/4.2.9"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.2.7"
20
+ CURRENT_VERSION = "4.2.9"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage