tokensafe 4.6.4 → 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.
@@ -0,0 +1,328 @@
1
+ """Agent Client Protocol (ACP) server over stdio.
2
+
3
+ ACP is how editors that do not host their own agent run an external one: Zed
4
+ spawns the agent as a subprocess and speaks JSON-RPC 2.0 over stdin/stdout;
5
+ JetBrains AI Assistant does the same via a custom agent entry; Neovim
6
+ (CodeCompanion, avante) and Emacs (agent-shell) have ACP clients too. Shipping
7
+ this adapter gives TokenSafe a native agent inside those editors without
8
+ anyone building an editor.
9
+
10
+ Scope of this server: sessions, prompts, streaming updates, tool call
11
+ visibility and cancellation. Embedded context (text blocks) is accepted;
12
+ images are rejected with an explanation because the loop has no vision path.
13
+ There is no interactive permission prompt yet — tool calls run under the same
14
+ guard as the MCP server (destructive commands and secret reads are refused),
15
+ which is the documented v1 boundary.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+ import sys
23
+ import threading
24
+ import uuid
25
+ from dataclasses import dataclass, field
26
+ from typing import Any, Callable, Dict, IO, List, Optional
27
+
28
+ from src.agent.loop import DEFAULT_SYSTEM_PROMPT, AgentConfig, AgentLoop, RunResult
29
+ from src.agent.providers import Provider, ProviderError, resolve_provider
30
+
31
+ PROTOCOL_VERSION = 1
32
+ SERVER_NAME = "tokensafe-agent"
33
+
34
+ _STOP_REASONS = {"end_turn", "max_tokens", "max_turn_requests", "refusal", "cancelled"}
35
+
36
+
37
+ def _map_stop(reason: str) -> str:
38
+ if reason in _STOP_REASONS:
39
+ return reason
40
+ if reason == "budget_exceeded":
41
+ return "max_turn_requests"
42
+ if reason == "empty_prompt":
43
+ return "end_turn"
44
+ return "end_turn"
45
+
46
+
47
+ @dataclass
48
+ class _Session:
49
+ session_id: str
50
+ root: str
51
+ loop: AgentLoop
52
+ cancel: threading.Event = field(default_factory=threading.Event)
53
+
54
+
55
+ class AcpServer:
56
+ """Minimal, testable ACP server.
57
+
58
+ ``provider_factory`` exists so tests (and embedders) can inject a
59
+ deterministic provider instead of reaching the network.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ reader: IO[str],
65
+ writer: IO[str],
66
+ provider_factory: Optional[Callable[[str, str], Provider]] = None,
67
+ client_name: str = "",
68
+ ):
69
+ self._reader = reader
70
+ self._writer = writer
71
+ self._write_lock = threading.Lock()
72
+ self._sessions: Dict[str, _Session] = {}
73
+ self._workers: List[threading.Thread] = []
74
+ self._provider_factory = provider_factory or _default_provider
75
+ self._client_name = client_name
76
+
77
+ # -- io ----------------------------------------------------------------
78
+
79
+ def _write(self, message: Dict[str, Any]) -> None:
80
+ payload = json.dumps(message, ensure_ascii=False)
81
+ with self._write_lock:
82
+ try:
83
+ self._writer.write(payload + "\n")
84
+ self._writer.flush()
85
+ except Exception:
86
+ pass
87
+
88
+ def _respond(self, request_id: Any, result: Dict[str, Any]) -> None:
89
+ self._write({"jsonrpc": "2.0", "id": request_id, "result": result})
90
+
91
+ def _error(self, request_id: Any, code: int, message: str) -> None:
92
+ self._write({"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}})
93
+
94
+ def _notify(self, method: str, params: Dict[str, Any]) -> None:
95
+ self._write({"jsonrpc": "2.0", "method": method, "params": params})
96
+
97
+ # -- main loop ---------------------------------------------------------
98
+
99
+ def serve(self) -> None:
100
+ for line in self._reader:
101
+ line = line.strip()
102
+ if not line:
103
+ continue
104
+ try:
105
+ message = json.loads(line)
106
+ except Exception:
107
+ continue
108
+ if isinstance(message, dict):
109
+ self.handle(message)
110
+ self.wait_idle()
111
+
112
+ def wait_idle(self, timeout: float = 30.0) -> None:
113
+ """Join in-flight prompt workers (used by tests and graceful shutdown)."""
114
+ for worker in list(self._workers):
115
+ worker.join(timeout)
116
+
117
+ # -- dispatch ----------------------------------------------------------
118
+
119
+ def handle(self, message: Dict[str, Any]) -> None:
120
+ method = message.get("method")
121
+ if not isinstance(method, str):
122
+ return # client responses to agent requests are not used yet
123
+ request_id = message.get("id")
124
+ params = message.get("params") if isinstance(message.get("params"), dict) else {}
125
+
126
+ if request_id is None:
127
+ self._handle_notification(method, params)
128
+ return
129
+
130
+ try:
131
+ if method == "initialize":
132
+ self._respond(request_id, self._initialize(params))
133
+ elif method == "authenticate":
134
+ self._respond(request_id, {})
135
+ elif method == "session/new":
136
+ self._respond(request_id, self._new_session(params))
137
+ elif method == "session/prompt":
138
+ self._start_prompt(request_id, params)
139
+ else:
140
+ self._error(request_id, -32601, f"Method not found: {method}")
141
+ except ProviderError as exc:
142
+ self._error(request_id, -32000, str(exc))
143
+ except Exception as exc:
144
+ self._error(request_id, -32603, f"{type(exc).__name__}: {exc}")
145
+
146
+ def _handle_notification(self, method: str, params: Dict[str, Any]) -> None:
147
+ if method == "session/cancel":
148
+ session = self._sessions.get(str(params.get("sessionId") or ""))
149
+ if session:
150
+ session.cancel.set()
151
+ # Client notifications we do not model (fs/terminal capability updates)
152
+ # are ignored rather than answered: notifications must never get a reply.
153
+
154
+ # -- methods -----------------------------------------------------------
155
+
156
+ def _initialize(self, params: Dict[str, Any]) -> Dict[str, Any]:
157
+ requested = params.get("protocolVersion")
158
+ version = requested if requested == PROTOCOL_VERSION else PROTOCOL_VERSION
159
+ client_info = params.get("clientInfo") if isinstance(params.get("clientInfo"), dict) else {}
160
+ if client_info.get("name"):
161
+ self._client_name = str(client_info["name"])
162
+ return {
163
+ "protocolVersion": version,
164
+ "agentCapabilities": {
165
+ "promptCapabilities": {"image": False, "audio": False, "embeddedContext": True},
166
+ "loadSession": False,
167
+ },
168
+ "agentInfo": {"name": SERVER_NAME, "version": _version()},
169
+ "authMethods": [],
170
+ }
171
+
172
+ def _new_session(self, params: Dict[str, Any]) -> Dict[str, Any]:
173
+ cwd = str(params.get("cwd") or "").strip()
174
+ root = os.path.realpath(cwd) if cwd and os.path.isdir(cwd) else os.path.realpath(os.getcwd())
175
+ session_id = f"acp-{uuid.uuid4().hex[:12]}"
176
+ provider = self._provider_factory(root, session_id)
177
+ config = AgentConfig(
178
+ system_prompt=(
179
+ DEFAULT_SYSTEM_PROMPT
180
+ + f"\n\nActive workspace: {root}\n"
181
+ + "All paths are resolved against this root. Absolute paths outside it are refused."
182
+ )
183
+ )
184
+ loop = AgentLoop(
185
+ root=root,
186
+ session_id=f"acp:{session_id}",
187
+ provider=provider,
188
+ config=config,
189
+ event_sink=lambda event: self._forward_update(session_id, event),
190
+ )
191
+ self._sessions[session_id] = _Session(session_id=session_id, root=root, loop=loop)
192
+ return {"sessionId": session_id}
193
+
194
+ def _start_prompt(self, request_id: Any, params: Dict[str, Any]) -> None:
195
+ session_id = str(params.get("sessionId") or "")
196
+ session = self._sessions.get(session_id)
197
+ if not session:
198
+ self._error(request_id, -32602, f"unknown sessionId '{session_id}'")
199
+ return
200
+ text, rejected = _prompt_text(params.get("prompt"))
201
+ if rejected:
202
+ self._notify(
203
+ "session/update",
204
+ {
205
+ "sessionId": session_id,
206
+ "update": {
207
+ "sessionUpdate": "agent_message_chunk",
208
+ "content": {"type": "text", "text": rejected},
209
+ },
210
+ },
211
+ )
212
+ if not text.strip():
213
+ self._respond(request_id, {"stopReason": "end_turn"})
214
+ return
215
+
216
+ session.cancel.clear()
217
+
218
+ def worker() -> None:
219
+ try:
220
+ result: RunResult = session.loop.run(text, cancel=session.cancel)
221
+ self._respond(request_id, {"stopReason": _map_stop(result.stop_reason)})
222
+ except ProviderError as exc:
223
+ self._error(request_id, -32000, str(exc))
224
+ except Exception as exc:
225
+ self._error(request_id, -32603, f"{type(exc).__name__}: {exc}")
226
+
227
+ thread = threading.Thread(target=worker, name=f"acp-prompt-{session_id}", daemon=True)
228
+ self._workers.append(thread)
229
+ thread.start()
230
+
231
+ def _forward_update(self, session_id: str, event: Dict[str, Any]) -> None:
232
+ kind = event.get("type")
233
+ update: Optional[Dict[str, Any]] = None
234
+ if kind == "text" and event.get("text"):
235
+ update = {
236
+ "sessionUpdate": "agent_message_chunk",
237
+ "content": {"type": "text", "text": event["text"]},
238
+ }
239
+ elif kind == "thinking" and event.get("text"):
240
+ update = {
241
+ "sessionUpdate": "agent_thought_chunk",
242
+ "content": {"type": "text", "text": event["text"]},
243
+ }
244
+ elif kind == "tool_call":
245
+ update = {
246
+ "sessionUpdate": "tool_call",
247
+ "toolCallId": event.get("id") or "",
248
+ "title": _tool_title(str(event.get("name") or ""), event.get("arguments")),
249
+ "kind": event.get("kind") or "other",
250
+ "status": "in_progress",
251
+ "rawInput": event.get("arguments"),
252
+ }
253
+ elif kind == "tool_result":
254
+ update = {
255
+ "sessionUpdate": "tool_call_update",
256
+ "toolCallId": event.get("id") or "",
257
+ "status": "completed" if event.get("ok") else "failed",
258
+ "content": [
259
+ {"type": "content", "content": {"type": "text", "text": event.get("text") or ""}}
260
+ ],
261
+ }
262
+ if update is not None:
263
+ self._notify("session/update", {"sessionId": session_id, "update": update})
264
+
265
+
266
+ def _prompt_text(blocks: Any) -> tuple[str, str]:
267
+ """Flatten ACP content blocks into one prompt; return (text, rejection_note)."""
268
+ if isinstance(blocks, str):
269
+ return blocks, ""
270
+ if not isinstance(blocks, list):
271
+ return "", ""
272
+ parts: List[str] = []
273
+ notes: List[str] = []
274
+ for block in blocks:
275
+ if not isinstance(block, dict):
276
+ continue
277
+ block_type = block.get("type")
278
+ if block_type == "text":
279
+ parts.append(str(block.get("text") or ""))
280
+ elif block_type == "resource_link":
281
+ uri = str(block.get("uri") or "")
282
+ parts.append(f"[resource] {uri}")
283
+ elif block_type == "image":
284
+ notes.append("Image input is not supported by the TokenSafe agent yet; describe it in text.")
285
+ elif block_type == "resource":
286
+ resource = block.get("resource") or {}
287
+ if isinstance(resource, dict) and resource.get("text"):
288
+ parts.append(str(resource["text"]))
289
+ return "\n".join(part for part in parts if part).strip(), " ".join(notes)
290
+
291
+
292
+ def _tool_title(name: str, arguments: Any) -> str:
293
+ if isinstance(arguments, dict):
294
+ target = (
295
+ arguments.get("path")
296
+ or arguments.get("query")
297
+ or arguments.get("pattern")
298
+ or arguments.get("action")
299
+ or ""
300
+ )
301
+ if target:
302
+ return f"{name}: {str(target)[:120]}"
303
+ return name or "tool"
304
+
305
+
306
+ def _default_provider(root: str, session_id: str) -> Provider:
307
+ return resolve_provider()
308
+
309
+
310
+ def _version() -> str:
311
+ try:
312
+ from src.version_checker import CURRENT_VERSION
313
+ return CURRENT_VERSION
314
+ except Exception:
315
+ return "0.0.0"
316
+
317
+
318
+ def run_acp_server(provider_factory: Optional[Callable[[str, str], Provider]] = None) -> None:
319
+ server = AcpServer(sys.stdin, sys.stdout, provider_factory=provider_factory)
320
+ server.serve()
321
+
322
+
323
+ def main() -> None:
324
+ run_acp_server()
325
+
326
+
327
+ if __name__ == "__main__":
328
+ main()
@@ -0,0 +1,11 @@
1
+ """In-process agent kernel.
2
+
3
+ TokenSafe started as a hook-based add-on: another harness owned the turn and
4
+ TokenSafe reacted to it. This package owns the turn instead — provider router,
5
+ streaming, tool dispatch and context governance in one loop — so the same
6
+ kernel can be driven by the ACP server, the CLI, or a test harness.
7
+
8
+ Import cost matters here: nothing in this package imports ``src.mcp_server`` at
9
+ module level, because the MCP server is a large dependency graph and the
10
+ provider layer must stay usable (and testable) without it.
11
+ """
@@ -0,0 +1,99 @@
1
+ """Shared context-governance kernel.
2
+
3
+ Both the lifecycle hooks and the in-process agent loop call these functions.
4
+ The hook path and the agent path must never drift into two different
5
+ compaction policies: that is how a product ends up with two metrics stories
6
+ and two definitions of "saved tokens".
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ from src.compactor import PromptCompactor
15
+ from src.governor import ContextBudget, ContextGovernor
16
+ from src.history_compactor import HistoryCompactor
17
+ from src.tokenizer import count_tokens
18
+
19
+ # Below this saving a prompt rewrite is noise: it burns a rewrite and changes
20
+ # the model's instructions for less than a line of text.
21
+ MIN_PROMPT_SAVING = 5
22
+
23
+
24
+ def compact_prompt(text: str, enable_distill: bool = True) -> Dict[str, Any]:
25
+ """Compile a user prompt into TOCP intent form (same call the hook makes)."""
26
+ return PromptCompactor.compact(text, enable_distill=enable_distill)
27
+
28
+
29
+ def fold_history(transcript_path: str, invocation_num: int) -> Tuple[Optional[str], int, int, Dict[str, Any]]:
30
+ """Fold past turns into a Consolidated State Ledger."""
31
+ return HistoryCompactor.fold_transcript(transcript_path, invocation_num)
32
+
33
+
34
+ def measure_transcript(transcript_path: str) -> int:
35
+ """Real token mass of a session transcript (0 when unreadable)."""
36
+ try:
37
+ return int(HistoryCompactor.measure_transcript(transcript_path) or 0)
38
+ except Exception:
39
+ return 0
40
+
41
+
42
+ def estimate_budget(
43
+ tracker,
44
+ session_id: str,
45
+ model: str = "",
46
+ history_tokens: int = 0,
47
+ transcript_path: str = "",
48
+ ) -> Dict[str, Any]:
49
+ """Context Budget HUD, shared by hooks and the in-loop governor."""
50
+ return ContextBudget.estimate(
51
+ tracker,
52
+ session_id=session_id,
53
+ model=model,
54
+ history_tokens=history_tokens,
55
+ transcript_path=transcript_path,
56
+ )
57
+
58
+
59
+ def govern_messages(
60
+ messages: List[Dict[str, Any]],
61
+ session_id: str,
62
+ model: str = "",
63
+ max_tokens: Optional[int] = None,
64
+ target_tokens: Optional[int] = None,
65
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
66
+ """Trim the live message list before a model call.
67
+
68
+ ``ContextGovernor`` is the single implementation: it compacts code blocks,
69
+ folds deep history into a ledger and records the CONTEXT_GOVERNOR metric.
70
+ """
71
+ return ContextGovernor.govern_messages(
72
+ messages,
73
+ max_tokens=max_tokens,
74
+ target_tokens=target_tokens,
75
+ session_id=session_id,
76
+ model=model,
77
+ )
78
+
79
+
80
+ def resolve_window(model: str = "", window_tokens: Optional[int] = None) -> int:
81
+ return ContextBudget.resolve_window(model, window_tokens)
82
+
83
+
84
+ def messages_tokens(messages: List[Dict[str, Any]]) -> int:
85
+ """Cheap token mass of a message list (content + serialized tool calls)."""
86
+ total = 0
87
+ for msg in messages:
88
+ if not isinstance(msg, dict):
89
+ total += count_tokens(str(msg))
90
+ continue
91
+ content = msg.get("content")
92
+ if isinstance(content, str):
93
+ total += count_tokens(content)
94
+ elif content is not None:
95
+ total += count_tokens(json.dumps(content, ensure_ascii=False))
96
+ for call in msg.get("tool_calls") or []:
97
+ total += count_tokens(json.dumps(call, ensure_ascii=False))
98
+ total += 4 # role/separator overhead
99
+ return total