needlepath-litellm 0.2.3__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,23 @@
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
+
5
22
  ## 0.2.3 — 2026-11-05
6
23
 
7
24
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: needlepath-litellm
3
- Version: 0.2.3
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.3"
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
 
@@ -20,7 +20,7 @@ original is the one thing that may not be installed.
20
20
 
21
21
  from __future__ import annotations
22
22
 
23
- from typing import Any, Dict, List, Optional, Sequence, Tuple
23
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
24
24
 
25
25
  from needlepath import ContextRecord, RecordKind, SelectionResult
26
26
 
@@ -117,11 +117,70 @@ def is_prunable(
117
117
  return False
118
118
 
119
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
+
120
178
  def build_records(
121
179
  messages: Sequence[Dict[str, Any]],
122
180
  *,
123
181
  include_assistant: bool = False,
124
182
  include_user: bool = False,
183
+ tool_sources: Optional[Mapping[str, str]] = None,
125
184
  ) -> Tuple[List[ContextRecord], Dict[str, int]]:
126
185
  """Records for every prunable, non-empty message, plus a ``record_id → index`` map.
127
186
 
@@ -141,6 +200,7 @@ def build_records(
141
200
  """
142
201
  records: List[ContextRecord] = []
143
202
  index_by_id: Dict[str, int] = {}
203
+ call_names = tool_names_by_row(messages)
144
204
  for index, message in enumerate(messages):
145
205
  if not isinstance(message, dict):
146
206
  continue
@@ -151,14 +211,19 @@ def build_records(
151
211
  continue
152
212
  record_id = f"m{index}"
153
213
  index_by_id[record_id] = index
154
- 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
155
219
  records.append(
156
220
  ContextRecord(
157
221
  text=text,
158
222
  kind=message_kind(message),
159
223
  id=record_id,
224
+ source=(tool_sources or {}).get(title) if title else None,
160
225
  source_kind=str(message.get("role", "")).strip().lower() or "unknown",
161
- title=str(name)[:120] if isinstance(name, str) and name else None,
226
+ title=title,
162
227
  )
163
228
  )
164
229
  return records, index_by_id