needlepath-litellm 0.2.2__tar.gz → 0.2.4__tar.gz

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.
@@ -2,6 +2,49 @@
2
2
 
3
3
  All notable changes to the `needlepath-litellm` Python package are documented here.
4
4
 
5
+ ## 0.2.4 - 2026-12-02
6
+
7
+ - Requires `needlepath>=0.2.5`.
8
+
9
+ ### Changed
10
+
11
+ - **Shadow mode no longer hands back a quarantined instruction.** The guardrail's
12
+ own shadow guard restored the original for every unprotected delivery,
13
+ including one the engine had just removed an instruction from. Shadow now
14
+ suspends ordinary trimming only: a `sanitized_fallback` and a selection
15
+ whose receipt reports `security_action: quarantine` are installed in a
16
+ shadow run exactly as in a live one, with `shadow: true` and
17
+ `applied: true` on the receipt. A selection with nothing quarantined is
18
+ measured and not applied, as before. The rule is the core client's
19
+ (`SelectionResult.security_delivery`); requires the `needlepath` release
20
+ that adds it.
21
+
22
+ ## 0.2.3 — 2026-11-05
23
+
24
+ ### Fixed
25
+
26
+ - **A protected record the length guard would keep is withheld, never kept.**
27
+ Under workspace protection (the engine's `governance` forbids raw-context
28
+ fallback) and a verdict that is not blocked, `apply_selection` kept an
29
+ individual original whenever its excerpt or placeholder was empty or not
30
+ shorter, and the guardrail only declined when the aggregate rewrite showed
31
+ no saving, so a larger saving elsewhere masked the per-record refusal and
32
+ the protected original reached the model. Such a record now collapses to
33
+ the withheld notice; the aggregate no-saving decline does not apply under
34
+ protection, since the rewrite holds no original. The engine's own stop
35
+ conditions (an empty or unusable protected response) still raise.
36
+ - **Shadow never restores a protected original.** The adapter's own shadow
37
+ guard exempted only a blocked verdict, so a protected engaged or sanitized
38
+ delivery (the core keeps it applied in a shadow run) was discarded and the
39
+ original forwarded. The guard now exempts every protected result
40
+ (`SelectionResult.protected`). Shadow still forwards the original for every
41
+ unprotected delivery.
42
+ - **A defect while installing a protected result stops the call.** Selection
43
+ and installation shared one fail-open handler, so a failure after a
44
+ protected result had been returned restored the original. The install step
45
+ now runs under `SelectionResult.applying()`: under protection it raises
46
+ `NeedlepathGuardrailError`; otherwise it fails open as before.
47
+
5
48
  ## 0.2.2 — 2026-11-04
6
49
 
7
50
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: needlepath-litellm
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Needlepath context selection as a LiteLLM proxy CustomGuardrail.
5
5
  Project-URL: Homepage, https://nextmoca.com
6
6
  Author: Next Moca Global, Inc.
@@ -14,7 +14,7 @@ Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Typing :: Typed
15
15
  Requires-Python: >=3.9
16
16
  Requires-Dist: litellm[proxy]<2.0.0,>=1.70.0
17
- Requires-Dist: needlepath<1.0.0,>=0.2.3
17
+ Requires-Dist: needlepath<1.0.0,>=0.2.5
18
18
  Provides-Extra: dev
19
19
  Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
20
20
  Requires-Dist: pytest>=7; extra == 'dev'
@@ -57,7 +57,7 @@ from config with no code.
57
57
  |---|---|---|
58
58
  | `operating_point` | — | **Required.** An immutable label. Also `NEEDLEPATH_OPERATING_POINT`. |
59
59
  | `history_max_tokens` | `8000` | Both the trigger and the budget. Under it, no call is made. |
60
- | `shadow` | `false` | Measure and report; never apply. |
60
+ | `shadow` | `false` | Measure and report; never apply an ordinary selection. A security delivery (blocked, protected, `sanitized_fallback`, `security_action: quarantine`) is still installed. |
61
61
  | `enabled` | `true` | Kill switch. Needs no credentials when `false`. |
62
62
  | `include_assistant` / `include_user` | `false` | Widen beyond tool replies. |
63
63
  | `placeholder` | see source | Replaces an unselected tool reply. |
@@ -102,8 +102,9 @@ unmodified — the same `tokens_before`/`tokens_after` the metadata blob's
102
102
  placeholder text substituted for a declined reply. Use `.stats` for anything
103
103
  that has to be true of the request; use `.engine_stats` to reconcile against
104
104
  what the service measured or billed. In shadow mode `.stats.tokens_saved` is
105
- always `0` (nothing is ever applied); `.engine_stats.tokens_saved` carries the
106
- engine's prediction.
105
+ `0` for every ordinary selection (none is applied) and counts only a security
106
+ delivery, which shadow still installs; `.engine_stats.tokens_saved` carries
107
+ the engine's prediction.
107
108
 
108
109
  ## Hook coverage — read this before you deploy
109
110
 
@@ -198,11 +199,17 @@ connection pool; a client you passed in with `client=` is never closed for you.
198
199
 
199
200
  ## Shadow mode
200
201
 
201
- `shadow: true` makes every call and changes nothing. It is the day-one
202
- deployment: put it in front of real traffic, read the numbers, decide
202
+ `shadow: true` makes every call and applies no ordinary selection. It is the
203
+ day-one deployment: put it in front of real traffic, read the numbers, decide
203
204
  afterwards. Check `guardrail.engine_stats` for what the engine predicts a live
204
- run would save — `guardrail.stats` correctly shows `0` saved, since nothing was
205
- applied.
205
+ run would save — `guardrail.stats` correctly shows `0` saved for those calls,
206
+ since nothing was applied.
207
+
208
+ Shadow suspends trimming; it never undoes a security delivery. A blocked
209
+ verdict, a delivery under workspace protection, a `sanitized_fallback`, and a
210
+ selection whose receipt reports `security_action: quarantine` are installed in
211
+ shadow mode exactly as in live mode, and the request's `needlepath` metadata
212
+ carries `shadow: true` with `applied: true`.
206
213
 
207
214
  ## Failure behaviour
208
215
 
@@ -34,7 +34,7 @@ from config with no code.
34
34
  |---|---|---|
35
35
  | `operating_point` | — | **Required.** An immutable label. Also `NEEDLEPATH_OPERATING_POINT`. |
36
36
  | `history_max_tokens` | `8000` | Both the trigger and the budget. Under it, no call is made. |
37
- | `shadow` | `false` | Measure and report; never apply. |
37
+ | `shadow` | `false` | Measure and report; never apply an ordinary selection. A security delivery (blocked, protected, `sanitized_fallback`, `security_action: quarantine`) is still installed. |
38
38
  | `enabled` | `true` | Kill switch. Needs no credentials when `false`. |
39
39
  | `include_assistant` / `include_user` | `false` | Widen beyond tool replies. |
40
40
  | `placeholder` | see source | Replaces an unselected tool reply. |
@@ -79,8 +79,9 @@ unmodified — the same `tokens_before`/`tokens_after` the metadata blob's
79
79
  placeholder text substituted for a declined reply. Use `.stats` for anything
80
80
  that has to be true of the request; use `.engine_stats` to reconcile against
81
81
  what the service measured or billed. In shadow mode `.stats.tokens_saved` is
82
- always `0` (nothing is ever applied); `.engine_stats.tokens_saved` carries the
83
- engine's prediction.
82
+ `0` for every ordinary selection (none is applied) and counts only a security
83
+ delivery, which shadow still installs; `.engine_stats.tokens_saved` carries
84
+ the engine's prediction.
84
85
 
85
86
  ## Hook coverage — read this before you deploy
86
87
 
@@ -175,11 +176,17 @@ connection pool; a client you passed in with `client=` is never closed for you.
175
176
 
176
177
  ## Shadow mode
177
178
 
178
- `shadow: true` makes every call and changes nothing. It is the day-one
179
- deployment: put it in front of real traffic, read the numbers, decide
179
+ `shadow: true` makes every call and applies no ordinary selection. It is the
180
+ day-one deployment: put it in front of real traffic, read the numbers, decide
180
181
  afterwards. Check `guardrail.engine_stats` for what the engine predicts a live
181
- run would save — `guardrail.stats` correctly shows `0` saved, since nothing was
182
- applied.
182
+ run would save — `guardrail.stats` correctly shows `0` saved for those calls,
183
+ since nothing was applied.
184
+
185
+ Shadow suspends trimming; it never undoes a security delivery. A blocked
186
+ verdict, a delivery under workspace protection, a `sanitized_fallback`, and a
187
+ selection whose receipt reports `security_action: quarantine` are installed in
188
+ shadow mode exactly as in live mode, and the request's `needlepath` metadata
189
+ carries `shadow: true` with `applied: true`.
183
190
 
184
191
  ## Failure behaviour
185
192
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "needlepath-litellm"
7
- version = "0.2.2"
7
+ version = "0.2.4"
8
8
  description = "Needlepath context selection as a LiteLLM proxy CustomGuardrail."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -27,7 +27,7 @@ classifiers = [
27
27
  # package is for the proxy, so it asks for the proxy: a guardrail that imports
28
28
  # cleanly and is never invoked is the worst of both worlds.
29
29
  dependencies = [
30
- "needlepath>=0.2.3,<1.0.0",
30
+ "needlepath>=0.2.5,<1.0.0",
31
31
  "litellm[proxy]>=1.70.0,<2.0.0",
32
32
  ]
33
33
 
@@ -11,11 +11,16 @@ while keeping its ``tool`` reply (or the reverse) is rejected by every provider,
11
11
  and rewriting content in place makes the pairing unbreakable by construction.
12
12
 
13
13
  **Invariant 2 — a rewrite never grows a message and never empties one.**
14
+ Refusing a rewrite keeps the original, which is the right degradation for an
15
+ ordinary selection and the wrong one under workspace protection: when the
16
+ engine's ``governance`` forbids raw-context fallback, a refused rewrite
17
+ collapses to the withheld notice instead (``protected_notice``), because the
18
+ original is the one thing that may not be installed.
14
19
  """
15
20
 
16
21
  from __future__ import annotations
17
22
 
18
- from typing import Any, Dict, List, Optional, Sequence, Tuple
23
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
19
24
 
20
25
  from needlepath import ContextRecord, RecordKind, SelectionResult
21
26
 
@@ -112,11 +117,70 @@ def is_prunable(
112
117
  return False
113
118
 
114
119
 
120
+ def tool_names_by_row(messages: Sequence[Dict[str, Any]]) -> Dict[int, str]:
121
+ """``row index -> tool name`` for every ``role: tool`` row whose call can be found.
122
+
123
+ The OpenAI wire format names a tool on the assistant turn that called it;
124
+ the ``role: tool`` result that answers it carries only ``tool_call_id``.
125
+ Each result is matched to the nearest preceding assistant call with that
126
+ id, so an id reused in a later turn never relabels an earlier result. The
127
+ name is a label the engine matches a workspace data scope against; nothing
128
+ here weighs, ranks or drops a record.
129
+ """
130
+ current: Dict[str, str] = {}
131
+ names: Dict[int, str] = {}
132
+ for index, message in enumerate(messages):
133
+ if not isinstance(message, dict):
134
+ continue
135
+ role = message.get("role")
136
+ if role == "assistant" and isinstance(message.get("tool_calls"), list):
137
+ for call in message["tool_calls"]:
138
+ if not isinstance(call, dict):
139
+ continue
140
+ call_id = call.get("id")
141
+ function = call.get("function")
142
+ name = function.get("name") if isinstance(function, dict) else None
143
+ if isinstance(call_id, str) and call_id and isinstance(name, str) and name.strip():
144
+ current[call_id] = name.strip()
145
+ elif role == "tool":
146
+ call_id = message.get("tool_call_id")
147
+ if isinstance(call_id, str) and call_id in current:
148
+ names[index] = current[call_id]
149
+ return names
150
+
151
+
152
+ def validate_tool_sources(value: Any) -> Dict[str, str]:
153
+ """A ``tool name -> source label`` map from config, or ``ValueError``.
154
+
155
+ Refused at startup rather than ignored: a deployment that believes its
156
+ tools carry source labels, and does not, would see every result outside
157
+ its workspace data scope.
158
+ """
159
+ if value is None:
160
+ return {}
161
+ if not isinstance(value, Mapping):
162
+ raise ValueError("tool_sources must be a mapping of tool name to source label")
163
+ out: Dict[str, str] = {}
164
+ for tool, source in value.items():
165
+ if (
166
+ not isinstance(tool, str)
167
+ or not tool.strip()
168
+ or not isinstance(source, str)
169
+ or not source.strip()
170
+ ):
171
+ raise ValueError(
172
+ "tool_sources entries must be non-empty strings: {tool name: source label}"
173
+ )
174
+ out[tool.strip()] = source.strip()
175
+ return out
176
+
177
+
115
178
  def build_records(
116
179
  messages: Sequence[Dict[str, Any]],
117
180
  *,
118
181
  include_assistant: bool = False,
119
182
  include_user: bool = False,
183
+ tool_sources: Optional[Mapping[str, str]] = None,
120
184
  ) -> Tuple[List[ContextRecord], Dict[str, int]]:
121
185
  """Records for every prunable, non-empty message, plus a ``record_id → index`` map.
122
186
 
@@ -136,6 +200,7 @@ def build_records(
136
200
  """
137
201
  records: List[ContextRecord] = []
138
202
  index_by_id: Dict[str, int] = {}
203
+ call_names = tool_names_by_row(messages)
139
204
  for index, message in enumerate(messages):
140
205
  if not isinstance(message, dict):
141
206
  continue
@@ -146,14 +211,19 @@ def build_records(
146
211
  continue
147
212
  record_id = f"m{index}"
148
213
  index_by_id[record_id] = index
149
- name = message.get("name")
214
+ # The assistant call that produced a tool result names it; a `name` on
215
+ # the result row is used only when that call cannot be found (and for
216
+ # legacy `role: function` rows, which carry no call id).
217
+ name = call_names.get(index) or message.get("name")
218
+ title = str(name).strip()[:120] if isinstance(name, str) and name.strip() else None
150
219
  records.append(
151
220
  ContextRecord(
152
221
  text=text,
153
222
  kind=message_kind(message),
154
223
  id=record_id,
224
+ source=(tool_sources or {}).get(title) if title else None,
155
225
  source_kind=str(message.get("role", "")).strip().lower() or "unknown",
156
- title=str(name)[:120] if isinstance(name, str) and name else None,
226
+ title=title,
157
227
  )
158
228
  )
159
229
  return records, index_by_id
@@ -199,14 +269,22 @@ def apply_selection(
199
269
  index_by_id: Dict[str, int],
200
270
  placeholder: str,
201
271
  withhold: bool = False,
272
+ protected_notice: Optional[str] = None,
202
273
  ) -> Tuple[List[Dict[str, Any]], int, int]:
203
274
  """Rewrite selected and unselected messages. Returns (messages, before, after).
204
275
 
205
- ``withhold`` is the one exception to the length guards below, for a
206
- ``blocked`` verdict: every record collapses to ``placeholder`` (the
207
- withheld notice) whatever its length, because the original is the thing
208
- that must not be kept. ``excerpts`` is ignored; a blocked response
209
- carries none.
276
+ Two exceptions to the length guards below, both for a response under
277
+ workspace protection, where the original is the thing that must not be
278
+ kept:
279
+
280
+ * ``withhold``, for a ``blocked`` verdict: every record collapses to
281
+ ``placeholder`` (the withheld notice) whatever its length. ``excerpts``
282
+ is ignored; a blocked response carries none.
283
+ * ``protected_notice``, for any other protected delivery: a record whose
284
+ rewrite the guards refuse collapses to this notice instead of keeping
285
+ the original. The refusal is per record, and a caller that only checks
286
+ the aggregate saving cannot see it — a large saving elsewhere would mask
287
+ one kept original and send it to the model.
210
288
 
211
289
  Every rewritten message is a **new dict**. The caller's own message objects
212
290
  are never mutated: on a proxy they can be shared with logging, with a retry
@@ -225,28 +303,17 @@ def apply_selection(
225
303
  original_text = content_text(original.get("content"))
226
304
  before += approx_tokens(original_text)
227
305
  if withhold:
228
- replacement = dict(original)
229
- replacement["content"] = placeholder
230
- out[index] = replacement
231
- after += approx_tokens(placeholder)
232
- continue
233
- excerpt = excerpts.get(record_id)
234
- if excerpt is None and not placeholder.strip():
235
- # Invariant 2, at the mutation boundary. A blank custom placeholder
236
- # would rewrite a non-empty message to nothing — the pairing
237
- # survives, the content does not. Refused rather than trusted.
238
- after += approx_tokens(original_text)
239
- continue
240
- if excerpt is None:
241
- new_text = placeholder
242
- elif not excerpt.strip() or len(excerpt) >= len(original_text):
243
- after += approx_tokens(original_text)
244
- continue
306
+ new_text: Optional[str] = placeholder
245
307
  else:
246
- new_text = excerpt
247
- if len(new_text) >= len(original_text):
248
- after += approx_tokens(original_text)
249
- continue
308
+ new_text = _rewrite_for(excerpts.get(record_id), original_text, placeholder)
309
+ if new_text is None and protected_notice is None:
310
+ # Invariant 2 refused the rewrite: the original stays.
311
+ after += approx_tokens(original_text)
312
+ continue
313
+ if new_text is None:
314
+ # Under workspace protection the original is the one thing
315
+ # that may not be installed. Withheld, with the notice.
316
+ new_text = protected_notice
250
317
  replacement = dict(original)
251
318
  replacement["content"] = new_text
252
319
  out[index] = replacement
@@ -254,6 +321,24 @@ def apply_selection(
254
321
  return out, before, after
255
322
 
256
323
 
324
+ def _rewrite_for(excerpt: Optional[str], original_text: str, placeholder: str) -> Optional[str]:
325
+ """What replaces a message, or ``None`` to refuse the rewrite.
326
+
327
+ Invariant 2, at the mutation boundary. Every ``None`` here is a rewrite
328
+ that would grow the message or empty it: a blank custom placeholder (the
329
+ pairing would survive, the content would not), a placeholder or an
330
+ excerpt that is not shorter than the message, an excerpt with nothing in
331
+ it.
332
+ """
333
+ if excerpt is None:
334
+ if not placeholder.strip() or len(placeholder) >= len(original_text):
335
+ return None
336
+ return placeholder
337
+ if not excerpt.strip() or len(excerpt) >= len(original_text):
338
+ return None
339
+ return excerpt
340
+
341
+
257
342
  def withheld_notice(result: SelectionResult) -> str:
258
343
  """The model-facing text installed for records workspace policy withheld.
259
344