agentic-platform-standin 0.1.0__py3-none-any.whl

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.
Files changed (36) hide show
  1. agentic_platform_standin/__init__.py +1 -0
  2. agentic_platform_standin/__main__.py +24 -0
  3. agentic_platform_standin/_jcs.py +218 -0
  4. agentic_platform_standin/app.py +53 -0
  5. agentic_platform_standin/app_tools.py +166 -0
  6. agentic_platform_standin/auth.py +120 -0
  7. agentic_platform_standin/control.py +329 -0
  8. agentic_platform_standin/db.py +164 -0
  9. agentic_platform_standin/dpop.py +101 -0
  10. agentic_platform_standin/idempotency.py +81 -0
  11. agentic_platform_standin/kb_index.py +271 -0
  12. agentic_platform_standin/openapi.json +6328 -0
  13. agentic_platform_standin/routes_a2a.py +488 -0
  14. agentic_platform_standin/routes_approvals.py +48 -0
  15. agentic_platform_standin/routes_datasets.py +47 -0
  16. agentic_platform_standin/routes_kb.py +222 -0
  17. agentic_platform_standin/routes_llm.py +165 -0
  18. agentic_platform_standin/routes_me.py +23 -0
  19. agentic_platform_standin/routes_meta.py +23 -0
  20. agentic_platform_standin/routes_ontology.py +276 -0
  21. agentic_platform_standin/routes_toolchains.py +264 -0
  22. agentic_platform_standin/routes_vision.py +262 -0
  23. agentic_platform_standin/runtime.py +70 -0
  24. agentic_platform_standin/settings.py +146 -0
  25. agentic_platform_standin/timeutil.py +8 -0
  26. agentic_platform_standin/vision/__init__.py +2 -0
  27. agentic_platform_standin/vision/images.py +43 -0
  28. agentic_platform_standin/vision/metrics.py +51 -0
  29. agentic_platform_standin/vision/onnx_io.py +75 -0
  30. agentic_platform_standin/vision/runner.py +304 -0
  31. agentic_platform_standin/vision/scripted.py +83 -0
  32. agentic_platform_standin/vision/train.py +89 -0
  33. agentic_platform_standin-0.1.0.dist-info/METADATA +180 -0
  34. agentic_platform_standin-0.1.0.dist-info/RECORD +36 -0
  35. agentic_platform_standin-0.1.0.dist-info/WHEEL +4 -0
  36. agentic_platform_standin-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1 @@
1
+ """Stand-in for the agentic platform's /open/v1 LLM, KB and ontology services. Not app code."""
@@ -0,0 +1,24 @@
1
+ import os
2
+ from collections.abc import Mapping
3
+
4
+ import uvicorn
5
+
6
+ from agentic_platform_standin.app import create_app
7
+ from agentic_platform_standin.settings import Settings
8
+
9
+ # Every interface by default: the image and compose reach the stand-in over their network.
10
+ # `run_standin()` sets STANDIN_HOST=127.0.0.1, so a test run is not exposed beyond the machine.
11
+ DEFAULT_HOST = "0.0.0.0"
12
+
13
+
14
+ def bind_host(environ: Mapping[str, str] = os.environ) -> str:
15
+ return environ.get("STANDIN_HOST") or DEFAULT_HOST
16
+
17
+
18
+ def main() -> None:
19
+ uvicorn.run(create_app(Settings.from_env()), host=bind_host(),
20
+ port=int(os.environ.get("STANDIN_PORT", "8013")))
21
+
22
+
23
+ if __name__ == "__main__":
24
+ main()
@@ -0,0 +1,218 @@
1
+ """RFC 8785 (JSON Canonicalization Scheme, JCS) for the platform's hashed documents.
2
+
3
+ THIS FILE IMPORTS ONLY THE STANDARD LIBRARY, on purpose: the X5 export package ships it byte for byte
4
+ inside its read script, so a customer can recompute a hash with a plain ``python3`` and no platform on
5
+ the path. ``tests/test_jcs.py`` pins that with an AST walk. Do not add an ``app.*`` import here.
6
+
7
+ Why not ``json.dumps(sort_keys=True, separators=(",", ":"))``: that form is Python's, not a standard.
8
+ It prints ``1.0`` where JCS prints ``1``, ``1e-05`` where JCS prints ``0.00001``, emits ``NaN`` (not
9
+ JSON), prints any big integer exactly, and orders keys by code point where JCS orders them by UTF-16
10
+ code unit. A hash that leaves the platform (a card in a customer archive) must be a function of the
11
+ document's JSON data model, so every reader in any language can recompute it.
12
+
13
+ What is accepted (anything else is a ``JcsError`` with a stable ``.code``; callers pass
14
+ ``model_dump(mode="json")`` output, never a model, datetime, UUID, Decimal, set or bytes):
15
+
16
+ * ``None`` / ``bool`` / ``int`` / ``float`` / ``str`` / ``list`` / ``tuple`` / ``dict`` with ``str`` keys;
17
+ * an ``int`` only within +-(2**53 - 1) (I-JSON: JCS numbers are IEEE doubles, so a bigger integer would
18
+ be silently rounded and two different documents could hash the same): ``jcs.integer_out_of_range``;
19
+ * a ``float`` only if finite: ``jcs.non_finite_number``;
20
+ * a string without a lone surrogate (it has no UTF-8 form): ``jcs.lone_surrogate``;
21
+ * at most ``MAX_DEPTH`` nested containers: ``jcs.too_deep``.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import hashlib
27
+ import json
28
+ import math
29
+ import re
30
+ from typing import Any
31
+
32
+ #: Largest integer an IEEE 754 double (and so a JCS number) holds exactly: 2**53 - 1.
33
+ MAX_SAFE_INTEGER = 2**53 - 1
34
+ #: Nested containers allowed (a card is under 10 deep; this bounds hostile input, no RecursionError).
35
+ MAX_DEPTH = 64
36
+
37
+ _NEEDS_ESCAPE = re.compile(r'[\x00-\x1f"\\]')
38
+ _SURROGATE = re.compile("[\ud800-\udfff]")
39
+ _SHORT_ESCAPES = {
40
+ "\b": "\\b",
41
+ "\t": "\\t",
42
+ "\n": "\\n",
43
+ "\f": "\\f",
44
+ "\r": "\\r",
45
+ '"': '\\"',
46
+ "\\": "\\\\",
47
+ }
48
+
49
+
50
+ class JcsError(ValueError):
51
+ """A document JCS refuses. ``code`` is a stable ``jcs.<reason>`` string; ``str(exc)`` is the code."""
52
+
53
+ def __init__(self, code: str):
54
+ super().__init__(code)
55
+ self.code = code
56
+
57
+
58
+ def number_to_string(x: int | float) -> str:
59
+ """The ECMAScript ``Number::toString(10)`` form of a number (RFC 8785 section 3.2.2.3)."""
60
+ if isinstance(x, bool):
61
+ raise JcsError("jcs.unsupported_type")
62
+ if isinstance(x, int):
63
+ if abs(x) > MAX_SAFE_INTEGER:
64
+ raise JcsError("jcs.integer_out_of_range")
65
+ return str(int(x))
66
+ if not isinstance(x, float):
67
+ raise JcsError("jcs.unsupported_type")
68
+ x = float(x)
69
+ if not math.isfinite(x):
70
+ raise JcsError("jcs.non_finite_number")
71
+ if x == 0:
72
+ return "0" # also -0.0
73
+ if x < 0:
74
+ return "-" + number_to_string(-x)
75
+ # CPython's repr is the shortest round-trip form (David Gay), the digits and the tie rule
76
+ # ECMAScript requires; only the layout differs. Read the digits and the decimal exponent off it.
77
+ mantissa, _, exp = repr(x).partition("e")
78
+ int_part, _, frac_part = mantissa.partition(".")
79
+ raw = int_part + frac_part
80
+ stripped = raw.lstrip("0")
81
+ leading_zeros = len(raw) - len(stripped)
82
+ digits = stripped.rstrip("0") # s
83
+ k = len(digits)
84
+ n = len(int_part) + (int(exp) if exp else 0) - leading_zeros # x = 0.s * 10**n
85
+ if k <= n <= 21:
86
+ return digits + "0" * (n - k)
87
+ if 0 < n <= 21:
88
+ return digits[:n] + "." + digits[n:]
89
+ if -6 < n <= 0:
90
+ return "0." + "0" * (-n) + digits
91
+ mant = digits if k == 1 else digits[0] + "." + digits[1:]
92
+ return mant + "e" + ("+" if n - 1 >= 0 else "-") + str(abs(n - 1))
93
+
94
+
95
+ def _check_string(s: str) -> None:
96
+ if _SURROGATE.search(s):
97
+ raise JcsError("jcs.lone_surrogate")
98
+
99
+
100
+ def _quote(s: str) -> str:
101
+ """``JSON.stringify`` QuoteJSONString (RFC 8785 section 3.2.2.2); ``/`` and non-ASCII stay literal."""
102
+ _check_string(s)
103
+ return (
104
+ '"'
105
+ + _NEEDS_ESCAPE.sub(lambda m: _SHORT_ESCAPES.get(m.group(), "\\u%04x" % ord(m.group())), s)
106
+ + '"'
107
+ )
108
+
109
+
110
+ def _serialize(value: Any, depth: int, out: list[str]) -> None:
111
+ # bool is tested BEFORE int (True is an int in Python).
112
+ if value is None:
113
+ out.append("null")
114
+ elif value is True:
115
+ out.append("true")
116
+ elif value is False:
117
+ out.append("false")
118
+ elif isinstance(value, (int, float)):
119
+ out.append(number_to_string(value))
120
+ elif isinstance(value, str):
121
+ out.append(_quote(value))
122
+ elif isinstance(value, (list, tuple)):
123
+ if depth + 1 > MAX_DEPTH:
124
+ raise JcsError("jcs.too_deep")
125
+ out.append("[")
126
+ for i, item in enumerate(value):
127
+ if i:
128
+ out.append(",")
129
+ _serialize(item, depth + 1, out)
130
+ out.append("]")
131
+ elif isinstance(value, dict):
132
+ if depth + 1 > MAX_DEPTH:
133
+ raise JcsError("jcs.too_deep")
134
+ if any(not isinstance(k, str) for k in value):
135
+ raise JcsError("jcs.non_string_key")
136
+ for k in value:
137
+ _check_string(k)
138
+ # UTF-16 big-endian bytes compare as UTF-16 code units (RFC 8785 section 3.2.3), which differs
139
+ # from Python's code point order when an astral character meets U+E000..U+FFFF.
140
+ out.append("{")
141
+ for i, k in enumerate(sorted(value, key=lambda key: key.encode("utf-16-be"))):
142
+ if i:
143
+ out.append(",")
144
+ out.append(_quote(k))
145
+ out.append(":")
146
+ _serialize(value[k], depth + 1, out)
147
+ out.append("}")
148
+ else:
149
+ raise JcsError("jcs.unsupported_type")
150
+
151
+
152
+ def canonicalize(value: Any) -> bytes:
153
+ """The RFC 8785 canonical UTF-8 bytes of ``value``."""
154
+ out: list[str] = []
155
+ _serialize(value, 0, out)
156
+ return "".join(out).encode("utf-8")
157
+
158
+
159
+ def sha256_hex(value: Any) -> str:
160
+ """Lowercase hex sha256 of ``canonicalize(value)``."""
161
+ return hashlib.sha256(canonicalize(value)).hexdigest()
162
+
163
+
164
+ def _no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
165
+ result: dict[str, Any] = {}
166
+ for key, val in pairs:
167
+ if key in result:
168
+ raise JcsError("jcs.duplicate_key")
169
+ result[key] = val
170
+ return result
171
+
172
+
173
+ def _refuse_constant(_name: str) -> Any:
174
+ raise JcsError("jcs.non_finite_number")
175
+
176
+
177
+ def _parse_int(literal: str) -> int:
178
+ try:
179
+ return int(literal)
180
+ except ValueError: # past Python's integer digit limit: far beyond 2**53 - 1
181
+ raise JcsError("jcs.integer_out_of_range") from None
182
+
183
+
184
+ def loads_strict(data: str | bytes) -> Any:
185
+ """Parse JSON the way a verifier must before it hashes: I-JSON strict.
186
+
187
+ Bytes are decoded as strict UTF-8 and a BOM is refused; a duplicate object key, ``NaN`` /
188
+ ``Infinity`` and every value ``canonicalize`` refuses (big integer, lone surrogate, too deep) are
189
+ errors, not silently merged or rounded. A number with a fraction or exponent becomes a ``float``,
190
+ an integer literal an ``int``, so ``canonicalize(loads_strict(b))`` is what any JCS implementation
191
+ makes of ``b``.
192
+ """
193
+ if isinstance(data, (bytes, bytearray, memoryview)):
194
+ try:
195
+ text = bytes(data).decode("utf-8")
196
+ except UnicodeDecodeError:
197
+ raise JcsError("jcs.invalid_utf8") from None
198
+ elif isinstance(data, str):
199
+ text = data
200
+ else:
201
+ raise JcsError("jcs.unsupported_type")
202
+ if text.startswith("\ufeff"):
203
+ raise JcsError("jcs.bom_not_allowed")
204
+ try:
205
+ value = json.loads(
206
+ text,
207
+ object_pairs_hook=_no_duplicates,
208
+ parse_constant=_refuse_constant,
209
+ parse_int=_parse_int,
210
+ )
211
+ except JcsError:
212
+ raise
213
+ except RecursionError:
214
+ raise JcsError("jcs.too_deep") from None
215
+ except ValueError: # JSONDecodeError
216
+ raise JcsError("jcs.invalid_json") from None
217
+ canonicalize(value) # the same value rules as the writer (range, surrogates, depth)
218
+ return value
@@ -0,0 +1,53 @@
1
+ """The stand-in platform: serves the /open/v1 shapes of the platform's open API (the OpenAPI snapshot)
2
+ for app development and SDK conformance tests, and image-classification training. Not app code."""
3
+ from __future__ import annotations
4
+
5
+ import jwt
6
+ from fastapi import FastAPI
7
+
8
+ from agentic_platform_standin import (
9
+ control,
10
+ routes_a2a,
11
+ routes_approvals,
12
+ routes_datasets,
13
+ routes_kb,
14
+ routes_llm,
15
+ routes_me,
16
+ routes_meta,
17
+ routes_ontology,
18
+ routes_toolchains,
19
+ routes_vision,
20
+ )
21
+ from agentic_platform_standin.db import make_sessionmaker
22
+ from agentic_platform_standin.kb_index import make_embedder, sweep_unfinished
23
+ from agentic_platform_standin.runtime import Runtime
24
+ from agentic_platform_standin.settings import Settings
25
+ from agentic_platform_standin.vision.runner import sweep_vision
26
+
27
+
28
+ def create_app(settings: Settings, jwks_client=None) -> FastAPI:
29
+ app = FastAPI(title="agentic-platform stand-in", docs_url=None, redoc_url=None)
30
+ app.state.settings = settings
31
+ app.state.jwks = jwks_client or jwt.PyJWKClient(settings.jwks_url)
32
+ app.state.Session = make_sessionmaker(settings.database_url)
33
+ app.state.embedder = make_embedder(settings)
34
+ app.state.runtime = Runtime()
35
+ sweep_unfinished(app.state.Session)
36
+ sweep_vision(app.state.Session)
37
+ if settings.embedder != "hash":
38
+ # Load the model now: the first retrieve must not import torch under the app's 10 s timeout.
39
+ app.state.embedder.encode(["warmup"])
40
+ app.include_router(routes_me.router)
41
+ app.include_router(routes_llm.router)
42
+ app.include_router(routes_kb.router)
43
+ app.include_router(routes_ontology.router)
44
+ app.include_router(routes_vision.router)
45
+ app.include_router(routes_datasets.router)
46
+ app.include_router(routes_toolchains.router)
47
+ app.include_router(routes_a2a.router)
48
+ app.include_router(routes_approvals.router)
49
+ app.include_router(routes_meta.router)
50
+ routes_vision.install_upload_cap(app)
51
+ if settings.control:
52
+ control.mount(app)
53
+ return app
@@ -0,0 +1,166 @@
1
+ """The stand-in's app tool callback (spec §4.7): the scripted agent calls an app's own MCP tool endpoint as the user.
2
+
3
+ Control API: ``POST /_standin/app-tools {"slug", "url", "secret"}`` registers an app's tool endpoint and
4
+ its secret (registering again replaces them: that is a rotation to the stand-in). A message whose text is
5
+ ``app-tool:<slug>.<tool> {json arguments}`` makes the scripted agent call that tool: it speaks MCP (Streamable HTTP,
6
+ JSON or SSE answers) with a fresh HS256 token per request, ``purpose: "sync"`` for ``initialize`` and the
7
+ notification, ``purpose: "call"`` for ``tools/call``, minted the platform's way (claims: sdk/spec/README.md "App tool
8
+ callback"). The task's text becomes the tool's summary; with the chat-events extension the run is narrated as a
9
+ ``tool_call`` (``origin: "app"``) and a ``tool_result`` (with ``ref``). A refused or unreachable endpoint is a failed
10
+ tool result (``app_tool.refused`` / ``app_tool.unavailable``), never a failed task.
11
+
12
+ The stand-in never reaches a private address on its own: tests set ``app.state.app_tool_transport`` (an httpx
13
+ transport, e.g. ``httpx.ASGITransport(app=sample_app)``) to call an app in process.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import json
20
+ import re
21
+ import time
22
+ import uuid
23
+ from typing import Any
24
+
25
+ import httpx
26
+ import jwt
27
+ from pydantic import BaseModel, Field
28
+
29
+ from agentic_platform_standin._jcs import canonicalize
30
+ from agentic_platform_standin.auth import Caller
31
+
32
+ APP_CONTEXT_KEY = "agentic.app_context"
33
+ TOKEN_LIFETIME_S = 120
34
+ TIMEOUT_S = 30.0
35
+ PROTOCOL_VERSION = "2025-06-18"
36
+ _SCRIPT = re.compile(r"^app-tool:([a-z0-9][a-z0-9-]*)\.([A-Za-z0-9_.-]+)(?:[ \t]+(\{.*\}))?[ \t]*$", re.DOTALL)
37
+
38
+
39
+ class AppToolIn(BaseModel):
40
+ slug: str = Field(pattern=r"^[a-z0-9][a-z0-9-]{0,62}$")
41
+ url: str = Field(min_length=1, max_length=2048)
42
+ secret: str = Field(min_length=8, max_length=512)
43
+
44
+
45
+ def parse_script(text: str) -> tuple[str, str, dict] | None:
46
+ """``(slug, tool, arguments)`` of an ``app-tool:<slug>.<tool> {json}`` message, else None."""
47
+ found = _SCRIPT.match(text.strip())
48
+ if found is None:
49
+ return None
50
+ try:
51
+ arguments = json.loads(found.group(3) or "{}")
52
+ except ValueError:
53
+ return None
54
+ return (found.group(1), found.group(2), arguments) if isinstance(arguments, dict) else None
55
+
56
+
57
+ def app_context_sha256(app_context: dict | None) -> str:
58
+ """The hash the token carries: SHA-256 of the RFC 8785 (JCS) form of the context, ``{}`` for none (a copy of the
59
+ SDK helper's rule, with a byte-identical ``_jcs.py``; the SDK's tests assert the two agree)."""
60
+ return hashlib.sha256(canonicalize(app_context or {})).hexdigest()
61
+
62
+
63
+ def mint(secret: str, claims: dict, kid: str = "standin") -> str:
64
+ return jwt.encode(claims, secret, algorithm="HS256", headers={"kid": kid})
65
+
66
+
67
+ def _claims(slug: str, purpose: str, issuer: str, **call: Any) -> dict:
68
+ now = int(time.time())
69
+ claims = {"iss": issuer, "aud": slug}
70
+ if purpose == "call":
71
+ claims.update(call)
72
+ claims.update({"purpose": purpose, "iat": now, "exp": now + TOKEN_LIFETIME_S, "jti": uuid.uuid4().hex})
73
+ return claims
74
+
75
+
76
+ class _Refused(Exception):
77
+ pass
78
+
79
+
80
+ class _Unavailable(Exception):
81
+ pass
82
+
83
+
84
+ def _rpc_result(response: httpx.Response, request_id: int) -> dict:
85
+ """The JSON-RPC result in a JSON or SSE body."""
86
+ if response.status_code in (401, 403):
87
+ raise _Refused
88
+ if response.status_code >= 300:
89
+ raise _Unavailable
90
+ content_type = response.headers.get("content-type", "")
91
+ if content_type.startswith("text/event-stream"):
92
+ docs = []
93
+ for block in response.text.replace("\r\n", "\n").split("\n\n"):
94
+ data = "\n".join(line[5:].lstrip() for line in block.split("\n") if line.startswith("data:"))
95
+ if data:
96
+ try:
97
+ docs.append(json.loads(data))
98
+ except ValueError:
99
+ raise _Unavailable from None
100
+ elif content_type.startswith("application/json"):
101
+ try:
102
+ body = response.json()
103
+ except ValueError:
104
+ raise _Unavailable from None
105
+ docs = body if isinstance(body, list) else [body]
106
+ else:
107
+ raise _Unavailable
108
+ for doc in docs:
109
+ if isinstance(doc, dict) and doc.get("id") == request_id:
110
+ if "result" not in doc or not isinstance(doc["result"], dict):
111
+ raise _Unavailable # a JSON-RPC error: a protocol error for the agent
112
+ return doc["result"]
113
+ raise _Unavailable
114
+
115
+
116
+ async def run_tool(
117
+ entry: dict, *, slug: str, tool: str, arguments: dict, who: Caller, issuer: str, task: dict, call_id: str,
118
+ app_context: dict, transport: httpx.AsyncBaseTransport | None = None,
119
+ ) -> dict:
120
+ """Calls the tool; returns the ``tool_result`` event fields (``ok``, ``summary``, ``ref``?, ``error_code``?)."""
121
+ secret = entry["secret"]
122
+ base = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json",
123
+ "MCP-Protocol-Version": PROTOCOL_VERSION}
124
+
125
+ async def post(client: httpx.AsyncClient, token: str, doc: dict, headers: dict) -> httpx.Response:
126
+ return await client.post(entry["url"], json=doc, headers={**base, **headers,
127
+ "Authorization": f"Bearer {token}"})
128
+
129
+ def sync() -> str:
130
+ return mint(secret, _claims(slug, "sync", issuer))
131
+
132
+ try:
133
+ async with httpx.AsyncClient(transport=transport, timeout=TIMEOUT_S, follow_redirects=False) as client:
134
+ session: dict = {}
135
+ init = await post(client, sync(), {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
136
+ "protocolVersion": PROTOCOL_VERSION, "capabilities": {},
137
+ "clientInfo": {"name": "agentic-standin", "version": "0"}}}, {})
138
+ _rpc_result(init, 1)
139
+ if init.headers.get("mcp-session-id"):
140
+ session = {"Mcp-Session-Id": init.headers["mcp-session-id"]}
141
+ ack = await post(client, sync(), {"jsonrpc": "2.0", "method": "notifications/initialized"}, session)
142
+ if ack.status_code in (401, 403):
143
+ raise _Refused
144
+ if ack.status_code >= 300:
145
+ raise _Unavailable
146
+ claims = _claims(
147
+ slug, "call", issuer, sub=who.sub, sub_iss=issuer, ws=who.workspace_id, task=task["id"],
148
+ ctx=task["context"], tool=tool, call=call_id, app_ctx_sha256=app_context_sha256(app_context))
149
+ answer = await post(client, mint(secret, claims), {
150
+ "jsonrpc": "2.0", "id": 2, "method": "tools/call",
151
+ "params": {"name": tool, "arguments": arguments, "_meta": {APP_CONTEXT_KEY: app_context}}}, session)
152
+ result = _rpc_result(answer, 2)
153
+ except _Refused:
154
+ return {"ok": False, "summary": "", "error_code": "app_tool.refused"}
155
+ except (_Unavailable, httpx.HTTPError):
156
+ return {"ok": False, "summary": "", "error_code": "app_tool.unavailable"}
157
+ text = "\n".join(c["text"] for c in result.get("content") or []
158
+ if isinstance(c, dict) and c.get("type") == "text" and isinstance(c.get("text"), str))[:2048]
159
+ if result.get("isError") is True:
160
+ return {"ok": False, "summary": text, "error_code": "app_tool.tool_error"}
161
+ out: dict = {"ok": True, "summary": text}
162
+ ref = (result.get("structuredContent") or {}).get("ref")
163
+ if (isinstance(ref, dict) and isinstance(ref.get("kind"), str) and isinstance(ref.get("id"), str)
164
+ and ref["kind"].startswith(f"{slug}.")):
165
+ out["ref"] = {"kind": ref["kind"], "id": ref["id"]}
166
+ return out
@@ -0,0 +1,120 @@
1
+ """Who is calling, the way the platform decides it. Two doors:
2
+ - an app token: RS256 via JWKS, iss, aud, azp; the caller's app is the token's azp, the member is its email.
3
+ - an API key (`agk_...`, from STANDIN_API_KEYS): `Authorization: Bearer agk_...`, or `DPoP agk_...` with a
4
+ `DPoP:` proof header. A key acts for one workspace member and belongs to one app. A key bound to a DPoP
5
+ key (`!dpop`) needs a valid proof on every request; the first proof seen sets the thumbprint.
6
+ The workspace comes from X-Workspace-Id (absent = the caller's only workspace)."""
7
+ from __future__ import annotations
8
+
9
+ import uuid
10
+ from dataclasses import dataclass
11
+
12
+ import jwt
13
+ from fastapi import HTTPException, Request
14
+
15
+ from agentic_platform_standin import dpop
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Caller:
20
+ sub: str
21
+ email: str
22
+ name: str | None
23
+ workspace_id: str
24
+ role: str
25
+ app: str = ""
26
+ client_id: str | None = None # set for an API key; an app token has none
27
+
28
+
29
+ def _htu(request: Request) -> str:
30
+ base = request.app.state.settings.public_url or f"{request.url.scheme}://{request.url.netloc}"
31
+ return f"{base}{request.url.path}"
32
+
33
+
34
+ def _refuse(request: Request, code: str, *, www: str | None = None) -> HTTPException:
35
+ """A 401 of the key door. In nonce mode every one of them hands out a fresh nonce."""
36
+ headers = {}
37
+ if www:
38
+ headers["WWW-Authenticate"] = www
39
+ st = request.app.state
40
+ if st.settings.dpop_nonce:
41
+ headers["DPoP-Nonce"] = st.runtime.make_nonce()
42
+ return HTTPException(401, code, headers=headers or None)
43
+
44
+
45
+ _CHALLENGE = 'DPoP algs="ES256"'
46
+ _INVALID = 'DPoP algs="ES256", error="invalid_dpop_proof"'
47
+ _NONCE = 'DPoP algs="ES256", error="use_dpop_nonce"'
48
+
49
+
50
+ def _judge_proof(request: Request, key: str, scheme: str) -> None:
51
+ """Raises the gateway.dpop_* refusal for a key that is bound to a DPoP key; returns when the proof is good."""
52
+ proof = request.headers.get("dpop")
53
+ if scheme != "dpop" or not proof:
54
+ raise _refuse(request, "gateway.dpop_proof_required", www=_CHALLENGE)
55
+ st = request.app.state
56
+ try:
57
+ payload, thumb = dpop.verify(proof, method=request.method, htu=_htu(request), token=key)
58
+ except dpop.BadProof:
59
+ raise _refuse(request, "gateway.dpop_proof_invalid", www=_INVALID) from None
60
+ if st.runtime.bind(key, thumb) != thumb:
61
+ raise _refuse(request, "gateway.dpop_proof_invalid", www=_INVALID)
62
+ if st.settings.dpop_nonce and not st.runtime.nonce_ok(payload.get("nonce")):
63
+ raise _refuse(request, "gateway.dpop_nonce_required", www=_NONCE)
64
+ if not st.runtime.see_jti(payload["jti"]):
65
+ raise _refuse(request, "gateway.dpop_proof_invalid", www=_INVALID)
66
+
67
+
68
+ def _workspace(request: Request) -> str:
69
+ s = request.app.state.settings
70
+ ws = request.headers.get("x-workspace-id") or s.workspace_id
71
+ if ws != s.workspace_id:
72
+ raise HTTPException(404, "workspace.not_found")
73
+ return ws
74
+
75
+
76
+ def _api_key_caller(request: Request, scheme: str, key: str) -> Caller:
77
+ s = request.app.state.settings
78
+ spec = s.api_keys.get(key)
79
+ if spec is None:
80
+ raise _refuse(request, "gateway.invalid_key")
81
+ if spec.bound:
82
+ _judge_proof(request, key, scheme)
83
+ elif s.dpop_required:
84
+ raise _refuse(request, "gateway.dpop_binding_required", www=_CHALLENGE)
85
+ elif scheme == "dpop": # a DPoP scheme on a key that is not bound to one
86
+ raise _refuse(request, "gateway.dpop_proof_invalid", www=_INVALID)
87
+ role = s.members.get(spec.email)
88
+ if role is None:
89
+ raise HTTPException(403, "gateway.owner_not_member")
90
+ ws = _workspace(request)
91
+ return Caller(sub=str(uuid.uuid5(uuid.NAMESPACE_URL, f"standin:member:{spec.email}")), email=spec.email,
92
+ name=spec.email.split("@")[0].title(), workspace_id=ws, role=role,
93
+ app=spec.app or s.allowed_azp[0],
94
+ client_id=str(uuid.uuid5(uuid.NAMESPACE_URL, f"standin:key:{key}")))
95
+
96
+
97
+ def caller(request: Request) -> Caller:
98
+ st = request.app.state
99
+ s = st.settings
100
+ header = request.headers.get("authorization", "")
101
+ scheme, _, credential = header.partition(" ")
102
+ if credential.startswith("agk_") and scheme.lower() in ("bearer", "dpop"):
103
+ return _api_key_caller(request, scheme.lower(), credential.strip())
104
+ token = header[7:] if header.lower().startswith("bearer ") else ""
105
+ try:
106
+ key = st.jwks.get_signing_key_from_jwt(token).key
107
+ claims = jwt.decode(token, key, algorithms=["RS256"], audience=s.audience, issuer=s.issuer, leeway=60,
108
+ options={"require": ["exp", "iss", "aud", "sub"]})
109
+ except Exception: # noqa: BLE001 - any verification failure is the same refusal
110
+ raise HTTPException(401, "auth.token_invalid") from None
111
+ azp = claims.get("azp")
112
+ if azp not in s.allowed_azp:
113
+ raise HTTPException(401, "auth.app_not_registered")
114
+ email = str(claims.get("email") or "").lower()
115
+ role = s.members.get(email)
116
+ if role is None:
117
+ raise HTTPException(409, "workspace.no_workspace")
118
+ ws = _workspace(request)
119
+ return Caller(sub=str(claims["sub"]), email=email, name=claims.get("name"), workspace_id=ws, role=role,
120
+ app=azp)