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
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Who is who: one table of people and their accounts, the same answer for every host that asks.
|
|
2
|
+
|
|
3
|
+
A host reports who is speaking as an account, `<platform>:<id>` (`aiocqhttp:10001`). An identity provider
|
|
4
|
+
turns an account into the name of a person the operator chose, or, for an account nobody listed, into a
|
|
5
|
+
stand-in code that is stable inside one store and means nothing outside it. The gateway resolves every
|
|
6
|
+
account before any guard or store sees it (gateway/fields.py), so a raw account is never stored or logged.
|
|
7
|
+
|
|
8
|
+
The built-in provider is `table`, configured by `[identity]` (docs/configuration.md). To write another one,
|
|
9
|
+
subclass IdentityProvider, register it as kind "identity" and name it in `type` (docs/extending.md).
|
|
10
|
+
|
|
11
|
+
Standard library only.
|
|
12
|
+
"""
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
|
|
16
|
+
from .errors import ConfigError
|
|
17
|
+
from .gateway.tokens import usable_token
|
|
18
|
+
from .model import PERSON, RESERVED_PEOPLE, valid_account
|
|
19
|
+
from .registry import register
|
|
20
|
+
|
|
21
|
+
CODE_PREFIX = "anon:"
|
|
22
|
+
CODE_CHARS = 16 # hex characters of the stand-in code: 64 bits
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class IdentityProvider:
|
|
26
|
+
"""The interface of an identity provider. Every method must be quick and must never raise for an
|
|
27
|
+
odd account (an unknown one resolves to None).
|
|
28
|
+
|
|
29
|
+
resolve(account) the person's name, or None when the account is in no one's list
|
|
30
|
+
owner the name of the owner
|
|
31
|
+
code(account, scope)
|
|
32
|
+
the stand-in for an account nobody listed: "anon:" and 16 hex characters. `scope` names
|
|
33
|
+
the store the record goes to, so the same account has another code in another store
|
|
34
|
+
people() {name: number of accounts}, never the accounts themselves (for `check`)
|
|
35
|
+
has_key True when a key for the codes is configured (never the key)
|
|
36
|
+
ready True when code() may be used: a key is there and strong enough
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def owner(self):
|
|
41
|
+
raise NotImplementedError
|
|
42
|
+
|
|
43
|
+
def resolve(self, account):
|
|
44
|
+
raise NotImplementedError
|
|
45
|
+
|
|
46
|
+
def code(self, account, scope):
|
|
47
|
+
raise NotImplementedError
|
|
48
|
+
|
|
49
|
+
def people(self):
|
|
50
|
+
raise NotImplementedError
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def has_key(self):
|
|
54
|
+
return True
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def ready(self):
|
|
58
|
+
return True
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _label(name, number):
|
|
62
|
+
"""How an error names one person of the table: by name when it is a plain name (never an account), else
|
|
63
|
+
by position."""
|
|
64
|
+
if isinstance(name, str) and PERSON.fullmatch(name) is not None:
|
|
65
|
+
return "identity.people.%s" % name
|
|
66
|
+
return "identity.people (person %d)" % number
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@register("identity", "table")
|
|
70
|
+
class TableIdentity(IdentityProvider):
|
|
71
|
+
"""A fixed table of people and their accounts from the configuration; stand-in codes are
|
|
72
|
+
HMAC-SHA256 of the store's name and the account under a key from the environment."""
|
|
73
|
+
|
|
74
|
+
def __init__(self, people=None, hash_key=None, **unknown):
|
|
75
|
+
if unknown:
|
|
76
|
+
raise ConfigError("identity: unknown setting %s (known: type, hash_key_env, people)"
|
|
77
|
+
% ", ".join(sorted(str(key) for key in unknown)))
|
|
78
|
+
if hash_key is not None and (not isinstance(hash_key, str) or not hash_key):
|
|
79
|
+
raise ConfigError("identity.hash_key_env must name an environment variable that holds the key")
|
|
80
|
+
self._key = hash_key
|
|
81
|
+
self._people = {} # name -> tuple of accounts
|
|
82
|
+
self._by_account = {}
|
|
83
|
+
self._owner = None
|
|
84
|
+
self._load(people)
|
|
85
|
+
|
|
86
|
+
def _load(self, people):
|
|
87
|
+
if not isinstance(people, dict) or not people:
|
|
88
|
+
raise ConfigError("identity.people must list the people: one table [identity.people.<name>] each, "
|
|
89
|
+
"one of them with owner = true")
|
|
90
|
+
owners = []
|
|
91
|
+
for number, (name, spec) in enumerate(people.items(), 1):
|
|
92
|
+
where = _label(name, number)
|
|
93
|
+
if not isinstance(name, str) or PERSON.fullmatch(name) is None:
|
|
94
|
+
raise ConfigError("identity.people (person %d): a name is lower-case letters, digits, _ and -, "
|
|
95
|
+
"starting with a letter or digit, at most 32 characters" % number)
|
|
96
|
+
if name in RESERVED_PEOPLE:
|
|
97
|
+
raise ConfigError("%s: the names %s are reserved" % (where, " and ".join(RESERVED_PEOPLE)))
|
|
98
|
+
if not isinstance(spec, dict):
|
|
99
|
+
raise ConfigError("[%s] must be a table" % where)
|
|
100
|
+
unknown = set(spec) - {"owner", "accounts"}
|
|
101
|
+
if unknown:
|
|
102
|
+
raise ConfigError("%s: unknown setting %s (known: owner, accounts)"
|
|
103
|
+
% (where, ", ".join(sorted(str(key) for key in unknown))))
|
|
104
|
+
if not isinstance(spec.get("owner", False), bool):
|
|
105
|
+
raise ConfigError("%s.owner must be true or false" % where)
|
|
106
|
+
accounts = spec.get("accounts", [])
|
|
107
|
+
if not isinstance(accounts, list):
|
|
108
|
+
raise ConfigError("%s.accounts must be a list of accounts, each <platform>:<id>" % where)
|
|
109
|
+
for index, account in enumerate(accounts, 1):
|
|
110
|
+
if not valid_account(account):
|
|
111
|
+
raise ConfigError("%s.accounts: entry %d is not an account of the form <platform>:<id> "
|
|
112
|
+
"(platform in lower case, no spaces, at most 64 characters in all)"
|
|
113
|
+
% (where, index))
|
|
114
|
+
if account in self._by_account:
|
|
115
|
+
other = self._by_account[account]
|
|
116
|
+
raise ConfigError("identity.people: an account is listed %s" % (
|
|
117
|
+
"twice for %s" % name if other == name else "for both %s and %s" % (other, name)))
|
|
118
|
+
self._by_account[account] = name
|
|
119
|
+
self._people[name] = tuple(accounts)
|
|
120
|
+
if spec.get("owner", False):
|
|
121
|
+
owners.append(name)
|
|
122
|
+
if len(owners) != 1:
|
|
123
|
+
raise ConfigError("identity.people: exactly one person must have owner = true (found %d)" % len(owners))
|
|
124
|
+
self._owner = owners[0]
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def owner(self):
|
|
128
|
+
return self._owner
|
|
129
|
+
|
|
130
|
+
def resolve(self, account):
|
|
131
|
+
try:
|
|
132
|
+
return self._by_account.get(account)
|
|
133
|
+
except TypeError: # an unhashable value is no account
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
def people(self):
|
|
137
|
+
return {name: len(accounts) for name, accounts in self._people.items()}
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def has_key(self):
|
|
141
|
+
return bool(self._key)
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def ready(self):
|
|
145
|
+
return bool(usable_token(self._key))
|
|
146
|
+
|
|
147
|
+
def code(self, account, scope):
|
|
148
|
+
if not self._key:
|
|
149
|
+
raise ValueError("no hash key is configured")
|
|
150
|
+
message = (scope + "\n" + account).encode("utf-8", "surrogateescape")
|
|
151
|
+
mac = hmac.new(self._key.encode("utf-8", "surrogateescape"), message, hashlib.sha256)
|
|
152
|
+
return CODE_PREFIX + mac.hexdigest()[:CODE_CHARS]
|
|
@@ -1,9 +1,140 @@
|
|
|
1
1
|
"""The small data shapes that pieces hand to each other. Standard library only."""
|
|
2
|
+
import collections.abc
|
|
3
|
+
import datetime
|
|
4
|
+
import re
|
|
5
|
+
import unicodedata
|
|
2
6
|
from dataclasses import dataclass, field
|
|
3
7
|
|
|
4
8
|
TENANT_STORE = "@tenant"
|
|
5
9
|
# How a tenant client's tenant is known: named in each request body, or carried by the token itself.
|
|
6
10
|
TENANT_BINDINGS = ("request", "token")
|
|
11
|
+
# Who may see a store's content or a client's output, narrowest first: the order is the width.
|
|
12
|
+
AUDIENCES = ("owner", "group", "public")
|
|
13
|
+
# The facts a memory may carry beside its text and date; each a short string, all optional.
|
|
14
|
+
FIELDS = ("speaker", "about", "channel", "audience", "origin", "event_date", "kind")
|
|
15
|
+
MAX_FIELD = 128 # characters in one field value
|
|
16
|
+
# Where a memory came from, as the host says it (a record of what was claimed, never a grant of anything),
|
|
17
|
+
# and what sort of fact it is. A request may carry these two, and the channel, event_date and audience.
|
|
18
|
+
ORIGINS = ("said", "tool", "curated", "derived")
|
|
19
|
+
KINDS = ("identity", "preference", "event", "plan", "entity")
|
|
20
|
+
DEFAULT_ORIGINS = ("said", "tool") # the origins a client may write unless its policy says otherwise
|
|
21
|
+
|
|
22
|
+
# Who is speaking, as a host reports it: an account "<platform>:<id>" (see identity.py). One definition, used by
|
|
23
|
+
# the request checks, the configuration and the identity table alike.
|
|
24
|
+
MAX_ACCOUNT_CHARS = 64
|
|
25
|
+
PLATFORM = re.compile(r"[a-z0-9][a-z0-9_.-]{0,31}")
|
|
26
|
+
PERSON = re.compile(r"[a-z0-9][a-z0-9_-]{0,31}") # a name the operator gives someone in the identity table
|
|
27
|
+
RESERVED_PEOPLE = ("self", "anon") # "self" speaks for the assistant, "anon" marks an account nobody listed
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def valid_platform(value):
|
|
31
|
+
"""True when `value` is a platform name: [a-z0-9][a-z0-9_.-]{0,31}."""
|
|
32
|
+
return isinstance(value, str) and PLATFORM.fullmatch(value) is not None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def valid_person(value):
|
|
36
|
+
"""True when `value` can name a person: [a-z0-9][a-z0-9_-]{0,31}, and is not reserved."""
|
|
37
|
+
return isinstance(value, str) and PERSON.fullmatch(value) is not None and value not in RESERVED_PEOPLE
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def valid_account(value):
|
|
41
|
+
"""True when `value` is an account: a platform, ":", then an id of at least one character without
|
|
42
|
+
whitespace or control characters; at most MAX_ACCOUNT_CHARS characters in all."""
|
|
43
|
+
if not isinstance(value, str) or len(value) > MAX_ACCOUNT_CHARS:
|
|
44
|
+
return False
|
|
45
|
+
platform, colon, ident = value.partition(":")
|
|
46
|
+
if not colon or not ident or PLATFORM.fullmatch(platform) is None:
|
|
47
|
+
return False
|
|
48
|
+
return not any(ch.isspace() or unicodedata.category(ch) == "Cc" for ch in ident)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def platform_of(account):
|
|
52
|
+
"""The platform part of an account (the text before the first ":")."""
|
|
53
|
+
return account.partition(":")[0]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# The optional keys of a message in a remember request that become record fields of the memory. One rule
|
|
57
|
+
# for each, used by the gateway (gateway.validate) and by the clients, so that they cannot disagree.
|
|
58
|
+
REQUEST_FIELDS = ("channel", "origin", "event_date", "kind", "audience")
|
|
59
|
+
_CHANNEL = re.compile(r"[a-z0-9][a-z0-9_.:-]{0,63}")
|
|
60
|
+
_DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def valid_channel(value):
|
|
64
|
+
"""True when `value` is a channel name: lower-case letters, digits and _ . : -, at most 64 characters."""
|
|
65
|
+
return isinstance(value, str) and _CHANNEL.fullmatch(value) is not None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def valid_event_date(value):
|
|
69
|
+
"""True when `value` is a real calendar date written YYYY-MM-DD and nothing else."""
|
|
70
|
+
if not isinstance(value, str) or _DATE.fullmatch(value) is None:
|
|
71
|
+
return False
|
|
72
|
+
try:
|
|
73
|
+
datetime.date.fromisoformat(value)
|
|
74
|
+
except ValueError:
|
|
75
|
+
return False
|
|
76
|
+
return True
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def valid_request_field(key, value):
|
|
80
|
+
"""True when `value` is a valid value of the request key `key` (one of REQUEST_FIELDS)."""
|
|
81
|
+
if key == "channel":
|
|
82
|
+
return valid_channel(value)
|
|
83
|
+
if key == "event_date":
|
|
84
|
+
return valid_event_date(value)
|
|
85
|
+
choices = {"origin": ORIGINS, "kind": KINDS, "audience": AUDIENCES}[key]
|
|
86
|
+
return isinstance(value, str) and value in choices
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
MAX_HISTORY = 6 # recent turns a recall request may carry
|
|
90
|
+
MAX_HISTORY_CHARS = 500 # characters in one turn
|
|
91
|
+
HISTORY_ROLES = ("user", "assistant")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def clean_history(value):
|
|
95
|
+
"""The "history" of a recall request as a new list of {"role", "content"} dicts, or None when it breaks the
|
|
96
|
+
rules. None (the key absent or null) is no history: []. Otherwise a list of at most MAX_HISTORY items, each an
|
|
97
|
+
object whose "role" is "user" or "assistant" and whose "content" is a string of 1 to MAX_HISTORY_CHARS
|
|
98
|
+
characters that is not blank; other keys of an item are dropped. One definition, used by the gateway and by
|
|
99
|
+
the clients, so that they cannot disagree."""
|
|
100
|
+
if value is None:
|
|
101
|
+
return []
|
|
102
|
+
if not isinstance(value, list) or len(value) > MAX_HISTORY:
|
|
103
|
+
return None
|
|
104
|
+
clean = []
|
|
105
|
+
for item in value:
|
|
106
|
+
if not isinstance(item, dict):
|
|
107
|
+
return None
|
|
108
|
+
role, content = item.get("role"), item.get("content")
|
|
109
|
+
if not isinstance(role, str) or role not in HISTORY_ROLES:
|
|
110
|
+
return None
|
|
111
|
+
if not isinstance(content, str) or not content.strip() or len(content) > MAX_HISTORY_CHARS:
|
|
112
|
+
return None
|
|
113
|
+
clean.append({"role": role, "content": content})
|
|
114
|
+
return clean
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def clean_fields(fields):
|
|
118
|
+
"""The fields of one memory as a new dict, or ValueError.
|
|
119
|
+
|
|
120
|
+
None or an empty mapping gives {}. Entries whose value is None are dropped. A key that is not in
|
|
121
|
+
FIELDS, or a value that is not a non-empty string of at most MAX_FIELD characters, raises ValueError
|
|
122
|
+
naming the key. Stores keep what they are given; what a value may be is the gateway's rule.
|
|
123
|
+
"""
|
|
124
|
+
if not fields:
|
|
125
|
+
return {}
|
|
126
|
+
if not isinstance(fields, collections.abc.Mapping):
|
|
127
|
+
raise ValueError("fields must be a mapping")
|
|
128
|
+
out = {}
|
|
129
|
+
for key, value in fields.items():
|
|
130
|
+
if key not in FIELDS:
|
|
131
|
+
raise ValueError("unknown field: %r" % (key,))
|
|
132
|
+
if value is None:
|
|
133
|
+
continue
|
|
134
|
+
if not isinstance(value, str) or not value or len(value) > MAX_FIELD:
|
|
135
|
+
raise ValueError("field %s must be a non-empty string of at most %d characters" % (key, MAX_FIELD))
|
|
136
|
+
out[key] = value
|
|
137
|
+
return out
|
|
7
138
|
|
|
8
139
|
|
|
9
140
|
@dataclass
|
|
@@ -15,18 +146,21 @@ class Hit:
|
|
|
15
146
|
returns it through read(); `date` is "YYYY-MM-DD" when the backend knows when the
|
|
16
147
|
memory is from; `meta` is anything the backend wants the recall stages to see
|
|
17
148
|
(where the memory came from, who said it). It is copied into Candidate.meta and
|
|
18
|
-
never returned to clients.
|
|
149
|
+
never returned to clients. `fields` holds the memory's recorded facts (see FIELDS), only the ones
|
|
150
|
+
that are set; {} for a memory without any and for a backend that keeps none.
|
|
19
151
|
"""
|
|
20
152
|
ref: str
|
|
21
153
|
score: float
|
|
22
154
|
text: str = ""
|
|
23
155
|
date: str | None = None
|
|
24
156
|
meta: dict = field(default_factory=dict)
|
|
157
|
+
fields: dict = field(default_factory=dict)
|
|
25
158
|
|
|
26
159
|
|
|
27
160
|
@dataclass
|
|
28
161
|
class Candidate:
|
|
29
|
-
"""A hit on its way through the recall stages. Stages may change score, text and meta.
|
|
162
|
+
"""A hit on its way through the recall stages. Stages may change score, text and meta.
|
|
163
|
+
`fields` is a copy of the hit's recorded facts (see FIELDS)."""
|
|
30
164
|
score: float
|
|
31
165
|
source: str
|
|
32
166
|
store: object
|
|
@@ -34,6 +168,7 @@ class Candidate:
|
|
|
34
168
|
text: str = ""
|
|
35
169
|
date: str | None = None
|
|
36
170
|
meta: dict = field(default_factory=dict)
|
|
171
|
+
fields: dict = field(default_factory=dict)
|
|
37
172
|
|
|
38
173
|
def as_item(self):
|
|
39
174
|
# "id" is the memory's ref in its store: opaque to clients, stable for one memory.
|
|
@@ -71,6 +206,23 @@ class ClientPolicy:
|
|
|
71
206
|
None means 10 x rate_limit. Only used for a tenant client: rotating tenant
|
|
72
207
|
ids cannot go around it.
|
|
73
208
|
pin_writes True when what this client writes is pinned: the forgetting curve never forgets it.
|
|
209
|
+
audience who sees what this client shows: "owner", "group" or "public" (see AUDIENCES). None
|
|
210
|
+
means "not declared": see reach. A client may only recall from stores at least as
|
|
211
|
+
wide as its audience.
|
|
212
|
+
explain True when this client may ask for an explained recall (POST /v1/explain): the
|
|
213
|
+
candidates a recall left out, with their scores and the step that removed them.
|
|
214
|
+
Off by default; only for owner-level clients.
|
|
215
|
+
origins the origins (see ORIGINS) a message this client writes may name; a message naming
|
|
216
|
+
another one is refused (403). Default ("said", "tool"). An origin is a record of what the
|
|
217
|
+
host says, nothing more: nothing is granted because of it.
|
|
218
|
+
fields the record fields (see FIELDS) added to every item this client recalls, "fields": {...},
|
|
219
|
+
for the ones the memory has. Empty by default: items carry no fields. A client whose
|
|
220
|
+
audience is not "owner" may not list "speaker" or "about".
|
|
221
|
+
platforms the platforms (the part of an account before ":") whose accounts this client may name as the
|
|
222
|
+
speaker or subject of a message, or as the speaker of a recall. Empty by default: it can name
|
|
223
|
+
none. Needs an identity table (see identity.py).
|
|
224
|
+
only_for names of people in the identity table: when set, every request this client makes is on behalf
|
|
225
|
+
of one of them (every user message, every recall names a speaker who is one of them).
|
|
74
226
|
"""
|
|
75
227
|
name: str
|
|
76
228
|
recall: tuple | None = None
|
|
@@ -84,6 +236,22 @@ class ClientPolicy:
|
|
|
84
236
|
rate_limit_total: int | None = None
|
|
85
237
|
tenant_binding: str = "request"
|
|
86
238
|
tenant_token_generation: int = 1
|
|
239
|
+
audience: str | None = None
|
|
240
|
+
explain: bool = False
|
|
241
|
+
origins: tuple = DEFAULT_ORIGINS
|
|
242
|
+
fields: tuple = ()
|
|
243
|
+
platforms: tuple = ()
|
|
244
|
+
only_for: tuple = ()
|
|
245
|
+
|
|
246
|
+
@property
|
|
247
|
+
def reach(self):
|
|
248
|
+
"""The resolved audience: the declared one, else owner for a private client, group for a
|
|
249
|
+
public tenant client and public for any other public client."""
|
|
250
|
+
if self.audience is not None:
|
|
251
|
+
return self.audience
|
|
252
|
+
if not self.public:
|
|
253
|
+
return "owner"
|
|
254
|
+
return "group" if self.tenants is not None else "public"
|
|
87
255
|
|
|
88
256
|
@property
|
|
89
257
|
def token_bound(self):
|
|
@@ -15,12 +15,13 @@ Standard library only.
|
|
|
15
15
|
import importlib
|
|
16
16
|
import threading
|
|
17
17
|
from importlib import metadata
|
|
18
|
+
from typing import Any
|
|
18
19
|
|
|
19
20
|
from .errors import ConfigError
|
|
20
21
|
|
|
21
|
-
KINDS = ("backend", "recall_stage", "write_guard", "redactor", "tenants", "forgetting_curve")
|
|
22
|
+
KINDS = ("backend", "recall_stage", "write_guard", "redactor", "tenants", "forgetting_curve", "identity")
|
|
22
23
|
|
|
23
|
-
_pieces = {kind: {} for kind in KINDS}
|
|
24
|
+
_pieces: dict[str, dict[str, Any]] = {kind: {} for kind in KINDS}
|
|
24
25
|
_lock = threading.Lock()
|
|
25
26
|
_builtins_loaded = False
|
|
26
27
|
|
|
@@ -96,7 +97,8 @@ def resolve(kind, name):
|
|
|
96
97
|
if factory is None:
|
|
97
98
|
factory = _from_entry_point(kind, name)
|
|
98
99
|
if factory is None:
|
|
99
|
-
raise ConfigError("no %s piece named %r (known: %s)"
|
|
100
|
+
raise ConfigError("no %s piece named %r (known: %s)"
|
|
101
|
+
% (kind, name, ", ".join(sorted(available(kind))) or "none"))
|
|
100
102
|
return factory
|
|
101
103
|
|
|
102
104
|
|
|
@@ -120,6 +122,7 @@ def create(kind, spec, **extra):
|
|
|
120
122
|
except TypeError as error:
|
|
121
123
|
# A wrong or missing option. The message names options, never their values.
|
|
122
124
|
raise ConfigError("%s %r: %s" % (kind, name, error)) from None
|
|
125
|
+
assert isinstance(name, str) # resolve() refused anything else above
|
|
123
126
|
if kind in NAMED_KINDS and ":" not in name:
|
|
124
127
|
_name(piece, name)
|
|
125
128
|
return piece
|
|
@@ -35,9 +35,10 @@ class CryptoMissing(RuntimeError):
|
|
|
35
35
|
|
|
36
36
|
def _aesgcm(key):
|
|
37
37
|
try:
|
|
38
|
-
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
38
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM # type: ignore[import-not-found] # optional extra
|
|
39
39
|
except ImportError:
|
|
40
|
-
raise CryptoMissing("主机 Python 缺少 cryptography 库,装好再备份:
|
|
40
|
+
raise CryptoMissing("主机 Python 缺少 cryptography 库,装好再备份:"
|
|
41
|
+
"python -m pip install cryptography") from None
|
|
41
42
|
if len(key) != KEY_LEN:
|
|
42
43
|
raise KeyFileError(f"密钥长度不对,应该是 {KEY_LEN} 个字节")
|
|
43
44
|
return AESGCM(key)
|
|
@@ -126,7 +127,7 @@ def can_open(blob, key):
|
|
|
126
127
|
aead = _aesgcm(key)
|
|
127
128
|
try:
|
|
128
129
|
aead.decrypt(blob[len(MAGIC):len(MAGIC) + NONCE_LEN], blob[len(MAGIC) + NONCE_LEN:], MAGIC)
|
|
129
|
-
except Exception:
|
|
130
|
+
except Exception: # noqa: BLE001 - any failure to authenticate means the key does not open the blob
|
|
130
131
|
return False
|
|
131
132
|
return True
|
|
132
133
|
|
|
@@ -183,7 +184,7 @@ def decrypt_to(blob, key, out_dir):
|
|
|
183
184
|
nonce = blob[len(MAGIC):len(MAGIC) + NONCE_LEN]
|
|
184
185
|
try:
|
|
185
186
|
data = aead.decrypt(nonce, blob[len(MAGIC) + NONCE_LEN:], MAGIC)
|
|
186
|
-
except Exception:
|
|
187
|
+
except Exception: # noqa: BLE001 - wrong key or a changed blob; no detail is passed on
|
|
187
188
|
raise DecryptError("密钥不对,或者加密包被改过") from None
|
|
188
189
|
# Anything the zip reader can raise on an authenticated but odd archive is a decrypt error, not a crash.
|
|
189
190
|
zip_errors = (zipfile.BadZipFile, zlib.error, NotImplementedError, EOFError, ValueError, RuntimeError)
|
|
@@ -111,7 +111,8 @@ def run_eval(backend, memories, queries, *, thresholds=THRESHOLDS, limits=LIMITS
|
|
|
111
111
|
if seed:
|
|
112
112
|
put = getattr(backend, "put", None)
|
|
113
113
|
if put is None:
|
|
114
|
-
raise ValueError("这个存储没有 put()
|
|
114
|
+
raise ValueError("这个存储没有 put(),没法写入示例记忆:"
|
|
115
|
+
"请先把示例记忆放进去,再用 seed=False(命令行 --no-seed)评测")
|
|
115
116
|
for ref, text in memories.items():
|
|
116
117
|
put(text, ref=ref)
|
|
117
118
|
out(f"已写入 {len(memories)} 条假记忆。")
|
|
@@ -140,6 +140,8 @@ def mint_token(cfg, client, tenant_id, env=None):
|
|
|
140
140
|
provider_spec = tenants.get(policy.tenants) if isinstance(tenants, dict) else None
|
|
141
141
|
if not isinstance(provider_spec, dict):
|
|
142
142
|
raise ValueError("客户端 %s 的租户提供方 %s 没有配置" % (client, policy.tenants))
|
|
143
|
+
# the audience is not the provider's
|
|
144
|
+
provider_spec, _ = config._split_audience("tenants", policy.tenants, provider_spec)
|
|
143
145
|
provider = registry.create("tenants", config.resolve_env(provider_spec, env, "tenants." + policy.tenants))
|
|
144
146
|
try:
|
|
145
147
|
valid = isinstance(tenant_id, str) and bool(provider.valid_id(tenant_id))
|
package/src/block.js
CHANGED
|
@@ -99,11 +99,14 @@ export function ageText(date, today, lang = 'zh') {
|
|
|
99
99
|
* labels { source name: label }; sources without one get defaultLabel
|
|
100
100
|
* defaultLabel label for an unknown source ('记忆' / 'memory')
|
|
101
101
|
* head the sentence after the opening tag
|
|
102
|
+
* noHead true: no opening sentence at all (`head` is ignored); the block then holds only the
|
|
103
|
+
* "today is ..." sentence, when there is one, the items and the "more" line. Not the same
|
|
104
|
+
* as head '', which is an empty line (as in the gateway's Python formatter).
|
|
102
105
|
* moreTemplate the "more" line, with one %d
|
|
103
106
|
* Throws on an unknown lang or a tag that is not a plain name: a wrong option is a bug in the
|
|
104
107
|
* caller, found at start-up and not in the middle of a chat.
|
|
105
108
|
*/
|
|
106
|
-
export function createFormatter({ lang = 'zh', tag = 'memory_data', labels = {}, defaultLabel, head, moreTemplate } = {}) {
|
|
109
|
+
export function createFormatter({ lang = 'zh', tag = 'memory_data', labels = {}, defaultLabel, head, noHead = false, moreTemplate } = {}) {
|
|
107
110
|
if (typeof lang !== 'string' || !Object.hasOwn(DEFAULTS, lang)) {
|
|
108
111
|
throw new RangeError('lang must be one of: ' + Object.keys(DEFAULTS).sort().join(', '))
|
|
109
112
|
}
|
|
@@ -113,6 +116,7 @@ export function createFormatter({ lang = 'zh', tag = 'memory_data', labels = {},
|
|
|
113
116
|
const d = DEFAULTS[lang]
|
|
114
117
|
const labelMap = new Map(Object.entries(labels ?? {}))
|
|
115
118
|
const fallbackLabel = defaultLabel ?? d.label
|
|
119
|
+
const headless = noHead === true
|
|
116
120
|
const headLine = head ?? d.head
|
|
117
121
|
const moreLine = moreTemplate ?? d.more
|
|
118
122
|
// Any opening or closing form of the tag, with case and whitespace variants. The leading "<"
|
|
@@ -160,8 +164,10 @@ export function createFormatter({ lang = 'zh', tag = 'memory_data', labels = {},
|
|
|
160
164
|
}
|
|
161
165
|
if (!lines.length) return ''
|
|
162
166
|
if (Number.isInteger(more) && more > 0) lines.push(fillMore(moreLine, more))
|
|
163
|
-
const
|
|
164
|
-
|
|
167
|
+
const dateSentence = now === null ? '' : d.today.replace('%s', () => now)
|
|
168
|
+
// Without a head there is no gap and no empty line: the first line is the date sentence or the first item.
|
|
169
|
+
const intro = headless ? dateSentence : now === null ? headLine : headLine + d.headGap + dateSentence
|
|
170
|
+
return [`<${tag}>`, ...(headless && !intro ? [] : [intro]), ...lines, `</${tag}>`].join('\n')
|
|
165
171
|
}
|
|
166
172
|
|
|
167
173
|
/**
|
package/src/capture.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Automatic capture (modules.autoCapture): what the user types during a turn is kept in a list per
|
|
2
|
+
// session and, when the turn ends, sent to the gateway in batches within its limits. Only the user's
|
|
3
|
+
// own messages (never injected context, goal rounds or recall blocks), and only those worth a lookup.
|
|
4
|
+
// Fire and forget: a failure never reaches the turn. Logs name kinds of failure only, never a message.
|
|
5
|
+
import { buildQuery, codePointLength, meaningful, pyStrip } from './query.js'
|
|
6
|
+
import { isObject, isSubagent, isUserOrigin, kindOf, MAX_REMEMBER_CHARS, REQUEST_CONTEXT, speakerAccount, textOf } from './shared.js'
|
|
7
|
+
import { localTime } from './time.js'
|
|
8
|
+
|
|
9
|
+
const MAX_BATCH_MESSAGES = 20 // gateway limits of one /v1/remember
|
|
10
|
+
const MAX_BATCH_CHARS = 16000
|
|
11
|
+
|
|
12
|
+
/** Split messages into batches within the gateway's limits. A message over the per-message limit is
|
|
13
|
+
* left out, never cut. */
|
|
14
|
+
export function captureBatches(messages) {
|
|
15
|
+
const batches = []
|
|
16
|
+
let batch = []
|
|
17
|
+
let total = 0
|
|
18
|
+
for (const m of messages) {
|
|
19
|
+
const length = codePointLength(m.content)
|
|
20
|
+
if (length > MAX_REMEMBER_CHARS) continue
|
|
21
|
+
if (batch.length && (batch.length >= MAX_BATCH_MESSAGES || total + length > MAX_BATCH_CHARS)) {
|
|
22
|
+
batches.push(batch)
|
|
23
|
+
batch = []
|
|
24
|
+
total = 0
|
|
25
|
+
}
|
|
26
|
+
batch.push(m)
|
|
27
|
+
total += length
|
|
28
|
+
}
|
|
29
|
+
if (batch.length) batches.push(batch)
|
|
30
|
+
return batches
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} deps
|
|
35
|
+
* @param {Function} deps.client client(limit): a gateway client, or null while memory is unavailable
|
|
36
|
+
* @param {Function} deps.settings the current settings
|
|
37
|
+
* @param {Function} deps.formatter formatter(lang): the block formatter (its strip() removes recall blocks)
|
|
38
|
+
* @param {Function} deps.clock the clock: a Date, milliseconds or null
|
|
39
|
+
* @param {object} deps.log { warn, info }
|
|
40
|
+
* @returns {{ onSessionEvent: Function, onSessionDisposed: Function, clear: Function }}
|
|
41
|
+
*/
|
|
42
|
+
export function createCapture({ client, settings, formatter, clock, log }) {
|
|
43
|
+
const captured = new Map() // session id -> user messages of the running turn
|
|
44
|
+
|
|
45
|
+
function sendCaptured(messages) {
|
|
46
|
+
const c = client()
|
|
47
|
+
if (!c) {
|
|
48
|
+
log.warn('feiyu-memgate: capture skipped (memory unavailable)')
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
const speaker = speakerAccount(settings().advanced)
|
|
52
|
+
for (const batch of captureBatches(messages)) {
|
|
53
|
+
// Fire and forget: the turn is over and nothing waits for this.
|
|
54
|
+
Promise.resolve()
|
|
55
|
+
.then(() => c.rememberMessages(batch.map((m) => ({ ...m, speaker, origin: 'said' })), { context: REQUEST_CONTEXT.capture }))
|
|
56
|
+
.catch((error) => log.warn(`feiyu-memgate: capture failed (${kindOf(error)})`))
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// A message is kept out of automatic capture when it is not worth a lookup either (a command, only
|
|
61
|
+
// filler: buildQuery says so), or when it has fewer meaningful characters than advanced.captureMinChars
|
|
62
|
+
// (0 turns the length test off).
|
|
63
|
+
function worthCapturing(content) {
|
|
64
|
+
if (buildQuery(content, null) === null) return false
|
|
65
|
+
const min = settings().advanced.captureMinChars
|
|
66
|
+
return min === 0 || codePointLength(meaningful(content)) >= min
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function onSessionEvent(session, event) {
|
|
70
|
+
try {
|
|
71
|
+
if (!isObject(event) || isSubagent(session?.header)) return
|
|
72
|
+
const id = session?.id ?? session?.header?.id
|
|
73
|
+
if (id === undefined) return
|
|
74
|
+
if (event.type === 'user/message') {
|
|
75
|
+
// Only what the user typed: injected context, goal rounds and recall blocks have other sources.
|
|
76
|
+
if (!isUserOrigin(event.data)) return
|
|
77
|
+
const content = pyStrip(formatter().strip(textOf(event.data)))
|
|
78
|
+
if (!content || !worthCapturing(content)) return
|
|
79
|
+
const list = captured.get(id) ?? []
|
|
80
|
+
const time = localTime(clock())
|
|
81
|
+
list.push(time ? { role: 'user', content, time } : { role: 'user', content })
|
|
82
|
+
captured.set(id, list)
|
|
83
|
+
} else if (event.type === 'turn/end') {
|
|
84
|
+
const list = captured.get(id)
|
|
85
|
+
captured.delete(id)
|
|
86
|
+
if (list?.length) sendCaptured(list)
|
|
87
|
+
}
|
|
88
|
+
} catch (error) {
|
|
89
|
+
log.warn(`feiyu-memgate: capture skipped (${kindOf(error)})`)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function onSessionDisposed(session) {
|
|
94
|
+
captured.delete(session?.id ?? session?.header?.id)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return { onSessionEvent, onSessionDisposed, clear: () => captured.clear() }
|
|
98
|
+
}
|
package/src/catalogue.js
CHANGED
|
@@ -108,19 +108,19 @@ export const CATALOGUE = deepFreeze([
|
|
|
108
108
|
export const TIER_NOTES = deepFreeze({
|
|
109
109
|
lightest: {
|
|
110
110
|
en: 'Smallest download, Chinese only: recall by meaning instead of shared words, at the lowest cost.',
|
|
111
|
-
zh: '
|
|
111
|
+
zh: '下载最小,仅支持中文:使用语义检索而非关键词检索,开销最低。',
|
|
112
112
|
},
|
|
113
113
|
light: {
|
|
114
114
|
en: 'Chinese only, a larger model than the lightest tier for steadier Chinese recall.',
|
|
115
|
-
zh: '
|
|
115
|
+
zh: '仅支持中文,模型比最轻档更大,中文召回更稳定。',
|
|
116
116
|
},
|
|
117
117
|
'upper-middle': {
|
|
118
118
|
en: 'Multilingual with long inputs: a balance of size and quality for mixed Chinese and English memories.',
|
|
119
|
-
zh: '
|
|
119
|
+
zh: '支持多语言和长文本:兼顾体积与效果,适合中英文混合的记忆。',
|
|
120
120
|
},
|
|
121
121
|
top: {
|
|
122
122
|
en: 'Multilingual with long inputs: the largest download and the strongest recall of the list.',
|
|
123
|
-
zh: '
|
|
123
|
+
zh: '支持多语言和长文本:下载最大,召回效果为列表中最好。',
|
|
124
124
|
},
|
|
125
125
|
})
|
|
126
126
|
|