tokensafe 4.6.4 → 4.7.1

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 (44) hide show
  1. package/.codex-plugin/plugin.json +2 -2
  2. package/LICENSE +202 -21
  3. package/README.md +30 -4
  4. package/hooks/claude_code_hook.py +17 -15
  5. package/hooks/kimi_hook.py +14 -12
  6. package/hooks/pre_invocation.py +7 -12
  7. package/hooks/session_start.py +8 -2
  8. package/kimi.plugin.json +2 -2
  9. package/package.json +2 -2
  10. package/plugin.json +2 -1
  11. package/rules/AGENTS.md +1 -1
  12. package/server.json +3 -3
  13. package/src/acp/__init__.py +15 -0
  14. package/src/acp/server.py +328 -0
  15. package/src/adapter_core.py +2 -1
  16. package/src/agent/__init__.py +11 -0
  17. package/src/agent/context.py +99 -0
  18. package/src/agent/loop.py +385 -0
  19. package/src/agent/pricing.py +77 -0
  20. package/src/agent/providers.py +486 -0
  21. package/src/agent/tools.py +98 -0
  22. package/src/agent_firewall.py +16 -1
  23. package/src/auto_inject.py +93 -7
  24. package/src/batch_editor.py +106 -15
  25. package/src/bench/__init__.py +1 -0
  26. package/src/bench/driver.py +234 -0
  27. package/src/bench/go_target.py +646 -0
  28. package/src/bench/mechanics.py +214 -0
  29. package/src/bench/react_target.py +541 -0
  30. package/src/bench/runner.py +331 -0
  31. package/src/bench/tokensafe_mcp.py +144 -0
  32. package/src/cli.py +156 -0
  33. package/src/history_compactor.py +200 -2
  34. package/src/installer.py +3 -3
  35. package/src/mcp_server.py +510 -237
  36. package/src/paths.py +41 -2
  37. package/src/retrofit.py +27 -5
  38. package/src/scaffold.py +8 -6
  39. package/src/scoped_search.py +67 -5
  40. package/src/session_brief.py +180 -15
  41. package/src/session_context.py +124 -0
  42. package/src/skeletonizer.py +9 -3
  43. package/src/telemetry_sync.py +1 -1
  44. package/src/version_checker.py +1 -1
@@ -10,10 +10,97 @@ from typing import Dict, Any, Optional, List, Tuple
10
10
  from src.tokenizer import count_tokens
11
11
 
12
12
 
13
+ def _block_text(content: Any) -> str:
14
+ """Plain text of a message content (plain string or typed block list)."""
15
+ if isinstance(content, str):
16
+ return content
17
+ if not isinstance(content, list):
18
+ return ""
19
+ parts: List[str] = []
20
+ for block in content:
21
+ if not isinstance(block, dict):
22
+ continue
23
+ btype = str(block.get("type") or "")
24
+ if btype in ("text", "thinking", "reasoning"):
25
+ text = block.get("text") or block.get("thinking")
26
+ if isinstance(text, str) and text:
27
+ parts.append(text)
28
+ elif btype == "tool_result":
29
+ nested = _block_text(block.get("content"))
30
+ if nested:
31
+ parts.append(nested)
32
+ return " ".join(parts)
33
+
34
+
35
+ def _model_io_parts(step: dict) -> Tuple[str, List[Tuple[str, dict]], str]:
36
+ """Normalize a ZCode `model_io` record into (text, tool_calls, user_prompt).
37
+
38
+ One record is one provider call: `request.messages` carries either only the
39
+ new messages (`messagesKind: "delta"`) or a window ending with the newest
40
+ message, while `response` holds that call's assistant output. Only the newest
41
+ message is new state, so folding stays linear instead of re-counting the
42
+ cumulative conversation once per record. `user_prompt` is non-empty when the
43
+ record sits on a turn boundary (the digest's active goal).
44
+ """
45
+ request = step.get("request") if isinstance(step.get("request"), dict) else {}
46
+ response = step.get("response") if isinstance(step.get("response"), dict) else {}
47
+
48
+ messages = request.get("messages") if isinstance(request.get("messages"), list) else []
49
+ newest: dict = messages[-1] if messages and isinstance(messages[-1], dict) else {}
50
+ newest_role = str(newest.get("role") or "")
51
+ newest_text = _block_text(newest.get("content"))
52
+
53
+ user_prompt = ""
54
+ if newest_role == "user":
55
+ candidate = newest_text.strip()
56
+ if candidate and not _is_injected_prompt(candidate):
57
+ user_prompt = candidate
58
+ if not user_prompt and request.get("messagesKind") in ("full", "delta"):
59
+ # Complete (or purely new) windows: the newest user message is this
60
+ # turn's prompt even when trailing tool results follow it.
61
+ for item in reversed(messages):
62
+ if not isinstance(item, dict) or item.get("role") != "user":
63
+ continue
64
+ candidate = _block_text(item.get("content")).strip()
65
+ if candidate and not _is_injected_prompt(candidate):
66
+ user_prompt = candidate
67
+ break
68
+
69
+ assistant_text = response.get("text")
70
+ if not isinstance(assistant_text, str):
71
+ assistant_text = ""
72
+ reasoning_text = response.get("reasoningText")
73
+ if not isinstance(reasoning_text, str):
74
+ reasoning_text = ""
75
+
76
+ parts: List[str] = []
77
+ if newest_role == "user" and newest_text.strip():
78
+ parts.append(newest_text) # the prompt itself leads the step
79
+ elif user_prompt:
80
+ parts.append(user_prompt) # prompt recovered from deeper in the window
81
+ if assistant_text.strip():
82
+ parts.append(assistant_text)
83
+ if reasoning_text.strip():
84
+ parts.append(reasoning_text)
85
+ if newest_role != "user" and newest_text.strip():
86
+ parts.append(newest_text)
87
+
88
+ calls: List[Tuple[str, dict]] = []
89
+ for call in response.get("toolCalls") or []:
90
+ if not isinstance(call, dict):
91
+ continue
92
+ args = call.get("input")
93
+ calls.append((str(call.get("name") or ""), args if isinstance(args, dict) else {}))
94
+
95
+ return "\n".join(part for part in parts if part), calls, user_prompt
96
+
97
+
13
98
  def _extract_step_text(step: dict) -> str:
14
99
  """Step text in any supported transcript format (Antigravity string/list, Claude Code text/thinking/tool_result)."""
15
100
  if not isinstance(step, dict):
16
101
  return ""
102
+ if step.get("type") == "model_io":
103
+ return _model_io_parts(step)[0]
17
104
  content = step.get("content")
18
105
  if isinstance(content, str) and content:
19
106
  return content
@@ -23,6 +110,61 @@ def _extract_step_text(step: dict) -> str:
23
110
  for b in content
24
111
  if isinstance(b, dict)
25
112
  ).strip()
113
+ # ZCode event log: {"type": "...", "payload": {...}}
114
+ payload = step.get("payload")
115
+ if isinstance(payload, dict):
116
+ pcontent = payload.get("content")
117
+ if isinstance(pcontent, str) and pcontent:
118
+ return pcontent
119
+ if isinstance(pcontent, list):
120
+ parts = [
121
+ str(b.get("text") or b.get("thinking") or "")
122
+ for b in pcontent
123
+ if isinstance(b, dict)
124
+ ]
125
+ joined = " ".join(parts).strip()
126
+ if joined:
127
+ return joined
128
+ pinput = payload.get("input")
129
+ if isinstance(pinput, str) and pinput:
130
+ return pinput
131
+ if step.get("type") == "turn_started" and isinstance(pinput, dict):
132
+ text = pinput.get("text") or pinput.get("prompt")
133
+ if isinstance(text, str) and text:
134
+ return text
135
+
136
+ # ZCode model-io log: {request:{body:{messages}}, response:{body:{choices}}}
137
+ response = step.get("response")
138
+ if isinstance(response, dict):
139
+ try:
140
+ msg = response["body"]["choices"][0]["message"]
141
+ except Exception:
142
+ msg = None
143
+ if isinstance(msg, dict):
144
+ content = msg.get("content")
145
+ if isinstance(content, str) and content:
146
+ return content
147
+ if isinstance(content, list):
148
+ joined = " ".join(
149
+ str(b.get("text") or "")
150
+ for b in content
151
+ if isinstance(b, dict)
152
+ ).strip()
153
+ if joined:
154
+ return joined
155
+ request = step.get("request")
156
+ if isinstance(request, dict):
157
+ try:
158
+ messages = request["body"]["messages"]
159
+ except Exception:
160
+ messages = None
161
+ if isinstance(messages, list):
162
+ for item in reversed(messages):
163
+ if isinstance(item, dict) and item.get("role") == "user":
164
+ content = item.get("content")
165
+ if isinstance(content, str) and content:
166
+ return content
167
+
26
168
  message = step.get("message")
27
169
  if not isinstance(message, dict):
28
170
  return ""
@@ -80,12 +222,40 @@ def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
80
222
  calls: List[Tuple[str, dict]] = []
81
223
  if not isinstance(step, dict):
82
224
  return calls
225
+ if step.get("type") == "model_io":
226
+ return _model_io_parts(step)[1]
83
227
  tc_list = step.get("tool_calls")
84
228
  if isinstance(tc_list, list):
85
229
  for tc in tc_list:
86
230
  if isinstance(tc, dict):
87
231
  args = tc.get("args")
88
232
  calls.append((str(tc.get("name", "")), args if isinstance(args, dict) else {}))
233
+ response = step.get("response")
234
+ if isinstance(response, dict):
235
+ try:
236
+ message = response["body"]["choices"][0]["message"]
237
+ except Exception:
238
+ message = None
239
+ if isinstance(message, dict):
240
+ for tc in message.get("tool_calls") or []:
241
+ fn = (tc or {}).get("function") or {}
242
+ name = str(fn.get("name") or "")
243
+ raw_args = fn.get("arguments")
244
+ args = {}
245
+ if isinstance(raw_args, str):
246
+ try:
247
+ args = json.loads(raw_args)
248
+ except Exception:
249
+ args = {}
250
+ elif isinstance(raw_args, dict):
251
+ args = raw_args
252
+ calls.append((name, args if isinstance(args, dict) else {}))
253
+
254
+ payload = step.get("payload")
255
+ if isinstance(payload, dict) and step.get("type") == "tool_call_scheduled":
256
+ args = payload.get("input")
257
+ calls.append((str(payload.get("toolName", "")), args if isinstance(args, dict) else {}))
258
+
89
259
  message = step.get("message")
90
260
  if isinstance(message, dict):
91
261
  mc = message.get("content")
@@ -96,6 +266,21 @@ def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
96
266
  calls.append((str(block.get("name", "")), inp if isinstance(inp, dict) else {}))
97
267
  return calls
98
268
 
269
+ _INJECTED_PROMPT_MARKERS = (
270
+ "<system-reminder",
271
+ "critical: respond with text",
272
+ "respond with text only",
273
+ "[tokensafe",
274
+ "[oumv",
275
+ )
276
+
277
+
278
+ def _is_injected_prompt(text: str) -> bool:
279
+ """True for harness-injected reminders that arrive as user-role messages."""
280
+ lowered = text.lower()
281
+ return any(marker in lowered for marker in _INJECTED_PROMPT_MARKERS)
282
+
283
+
99
284
  def _clean_goal_text(text: str) -> str:
100
285
  """Extracts a clean, single-sentence goal from raw user text or prompt."""
101
286
  if not text:
@@ -143,6 +328,8 @@ class HistoryCompactor:
143
328
 
144
329
  if source == "USER_EXPLICIT" or stype == "USER_INPUT" or role == "user":
145
330
  raw_txt = _extract_step_text(step)
331
+ if _is_injected_prompt(raw_txt):
332
+ continue
146
333
  cleaned = _clean_goal_text(raw_txt)
147
334
  if cleaned:
148
335
  active_goal = cleaned
@@ -152,6 +339,8 @@ class HistoryCompactor:
152
339
  # Fallback to key turns if any
153
340
  for step in steps:
154
341
  raw_txt = _extract_step_text(step)
342
+ if _is_injected_prompt(raw_txt):
343
+ continue
155
344
  cleaned = _clean_goal_text(raw_txt)
156
345
  if cleaned and len(cleaned) > 15:
157
346
  active_goal = cleaned
@@ -261,9 +450,18 @@ class HistoryCompactor:
261
450
  line = line.strip()
262
451
  if line:
263
452
  try:
264
- steps.append(json.loads(line))
453
+ parsed = json.loads(line)
265
454
  except Exception:
266
- pass
455
+ continue
456
+ # A model-io record whose newest message is the user's
457
+ # prompt is the turn boundary the digest looks for.
458
+ if (
459
+ isinstance(parsed, dict)
460
+ and parsed.get("type") == "model_io"
461
+ and _model_io_parts(parsed)[2]
462
+ ):
463
+ parsed["role"] = "user"
464
+ steps.append(parsed)
267
465
  except Exception:
268
466
  return None, 0, 0, {}
269
467
 
package/src/installer.py CHANGED
@@ -48,10 +48,10 @@ UNIFIED_TOKENSAFE_RULE = (
48
48
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
49
49
  "Always use `tokensafe` MCP tools (`smart_read_file`, `scoped_search`, `apply_edits`, `repo_map`, `session_context`, `oumv`, `run_helper`) over default raw file reads or high-output terminal executions.\n\n"
50
50
  "1. **Zero Raw Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). Use `tokensafe:scoped_search(query, path='.', scope='code')` for single searches (`mode='auto'|'text'|'regex'|'glob'|'fuzzy'|'git'`) or `queries=[...]` for up to 20 concurrent queries in one call.\n"
51
- "2. **Mandatory Symbol, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
51
+ "2. **Mandatory Symbol, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). `symbol` accepts an identifier, a qualified member (`Type.Method`) or an endpoint target (`'POST /api/orders'`): when the target is not a declaration in that file you get the enclosing handler body (or a tight ±window around the hit) with line numbers — that is the slice you edit, never a folded skeleton you have to re-read. Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
52
52
  "3. **Repeat Read Deduplication**: Never re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`).\n"
53
- "4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`.\n"
54
- "5. **Architecture Graph, API Surface & Directory Tree (`repo_map`)**: For any codebase inquiry or refactor, FIRST call `tokensafe:repo_map(view='graph', project_path=...)` for God Nodes (<250 tokens). Use `view='api'` for exported types/interfaces and `view='tree'` instead of `ls -la`.\n"
53
+ "4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`. For a failing test, one hunk + `verify='auto'` (the project's own declared test command) per attempt: the edit and the verdict come back in one call, so read the reported line and apply the next hunk instead of rewriting whole files.\n"
54
+ "5. **Architecture Graph, API Surface & Directory Tree (`repo_map`)**: For an unfamiliar repository or a broad refactor, FIRST call `tokensafe:repo_map(view='graph', project_path=...)` for God Nodes (<250 tokens). Use `view='api'` for exported types/interfaces and `view='tree'` instead of `ls -la`. Skip the map when the task already names the failing endpoint, symbol or file — go straight to `scoped_search` + `smart_read_file`.\n"
55
55
  "6. **Utilities (`run_helper`)**: Use `tokensafe:run_helper(action=...)` for rare/auxiliary operations: `'sanitize'` (rewrite shell/test commands), `'guard'` (pre-flight secret/safety audit), `'diff'` (slice diff), `'deps'` (lockfile point lookup), `'web'` (fetch clean Markdown), `'expand'` (restore `#hash`), `'image'` (downscale >1024px), and `'compress'` (TOCP prompt).\n"
56
56
  "7. **Compact Tests & Build Output**: Run noisy commands, builds, and test suites via `tokensafe wrap '<cmd>'` or `tokensafe tests [cmd]` (clean 1-line summary on pass, full trace on failure; never leave `vitest`/`jest`/`bun` in watch mode).\n"
57
57
  "8. **Styles & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `smart_read_file` preserves design tokens (`:root`, `@theme`, CSS variables) in full.\n"