dsh-feiyu-memgate 0.3.2 → 0.4.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.
- package/CHANGELOG.md +73 -12
- package/README.md +68 -11
- package/README.zh.md +93 -36
- package/client/README.md +267 -0
- package/client/art/mascot-asleep.webp +0 -0
- package/client/art/mascot-busy.webp +0 -0
- package/client/art/mascot-nag.webp +0 -0
- package/client/art/mascot-ready.webp +0 -0
- package/client/art/mascot-trouble.webp +0 -0
- package/client/client.js +4226 -1269
- package/client/src/clipboard.cjs +52 -0
- package/client/src/constants.cjs +43 -0
- package/client/src/fields.cjs +960 -0
- package/client/src/hooks.cjs +220 -0
- package/client/src/i18n.cjs +444 -0
- package/client/src/index.cjs +69 -0
- package/client/src/kit/controls.cjs +189 -0
- package/client/src/kit/icons.cjs +40 -0
- package/client/src/kit/layout.cjs +124 -0
- package/client/src/layout.cjs +143 -0
- package/client/src/model/changelog.cjs +29 -0
- package/client/src/model/feedback.cjs +168 -0
- package/client/src/model/form.cjs +83 -0
- package/client/src/model/models.cjs +87 -0
- package/client/src/model/overview.cjs +111 -0
- package/client/src/model/page.cjs +104 -0
- package/client/src/model/status.cjs +57 -0
- package/client/src/model/trial.cjs +111 -0
- package/client/src/net.cjs +101 -0
- package/client/src/react.cjs +11 -0
- package/client/src/theme/page.css +1284 -0
- package/client/src/theme/styles.cjs +43 -0
- package/client/src/view/feedback.cjs +180 -0
- package/client/src/view/field-row.cjs +98 -0
- package/client/src/view/hero.cjs +54 -0
- package/client/src/view/markdown.cjs +96 -0
- package/client/src/view/models.cjs +154 -0
- package/client/src/view/page.cjs +199 -0
- package/client/src/view/settings-tab.cjs +78 -0
- package/client/src/view/tabs.cjs +71 -0
- package/client/src/view/trial.cjs +84 -0
- package/docs/DETAIL.en.md +55 -6
- package/docs/DETAIL.md +63 -14
- package/locale/zh.json +1 -1
- package/package.json +2 -1
- package/python/GATEWAY_VERSION.json +37 -31
- package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
- package/python/feiyu_memgate/backends/base.py +121 -6
- package/python/feiyu_memgate/backends/embedding.py +265 -178
- package/python/feiyu_memgate/backends/hybrid.py +330 -83
- package/python/feiyu_memgate/backends/inmemory.py +115 -24
- package/python/feiyu_memgate/backends/openviking.py +7 -10
- package/python/feiyu_memgate/backends/sqlite.py +129 -145
- package/python/feiyu_memgate/builtins.py +1 -0
- package/python/feiyu_memgate/cli.py +124 -20
- package/python/feiyu_memgate/client/block.py +4 -2
- package/python/feiyu_memgate/client/http.py +106 -19
- package/python/feiyu_memgate/client/local.py +4 -3
- package/python/feiyu_memgate/config.py +118 -24
- package/python/feiyu_memgate/core/limits.py +2 -1
- package/python/feiyu_memgate/core/pool.py +29 -2
- package/python/feiyu_memgate/core/recall.py +179 -10
- package/python/feiyu_memgate/core/redact.py +4 -2
- package/python/feiyu_memgate/core/stages.py +52 -9
- package/python/feiyu_memgate/core/tidy.py +2 -1
- package/python/feiyu_memgate/core/watch.py +3 -2
- package/python/feiyu_memgate/core/write.py +9 -3
- package/python/feiyu_memgate/forgetting/archive.py +38 -10
- package/python/feiyu_memgate/forgetting/engine.py +46 -10
- package/python/feiyu_memgate/forgetting/stage.py +4 -2
- package/python/feiyu_memgate/gateway/app.py +168 -272
- package/python/feiyu_memgate/gateway/fields.py +121 -0
- package/python/feiyu_memgate/gateway/policies.py +162 -0
- package/python/feiyu_memgate/gateway/server.py +12 -4
- package/python/feiyu_memgate/gateway/tokens.py +137 -0
- package/python/feiyu_memgate/gateway/validate.py +120 -0
- package/python/feiyu_memgate/identity.py +152 -0
- package/python/feiyu_memgate/model.py +170 -2
- package/python/feiyu_memgate/registry.py +6 -3
- package/python/feiyu_memgate/tools/crypto.py +5 -4
- package/python/feiyu_memgate/tools/evaluate.py +2 -1
- package/python/feiyu_memgate/tools/tenants.py +2 -0
- package/src/block.js +9 -3
- package/src/capture.js +98 -0
- package/src/catalogue.js +4 -4
- package/src/changelog.js +72 -0
- package/src/client.js +145 -10
- package/src/commands.js +112 -62
- package/src/config.js +139 -62
- package/src/followup.js +139 -0
- package/src/gateway.js +79 -4
- package/src/migrate.py +54 -9
- package/src/mirror.py +44 -7
- package/src/plugin.js +416 -412
- package/src/pool.js +298 -0
- package/src/recent.js +68 -0
- package/src/relevance.js +80 -0
- package/src/routes.js +320 -0
- package/src/setup.js +36 -36
- package/src/shared.js +77 -0
- package/src/tiers.js +4 -4
- package/src/time.js +27 -0
- package/src/tools.js +164 -0
|
@@ -9,49 +9,49 @@ raise; an error body is always {"error": <human text>, "code": <stable code>}
|
|
|
9
9
|
(the codes are listed in docs/api.md).
|
|
10
10
|
|
|
11
11
|
Standard library only.
|
|
12
|
+
|
|
13
|
+
The parts that need no Gateway live beside it: tokens.py (token floor and the tenant token
|
|
14
|
+
format), validate.py (request-body checks and their limits) and policies.py (start-up checks).
|
|
15
|
+
Their public names are re-exported here, so this module stays the one place to import from.
|
|
12
16
|
"""
|
|
13
|
-
import base64
|
|
14
17
|
import collections
|
|
15
|
-
import hashlib
|
|
16
18
|
import hmac
|
|
17
|
-
import math
|
|
18
|
-
import re
|
|
19
|
-
import struct
|
|
20
19
|
import sys
|
|
21
20
|
import threading
|
|
22
21
|
import time
|
|
22
|
+
from typing import Any
|
|
23
23
|
|
|
24
24
|
from .. import registry
|
|
25
25
|
from ..core import limits, stages as stages_module, write as write_module
|
|
26
26
|
from ..core.pool import POOL_SIZE, Pool
|
|
27
27
|
from ..core.recall import BUSY, OK, RECALL_DEADLINE, MAX_WAIT, RecallContext, StageError, call, piece_name, recall
|
|
28
28
|
from ..core.watch import ExtractionWatch, RecallFailures
|
|
29
|
-
from ..errors import
|
|
30
|
-
from ..model import
|
|
31
|
-
|
|
32
|
-
|
|
29
|
+
from ..errors import WriteRejected
|
|
30
|
+
from ..model import TENANT_STORE, platform_of, valid_account
|
|
31
|
+
from . import policies
|
|
32
|
+
from .fields import Refused, request_fields
|
|
33
|
+
# The names below were defined in this module before it was split. They are imported here for
|
|
34
|
+
# the callers and tests that still reach them as attributes of gateway.app (re-exports).
|
|
35
|
+
from ..errors import ConfigError # noqa: F401
|
|
36
|
+
from ..model import AUDIENCES, TENANT_BINDINGS # noqa: F401
|
|
37
|
+
from .policies import _audience_choices # noqa: F401
|
|
38
|
+
from .tokens import ( # noqa: F401
|
|
39
|
+
MAX_TENANT_ID_BYTES, MAX_TENANT_TOKEN_CHARS, MIN_TOKEN_CHARS, PLACEHOLDER_TOKEN, RANDOM_SECRET_CHARS,
|
|
40
|
+
RANDOM_SECRET_DISTINCT, TENANT_TOKEN_LABEL, TENANT_TOKEN_PREFIX, _B64URL, _MAC_BYTES, _b64, _b64_chars,
|
|
41
|
+
_secret_bytes, _unb64, mint_tenant_token, minting_secret_looks_weak, parse_tenant_token, tenant_token_mac,
|
|
42
|
+
usable_token)
|
|
43
|
+
from .validate import ( # noqa: F401
|
|
44
|
+
MAX_CONTEXT_KEYS, MAX_CONTEXT_KEY_CHARS, MAX_CONTEXT_VALUE_CHARS, MAX_MESSAGE_CHARS, MAX_MESSAGES,
|
|
45
|
+
MAX_QUERY_CHARS, MAX_SPEAKER_CHARS, MAX_TIME_CHARS, MAX_TOTAL_CHARS, MAX_USED, MAX_USED_ID_CHARS,
|
|
46
|
+
MAX_USED_SOURCE_CHARS, _BadMessages, _check_shape, _valid_context, _valid_history, _valid_messages, _valid_used)
|
|
47
|
+
|
|
48
|
+
DEFAULT_LIMIT = 8
|
|
33
49
|
MAX_LIMIT = 10
|
|
34
|
-
MAX_QUERY_CHARS = 500
|
|
35
|
-
MAX_MESSAGES = 20
|
|
36
|
-
MAX_MESSAGE_CHARS = 4000
|
|
37
|
-
MAX_TOTAL_CHARS = 16000
|
|
38
|
-
MAX_TIME_CHARS = 40
|
|
39
|
-
MAX_SPEAKER_CHARS = 64
|
|
40
|
-
MAX_CONTEXT_KEYS = 16
|
|
41
|
-
MAX_CONTEXT_KEY_CHARS = 64
|
|
42
|
-
MAX_CONTEXT_VALUE_CHARS = 200
|
|
43
|
-
MAX_USED = 20
|
|
44
|
-
MAX_USED_SOURCE_CHARS = 128
|
|
45
|
-
MAX_USED_ID_CHARS = 512
|
|
46
50
|
USED_DEADLINE = 3.0
|
|
47
51
|
COLD_RECALL_DEADLINE = 8.0
|
|
48
52
|
COLD_AFTER = 600.0 # a local embedding model is often unloaded after 10 idle minutes
|
|
49
53
|
REMEMBER_DEADLINE = 10.0
|
|
50
54
|
TENANT_PER_TENANT = 2
|
|
51
|
-
# Tokens shorter than this, or the placeholder of the example configuration, are not loaded,
|
|
52
|
-
# so a hand-copied example never guards a route with a public string.
|
|
53
|
-
MIN_TOKEN_CHARS = 32
|
|
54
|
-
PLACEHOLDER_TOKEN = "change-me"
|
|
55
55
|
|
|
56
56
|
Reply = collections.namedtuple("Reply", "status body note", defaults=("",))
|
|
57
57
|
|
|
@@ -66,121 +66,6 @@ def stderr_log(line):
|
|
|
66
66
|
sys.stderr.flush()
|
|
67
67
|
|
|
68
68
|
|
|
69
|
-
def usable_token(value):
|
|
70
|
-
"""value when it can guard a route, "" when it is missing, the placeholder or shorter than MIN_TOKEN_CHARS."""
|
|
71
|
-
if not isinstance(value, str) or value in ("", PLACEHOLDER_TOKEN) or len(value) < MIN_TOKEN_CHARS:
|
|
72
|
-
return ""
|
|
73
|
-
return value
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
# ---------------------------------------------------------------- tenant-bound tokens
|
|
77
|
-
#
|
|
78
|
-
# A client with tenant_binding = "token" holds a minting secret that never authenticates a
|
|
79
|
-
# request by itself. A request token is
|
|
80
|
-
#
|
|
81
|
-
# fmg1.<base64url(tenant id, UTF-8), no padding>.<base64url(HMAC-SHA256(secret, context)), no padding>
|
|
82
|
-
#
|
|
83
|
-
# where context frames, each as a 4-byte big-endian length followed by the bytes: TENANT_TOKEN_LABEL,
|
|
84
|
-
# the client name (UTF-8), the client's tenants provider name (UTF-8), the token generation (decimal
|
|
85
|
-
# ASCII) and the tenant id (UTF-8). The length prefixes make the framing unambiguous; the label keeps
|
|
86
|
-
# these MACs apart from any other use of the secret; the client name keeps one client's tokens from
|
|
87
|
-
# authenticating as another's; the provider name keeps a token from following its client when the
|
|
88
|
-
# client is pointed at another provider (the same id there may be someone else); the generation lets
|
|
89
|
-
# the operator void every token of a client at once. Verification needs no state. The tenant id is
|
|
90
|
-
# encoded, not encrypted: whoever holds a token can read which tenant it names.
|
|
91
|
-
#
|
|
92
|
-
# Anyone holding one token can test guesses of the minting secret offline, at no cost to the gateway,
|
|
93
|
-
# so the secret must be random (secrets.token_urlsafe(32)), never a phrase: see minting_secret_looks_weak().
|
|
94
|
-
|
|
95
|
-
TENANT_TOKEN_PREFIX = "fmg1"
|
|
96
|
-
TENANT_TOKEN_LABEL = b"feiyu-memgate tenant token v1"
|
|
97
|
-
MAX_TENANT_ID_BYTES = 256
|
|
98
|
-
_MAC_BYTES = 32 # HMAC-SHA256
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
def _b64_chars(n):
|
|
102
|
-
"""Characters of n bytes in unpadded base64url."""
|
|
103
|
-
return (4 * n + 2) // 3
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
MAX_TENANT_TOKEN_CHARS = len(TENANT_TOKEN_PREFIX) + 1 + _b64_chars(MAX_TENANT_ID_BYTES) + 1 + _b64_chars(_MAC_BYTES)
|
|
107
|
-
_B64URL = re.compile(r"[A-Za-z0-9_-]+")
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
def _b64(raw):
|
|
111
|
-
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
def _unb64(text):
|
|
115
|
-
"""The bytes of unpadded base64url text written in its one canonical spelling, else None.
|
|
116
|
-
Padding, the standard alphabet, whitespace and non-zero unused trailing bits are all refused, so
|
|
117
|
-
a token has exactly one accepted spelling."""
|
|
118
|
-
if not text or not text.isascii() or len(text) % 4 == 1 or _B64URL.fullmatch(text) is None:
|
|
119
|
-
return None
|
|
120
|
-
try:
|
|
121
|
-
raw = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
122
|
-
except ValueError: # binascii.Error
|
|
123
|
-
return None
|
|
124
|
-
return raw if _b64(raw) == text else None
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def _secret_bytes(secret):
|
|
128
|
-
# As the presented plain tokens are compared: an odd environment value still has one byte form.
|
|
129
|
-
return secret.encode("utf-8", "surrogateescape")
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
def tenant_token_mac(secret, client, provider, generation, tenant_id):
|
|
133
|
-
"""HMAC-SHA256 of one (client, tenants provider, generation, tenant) under a client's minting secret."""
|
|
134
|
-
fields = (TENANT_TOKEN_LABEL, client.encode("utf-8"), provider.encode("utf-8"), str(generation).encode("ascii"),
|
|
135
|
-
tenant_id.encode("utf-8"))
|
|
136
|
-
context = b"".join(struct.pack(">I", len(field)) + field for field in fields)
|
|
137
|
-
return hmac.new(_secret_bytes(secret), context, hashlib.sha256).digest()
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
def mint_tenant_token(secret, client, provider, generation, tenant_id):
|
|
141
|
-
"""The request token of `client` (whose tenants provider is `provider`) bound to `tenant_id`.
|
|
142
|
-
Raises ValueError for an empty tenant id or one over MAX_TENANT_ID_BYTES bytes of UTF-8 (the
|
|
143
|
-
message holds no secret)."""
|
|
144
|
-
if not isinstance(tenant_id, str):
|
|
145
|
-
raise ValueError("the tenant id must be text")
|
|
146
|
-
raw = tenant_id.encode("utf-8") # strict: a lone surrogate has no UTF-8 form
|
|
147
|
-
if not 0 < len(raw) <= MAX_TENANT_ID_BYTES:
|
|
148
|
-
raise ValueError("the tenant id must be 1 to %d bytes of UTF-8" % MAX_TENANT_ID_BYTES)
|
|
149
|
-
mac = tenant_token_mac(secret, client, provider, generation, tenant_id)
|
|
150
|
-
return "%s.%s.%s" % (TENANT_TOKEN_PREFIX, _b64(raw), _b64(mac))
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
# A heuristic, not a measure of entropy: secrets.token_urlsafe(32) gives 43 characters drawn from 64,
|
|
154
|
-
# so a shorter secret, or one built from few distinct characters, was probably not made that way.
|
|
155
|
-
RANDOM_SECRET_CHARS = 43
|
|
156
|
-
RANDOM_SECRET_DISTINCT = 16
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
def minting_secret_looks_weak(secret):
|
|
160
|
-
"""True when a minting secret does not look randomly generated (shorter than 43 characters or
|
|
161
|
-
fewer than 16 distinct ones). A token lets its holder guess the secret offline, unlike a plain
|
|
162
|
-
token, which can only be guessed against the gateway and its rate limit."""
|
|
163
|
-
return len(secret) < RANDOM_SECRET_CHARS or len(set(secret)) < RANDOM_SECRET_DISTINCT
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
def parse_tenant_token(presented):
|
|
167
|
-
"""(tenant id, MAC bytes) of a token in the tenant-bound format, else None. Only the public
|
|
168
|
-
structure is checked here, its length first; the MAC is checked by the gateway, which knows the
|
|
169
|
-
secrets, and the tenant id by the client's provider."""
|
|
170
|
-
if not isinstance(presented, str) or len(presented) > MAX_TENANT_TOKEN_CHARS:
|
|
171
|
-
return None
|
|
172
|
-
parts = presented.split(".")
|
|
173
|
-
if len(parts) != 3 or parts[0] != TENANT_TOKEN_PREFIX:
|
|
174
|
-
return None
|
|
175
|
-
raw, mac = _unb64(parts[1]), _unb64(parts[2])
|
|
176
|
-
if raw is None or mac is None or len(mac) != _MAC_BYTES or not 0 < len(raw) <= MAX_TENANT_ID_BYTES:
|
|
177
|
-
return None
|
|
178
|
-
try:
|
|
179
|
-
return raw.decode("utf-8"), mac # strict: one tenant id, one byte form
|
|
180
|
-
except UnicodeDecodeError:
|
|
181
|
-
return None
|
|
182
|
-
|
|
183
|
-
|
|
184
69
|
def default_stages():
|
|
185
70
|
return [registry.create("recall_stage", name) for name in stages_module.DEFAULT_STAGES]
|
|
186
71
|
|
|
@@ -198,88 +83,6 @@ def _join(notes):
|
|
|
198
83
|
return ",".join(seen)
|
|
199
84
|
|
|
200
85
|
|
|
201
|
-
def _valid_context(value):
|
|
202
|
-
"""The request's "context" object as a dict ({} when absent), or None when it breaks
|
|
203
|
-
the rules: at most MAX_CONTEXT_KEYS keys, each value a short string, a number or a boolean."""
|
|
204
|
-
if value is None:
|
|
205
|
-
return {}
|
|
206
|
-
if not isinstance(value, dict) or len(value) > MAX_CONTEXT_KEYS:
|
|
207
|
-
return None
|
|
208
|
-
for key, item in value.items():
|
|
209
|
-
if not isinstance(key, str) or not key or len(key) > MAX_CONTEXT_KEY_CHARS:
|
|
210
|
-
return None
|
|
211
|
-
if isinstance(item, bool):
|
|
212
|
-
continue
|
|
213
|
-
if isinstance(item, (int, float)):
|
|
214
|
-
if isinstance(item, float) and not math.isfinite(item):
|
|
215
|
-
return None
|
|
216
|
-
continue
|
|
217
|
-
if not isinstance(item, str) or len(item) > MAX_CONTEXT_VALUE_CHARS:
|
|
218
|
-
return None
|
|
219
|
-
return dict(value)
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
def _valid_used(items):
|
|
223
|
-
"""The "used" list as [(source, id)], or None when it breaks the rules: a list of at most
|
|
224
|
-
MAX_USED objects, each with a non-empty string "source" and "id" of sane length. An empty
|
|
225
|
-
list is fine (nothing used). Other keys are ignored, so a recall result can be passed as it is."""
|
|
226
|
-
if not isinstance(items, list) or len(items) > MAX_USED:
|
|
227
|
-
return None
|
|
228
|
-
clean = []
|
|
229
|
-
for item in items:
|
|
230
|
-
if not isinstance(item, dict):
|
|
231
|
-
return None
|
|
232
|
-
source, ref = item.get("source"), item.get("id")
|
|
233
|
-
if not isinstance(source, str) or not source or len(source) > MAX_USED_SOURCE_CHARS:
|
|
234
|
-
return None
|
|
235
|
-
if not isinstance(ref, str) or not ref or len(ref) > MAX_USED_ID_CHARS:
|
|
236
|
-
return None
|
|
237
|
-
clean.append((source, ref))
|
|
238
|
-
return clean
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
def _valid_messages(messages):
|
|
242
|
-
"""The messages as [{"role", "content", optional "time", "speaker"}], or None when the
|
|
243
|
-
shape is wrong. Over-long content is rejected, not truncated; other keys are dropped."""
|
|
244
|
-
if not isinstance(messages, list) or not 0 < len(messages) <= MAX_MESSAGES:
|
|
245
|
-
return None
|
|
246
|
-
clean = []
|
|
247
|
-
total = 0
|
|
248
|
-
for m in messages:
|
|
249
|
-
if not isinstance(m, dict):
|
|
250
|
-
return None
|
|
251
|
-
role, content = m.get("role"), m.get("content")
|
|
252
|
-
if role not in ("user", "assistant") or not isinstance(content, str):
|
|
253
|
-
return None
|
|
254
|
-
if not content.strip() or len(content) > MAX_MESSAGE_CHARS:
|
|
255
|
-
return None
|
|
256
|
-
total += len(content)
|
|
257
|
-
if total > MAX_TOTAL_CHARS:
|
|
258
|
-
return None
|
|
259
|
-
item = {"role": role, "content": content}
|
|
260
|
-
for key, cap in (("time", MAX_TIME_CHARS), ("speaker", MAX_SPEAKER_CHARS)):
|
|
261
|
-
value = m.get(key)
|
|
262
|
-
if value is None:
|
|
263
|
-
continue
|
|
264
|
-
if not isinstance(value, str) or len(value) > cap:
|
|
265
|
-
return None
|
|
266
|
-
item[key] = value
|
|
267
|
-
clean.append(item)
|
|
268
|
-
return clean
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
class _BadMessages(Exception):
|
|
272
|
-
"""A guard handed back something the backends cannot take (a forgotten return included)."""
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
def _check_shape(messages):
|
|
276
|
-
if not isinstance(messages, list) or not all(
|
|
277
|
-
isinstance(m, dict) and m.get("role") in ("user", "assistant") and isinstance(m.get("content"), str)
|
|
278
|
-
for m in messages):
|
|
279
|
-
raise _BadMessages()
|
|
280
|
-
return messages
|
|
281
|
-
|
|
282
|
-
|
|
283
86
|
class Gateway:
|
|
284
87
|
"""stores name -> backend (the shared stores)
|
|
285
88
|
clients name -> ClientPolicy
|
|
@@ -290,8 +93,13 @@ class Gateway:
|
|
|
290
93
|
stages the recall stages, in order (default: the built-in set)
|
|
291
94
|
guards the write guards, in order (default: redact, daily_cap)
|
|
292
95
|
redactors {"private": fn, "public": fn}: the text cleaner for private and public clients
|
|
96
|
+
audiences {name: level}: who each store or tenants provider is for, "owner" (default for a
|
|
97
|
+
store), "group" (default for a tenants provider) or "public"; see audience_of
|
|
293
98
|
forgetting an optional forgetting.Forgetting: ranks older memories lower and, every
|
|
294
99
|
sweep_every_hours hours (0 = never), archives and removes the forgotten ones
|
|
100
|
+
identity an optional identity provider (feiyu_memgate.identity): with one, a message's speaker and
|
|
101
|
+
about are accounts, resolved to people before any guard or store sees them, and the
|
|
102
|
+
clients' platforms and only_for are enforced; without one, speaker is handled as it was
|
|
295
103
|
|
|
296
104
|
Workers: pool_size calls to the stores at once; tenant_pool_total tenant requests in
|
|
297
105
|
flight (default pool_size - 2), tenant_pool_per_tenant per tenant (default 2), and
|
|
@@ -303,11 +111,14 @@ class Gateway:
|
|
|
303
111
|
clock=time.monotonic, log=stderr_log, recall_deadline=RECALL_DEADLINE,
|
|
304
112
|
cold_recall_deadline=None, cold_after=COLD_AFTER, remember_deadline=REMEMBER_DEADLINE,
|
|
305
113
|
pool_size=POOL_SIZE, tenant_pool_total=None, tenant_pool_per_tenant=TENANT_PER_TENANT,
|
|
306
|
-
store_max_inflight=None, forgetting=None, sweep_every_hours=24):
|
|
114
|
+
store_max_inflight=None, forgetting=None, sweep_every_hours=24, audiences=None, identity=None):
|
|
307
115
|
self.stores = dict(stores)
|
|
308
116
|
self.clients = dict(clients)
|
|
309
117
|
self.tenants = dict(tenants or {})
|
|
118
|
+
self.audiences = self._load_audiences(audiences)
|
|
310
119
|
self._check_policies()
|
|
120
|
+
self.identity = identity
|
|
121
|
+
policies.check_identity(self.clients, identity)
|
|
311
122
|
self._tokens, self._minting = self._load_tokens(tokens)
|
|
312
123
|
self.stages = list(stages) if stages is not None else default_stages()
|
|
313
124
|
self.guards = list(guards) if guards is not None else default_guards()
|
|
@@ -343,41 +154,60 @@ class Gateway:
|
|
|
343
154
|
self._sweep_thread = None
|
|
344
155
|
self._started = []
|
|
345
156
|
self._closed = False
|
|
157
|
+
self._stamp_shared_stores()
|
|
158
|
+
|
|
159
|
+
def _load_audiences(self, audiences):
|
|
160
|
+
"""name -> level for every store and tenants provider; what was not declared gets its default."""
|
|
161
|
+
levels, self._declared = policies.load_audiences(self.stores, self.tenants, audiences)
|
|
162
|
+
return levels
|
|
163
|
+
|
|
164
|
+
def audience_of(self, name):
|
|
165
|
+
"""The level of a store or a tenants provider: who its content may be shown to."""
|
|
166
|
+
try:
|
|
167
|
+
return self.audiences[name]
|
|
168
|
+
except KeyError:
|
|
169
|
+
raise KeyError("no store or tenants provider named %r" % name) from None
|
|
170
|
+
|
|
171
|
+
@staticmethod
|
|
172
|
+
def _stamp(store, level):
|
|
173
|
+
"""Give the records of `store` that have no audience the store's `level`, once: the first time a
|
|
174
|
+
store keeps fields and is stamped, its records get `level` and its recall check (record_audience)
|
|
175
|
+
starts. A store without `stamp_audience` is left alone; a stamped one costs a flag test."""
|
|
176
|
+
stamp = getattr(store, "stamp_audience", None)
|
|
177
|
+
if callable(stamp):
|
|
178
|
+
stamp(level)
|
|
179
|
+
|
|
180
|
+
def _stamp_shared_stores(self):
|
|
181
|
+
"""Stamp every shared store with its declared level, once, when the gateway is built."""
|
|
182
|
+
for name, store in self.stores.items():
|
|
183
|
+
self._stamp(store, self.audiences[name])
|
|
184
|
+
|
|
185
|
+
def tenant_store(self, name, tenant_id):
|
|
186
|
+
"""The store the tenants provider `name` has for `tenant_id`, stamped with the provider's level
|
|
187
|
+
(see _stamp), or None for an unknown tenant. The provider's cache stays the provider's: nothing
|
|
188
|
+
here is held under a lock."""
|
|
189
|
+
store = self.tenants[name].store(tenant_id)
|
|
190
|
+
if store is not None:
|
|
191
|
+
self._stamp(store, self.audiences[name])
|
|
192
|
+
return store
|
|
193
|
+
|
|
194
|
+
def _check_audience(self, where, policy):
|
|
195
|
+
"""The two audience rules: a client reads only stores at least as wide as its own audience,
|
|
196
|
+
and a client serving many groups reads no store that belongs to one group."""
|
|
197
|
+
policies.check_audience(where, policy, self.audiences, self._declared)
|
|
346
198
|
|
|
347
199
|
def _check_policies(self):
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
self._check_binding(where, policy)
|
|
356
|
-
for store in policy.recall or ():
|
|
357
|
-
if store == TENANT_STORE:
|
|
358
|
-
if policy.tenants is None:
|
|
359
|
-
raise ConfigError("%s.recall names %r but the client has no tenants" % (where, TENANT_STORE))
|
|
360
|
-
elif store not in self.stores:
|
|
361
|
-
raise ConfigError("%s.recall names an unknown store %r" % (where, store))
|
|
362
|
-
if policy.write == TENANT_STORE:
|
|
363
|
-
if policy.tenants is None:
|
|
364
|
-
raise ConfigError("%s.write is %r but the client has no tenants" % (where, TENANT_STORE))
|
|
365
|
-
elif policy.write is not None:
|
|
366
|
-
if policy.write not in self.stores:
|
|
367
|
-
raise ConfigError("%s.write names an unknown store %r" % (where, policy.write))
|
|
368
|
-
if not getattr(self.stores[policy.write], "writable", False):
|
|
369
|
-
raise ConfigError("%s.write names the read-only store %r" % (where, policy.write))
|
|
200
|
+
policies.check_policies(self.stores, self.tenants, self.clients, self.audiences, self._declared)
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def _check_explain(where, policy):
|
|
204
|
+
"""An explained recall shows what a recall left out, so only a client that recalls and
|
|
205
|
+
shows its answer to no one but the owner may have it."""
|
|
206
|
+
policies.check_explain(where, policy)
|
|
370
207
|
|
|
371
208
|
@staticmethod
|
|
372
209
|
def _check_binding(where, policy):
|
|
373
|
-
|
|
374
|
-
raise ConfigError("%s.tenant_binding must be \"request\" or \"token\"" % where)
|
|
375
|
-
if policy.tenant_binding == "token" and policy.tenants is None:
|
|
376
|
-
raise ConfigError("%s.tenant_binding = \"token\" needs tenants: only a tenant client has a tenant "
|
|
377
|
-
"to bind its tokens to" % where)
|
|
378
|
-
generation = policy.tenant_token_generation
|
|
379
|
-
if isinstance(generation, bool) or not isinstance(generation, int) or generation < 1:
|
|
380
|
-
raise ConfigError("%s.tenant_token_generation must be a positive integer" % where)
|
|
210
|
+
policies.check_binding(where, policy)
|
|
381
211
|
|
|
382
212
|
def _load_tokens(self, tokens):
|
|
383
213
|
"""(plain, minting): name -> token bytes of the clients that present their token as it is,
|
|
@@ -389,6 +219,7 @@ class Gateway:
|
|
|
389
219
|
A minting secret must pass usable_token(), as the configuration loader requires of every
|
|
390
220
|
token: a gateway built in code gets the same floor, as a ConfigError, because a token's
|
|
391
221
|
holder can guess a weak secret offline."""
|
|
222
|
+
owner: dict[str, str]
|
|
392
223
|
plain, minting, owner = {}, {}, {}
|
|
393
224
|
for name, token in tokens.items():
|
|
394
225
|
if not token or name not in self.clients:
|
|
@@ -483,8 +314,9 @@ class Gateway:
|
|
|
483
314
|
|
|
484
315
|
def admit(self, name, action, bound_tenant=None):
|
|
485
316
|
"""The checks that need no request body: rate limits, then permission.
|
|
486
|
-
`action` is "recall", "used" (both need the right to recall)
|
|
487
|
-
as for recall(). Returns a Reply to refuse, None to
|
|
317
|
+
`action` is "recall", "used" (both need the right to recall), "explain" (needs that and the
|
|
318
|
+
client's explain setting) or "remember"; bound_tenant is as for recall(). Returns a Reply to refuse, None to
|
|
319
|
+
go on.
|
|
488
320
|
|
|
489
321
|
A tenant-bound client's whole rate limiting happens here, per tenant and in total, because
|
|
490
322
|
its tenant is known before the body is read; a caller that skips admit() (an in-process call
|
|
@@ -512,7 +344,10 @@ class Gateway:
|
|
|
512
344
|
limit = policy.total_rate_limit if policy.tenants is not None else policy.rate_limit
|
|
513
345
|
if not self.limiter.allow(name, limit):
|
|
514
346
|
return error_reply(429, "rate_limited", "rate limited")
|
|
515
|
-
|
|
347
|
+
if action == "remember":
|
|
348
|
+
allowed = policy.can_write
|
|
349
|
+
else:
|
|
350
|
+
allowed = policy.can_recall and (action != "explain" or policy.explain)
|
|
516
351
|
if not allowed:
|
|
517
352
|
return error_reply(403, "forbidden", "forbidden")
|
|
518
353
|
return None
|
|
@@ -541,9 +376,10 @@ class Gateway:
|
|
|
541
376
|
provider = self.tenants[policy.tenants]
|
|
542
377
|
if not isinstance(tenant_id, str) or not provider.valid_id(tenant_id):
|
|
543
378
|
return error_reply(400, "bad_tenant", "bad tenant_id")
|
|
544
|
-
if not policy.token_bound and not self.limiter.allow(
|
|
379
|
+
if not policy.token_bound and not self.limiter.allow(
|
|
380
|
+
self._tenant_rate_key(policy, tenant_id), policy.rate_limit):
|
|
545
381
|
return error_reply(429, "rate_limited", "rate limited")
|
|
546
|
-
store =
|
|
382
|
+
store = self.tenant_store(policy.tenants, tenant_id)
|
|
547
383
|
if store is None:
|
|
548
384
|
return error_reply(403, "unknown_tenant", "unknown tenant")
|
|
549
385
|
return tenant_id, store
|
|
@@ -601,7 +437,18 @@ class Gateway:
|
|
|
601
437
|
bound_tenant: the tenant a tenant-bound client's token names (see identify), else None."""
|
|
602
438
|
return self._guarded(self._recall, name, body, bound_tenant)
|
|
603
439
|
|
|
604
|
-
def
|
|
440
|
+
def explain(self, name, body, bound_tenant=None):
|
|
441
|
+
"""Like recall(), and the answer also says what became of every candidate: "stages" and
|
|
442
|
+
"candidates" (see core.recall.Trace). Only for a client whose policy has explain. It counts
|
|
443
|
+
as no use: the stages' finish() does not run."""
|
|
444
|
+
return self._guarded(self._explain, name, body, bound_tenant)
|
|
445
|
+
|
|
446
|
+
def _explain(self, name, body, bound_tenant):
|
|
447
|
+
if not self.clients[name].explain:
|
|
448
|
+
return error_reply(403, "forbidden", "forbidden")
|
|
449
|
+
return self._recall(name, body, bound_tenant, trace=True)
|
|
450
|
+
|
|
451
|
+
def _recall(self, name, body, bound_tenant, trace=False):
|
|
605
452
|
policy = self.clients[name]
|
|
606
453
|
if not policy.can_recall:
|
|
607
454
|
return error_reply(403, "forbidden", "forbidden")
|
|
@@ -618,12 +465,21 @@ class Gateway:
|
|
|
618
465
|
context = _valid_context(body.get("context"))
|
|
619
466
|
if context is None:
|
|
620
467
|
return error_reply(400, "bad_context", "bad context")
|
|
468
|
+
history = _valid_history(body.get("history"))
|
|
469
|
+
if history is None:
|
|
470
|
+
return error_reply(400, "bad_history", "bad history")
|
|
471
|
+
person = None
|
|
472
|
+
if self.identity is not None:
|
|
473
|
+
person = self._asker(policy, tenant_id, body)
|
|
474
|
+
if isinstance(person, Reply):
|
|
475
|
+
return person
|
|
621
476
|
key = self._admit_tenant(policy, tenant_id)
|
|
622
477
|
if key is False:
|
|
623
478
|
self.recall_busy.record()
|
|
624
479
|
return error_reply(503, "busy", "busy", "tenant-budget")
|
|
625
480
|
try:
|
|
626
|
-
return self._search(policy, tenant_id, tenant_store, query, max(1, min(limit, MAX_LIMIT)), context
|
|
481
|
+
return self._search(policy, tenant_id, tenant_store, query, max(1, min(limit, MAX_LIMIT)), context,
|
|
482
|
+
trace, person, history)
|
|
627
483
|
finally:
|
|
628
484
|
if key:
|
|
629
485
|
self.tenant_budget.release(key)
|
|
@@ -639,15 +495,17 @@ class Gateway:
|
|
|
639
495
|
stores[name] = self.stores[name]
|
|
640
496
|
return stores
|
|
641
497
|
|
|
642
|
-
def _search(self, policy, tenant_id, tenant_store, query, limit, context
|
|
498
|
+
def _search(self, policy, tenant_id, tenant_store, query, limit, context, trace=False, person=None,
|
|
499
|
+
history=()):
|
|
643
500
|
stores = self._recall_stores(policy, tenant_store)
|
|
644
|
-
notes = []
|
|
501
|
+
notes = ["explain"] if trace else []
|
|
645
502
|
deadline_s = self.recall_deadline_now() if stores else self.recall_deadline
|
|
646
503
|
ctx = RecallContext(query, limit, pool=self.pool, clock=self.clock, deadline=self.clock() + deadline_s,
|
|
647
504
|
public=policy.public, redact=self._redactor(policy), client=policy.name,
|
|
648
505
|
tenant_id=tenant_id, notes=notes, context=context, log=self._log,
|
|
649
506
|
tenant_source=policy.tenants if TENANT_STORE in policy.recall else None,
|
|
650
|
-
slots=self.store_slots, keep=self._keep(policy)
|
|
507
|
+
slots=self.store_slots, keep=self._keep(policy), audience=policy.reach, trace=trace,
|
|
508
|
+
show_fields=policy.fields, person=person, history=history)
|
|
651
509
|
try:
|
|
652
510
|
out = recall(stores, self.stages, ctx)
|
|
653
511
|
except StageError:
|
|
@@ -710,7 +568,7 @@ class Gateway:
|
|
|
710
568
|
"""Record a use for each reported memory that exists. Returns how many. A memory is known
|
|
711
569
|
when the ledger has a row for it or its store can read it: made-up ids record nothing."""
|
|
712
570
|
f = self.forgetting
|
|
713
|
-
by_key = {}
|
|
571
|
+
by_key: dict[Any, list[Any]] = {}
|
|
714
572
|
for source, ref in dict.fromkeys(items):
|
|
715
573
|
if not f.manages(source):
|
|
716
574
|
continue
|
|
@@ -719,7 +577,7 @@ class Gateway:
|
|
|
719
577
|
deadline = self.clock() + USED_DEADLINE
|
|
720
578
|
recorded = 0
|
|
721
579
|
for (key, source, tenant), refs in by_key.items():
|
|
722
|
-
store = self.
|
|
580
|
+
store = self.tenant_store(source, tenant_id) if tenant else self.stores[source]
|
|
723
581
|
if store is None:
|
|
724
582
|
continue
|
|
725
583
|
known = f.ledger.get_many(key, refs)
|
|
@@ -732,8 +590,12 @@ class Gateway:
|
|
|
732
590
|
# ---------------------------------------------------------------- remember
|
|
733
591
|
|
|
734
592
|
def remember(self, name, body, bound_tenant=None):
|
|
735
|
-
"""Store {"messages": [{"role", "content", "time"?, "speaker"
|
|
736
|
-
"context": {...}} for the client `name`. bound_tenant: as
|
|
593
|
+
"""Store {"messages": [{"role", "content", "time"?, "speaker"?, "channel"?, "origin"?, "event_date"?,
|
|
594
|
+
"kind"?, "audience"?}], "tenant_id": str, "context": {...}} for the client `name`. bound_tenant: as
|
|
595
|
+
for recall().
|
|
596
|
+
|
|
597
|
+
The last five keys are record fields (gateway/fields.py): a store that keeps fields stores them,
|
|
598
|
+
together with the audience of every record; the guards see them as the message key "fields"."""
|
|
737
599
|
return self._guarded(self._remember, name, body, bound_tenant)
|
|
738
600
|
|
|
739
601
|
def _remember(self, name, body, bound_tenant):
|
|
@@ -744,17 +606,23 @@ class Gateway:
|
|
|
744
606
|
if isinstance(tenant, Reply):
|
|
745
607
|
return tenant
|
|
746
608
|
tenant_id, tenant_store = tenant
|
|
747
|
-
messages = _valid_messages(body.get("messages"))
|
|
609
|
+
messages = _valid_messages(body.get("messages"), accounts=self.identity is not None)
|
|
748
610
|
if messages is None:
|
|
749
611
|
return error_reply(400, "bad_messages", "bad messages")
|
|
750
612
|
context = _valid_context(body.get("context"))
|
|
751
613
|
if context is None:
|
|
752
614
|
return error_reply(400, "bad_context", "bad context")
|
|
615
|
+
store = tenant_store if policy.write == TENANT_STORE else self.stores[policy.write]
|
|
616
|
+
try:
|
|
617
|
+
messages = request_fields(messages, level=self.audiences[self._write_source(policy)], policy=policy,
|
|
618
|
+
context=context, keeps=getattr(store, "stores_fields", False) is True,
|
|
619
|
+
identity=self.identity, scope=self._scope(policy, tenant_id, policy.write))
|
|
620
|
+
except Refused as refused:
|
|
621
|
+
return error_reply(refused.status, refused.code, refused.text)
|
|
753
622
|
key = self._admit_tenant(policy, tenant_id)
|
|
754
623
|
if key is False:
|
|
755
624
|
return error_reply(503, "busy", "busy", "tenant-budget")
|
|
756
625
|
try:
|
|
757
|
-
store = tenant_store if policy.write == TENANT_STORE else self.stores[policy.write]
|
|
758
626
|
ctx = write_module.WriteContext(policy, tenant_id, self._redactor(policy), context)
|
|
759
627
|
return self._write(policy, store, messages, ctx)
|
|
760
628
|
finally:
|
|
@@ -831,6 +699,33 @@ class Gateway:
|
|
|
831
699
|
def _write_source(policy):
|
|
832
700
|
return policy.tenants if policy.write == TENANT_STORE else policy.write
|
|
833
701
|
|
|
702
|
+
@staticmethod
|
|
703
|
+
def _scope(policy, tenant_id, entry):
|
|
704
|
+
"""The scope of the stand-in codes for the store a policy entry names: the store's name, and for the
|
|
705
|
+
tenant's own store the provider's name, ":" and the tenant id."""
|
|
706
|
+
return "%s:%s" % (policy.tenants, tenant_id) if entry == TENANT_STORE else entry
|
|
707
|
+
|
|
708
|
+
def _asker(self, policy, tenant_id, body):
|
|
709
|
+
"""The resolved speaker of a recall or explain body (None when it names none), or a Reply to refuse
|
|
710
|
+
it. Only with an identity table: the body's "speaker" must be an account of a platform the client
|
|
711
|
+
lists, and a client with only_for must name one of those people. A speaker nobody listed is the
|
|
712
|
+
stand-in code for the store the client writes to, else the first it recalls from ("anon" when there
|
|
713
|
+
is none, or no key)."""
|
|
714
|
+
asked = body.get("speaker")
|
|
715
|
+
if asked is not None and not valid_account(asked):
|
|
716
|
+
return error_reply(400, "bad_speaker", "bad speaker")
|
|
717
|
+
if asked is not None and platform_of(asked) not in policy.platforms:
|
|
718
|
+
return error_reply(403, "forbidden", "forbidden")
|
|
719
|
+
person = None if asked is None else self.identity.resolve(asked)
|
|
720
|
+
if policy.only_for and (person is None or person not in policy.only_for):
|
|
721
|
+
return error_reply(403, "forbidden", "forbidden")
|
|
722
|
+
if asked is None or person is not None:
|
|
723
|
+
return person
|
|
724
|
+
entry = policy.write if policy.can_write else (policy.recall or (None,))[0]
|
|
725
|
+
if entry is None or not self.identity.has_key:
|
|
726
|
+
return "anon"
|
|
727
|
+
return self.identity.code(asked, self._scope(policy, tenant_id, entry))
|
|
728
|
+
|
|
834
729
|
def _pin_write(self, policy, store, tenant_id, receipt):
|
|
835
730
|
"""Pin what a pin_writes client just wrote. Returns a callback for the write watch
|
|
836
731
|
when the store cannot name the memories yet, else None. Never raises."""
|
|
@@ -856,7 +751,7 @@ class Gateway:
|
|
|
856
751
|
def sweep_targets(self):
|
|
857
752
|
"""{ledger key: store} of everything the forgetting task looks after: the managed shared
|
|
858
753
|
stores, and every tenant of each managed tenants provider that can list its tenants."""
|
|
859
|
-
targets = {}
|
|
754
|
+
targets: dict[Any, Any] = {}
|
|
860
755
|
if self.forgetting is None:
|
|
861
756
|
return targets
|
|
862
757
|
for name, store in self.stores.items():
|
|
@@ -866,7 +761,7 @@ class Gateway:
|
|
|
866
761
|
if not self.forgetting.manages(name) or not callable(getattr(provider, "list", None)):
|
|
867
762
|
continue
|
|
868
763
|
for tenant_id in provider.list():
|
|
869
|
-
store =
|
|
764
|
+
store = self.tenant_store(name, tenant_id)
|
|
870
765
|
if store is not None:
|
|
871
766
|
targets[self.forgetting.key(name, tenant_id)] = store
|
|
872
767
|
return targets
|
|
@@ -926,7 +821,8 @@ class Gateway:
|
|
|
926
821
|
"""(kind, piece) of every piece with a lifecycle, each object once, in start order."""
|
|
927
822
|
seen, out = set(), []
|
|
928
823
|
groups = (("store", self.stores.values()), ("tenants", self.tenants.values()),
|
|
929
|
-
("stage", self.stages), ("guard", self.guards)
|
|
824
|
+
("stage", self.stages), ("guard", self.guards),
|
|
825
|
+
("identity", [] if self.identity is None else [self.identity]))
|
|
930
826
|
for kind, pieces in groups:
|
|
931
827
|
for piece in pieces:
|
|
932
828
|
if id(piece) not in seen:
|