amfs-http-server 0.3.55__tar.gz → 0.3.62__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.
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: amfs-http-server
3
- Version: 0.3.55
3
+ Version: 0.3.62
4
4
  Summary: AMFS HTTP/REST API server with SSE support
5
5
  License-Expression: Apache-2.0
6
6
  Requires-Python: >=3.11
7
- Requires-Dist: amfs-core>=0.3.45
8
- Requires-Dist: amfs>=0.5.37
7
+ Requires-Dist: amfs-core>=0.3.53
8
+ Requires-Dist: amfs>=0.5.40
9
9
  Requires-Dist: fastapi>=0.115
10
10
  Requires-Dist: httpx>=0.27
11
11
  Requires-Dist: sse-starlette>=2.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "amfs-http-server"
3
- version = "0.3.55"
3
+ version = "0.3.62"
4
4
  description = "AMFS HTTP/REST API server with SSE support"
5
5
  requires-python = ">=3.11"
6
6
  license = "Apache-2.0"
@@ -13,7 +13,7 @@ dependencies = [
13
13
  # this tree is what test_dependency_floors forbids.
14
14
  # 0.5.18 for AgentMemory.as_agent, which the agent detail page calls to list
15
15
  # an agent's entries as that agent rather than as the server.
16
- "amfs>=0.5.37",
16
+ "amfs>=0.5.40",
17
17
  # 0.3.23 is real in the silent way: the write path calls
18
18
  # adapter.scope_counts(), which is a default on AdapterABC from 0.3.23. On an
19
19
  # older core the adapters that do not override it — filesystem, S3 — have no
@@ -27,7 +27,7 @@ dependencies = [
27
27
  # unexpected keyword, _scope_block swallows it, and the block disappears —
28
28
  # while an adapter that ignored the argument instead would name another
29
29
  # agent's private keys. Either way the floor is what makes the rule real.
30
- "amfs-core>=0.3.45",
30
+ "amfs-core>=0.3.53",
31
31
  "fastapi>=0.115",
32
32
  # 0.37 is where uvicorn.run() grew timeout_worker_healthcheck, which
33
33
  # main() passes unconditionally; on anything older that is a TypeError
@@ -0,0 +1,396 @@
1
+ """Byte-faithful capture of a proxied chat completion (t2-8e, OSS half).
2
+
3
+ The memory proxy forwards an OpenAI-shaped request to a frontier model and
4
+ hands the answer back. What training needs from that exchange is the whole of
5
+ it — the request body as sent (model, every message in the history, the tool
6
+ schemas, the sampling options), and the response as received, reassembled
7
+ from the SSE deltas when it streamed — kept as it was on the wire rather than
8
+ as a paraphrase, and tied to the bytes by hash so a reader can tell a faithful
9
+ copy from a reconstruction.
10
+
11
+ This module is the data shape and the capture surface. It does not select,
12
+ render or train — that is the Pro side's — and it is **off by default**:
13
+ ``capture_enabled(request)`` is true only when ``AMFS_PROXY_CAPTURE=true`` or
14
+ when the hosting layer has installed an opt-in resolver (``set_opt_in``) that
15
+ says so for this request's account. Captured text goes through the secret
16
+ scanner before anything is persisted; a blocked message is replaced by a
17
+ marker, never written.
18
+
19
+ The payload travels as ``session_metadata["capture"]`` on a
20
+ :class:`~amfs_core.models.DecisionTrace` with no outcome — a capture is not
21
+ evidence and moves no confidence — persisted through the adapter's
22
+ ``save_trace`` and sealed by whatever seal path the server has. Retention is
23
+ the trace store's.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import logging
31
+ import os
32
+ import uuid
33
+ from collections.abc import Callable, Iterable
34
+ from datetime import UTC, datetime
35
+ from typing import Any
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ #: ``session_metadata`` key the payload travels under, and its shape version.
40
+ CAPTURE_KEY = "capture"
41
+ CAPTURE_VERSION = 1
42
+ #: The attribute stamped on a capture trace so a reader can find them.
43
+ CAPTURE_ATTRIBUTE = "capture"
44
+ CAPTURE_SOURCE_OPENROUTER = "openrouter_proxy"
45
+ #: Environment switch. Default off.
46
+ CAPTURE_ENV = "AMFS_PROXY_CAPTURE"
47
+ #: Request keys kept byte-for-byte. Everything else on the body is dropped so
48
+ #: a caller's unrelated extension fields do not ride into the trace store.
49
+ REQUEST_KEYS: tuple[str, ...] = (
50
+ "model",
51
+ "messages",
52
+ "tools",
53
+ "tool_choice",
54
+ "functions",
55
+ "function_call",
56
+ "temperature",
57
+ "top_p",
58
+ "max_tokens",
59
+ "max_completion_tokens",
60
+ "stop",
61
+ "seed",
62
+ "response_format",
63
+ "parallel_tool_calls",
64
+ "reasoning",
65
+ "n",
66
+ )
67
+ #: Marker left where the scanner blocked a message outright.
68
+ REDACTED = "[redacted by SafetyGate]"
69
+
70
+ _OptIn = Callable[[Any], bool]
71
+ _opt_in: _OptIn | None = None
72
+
73
+
74
+ def set_opt_in(resolver: _OptIn | None) -> None:
75
+ """Install the per-account opt-in. The hosting layer passes a callable
76
+ taking the request and answering whether this account asked for capture;
77
+ ``None`` removes it. The environment switch remains a global override."""
78
+ global _opt_in
79
+ _opt_in = resolver
80
+
81
+
82
+ def capture_enabled(request: Any = None) -> bool:
83
+ """Whether this exchange is captured. Default-off: the env switch, or the
84
+ installed opt-in resolver saying yes for this request."""
85
+ if os.environ.get(CAPTURE_ENV, "false").strip().lower() in ("1", "true", "yes", "on"):
86
+ return True
87
+ if _opt_in is None or request is None:
88
+ return False
89
+ try:
90
+ return bool(_opt_in(request))
91
+ except Exception: # noqa: BLE001 - an opt-in that errors is an opt-out
92
+ logger.debug("capture opt-in resolver raised; treating as off", exc_info=True)
93
+ return False
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # SSE reassembly
98
+ # ---------------------------------------------------------------------------
99
+
100
+
101
+ def reassemble_sse(chunks: Iterable[bytes]) -> dict[str, Any]:
102
+ """Rebuild one chat completion from its streamed deltas.
103
+
104
+ Follows the OpenAI streaming shape: each ``data:`` line is a chunk whose
105
+ ``choices[i].delta`` carries a piece of ``content``, ``role``, or a piece
106
+ of a tool call addressed by ``index`` (name and arguments arrive in
107
+ fragments); ``finish_reason`` lands on the last delta of a choice;
108
+ ``usage`` on a trailing chunk when the caller asked for it; ``[DONE]``
109
+ ends the stream. Returns a non-streaming-shaped response — ``choices[]``
110
+ with a full ``message`` — plus ``stream: true`` and the number of chunks
111
+ so a reader knows how it was obtained. Lines that are not JSON are kept
112
+ under ``unparsed`` rather than dropped.
113
+ """
114
+ buffer = b"".join(chunks)
115
+ text = buffer.decode("utf-8", errors="replace")
116
+ choices: dict[int, dict[str, Any]] = {}
117
+ head: dict[str, Any] = {}
118
+ usage: Any = None
119
+ unparsed: list[str] = []
120
+ n_chunks = 0
121
+ for raw_line in text.replace("\r\n", "\n").split("\n"):
122
+ line = raw_line.strip()
123
+ if not line or line.startswith(":"):
124
+ continue
125
+ if not line.startswith("data:"):
126
+ unparsed.append(line)
127
+ continue
128
+ data = line[5:].strip()
129
+ if data == "[DONE]":
130
+ break
131
+ try:
132
+ chunk = json.loads(data)
133
+ except ValueError:
134
+ unparsed.append(line)
135
+ continue
136
+ n_chunks += 1
137
+ for key in ("id", "model", "created", "system_fingerprint", "object", "provider"):
138
+ if key in chunk and key not in head:
139
+ head[key] = chunk[key]
140
+ if chunk.get("usage") is not None:
141
+ usage = chunk["usage"]
142
+ for choice in chunk.get("choices") or []:
143
+ idx = int(choice.get("index", 0) or 0)
144
+ slot = choices.setdefault(
145
+ idx,
146
+ {
147
+ "index": idx,
148
+ "message": {"role": "assistant", "content": ""},
149
+ "finish_reason": None,
150
+ "_tool_calls": {},
151
+ },
152
+ )
153
+ delta = choice.get("delta") or {}
154
+ if delta.get("role"):
155
+ slot["message"]["role"] = delta["role"]
156
+ piece = delta.get("content")
157
+ if isinstance(piece, str):
158
+ slot["message"]["content"] += piece
159
+ if delta.get("reasoning") is not None:
160
+ slot["message"]["reasoning"] = (slot["message"].get("reasoning") or "") + str(
161
+ delta["reasoning"]
162
+ )
163
+ for tc in delta.get("tool_calls") or []:
164
+ t_idx = int(tc.get("index", len(slot["_tool_calls"])) or 0)
165
+ target = slot["_tool_calls"].setdefault(
166
+ t_idx,
167
+ {"id": None, "type": "function", "function": {"name": "", "arguments": ""}},
168
+ )
169
+ if tc.get("id"):
170
+ target["id"] = tc["id"]
171
+ if tc.get("type"):
172
+ target["type"] = tc["type"]
173
+ fn = tc.get("function") or {}
174
+ if fn.get("name"):
175
+ target["function"]["name"] += fn["name"]
176
+ if fn.get("arguments"):
177
+ target["function"]["arguments"] += fn["arguments"]
178
+ if choice.get("finish_reason"):
179
+ slot["finish_reason"] = choice["finish_reason"]
180
+ out_choices = []
181
+ for idx in sorted(choices):
182
+ slot = choices[idx]
183
+ tool_calls = [slot["_tool_calls"][k] for k in sorted(slot["_tool_calls"])]
184
+ message = dict(slot["message"])
185
+ if tool_calls:
186
+ message["tool_calls"] = tool_calls
187
+ if message.get("content") == "":
188
+ message["content"] = None
189
+ out_choices.append(
190
+ {"index": idx, "message": message, "finish_reason": slot["finish_reason"]}
191
+ )
192
+ result: dict[str, Any] = {
193
+ **head,
194
+ "object": head.get("object", "chat.completion"),
195
+ "choices": out_choices,
196
+ "stream": True,
197
+ "chunks": n_chunks,
198
+ }
199
+ if usage is not None:
200
+ result["usage"] = usage
201
+ if unparsed:
202
+ result["unparsed"] = unparsed[:50]
203
+ return result
204
+
205
+
206
+ # ---------------------------------------------------------------------------
207
+ # The payload
208
+ # ---------------------------------------------------------------------------
209
+
210
+
211
+ def _sha256(data: bytes) -> str:
212
+ return hashlib.sha256(data).hexdigest()
213
+
214
+
215
+ def _scan(text: Any, scanner: Callable[[str], str | None] | None) -> Any:
216
+ if scanner is None or not isinstance(text, str) or not text:
217
+ return text
218
+ scanned = scanner(text)
219
+ return REDACTED if scanned is None else scanned
220
+
221
+
222
+ def _redact_tree(value: Any, scanner: Callable[[str], str | None] | None) -> Any:
223
+ """Run *scanner* over **every** string leaf of *value*, whatever the
224
+ shape: message ``content`` as text or parts, ``reasoning``, tool-call
225
+ arguments, tool results, tool schemas, and any field a provider adds
226
+ that this module has never heard of. Structure is preserved; dict keys
227
+ are not scanned (they are field names, not text). Enumerating the known
228
+ text fields was how ``reasoning`` and the ``tools`` schemas were stored
229
+ unscanned."""
230
+ if isinstance(value, str):
231
+ return _scan(value, scanner)
232
+ if isinstance(value, dict):
233
+ return {k: _redact_tree(v, scanner) for k, v in value.items()}
234
+ if isinstance(value, list):
235
+ return [_redact_tree(v, scanner) for v in value]
236
+ if isinstance(value, tuple):
237
+ return [_redact_tree(v, scanner) for v in value]
238
+ return value
239
+
240
+
241
+ def _redact_messages(messages: Any, scanner: Callable[[str], str | None] | None) -> Any:
242
+ """Scan every text field a message can carry. A list of messages in, the
243
+ same shape out; kept as the named entry point the tests and the trace
244
+ builder use, implemented as the structural walk."""
245
+ if not isinstance(messages, list):
246
+ return messages
247
+ return _redact_tree(messages, scanner)
248
+
249
+
250
+ def tool_calls_of(response: dict[str, Any]) -> list[dict[str, Any]]:
251
+ """The tool calls the model made, in the :class:`amfs_core.models.ToolCall`
252
+ shape ``DecisionTrace.tool_calls`` carries (``tool_name``, ``arguments``,
253
+ ``source``), parsed from the response's first choice. The result is not
254
+ known at capture time — the caller's agent runs the tool — so each call
255
+ stands as requested. Arguments that are not JSON are kept as text."""
256
+ calls: list[dict[str, Any]] = []
257
+ try:
258
+ message = (response.get("choices") or [{}])[0].get("message") or {}
259
+ except (AttributeError, IndexError, TypeError):
260
+ return calls
261
+ for tc in message.get("tool_calls") or []:
262
+ fn = (tc or {}).get("function") or {}
263
+ raw = fn.get("arguments")
264
+ args: Any = raw
265
+ if isinstance(raw, str):
266
+ try:
267
+ args = json.loads(raw)
268
+ except ValueError:
269
+ args = {"_raw": raw}
270
+ calls.append(
271
+ {
272
+ "tool_name": str(fn.get("name") or "tool"),
273
+ "arguments": args if isinstance(args, dict) else {"_raw": args},
274
+ "source": "capture",
275
+ }
276
+ )
277
+ return calls
278
+
279
+
280
+ def capture_payload(
281
+ request_body: dict[str, Any],
282
+ response: dict[str, Any],
283
+ *,
284
+ raw_request: bytes | None = None,
285
+ raw_response: bytes | None = None,
286
+ upstream_status: int | None = None,
287
+ scanner: Callable[[str], str | None] | None = None,
288
+ source: str = CAPTURE_SOURCE_OPENROUTER,
289
+ scope: str | None = None,
290
+ injected_facts: int = 0,
291
+ ) -> dict[str, Any]:
292
+ """The capture, redacted and hashed.
293
+
294
+ ``request`` keeps the fields in :data:`REQUEST_KEYS` as the caller sent
295
+ them — the full message history and the tool schemas included —
296
+ ``response`` is the upstream object (reassembled when streamed), both with
297
+ every text field run through *scanner*. The hashes are of the **raw**
298
+ bytes before redaction, so a holder of the original can verify the capture
299
+ is of that exchange; the redacted text itself is what is stored.
300
+ """
301
+ # The whole of both objects, not the fields known to hold text: tool
302
+ # schemas, reasoning, provider extensions and anything else a caller sends
303
+ # or a model returns are stored, so all of it is scanned.
304
+ request = _redact_tree({k: request_body[k] for k in REQUEST_KEYS if k in request_body}, scanner)
305
+ redacted_response = _redact_tree(dict(response or {}), scanner)
306
+ payload: dict[str, Any] = {
307
+ "capture_version": CAPTURE_VERSION,
308
+ "source": source,
309
+ "captured_at": datetime.now(UTC).isoformat(),
310
+ "scope": scope,
311
+ "injected_facts": int(injected_facts),
312
+ "request": request,
313
+ "response": redacted_response,
314
+ "upstream_status": upstream_status,
315
+ "streamed": bool(response.get("stream")) if isinstance(response, dict) else False,
316
+ }
317
+ if raw_request is not None:
318
+ payload["request_sha256"] = _sha256(raw_request)
319
+ payload["request_bytes"] = len(raw_request)
320
+ if raw_response is not None:
321
+ payload["response_sha256"] = _sha256(raw_response)
322
+ payload["response_bytes"] = len(raw_response)
323
+ return payload
324
+
325
+
326
+ def capture_trace(
327
+ payload: dict[str, Any],
328
+ *,
329
+ agent_id: str,
330
+ session_id: str | None = None,
331
+ namespace: str = "default",
332
+ scope: str | None = None,
333
+ ) -> Any:
334
+ """A :class:`DecisionTrace` carrying *payload*: no outcome, the model's
335
+ tool calls on ``tool_calls``, the last user turn as ``task_input`` and
336
+ the assistant's text as ``response_text`` (what the sealed record and the
337
+ training exporters already read), the whole capture under
338
+ ``session_metadata.capture``."""
339
+ from amfs_core.models import DecisionTrace, SessionMetadata
340
+
341
+ messages = (payload.get("request") or {}).get("messages") or []
342
+ task_input = None
343
+ for m in reversed(messages):
344
+ if isinstance(m, dict) and m.get("role") == "user":
345
+ c = m.get("content")
346
+ task_input = (
347
+ c
348
+ if isinstance(c, str)
349
+ else json.dumps(c, ensure_ascii=False)
350
+ if c is not None
351
+ else None
352
+ )
353
+ break
354
+ response = payload.get("response") or {}
355
+ try:
356
+ response_text = (response.get("choices") or [{}])[0].get("message", {}).get("content")
357
+ except (AttributeError, IndexError, TypeError):
358
+ response_text = None
359
+ meta = SessionMetadata(
360
+ attributes={
361
+ CAPTURE_ATTRIBUTE: payload.get("source", CAPTURE_SOURCE_OPENROUTER),
362
+ "source": "proxy",
363
+ },
364
+ **{CAPTURE_KEY: payload},
365
+ )
366
+ return DecisionTrace(
367
+ id=str(uuid.uuid4()),
368
+ agent_id=agent_id,
369
+ session_id=session_id or f"capture-{uuid.uuid4().hex[:12]}",
370
+ outcome_ref=None,
371
+ outcome_type=None,
372
+ decision_summary=f"captured {payload.get('source')} exchange"
373
+ + (f" on {scope}" if scope else ""),
374
+ task_input=task_input,
375
+ response_text=response_text if isinstance(response_text, str) else None,
376
+ tool_calls=tool_calls_of(response),
377
+ session_metadata=meta,
378
+ namespace=namespace,
379
+ )
380
+
381
+
382
+ __all__ = [
383
+ "CAPTURE_ATTRIBUTE",
384
+ "CAPTURE_ENV",
385
+ "CAPTURE_KEY",
386
+ "CAPTURE_SOURCE_OPENROUTER",
387
+ "CAPTURE_VERSION",
388
+ "REDACTED",
389
+ "REQUEST_KEYS",
390
+ "capture_enabled",
391
+ "capture_payload",
392
+ "capture_trace",
393
+ "reassemble_sse",
394
+ "set_opt_in",
395
+ "tool_calls_of",
396
+ ]
@@ -135,6 +135,13 @@ class RetrieveRequest(BaseModel):
135
135
 
136
136
  query: str
137
137
  entity_path: str | None = None
138
+ # Widens entity_path to that path and everything beneath it, on both the
139
+ # semantic and the lexical channel (see SearchRequest.include_descendants
140
+ # and amfs_core.scope). Off by default so an exact-match caller keeps
141
+ # getting exactly what it asked for. For a caller whose scope is a prefix
142
+ # rather than an entity — a served model trained on `research/*` with no
143
+ # path on the request — an exact match on the prefix finds nothing.
144
+ include_descendants: bool = False
138
145
  min_confidence: float = 0.0
139
146
  limit: int = 10
140
147
  semantic_weight: float = 0.5