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,385 @@
1
+ """The agent turn loop.
2
+
3
+ One loop, one registry, one context policy. It owns the turn that hooks used to
4
+ observe from the outside: call the model, execute tools through the canonical
5
+ MCP handler, feed results back, and govern the context between steps.
6
+
7
+ Deliberate choices:
8
+
9
+ * ``max_steps`` and ``budget_usd`` are hard caps, not suggestions — an agent
10
+ that can loop forever is a billing incident.
11
+ * Tool dispatch happens inside ``session_scope``, so every metric, pointer
12
+ cache entry and relative-path resolution in the tools belongs to *this*
13
+ session, never to a neighbouring one in the same process.
14
+ * The user prompt is not rewritten by default. Prompt compaction pays off when
15
+ a harness re-sends the prompt every turn (the hook case); in a loop the
16
+ prompt is sent once, so rewriting it only risks losing the user's words. The
17
+ real bloat is tool output and history, and that is what gets governed.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ import threading
25
+ from dataclasses import dataclass, field
26
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
27
+
28
+ from src.agent import context as kernel
29
+ from src.agent.providers import Provider, ProviderError, ToolCall, Usage, resolve_provider
30
+ from src.agent.tools import DEFAULT_TOOL_NAMES, ToolResult, dispatch_tool, tool_kind, tool_schemas
31
+ from src.session_context import current_root, session_scope
32
+
33
+ EventSink = Callable[[Dict[str, Any]], None]
34
+
35
+ DEFAULT_SYSTEM_PROMPT = """You are TokenSafe Agent, a coding agent that works inside one workspace.
36
+
37
+ Non-negotiable working rules:
38
+ - Never read whole files to find things. Use scoped_search (text/regex/glob/fuzzy) first, then smart_read_file with symbol= for the exact definition.
39
+ - Prefer one surgical call over five broad ones: smart_read_file accepts targets=[{path,symbol}] to bundle 2-8 symbols, repo_map gives the architecture (graph), exports (api) and tree.
40
+ - Edit with apply_edits (exact string targets) and cite locations as path:line. Do not print whole files.
41
+ - Run noisy commands (tests, builds) through run_helper(action="sanitize", command=...) so passing suites stay one line.
42
+ - If a read returns a pointer to content you no longer have, re-read that symbol with force_full=true once; do not guess.
43
+ - Stop when the task is done and state what changed. Do not keep exploring to look thorough.
44
+ """
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class AgentConfig:
49
+ model: str = ""
50
+ provider: str = ""
51
+ base_url: str = ""
52
+ max_steps: int = 16
53
+ budget_usd: float = 1.0
54
+ max_context_tokens: Optional[int] = None
55
+ system_prompt: str = DEFAULT_SYSTEM_PROMPT
56
+ tool_names: Sequence[str] = DEFAULT_TOOL_NAMES
57
+ compact_prompt_intake: bool = False
58
+ max_tool_result_chars: int = 24000
59
+
60
+
61
+ @dataclass
62
+ class RunResult:
63
+ text: str
64
+ stop_reason: str
65
+ steps: int
66
+ usage: Dict[str, Any]
67
+ compactions: List[Dict[str, Any]] = field(default_factory=list)
68
+ history: List[Dict[str, Any]] = field(default_factory=list)
69
+ tool_results: List[Dict[str, Any]] = field(default_factory=list)
70
+
71
+
72
+ class AgentLoop:
73
+ def __init__(
74
+ self,
75
+ root: Optional[str] = None,
76
+ session_id: str = "agent",
77
+ provider: Optional[Provider] = None,
78
+ config: Optional[AgentConfig] = None,
79
+ event_sink: Optional[EventSink] = None,
80
+ ):
81
+ self.config = config or AgentConfig()
82
+ self.root = os.path.realpath(root or current_root() or os.getcwd())
83
+ self.session_id = session_id or "agent"
84
+ self.provider = provider
85
+ self.event_sink = event_sink
86
+ self.history: List[Dict[str, Any]] = []
87
+ self.usage = Usage()
88
+ self._schemas: Optional[List[Dict[str, Any]]] = None
89
+
90
+ # -- plumbing ----------------------------------------------------------
91
+
92
+ @property
93
+ def model(self) -> str:
94
+ if self.provider is not None:
95
+ return self.provider.model
96
+ return self.config.model or os.environ.get("TOKENSAFE_AGENT_MODEL", "")
97
+
98
+ def tool_schemas(self) -> List[Dict[str, Any]]:
99
+ if self._schemas is None:
100
+ self._schemas = tool_schemas(self.config.tool_names)
101
+ return self._schemas
102
+
103
+ def num_tools(self) -> int:
104
+ return len(self.tool_schemas())
105
+
106
+ def _emit(self, event_type: str, **payload: Any) -> None:
107
+ if not self.event_sink:
108
+ return
109
+ try:
110
+ self.event_sink({"type": event_type, **payload})
111
+ except Exception:
112
+ # A broken UI must never break the agent turn.
113
+ pass
114
+
115
+ def _ensure_provider(self) -> Provider:
116
+ if self.provider is None:
117
+ self.provider = resolve_provider(
118
+ model=self.config.model,
119
+ provider=self.config.provider,
120
+ base_url=self.config.base_url,
121
+ )
122
+ return self.provider
123
+
124
+ def reset(self) -> None:
125
+ self.history = []
126
+ self.usage = Usage()
127
+
128
+ # -- context -----------------------------------------------------------
129
+
130
+ def _prepare_messages(self) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
131
+ system = {"role": "system", "content": self.config.system_prompt}
132
+ messages = [system] + self.history
133
+ window = kernel.resolve_window(self.model, self.config.max_context_tokens)
134
+ target = int(window * 0.75)
135
+ stats: Dict[str, Any] = {}
136
+ if kernel.messages_tokens(messages) > target:
137
+ governed, stats = kernel.govern_messages(
138
+ messages,
139
+ session_id=self.session_id,
140
+ model=self.model,
141
+ max_tokens=window,
142
+ target_tokens=target,
143
+ )
144
+ if stats.get("saved_tokens"):
145
+ if governed and governed[0].get("role") == "system":
146
+ messages = governed
147
+ else:
148
+ messages = [system] + governed
149
+ self.history = messages[1:]
150
+ else:
151
+ stats = {}
152
+ # Compaction (or a resumed history) can orphan a tool result from the
153
+ # assistant call that declared it; both wire formats reject that with a
154
+ # 400, so pair them up before every call.
155
+ self.history = scrub_tool_pairing(self.history)
156
+ messages = [system] + self.history
157
+ return messages, stats
158
+
159
+ # -- one provider call -------------------------------------------------
160
+
161
+ def _call_provider(
162
+ self,
163
+ messages: List[Dict[str, Any]],
164
+ cancel: Optional[threading.Event],
165
+ ) -> Tuple[str, List[ToolCall], str]:
166
+ provider = self._ensure_provider()
167
+ text_parts: List[str] = []
168
+ tool_calls: List[ToolCall] = []
169
+ stop_reason = ""
170
+ before = (self.usage.input_tokens, self.usage.output_tokens)
171
+ self.usage.calls += 1
172
+
173
+ for event in provider.stream(messages, tools=self.tool_schemas(), cancel=cancel):
174
+ if event.type == "text":
175
+ text_parts.append(event.text)
176
+ self._emit("text", text=event.text)
177
+ elif event.type == "thinking":
178
+ self._emit("thinking", text=event.text)
179
+ elif event.type == "tool_call" and event.tool_call:
180
+ tool_calls.append(event.tool_call)
181
+ self._emit(
182
+ "tool_call",
183
+ id=event.tool_call.id,
184
+ name=event.tool_call.name,
185
+ kind=tool_kind(event.tool_call.name),
186
+ arguments=_bounded_json(event.tool_call.arguments, 2000),
187
+ )
188
+ elif event.type == "usage":
189
+ self.usage.add(event.usage)
190
+ if (self.usage.input_tokens, self.usage.output_tokens) != before:
191
+ self._emit("usage", **self.usage.as_dict(self.model))
192
+ before = (self.usage.input_tokens, self.usage.output_tokens)
193
+ elif event.type == "done":
194
+ stop_reason = event.stop_reason or stop_reason
195
+ return "".join(text_parts), tool_calls, stop_reason
196
+
197
+ # -- turn --------------------------------------------------------------
198
+
199
+ def run(self, prompt: str, cancel: Optional[threading.Event] = None) -> RunResult:
200
+ """Run one user turn. Binds the session context for its whole duration."""
201
+ with session_scope(root=self.root, session_id=self.session_id, agent="tokensafe-agent"):
202
+ return self._run(prompt, cancel)
203
+
204
+ def _run(self, prompt: str, cancel: Optional[threading.Event]) -> RunResult:
205
+ prompt = (prompt or "").strip()
206
+ if not prompt:
207
+ return self._empty("empty_prompt")
208
+ if self.config.compact_prompt_intake:
209
+ prompt = self._compact_intake(prompt)
210
+
211
+ self.history.append({"role": "user", "content": prompt})
212
+ narration: List[str] = []
213
+ compactions: List[Dict[str, Any]] = []
214
+ tool_results: List[Dict[str, Any]] = []
215
+ stop_reason = "end_turn"
216
+ steps = 0
217
+
218
+ for step in range(max(1, self.config.max_steps)):
219
+ if cancel is not None and cancel.is_set():
220
+ stop_reason = "cancelled"
221
+ break
222
+ budget = self.usage.as_dict(self.model)
223
+ if budget.get("priced") and float(budget.get("usd") or 0.0) >= self.config.budget_usd:
224
+ stop_reason = "budget_exceeded"
225
+ break
226
+
227
+ steps = step + 1
228
+ messages, compaction = self._prepare_messages()
229
+ if compaction:
230
+ compactions.append(compaction)
231
+ self._emit(
232
+ "compaction",
233
+ before=compaction.get("initial_tokens", 0),
234
+ after=compaction.get("current_tokens", 0),
235
+ actions=compaction.get("actions", []),
236
+ )
237
+
238
+ text, calls, provider_stop = self._call_provider(messages, cancel)
239
+ if text:
240
+ narration.append(text)
241
+
242
+ assistant: Dict[str, Any] = {"role": "assistant", "content": text}
243
+ if calls:
244
+ assistant["tool_calls"] = [
245
+ {
246
+ "id": call.id,
247
+ "type": "function",
248
+ "function": {"name": call.name, "arguments": call.raw_arguments or json.dumps(call.arguments)},
249
+ }
250
+ for call in calls
251
+ ]
252
+ self.history.append(assistant)
253
+
254
+ if not calls:
255
+ stop_reason = provider_stop or "end_turn"
256
+ break
257
+ if cancel is not None and cancel.is_set():
258
+ stop_reason = "cancelled"
259
+ break
260
+
261
+ for call in calls:
262
+ result = self._execute(call)
263
+ self.history.append(
264
+ {"role": "tool", "tool_call_id": call.id, "content": result.text}
265
+ )
266
+ record = {
267
+ "id": call.id,
268
+ "name": call.name,
269
+ "ok": result.ok,
270
+ "truncated": result.truncated,
271
+ "chars": len(result.text or ""),
272
+ }
273
+ tool_results.append(record)
274
+ self._emit(
275
+ "tool_result",
276
+ id=call.id,
277
+ name=call.name,
278
+ ok=result.ok,
279
+ text=(result.text or "")[:8000],
280
+ truncated=result.truncated,
281
+ )
282
+ else:
283
+ stop_reason = "max_turn_requests"
284
+
285
+ result = RunResult(
286
+ text="\n\n".join(narration).strip(),
287
+ stop_reason=stop_reason,
288
+ steps=steps,
289
+ usage=self.usage.as_dict(self.model),
290
+ compactions=compactions,
291
+ history=list(self.history),
292
+ tool_results=tool_results,
293
+ )
294
+ self._emit("done", stop_reason=stop_reason, steps=steps, usage=result.usage)
295
+ return result
296
+
297
+ def _execute(self, call: ToolCall) -> ToolResult:
298
+ if call.parse_error:
299
+ return ToolResult(
300
+ name=call.name,
301
+ ok=False,
302
+ text=(
303
+ f"Tool call rejected: {call.parse_error}. Re-issue the call with valid JSON "
304
+ f"arguments for '{call.name}'."
305
+ ),
306
+ )
307
+ return dispatch_tool(call.name, call.arguments)
308
+
309
+ def _compact_intake(self, prompt: str) -> str:
310
+ """Optional hook-parity prompt rewrite, off by default (see module docstring)."""
311
+ if len(prompt) < 80:
312
+ return prompt
313
+ try:
314
+ compaction = kernel.compact_prompt(prompt)
315
+ except Exception:
316
+ return prompt
317
+ if compaction.get("saved_tokens", 0) >= 40 and compaction.get("reduction_pct", 0) >= 20:
318
+ self._emit(
319
+ "compaction",
320
+ before=compaction.get("original_tokens", 0),
321
+ after=compaction.get("compact_tokens", 0),
322
+ actions=["compact_prompt"],
323
+ )
324
+ return f"{prompt}\n\n[TOCP intent of the request above]: {compaction['compact_text']}"
325
+ return prompt
326
+
327
+ def _empty(self, reason: str) -> RunResult:
328
+ return RunResult(
329
+ text="",
330
+ stop_reason=reason,
331
+ steps=0,
332
+ usage=self.usage.as_dict(self.model),
333
+ history=list(self.history),
334
+ )
335
+
336
+
337
+ def _bounded_json(value: Any, limit: int) -> Any:
338
+ try:
339
+ rendered = json.dumps(value, ensure_ascii=False, sort_keys=True)
340
+ except Exception:
341
+ return str(value)[:limit]
342
+ if len(rendered) <= limit:
343
+ return value
344
+ return rendered[:limit] + "…"
345
+
346
+
347
+ def scrub_tool_pairing(history: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
348
+ """Drop tool results nothing declared, and declarations nothing answered.
349
+
350
+ Both keep the request valid for OpenAI-compatible and Anthropic endpoints
351
+ after an aggressive compaction pass: a ``tool`` message must answer a
352
+ ``tool_calls`` entry that precedes it, and every declared call must have a
353
+ result. Orphans are removed rather than filled with fake output.
354
+ """
355
+ answered = {
356
+ str(message.get("tool_call_id"))
357
+ for message in history
358
+ if message.get("role") == "tool" and message.get("tool_call_id")
359
+ }
360
+ declared = {
361
+ str(call.get("id"))
362
+ for message in history
363
+ if message.get("role") == "assistant"
364
+ for call in (message.get("tool_calls") or [])
365
+ if call.get("id")
366
+ }
367
+ keep_calls = answered & declared
368
+ scrubbed: List[Dict[str, Any]] = []
369
+ for message in history:
370
+ role = message.get("role")
371
+ if role == "assistant" and message.get("tool_calls"):
372
+ calls = [call for call in message["tool_calls"] if str(call.get("id")) in keep_calls]
373
+ if not calls:
374
+ if message.get("content"):
375
+ scrubbed.append({"role": "assistant", "content": message["content"]})
376
+ continue
377
+ patched = dict(message)
378
+ patched["tool_calls"] = calls
379
+ scrubbed.append(patched)
380
+ elif role == "tool":
381
+ if str(message.get("tool_call_id")) in keep_calls:
382
+ scrubbed.append(message)
383
+ else:
384
+ scrubbed.append(message)
385
+ return scrubbed
@@ -0,0 +1,77 @@
1
+ """Provider price table for the agent loop.
2
+
3
+ Prices are a pinned snapshot, not a live feed: the loop reports a USD figure
4
+ only for models it can price, and marks everything else ``priced: false``
5
+ instead of inventing a number. Override with ``TOKENSAFE_AGENT_PRICES_JSON``:
6
+
7
+ {"my-model": {"input_miss": 0.5, "input_hit": 0.1, "output": 2.0}}
8
+
9
+ Values are USD per 1M tokens, matching how providers publish them.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ from typing import Any, Dict, Optional
17
+
18
+ PRICE_SNAPSHOT = "2026-11-26"
19
+
20
+ # Only models whose published prices were verified for this snapshot live here.
21
+ # Adding a guess would make the spend report dishonest, which is worse than an
22
+ # unlabelled zero.
23
+ DEFAULT_PRICES: Dict[str, Dict[str, float]] = {
24
+ "deepseek-chat": {"input_miss": 0.27, "input_hit": 0.07, "output": 1.10},
25
+ "deepseek-flash": {"input_miss": 0.27, "input_hit": 0.07, "output": 1.10},
26
+ }
27
+
28
+
29
+ def _overrides() -> Dict[str, Dict[str, float]]:
30
+ raw = os.environ.get("TOKENSAFE_AGENT_PRICES_JSON", "").strip()
31
+ if not raw:
32
+ return {}
33
+ try:
34
+ parsed = json.loads(raw)
35
+ except Exception:
36
+ return {}
37
+ if not isinstance(parsed, dict):
38
+ return {}
39
+ clean: Dict[str, Dict[str, float]] = {}
40
+ for model, price in parsed.items():
41
+ if isinstance(price, dict):
42
+ try:
43
+ clean[str(model)] = {
44
+ "input_miss": float(price.get("input_miss", 0.0)),
45
+ "input_hit": float(price.get("input_hit", 0.0)),
46
+ "output": float(price.get("output", 0.0)),
47
+ }
48
+ except (TypeError, ValueError):
49
+ continue
50
+ return clean
51
+
52
+
53
+ def price_for(model: str) -> Optional[Dict[str, float]]:
54
+ key = (model or "").strip().lower()
55
+ if not key:
56
+ return None
57
+ table = dict(DEFAULT_PRICES)
58
+ table.update(_overrides())
59
+ return table.get(key)
60
+
61
+
62
+ def usd(
63
+ model: str,
64
+ input_miss_tokens: int,
65
+ cache_hit_tokens: int,
66
+ output_tokens: int,
67
+ ) -> Dict[str, Any]:
68
+ """Cost for one usage bucket. ``priced`` is False when the model is unknown."""
69
+ price = price_for(model)
70
+ if not price:
71
+ return {"usd": 0.0, "priced": False, "price_snapshot": PRICE_SNAPSHOT}
72
+ cost = (
73
+ max(0, int(input_miss_tokens)) / 1_000_000 * price["input_miss"]
74
+ + max(0, int(cache_hit_tokens)) / 1_000_000 * price["input_hit"]
75
+ + max(0, int(output_tokens)) / 1_000_000 * price["output"]
76
+ )
77
+ return {"usd": round(cost, 6), "priced": True, "price_snapshot": PRICE_SNAPSHOT}