Deploy AIOS web (React glide grid + FastAPI slice)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- RELEASES.json +1 -1
- VERSION +1 -1
- api/agent_directory.py +288 -0
- api/agent_inbox.py +682 -0
- api/agent_runtime.py +577 -27
- api/agent_tools.py +49 -0
- api/amazon_relational.py +7 -3
- api/application_registry.py +434 -42
- api/artifact_share.py +257 -0
- api/artifact_snapshot.py +466 -0
- api/assistant_artifacts.py +151 -2
- api/assistant_feed.py +71 -5
- api/assistant_files.py +62 -16
- api/assistant_log.py +101 -32
- api/assistant_memory.py +72 -20
- api/assistant_open_items.py +2 -1
- api/assistant_write_preview.py +198 -0
- api/deps.py +33 -62
- api/external_activity.py +6 -2
- api/external_openapi.py +2 -0
- api/loopy_file_tools.py +239 -6
- api/loopy_image.py +272 -0
- api/loopy_links.py +54 -0
- api/loopy_skill_tools.py +109 -1
- api/loopy_skills.py +108 -2
- api/loopy_tool_store.py +351 -0
- api/loopy_xlsx.py +141 -0
- api/main.py +2 -0
- api/meta_relational.py +1 -1
- api/model_router.py +2 -88
- api/odoo_purchasing.py +132 -4
- api/odoo_relational.py +691 -16
- api/provider_limits.py +2 -1
- api/providers.py +18 -11
- api/routes_admin.py +149 -0
- api/routes_applications.py +3 -3
- api/routes_assets.py +43 -24
- api/routes_assistant_memory.py +21 -4
- api/routes_connectors.py +53 -1
- api/routes_customers.py +10 -5
- api/routes_external.py +5 -4
- api/routes_files.py +3 -2
- api/routes_module_index.py +1 -6
- api/routes_nav.py +85 -0
- api/routes_odoo_tables.py +2 -0
- api/routes_products.py +9 -6
- api/routes_query.py +491 -94
- api/routes_shared_artifact.py +299 -0
- api/routes_shares.py +36 -0
- api/routes_sheet.py +55 -0
RELEASES.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
{
|
| 2 |
-
"current": "
|
| 3 |
"releases": []
|
| 4 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"current": "63d6a0ce4",
|
| 3 |
"releases": []
|
| 4 |
}
|
VERSION
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
63d6a0ce4
|
api/agent_directory.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The workspace directory tool: the people of the caller's own workspace and their access.
|
| 2 |
+
|
| 3 |
+
R84: the list never crosses tenants. `users._tenant_accounts` is the one tenant wall.
|
| 4 |
+
R92: each entry carries role, modules, databases, row limits and hidden fields.
|
| 5 |
+
R108(c): a field or database the CALLER cannot see is never named.
|
| 6 |
+
Every entry is a whitelist projection: no password hash, salt, MFA secret, recovery code,
|
| 7 |
+
session epoch, phone, email or avatar leaves this module.
|
| 8 |
+
"""
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
from core import perm_scope, perms, users
|
| 12 |
+
|
| 13 |
+
_LOG = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
HIDDEN_FIELD = "a hidden field"
|
| 16 |
+
LIMITED = "Limited by your access"
|
| 17 |
+
REFUSAL = "The directory of your workspace could not be read. Try again in a moment."
|
| 18 |
+
NOT_FOUND = "No one by that name uses Loopable in your workspace."
|
| 19 |
+
|
| 20 |
+
# Shell.tsx opens these workspace modules for every signed-in account.
|
| 21 |
+
_WORKSPACE_MODULES = ("Sheet", "Data", "App")
|
| 22 |
+
|
| 23 |
+
_OPS = {
|
| 24 |
+
"eq": "is", "neq": "is not", "contains": "contains", "doesNotContain": "does not contain",
|
| 25 |
+
"gt": "is more than", "gte": "is at least", "lt": "is less than", "lte": "is at most",
|
| 26 |
+
"within": "is within", "isAnyOf": "is one of", "isNoneOf": "is none of",
|
| 27 |
+
"hasAnyOf": "has any of", "hasAllOf": "has all of", "hasNoneOf": "has none of",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
SCHEMA = {
|
| 31 |
+
"type": "object",
|
| 32 |
+
"description": ("List the people of your own workspace, with each person's role, what they "
|
| 33 |
+
"can open, their row limits and hidden fields."),
|
| 34 |
+
"properties": {"username": {"type": "string"}},
|
| 35 |
+
"additionalProperties": False,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
_ADMITTED = {"who uses loopable here", "who uses loopable", "who uses loopable in my workspace",
|
| 40 |
+
"who is in my workspace", "who are the people in my workspace"}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def admits(question):
|
| 44 |
+
"""True for a directory question, so the router can skip its database match."""
|
| 45 |
+
import re
|
| 46 |
+
return " ".join(re.findall(r"\w+", str(question).casefold())) in _ADMITTED
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class DirectoryUnavailable(ValueError):
|
| 50 |
+
"""The registry or the caller's own account could not be read. Fail closed."""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _tenant(session):
|
| 54 |
+
want = str(getattr(session, "tenant", "") or "").strip().lower()
|
| 55 |
+
own = str((getattr(session, "user", None) or {}).get("tenant") or "").strip().lower()
|
| 56 |
+
if not want or (own and own != want):
|
| 57 |
+
raise DirectoryUnavailable(REFUSAL)
|
| 58 |
+
return want
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _accounts(session):
|
| 62 |
+
"""`[(username, record)]` of the caller's tenant. Refuses when the caller is not among them."""
|
| 63 |
+
tenant = _tenant(session)
|
| 64 |
+
accounts = users._tenant_accounts(tenant)
|
| 65 |
+
me = str(getattr(session, "uname", "") or "").strip().lower()
|
| 66 |
+
if not me or me not in {str(n).strip().lower() for n, _ in accounts}:
|
| 67 |
+
# An empty list is a failed read or a revoked caller. Never an answer.
|
| 68 |
+
raise DirectoryUnavailable(REFUSAL)
|
| 69 |
+
return sorted(accounts, key=lambda pair: str(pair[0]).lower())
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _lend(session):
|
| 73 |
+
from core import user_tables
|
| 74 |
+
return user_tables.lend_defs(session.runtime)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _databases(session, st):
|
| 78 |
+
"""`[{key, label}]`: every database this tenant governs, topics and its own `ut_*` tables."""
|
| 79 |
+
from core import registry, user_tables
|
| 80 |
+
ut = user_tables.nav_entries(viewer=session.uname, is_admin=True, st=st)
|
| 81 |
+
topics = list(registry.governable_modules().values())
|
| 82 |
+
return perms.tenant_governable_modules(session.runtime, topics, ut_entries=ut)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _modules(session):
|
| 86 |
+
"""`[{key, label}]`: the app surfaces this tenant is provisioned for."""
|
| 87 |
+
return [m for m in perms.governable_surface_modules()
|
| 88 |
+
if perms.tenant_has_module(session.runtime, m["key"])]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _fields(principal, key, st):
|
| 92 |
+
"""`{field_key: label}` this principal may see on `key`, or None when unreadable."""
|
| 93 |
+
try:
|
| 94 |
+
rows = perm_scope.scoped_fields(principal, key, st=st)
|
| 95 |
+
except Exception: # noqa: BLE001
|
| 96 |
+
return None
|
| 97 |
+
return {str(f["key"]): str(f.get("label") or f["key"])
|
| 98 |
+
for f in rows or () if isinstance(f, dict) and f.get("key")}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _name_field(seen, key):
|
| 102 |
+
"""The label of `key` when the caller can see it, else the hidden placeholder."""
|
| 103 |
+
return (seen or {}).get(str(key)) or HIDDEN_FIELD
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _value(leaf):
|
| 107 |
+
if isinstance(leaf.get("values"), list):
|
| 108 |
+
return ", ".join(str(v) for v in leaf["values"])
|
| 109 |
+
if leaf.get("op") == "between":
|
| 110 |
+
return f"{leaf.get('value')} and {leaf.get('value2')}"
|
| 111 |
+
return str(leaf.get("value") if leaf.get("value") is not None else "")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _leaf_sentence(leaf, seen):
|
| 115 |
+
"""One plain sentence for a filter leaf, or None when it names a field the caller cannot see."""
|
| 116 |
+
col = str(leaf.get("colId") or "")
|
| 117 |
+
if col not in (seen or {}):
|
| 118 |
+
return None
|
| 119 |
+
rhs = leaf.get("rhs")
|
| 120 |
+
if isinstance(rhs, dict):
|
| 121 |
+
if str(rhs.get("colId") or "") not in seen:
|
| 122 |
+
return None
|
| 123 |
+
target = seen[str(rhs["colId"])]
|
| 124 |
+
else:
|
| 125 |
+
target = _value(leaf)
|
| 126 |
+
op = str(leaf.get("op") or "")
|
| 127 |
+
label = seen[col]
|
| 128 |
+
if op == "isEmpty":
|
| 129 |
+
return f"{label} is empty"
|
| 130 |
+
if op == "isNotEmpty":
|
| 131 |
+
return f"{label} is not empty"
|
| 132 |
+
if op == "between":
|
| 133 |
+
return f"{label} is between {target}"
|
| 134 |
+
if op in _OPS:
|
| 135 |
+
return f"{label} {_OPS[op]} {target}".rstrip()
|
| 136 |
+
return f"{label} has a ranking condition"
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _node_sentence(node, seen):
|
| 140 |
+
if not isinstance(node, dict):
|
| 141 |
+
return None
|
| 142 |
+
if isinstance(node.get("children"), list):
|
| 143 |
+
parts = [_node_sentence(child, seen) for child in node["children"]]
|
| 144 |
+
if not parts or any(p is None for p in parts):
|
| 145 |
+
return None
|
| 146 |
+
joiner = " or " if node.get("conj") == "or" else " and "
|
| 147 |
+
return "(" + joiner.join(parts) + ")" if len(parts) > 1 else parts[0]
|
| 148 |
+
return _leaf_sentence(node, seen)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _filter_sentences(tree, seen, label):
|
| 152 |
+
"""Plain sentences for one stored filter tree. A leaf the caller cannot see reads LIMITED."""
|
| 153 |
+
if isinstance(tree, dict):
|
| 154 |
+
nodes = tree.get("nodes") if isinstance(tree.get("nodes"), list) else []
|
| 155 |
+
conj = "or" if tree.get("conj") == "or" else "and"
|
| 156 |
+
else:
|
| 157 |
+
nodes, conj = (tree if isinstance(tree, list) else []), "and"
|
| 158 |
+
parts = [_node_sentence(n, seen) for n in nodes]
|
| 159 |
+
if not parts:
|
| 160 |
+
return []
|
| 161 |
+
prefix = f"{label}: " if label else ""
|
| 162 |
+
if conj == "or":
|
| 163 |
+
if any(p is None for p in parts):
|
| 164 |
+
return [LIMITED]
|
| 165 |
+
return [prefix + " or ".join(parts)]
|
| 166 |
+
return [LIMITED if p is None else prefix + p for p in parts]
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _legacy_limits(rec):
|
| 170 |
+
out = []
|
| 171 |
+
labels = users.allowed_bus_labels(rec)
|
| 172 |
+
if "All" not in labels and labels:
|
| 173 |
+
out.append("Business unit is " + " or ".join(labels))
|
| 174 |
+
agent = perms.scope_agent(rec)
|
| 175 |
+
if agent:
|
| 176 |
+
out.append(f"Sales agent is {agent}")
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _entry(session, uname, rec, ctx):
|
| 181 |
+
"""The whitelist projection of one colleague, as the caller is allowed to see it."""
|
| 182 |
+
principal = users._public(uname, rec)
|
| 183 |
+
st, caller = ctx["st"], session.user
|
| 184 |
+
admin = perms.is_admin(principal)
|
| 185 |
+
modules = list(_WORKSPACE_MODULES) + [m["label"] for m in ctx["modules"]
|
| 186 |
+
if admin or perm_scope.nav_may_open(principal, m["key"], st=st)]
|
| 187 |
+
named, unnamed, limits, hidden = [], 0, [], []
|
| 188 |
+
for db in ctx["databases"]:
|
| 189 |
+
key = db["key"]
|
| 190 |
+
if not (admin or perm_scope.may_read(principal, key, st=st)):
|
| 191 |
+
continue
|
| 192 |
+
seen = ctx["seen"].get(key)
|
| 193 |
+
if seen is None:
|
| 194 |
+
# The caller cannot read this database: never name it, count it.
|
| 195 |
+
unnamed += 1
|
| 196 |
+
seen = {}
|
| 197 |
+
else:
|
| 198 |
+
named.append(db["label"])
|
| 199 |
+
if admin:
|
| 200 |
+
continue
|
| 201 |
+
stored = perm_scope.entry(principal, key) or {}
|
| 202 |
+
if perm_scope.is_migrated(principal) and stored.get("filter"):
|
| 203 |
+
limits.extend(_filter_sentences(stored["filter"], seen,
|
| 204 |
+
db["label"] if key in ctx["seen"] else ""))
|
| 205 |
+
theirs = _fields(principal, key, st)
|
| 206 |
+
keys = [str(k) for k in (stored.get("hiddenFields") or ()) if k]
|
| 207 |
+
if theirs is not None:
|
| 208 |
+
keys += [k for k in seen if k not in theirs and k not in keys]
|
| 209 |
+
hidden.extend(_name_field(seen, k) for k in keys)
|
| 210 |
+
if unnamed:
|
| 211 |
+
named.append(f"{unnamed} database{'' if unnamed == 1 else 's'} you cannot open")
|
| 212 |
+
if not admin and not perm_scope.is_migrated(principal):
|
| 213 |
+
limits = _legacy_limits(rec) + limits
|
| 214 |
+
return {"username": str(rec.get("username_original") or uname),
|
| 215 |
+
"name": str(rec.get("name") or uname),
|
| 216 |
+
"role": "Administrator" if admin else "Member",
|
| 217 |
+
"modules": modules, "databases": named,
|
| 218 |
+
"rowLimits": limits, "hiddenFields": hidden}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _context(session):
|
| 222 |
+
st = _lend(session)
|
| 223 |
+
databases = [d for d in _databases(session, st) if isinstance(d, dict) and d.get("key")]
|
| 224 |
+
caller = session.user
|
| 225 |
+
seen = {}
|
| 226 |
+
for db in databases:
|
| 227 |
+
if perm_scope.may_read(caller, db["key"], st=st):
|
| 228 |
+
seen[db["key"]] = _fields(caller, db["key"], st) or {}
|
| 229 |
+
return {"st": st, "databases": databases, "modules": _modules(session), "seen": seen}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def people(session):
|
| 233 |
+
"""Every active account of the caller's own workspace. Raises DirectoryUnavailable."""
|
| 234 |
+
try:
|
| 235 |
+
accounts = _accounts(session)
|
| 236 |
+
ctx = _context(session)
|
| 237 |
+
return [_entry(session, n, rec, ctx) for n, rec in accounts]
|
| 238 |
+
except DirectoryUnavailable:
|
| 239 |
+
raise
|
| 240 |
+
except Exception as exc: # noqa: BLE001
|
| 241 |
+
_LOG.warning("Workspace directory read failed (%s)", type(exc).__name__)
|
| 242 |
+
raise DirectoryUnavailable(REFUSAL) from exc
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _colleague(session, username):
|
| 246 |
+
"""One same-tenant account, or None when nobody matches. Raises DirectoryUnavailable."""
|
| 247 |
+
want = str(username or "").strip().casefold()
|
| 248 |
+
if not want:
|
| 249 |
+
return None
|
| 250 |
+
try:
|
| 251 |
+
accounts = _accounts(session)
|
| 252 |
+
match = [(n, rec) for n, rec in accounts
|
| 253 |
+
if want in {str(n).casefold(), str(rec.get("username_original") or "").casefold(),
|
| 254 |
+
str(rec.get("name") or "").strip().casefold()}]
|
| 255 |
+
if not match:
|
| 256 |
+
return None
|
| 257 |
+
return _entry(session, match[0][0], match[0][1], _context(session))
|
| 258 |
+
except DirectoryUnavailable:
|
| 259 |
+
raise
|
| 260 |
+
except Exception as exc: # noqa: BLE001
|
| 261 |
+
_LOG.warning("Workspace directory lookup failed (%s)", type(exc).__name__)
|
| 262 |
+
raise DirectoryUnavailable(REFUSAL) from exc
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def colleague(session, username):
|
| 266 |
+
"""One same-tenant active account by username or name, or None. Never crosses tenants."""
|
| 267 |
+
try:
|
| 268 |
+
return _colleague(session, username)
|
| 269 |
+
except DirectoryUnavailable:
|
| 270 |
+
return None
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def workspace_people(session, args):
|
| 274 |
+
"""The `workspace_people` tool: the caller's workspace roster, or one person in it."""
|
| 275 |
+
args = args if isinstance(args, dict) else {}
|
| 276 |
+
want = str(args.get("username") or "").strip()
|
| 277 |
+
try:
|
| 278 |
+
if want:
|
| 279 |
+
one = _colleague(session, want)
|
| 280 |
+
if one is None:
|
| 281 |
+
return {"people": [], "note": NOT_FOUND}
|
| 282 |
+
return {"people": [one]}
|
| 283 |
+
return {"people": people(session)}
|
| 284 |
+
except DirectoryUnavailable:
|
| 285 |
+
return {"ok": False, "refused": REFUSAL}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
TOOLS = ({"name": "workspace_people", "schema": SCHEMA, "fn": workspace_people, "effect": "read"},)
|
api/agent_inbox.py
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent messages: one person's agent sends an access request, a share or a question (C6).
|
| 2 |
+
|
| 3 |
+
R94: three kinds, one line of text each. A repeat within a day folds into the first message.
|
| 4 |
+
R108(l): the recipient gets one notice turn in their conversation at the next visit, and on
|
| 5 |
+
WhatsApp when connected and inside the 24-hour window (`assistant_feed.post` decides that).
|
| 6 |
+
R81: the inbox has no screen of its own. It lives in the chat.
|
| 7 |
+
R84: a recipient is resolved only among the caller's own workspace accounts.
|
| 8 |
+
`send` is the one door: the `agent_message` tool and the T28 route both use it.
|
| 9 |
+
R93 (S72-T28): an access request goes to the item's owner, and to the Administrators for a
|
| 10 |
+
database. Only a person's click on the C6 route reaches `decide_request`. No agent tool does.
|
| 11 |
+
"""
|
| 12 |
+
import copy
|
| 13 |
+
import datetime as _dt
|
| 14 |
+
import logging
|
| 15 |
+
import re
|
| 16 |
+
import secrets
|
| 17 |
+
|
| 18 |
+
import ai_enrich
|
| 19 |
+
import agent_directory
|
| 20 |
+
import assistant_log
|
| 21 |
+
from core import alerts, perms, users
|
| 22 |
+
|
| 23 |
+
_LOG = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
STORE_KEY = "agent_inbox"
|
| 26 |
+
KINDS = ("access_request", "share", "question")
|
| 27 |
+
TARGET_KINDS = ("database", "sheet", "view", "app")
|
| 28 |
+
ROLES = ("view", "edit")
|
| 29 |
+
ACTIONS = ["approve", "not_now"]
|
| 30 |
+
C6_KEYS = ("type", "request_id", "sender", "target", "text", "actions", "state")
|
| 31 |
+
TEXT_LIMIT = 280
|
| 32 |
+
FOLD_SECONDS = 24 * 3600
|
| 33 |
+
|
| 34 |
+
NOT_IN_WORKSPACE = "That person is not in your workspace."
|
| 35 |
+
TWO_NAMES = "Two people share that name. Use their username."
|
| 36 |
+
NOT_YOURSELF = "You cannot send a message to yourself."
|
| 37 |
+
NAME_ASK = "Name the person to ask."
|
| 38 |
+
NAME_TO = "Name the person to send this to."
|
| 39 |
+
NO_KIND = "Choose an access request, a share or a question."
|
| 40 |
+
NO_TEXT = "Write one line to send."
|
| 41 |
+
TOO_LONG = f"Keep the message to one line of {TEXT_LIMIT} characters or fewer."
|
| 42 |
+
NO_TARGET = "Name the database, sheet, view or app this message is about."
|
| 43 |
+
BAD_TARGET = "That target is not a database, sheet, view or app."
|
| 44 |
+
BAD_ROLE = "Ask for view or edit access."
|
| 45 |
+
APP_VIEW_ONLY = "Apps can only be shared for viewing."
|
| 46 |
+
UNAVAILABLE = "The message could not be sent. Try again in a moment."
|
| 47 |
+
NOT_FOUND = "I could not find that item."
|
| 48 |
+
OWN_ITEM = "That item is already yours."
|
| 49 |
+
ALREADY_HELD = "You already have that access."
|
| 50 |
+
NO_ANSWERER = "No one in your workspace can answer this request."
|
| 51 |
+
NO_REQUEST = "I could not find that request."
|
| 52 |
+
BAD_ACTION = "Choose approve or not now."
|
| 53 |
+
ONLY_ADMIN = "Only an Administrator can answer a database request."
|
| 54 |
+
ONLY_OWNER = "Only the owner of this item can answer this request."
|
| 55 |
+
USE_MANAGE_USERS = "Give access to this database in Manage users."
|
| 56 |
+
TURN_ON = "Turn this database on for them in Manage users."
|
| 57 |
+
CHANGED = "Someone changed who has access while you were answering. Try again."
|
| 58 |
+
NOT_GRANTED = "The access could not be granted. Try again in a moment."
|
| 59 |
+
NOT_ANSWERED = "The request could not be answered. Try again in a moment."
|
| 60 |
+
RANK = {None: 0, "view": 1, "edit": 2, "owner": 3}
|
| 61 |
+
|
| 62 |
+
SCHEMA = {
|
| 63 |
+
"type": "object",
|
| 64 |
+
"description": ("Send one short message to a person in your workspace: an access request, "
|
| 65 |
+
"a share or a question."),
|
| 66 |
+
"properties": {
|
| 67 |
+
"type": {"type": "string", "enum": list(KINDS)},
|
| 68 |
+
"to": {"type": "string"},
|
| 69 |
+
"target": {"type": "object", "properties": {
|
| 70 |
+
"kind": {"type": "string", "enum": list(TARGET_KINDS)},
|
| 71 |
+
"key": {"type": "string"},
|
| 72 |
+
"label": {"type": "string"}}, "additionalProperties": False},
|
| 73 |
+
"text": {"type": "string"},
|
| 74 |
+
"role": {"type": "string", "enum": list(ROLES)},
|
| 75 |
+
},
|
| 76 |
+
"required": ["type", "text"],
|
| 77 |
+
"additionalProperties": False,
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class Refused(ValueError):
|
| 82 |
+
"""A message that cannot be sent. The text is one plain sentence for the sender."""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class Denied(Exception):
|
| 86 |
+
"""A click on the C6 route that changes nothing: an HTTP status, a code and one sentence."""
|
| 87 |
+
|
| 88 |
+
def __init__(self, status, code, message):
|
| 89 |
+
super().__init__(message)
|
| 90 |
+
self.status, self.code, self.message = status, code, message
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _now(now=None):
|
| 94 |
+
if isinstance(now, _dt.datetime):
|
| 95 |
+
return now.astimezone(_dt.timezone.utc)
|
| 96 |
+
from core import write_execution
|
| 97 |
+
return write_execution.utcnow()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _age(created_at, now):
|
| 101 |
+
try:
|
| 102 |
+
return (now - _dt.datetime.fromisoformat(str(created_at))).total_seconds()
|
| 103 |
+
except (TypeError, ValueError):
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _recipient(session, who):
|
| 108 |
+
"""`(registry_key, record)` of one active account in the caller's tenant. Raises Refused."""
|
| 109 |
+
want = str(who or "").strip().casefold()
|
| 110 |
+
if not want:
|
| 111 |
+
raise Refused(NOT_IN_WORKSPACE)
|
| 112 |
+
try:
|
| 113 |
+
accounts = agent_directory._accounts(session)
|
| 114 |
+
except agent_directory.DirectoryUnavailable as exc:
|
| 115 |
+
raise Refused(UNAVAILABLE) from exc
|
| 116 |
+
match = [(n, rec) for n, rec in accounts
|
| 117 |
+
if want in {str(n).strip().casefold(),
|
| 118 |
+
str(rec.get("username_original") or "").strip().casefold()}]
|
| 119 |
+
if not match:
|
| 120 |
+
match = [(n, rec) for n, rec in accounts
|
| 121 |
+
if str(rec.get("name") or "").strip().casefold() == want]
|
| 122 |
+
if len(match) > 1:
|
| 123 |
+
raise Refused(TWO_NAMES)
|
| 124 |
+
if not match:
|
| 125 |
+
# One sentence for another tenant, an inactive account and nobody alike.
|
| 126 |
+
raise Refused(NOT_IN_WORKSPACE)
|
| 127 |
+
uname, rec = match[0]
|
| 128 |
+
uname = str(uname).strip().lower()
|
| 129 |
+
if uname == str(session.uname or "").strip().lower():
|
| 130 |
+
raise Refused(NOT_YOURSELF)
|
| 131 |
+
return uname, rec
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _text(value):
|
| 135 |
+
text = ai_enrich.no_dashes(" ".join(str(value or "").split())).strip()
|
| 136 |
+
if not text:
|
| 137 |
+
raise Refused(NO_TEXT)
|
| 138 |
+
if len(text) > TEXT_LIMIT:
|
| 139 |
+
raise Refused(TOO_LONG)
|
| 140 |
+
return text
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _target(kind, value):
|
| 144 |
+
if value is None or value == {}:
|
| 145 |
+
if kind == "question":
|
| 146 |
+
return None
|
| 147 |
+
raise Refused(NO_TARGET)
|
| 148 |
+
if not isinstance(value, dict):
|
| 149 |
+
raise Refused(BAD_TARGET)
|
| 150 |
+
tkind, key = str(value.get("kind") or ""), str(value.get("key") or "").strip()
|
| 151 |
+
if tkind not in TARGET_KINDS or not key or len(key) > 200:
|
| 152 |
+
raise Refused(BAD_TARGET)
|
| 153 |
+
label = ai_enrich.no_dashes(" ".join(str(value.get("label") or key).split()))[:160]
|
| 154 |
+
return {"kind": tkind, "key": key, "label": label or key}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# ── S72-T28: the real item behind a target, and who answers for it (R93) ──────────────────────
|
| 158 |
+
def _ids(key):
|
| 159 |
+
"""`key`, then its last part: a link key reads `<database>/<id>`."""
|
| 160 |
+
key = str(key or "").strip()
|
| 161 |
+
tail = re.split(r"[/:]", key)[-1].strip()
|
| 162 |
+
return [key] + ([tail] if tail and tail != key else [])
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _lower(value):
|
| 166 |
+
return str(value or "").strip().lower() or None
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _database_ref(session, key):
|
| 170 |
+
from core import user_tables
|
| 171 |
+
want = str(key).strip().casefold()
|
| 172 |
+
for db in agent_directory._databases(session, agent_directory._lend(session)) or ():
|
| 173 |
+
if not isinstance(db, dict) or not db.get("key"):
|
| 174 |
+
continue
|
| 175 |
+
if want not in {str(db["key"]).casefold(), str(db.get("label") or "").strip().casefold()}:
|
| 176 |
+
continue
|
| 177 |
+
oid = str(db["key"])
|
| 178 |
+
ref = {"kind": "database", "key": oid, "oid": oid, "label": db.get("label") or oid,
|
| 179 |
+
"owner": None, "creator": None}
|
| 180 |
+
if oid.startswith(user_tables.KEY_PREFIX):
|
| 181 |
+
table = user_tables.get_one(oid, session.runtime)
|
| 182 |
+
if not table:
|
| 183 |
+
return None
|
| 184 |
+
ref["creator"] = _lower(table.get("createdBy"))
|
| 185 |
+
return ref
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _sheet_ref(session, key):
|
| 190 |
+
from core import shares, sheets
|
| 191 |
+
for oid in _ids(key):
|
| 192 |
+
try:
|
| 193 |
+
book = sheets.get_workbook(session.runtime, oid)
|
| 194 |
+
except sheets.SheetRefusal:
|
| 195 |
+
continue
|
| 196 |
+
bid = str(book.get("id") or oid)
|
| 197 |
+
owner = (shares.grants("workbook", bid, st=session.runtime)["owner"]
|
| 198 |
+
or _lower(book.get("created_by")))
|
| 199 |
+
return {"kind": "sheet", "key": bid, "oid": bid, "label": book.get("name") or "A sheet",
|
| 200 |
+
"owner": owner, "book": book}
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _view_ref(session, key):
|
| 205 |
+
import routes_shares
|
| 206 |
+
from core import shares
|
| 207 |
+
for oid in _ids(key):
|
| 208 |
+
topic, creator, view = routes_shares._find_view_record(session, oid)
|
| 209 |
+
if not topic:
|
| 210 |
+
continue
|
| 211 |
+
database = {"customer": "customer_data", "product": "product_data"}.get(topic, topic)
|
| 212 |
+
owner = shares.grants("view", oid, st=session.runtime)["owner"] or _lower(creator)
|
| 213 |
+
return {"kind": "view", "key": f"{database}/{oid}", "oid": oid,
|
| 214 |
+
"label": (view or {}).get("name") or "A view", "owner": owner}
|
| 215 |
+
return None
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _app_ref(session, key):
|
| 219 |
+
import application_registry as apps
|
| 220 |
+
found = apps.load(session.runtime).get("applications") or {}
|
| 221 |
+
for oid in _ids(key):
|
| 222 |
+
app = found.get(oid)
|
| 223 |
+
if not isinstance(app, dict) or app.get("templateKind") == apps.FINANCE_TEMPLATE_KIND:
|
| 224 |
+
continue
|
| 225 |
+
dbs = [str(d) for d in app.get("compatibleDatabases") or () if d]
|
| 226 |
+
return {"kind": "app", "key": f"{dbs[0]}/{oid}" if dbs else oid, "oid": oid,
|
| 227 |
+
"label": app.get("name") or "An app", "owner": _lower(app.get("createdBy")),
|
| 228 |
+
"app": app}
|
| 229 |
+
return None
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
_RESOLVERS = {"database": _database_ref, "sheet": _sheet_ref, "view": _view_ref, "app": _app_ref}
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _resolve(session, target):
|
| 236 |
+
"""The real item behind a C6 target, with its real label and owner. Raises Refused."""
|
| 237 |
+
try:
|
| 238 |
+
ref = _RESOLVERS[target["kind"]](session, target["key"])
|
| 239 |
+
except Exception as exc: # noqa: BLE001
|
| 240 |
+
_LOG.warning("Inbox target was not resolved (%s)", type(exc).__name__)
|
| 241 |
+
ref = None
|
| 242 |
+
if not ref:
|
| 243 |
+
# One sentence for missing, unreadable and failed alike: a refusal never confirms an id.
|
| 244 |
+
raise Refused(NOT_FOUND)
|
| 245 |
+
ref["label"] = ai_enrich.no_dashes(" ".join(str(ref["label"]).split()))[:160] or ref["key"]
|
| 246 |
+
return ref
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _public_target(ref):
|
| 250 |
+
return {"kind": ref["kind"], "key": ref["key"], "label": ref["label"]}
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _held(session, ref, principal):
|
| 254 |
+
"""`principal`'s current role on the item: `owner`, `edit`, `view` or None."""
|
| 255 |
+
from core import perm_scope, shares, sheets, user_tables
|
| 256 |
+
import application_registry as apps
|
| 257 |
+
rt, uname = session.runtime, _lower((principal or {}).get("username"))
|
| 258 |
+
if not uname:
|
| 259 |
+
return None
|
| 260 |
+
if perms.is_admin(principal) or (ref["kind"] != "database" and ref.get("owner") == uname):
|
| 261 |
+
return "owner"
|
| 262 |
+
kind, oid = ref["kind"], ref["oid"]
|
| 263 |
+
if kind == "database":
|
| 264 |
+
if not perm_scope.may_read(principal, oid, st=rt):
|
| 265 |
+
return None
|
| 266 |
+
if oid.startswith(user_tables.KEY_PREFIX) and \
|
| 267 |
+
user_tables.may_edit_database(oid, uname, False, st=rt):
|
| 268 |
+
return "edit"
|
| 269 |
+
return "view"
|
| 270 |
+
if kind == "sheet":
|
| 271 |
+
return sheets.workbook_role(rt, ref["book"], uname)
|
| 272 |
+
if kind == "view":
|
| 273 |
+
return shares.role_for("view", oid, uname, st=rt)
|
| 274 |
+
if apps.may_edit(ref["app"], uname):
|
| 275 |
+
return "edit"
|
| 276 |
+
return "view" if apps.may_read(ref["app"], uname) else None
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def _answerers(session, ref):
|
| 280 |
+
"""`(usernames, owner)`: who answers a request about `ref` in the caller's tenant (R93).
|
| 281 |
+
|
| 282 |
+
A sheet, view or app goes to its active owner. A database, or an item whose owner is not
|
| 283 |
+
an active account here, goes to every active Administrator.
|
| 284 |
+
"""
|
| 285 |
+
active = {str(n).strip().lower(): rec for n, rec in agent_directory._accounts(session)}
|
| 286 |
+
owner = ref.get("owner")
|
| 287 |
+
if ref["kind"] != "database" and owner in active:
|
| 288 |
+
return [owner], owner
|
| 289 |
+
return sorted(n for n, rec in active.items() if perms.is_admin(rec)), None
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def _route_request(session, ref, role):
|
| 293 |
+
"""Recipients of an access request. Raises Refused for an item the sender already holds."""
|
| 294 |
+
me = _lower(session.uname)
|
| 295 |
+
if ref["kind"] != "database" and ref.get("owner") == me:
|
| 296 |
+
raise Refused(OWN_ITEM)
|
| 297 |
+
if RANK[_held(session, ref, session.user)] >= RANK[role]:
|
| 298 |
+
raise Refused(ALREADY_HELD)
|
| 299 |
+
try:
|
| 300 |
+
answerers, _owner = _answerers(session, ref)
|
| 301 |
+
except agent_directory.DirectoryUnavailable as exc:
|
| 302 |
+
raise Refused(UNAVAILABLE) from exc
|
| 303 |
+
recipients = [u for u in answerers if u != me]
|
| 304 |
+
if not recipients:
|
| 305 |
+
raise Refused(NO_ANSWERER)
|
| 306 |
+
return recipients
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _same(record, sender, recipients, kind, target, text, role, now):
|
| 310 |
+
"""True when `record` is an earlier copy of this message within a day."""
|
| 311 |
+
if record.get("type") != kind or (record.get("sender") or {}).get("username") != sender:
|
| 312 |
+
return False
|
| 313 |
+
if not set(recipients) & set(record.get("recipients") or ()):
|
| 314 |
+
return False
|
| 315 |
+
age = _age(record.get("created_at"), now)
|
| 316 |
+
if age is None or not 0 <= age < FOLD_SECONDS:
|
| 317 |
+
return False
|
| 318 |
+
theirs = record.get("target") or {}
|
| 319 |
+
mine = target or {}
|
| 320 |
+
if (theirs.get("kind"), theirs.get("key")) != (mine.get("kind"), mine.get("key")):
|
| 321 |
+
return False
|
| 322 |
+
if kind == "access_request":
|
| 323 |
+
return record.get("state") == "pending" and record.get("role") == role
|
| 324 |
+
return record.get("text") == text
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _title(record):
|
| 328 |
+
name = record["sender"]["name"]
|
| 329 |
+
label = (record.get("target") or {}).get("label") or ""
|
| 330 |
+
if record["type"] == "access_request":
|
| 331 |
+
level = "edit access" if record.get("role") == "edit" else "access"
|
| 332 |
+
return ai_enrich.no_dashes(f"{name} asks for {level} to {label}")
|
| 333 |
+
if record["type"] == "share":
|
| 334 |
+
return ai_enrich.no_dashes(f"{name} shared {label} with you")
|
| 335 |
+
return ai_enrich.no_dashes(f"{name} has a question" + (f" about {label}" if label else ""))
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def notice_payload(record, recipient=None):
|
| 339 |
+
"""The C6 payload of one record. `recipient` is reserved for per-recipient state."""
|
| 340 |
+
kind = record.get("type")
|
| 341 |
+
state = record.get("state") if kind == "access_request" else "pending"
|
| 342 |
+
if state not in ("pending", "approved", "declined"):
|
| 343 |
+
state = "pending"
|
| 344 |
+
actions = list(ACTIONS) if kind == "access_request" and state == "pending" else []
|
| 345 |
+
sender = record.get("sender") or {}
|
| 346 |
+
return {"type": kind, "request_id": record.get("request_id"),
|
| 347 |
+
"sender": {"username": str(sender.get("username") or ""),
|
| 348 |
+
"name": str(sender.get("name") or "")},
|
| 349 |
+
"target": copy.deepcopy(record.get("target")), "text": record.get("text") or "",
|
| 350 |
+
"actions": actions, "state": state}
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def get(rt, request_id):
|
| 354 |
+
"""One stored record, or None."""
|
| 355 |
+
return copy.deepcopy(((rt.get(STORE_KEY) or {}).get("requests") or {}).get(str(request_id)))
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def update(rt, request_id, fn):
|
| 359 |
+
"""Apply `fn(record) -> record` under the store lock. Returns the new record or None."""
|
| 360 |
+
out = []
|
| 361 |
+
|
| 362 |
+
def apply(raw):
|
| 363 |
+
data = copy.deepcopy(raw) if isinstance(raw, dict) else {}
|
| 364 |
+
requests = data.setdefault("requests", {})
|
| 365 |
+
current = requests.get(str(request_id))
|
| 366 |
+
if not isinstance(current, dict):
|
| 367 |
+
return data
|
| 368 |
+
new = fn(copy.deepcopy(current))
|
| 369 |
+
if not isinstance(new, dict):
|
| 370 |
+
raise ValueError("Updating an inbox request needs an object.")
|
| 371 |
+
new.update(request_id=current["request_id"], updated_at=_now().isoformat())
|
| 372 |
+
requests[str(request_id)] = new
|
| 373 |
+
out[:] = [copy.deepcopy(new)]
|
| 374 |
+
return data
|
| 375 |
+
|
| 376 |
+
rt.update(STORE_KEY, apply, flush="sync")
|
| 377 |
+
return out[0] if out else None
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _notice_id(rt, uname, request_id):
|
| 381 |
+
try:
|
| 382 |
+
turns = assistant_log.read(rt, uname, limit=20).get("turns") or []
|
| 383 |
+
except Exception: # noqa: BLE001
|
| 384 |
+
return None
|
| 385 |
+
return next((t.get("id") for t in reversed(turns)
|
| 386 |
+
if (t.get("payload") or {}).get("request_id") == request_id), None)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def _public(record, folded):
|
| 390 |
+
return {"ok": True, "folded": folded, "request_id": record["request_id"],
|
| 391 |
+
"type": record["type"], "state": record["state"],
|
| 392 |
+
"to": [str(u) for u in record.get("recipients") or ()],
|
| 393 |
+
"target": copy.deepcopy(record.get("target")), "text": record["text"]}
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def _send(session, kind, to, target, text, role, now):
|
| 397 |
+
if kind not in KINDS:
|
| 398 |
+
raise Refused(NO_KIND)
|
| 399 |
+
# R93: an access request is routed to whoever may answer it, so `to` is not needed there.
|
| 400 |
+
if kind != "access_request" and not str(to or "").strip():
|
| 401 |
+
raise Refused(NAME_TO)
|
| 402 |
+
if role not in ROLES:
|
| 403 |
+
raise Refused(BAD_ROLE)
|
| 404 |
+
text = _text(text)
|
| 405 |
+
target = _target(kind, target)
|
| 406 |
+
if kind == "access_request":
|
| 407 |
+
if target["kind"] == "app" and role != "view":
|
| 408 |
+
raise Refused(APP_VIEW_ONLY)
|
| 409 |
+
ref = _resolve(session, target)
|
| 410 |
+
recipients = _route_request(session, ref, role)
|
| 411 |
+
target = _public_target(ref)
|
| 412 |
+
else:
|
| 413 |
+
recipients = [_recipient(session, to)[0]]
|
| 414 |
+
if target is not None:
|
| 415 |
+
ref = _resolve(session, target)
|
| 416 |
+
if _held(session, ref, session.user) is None:
|
| 417 |
+
raise Refused(NOT_FOUND)
|
| 418 |
+
target = _public_target(ref)
|
| 419 |
+
me = str(session.uname or "").strip().lower()
|
| 420 |
+
sender = {"username": me, "name": str((session.user or {}).get("name") or me)}
|
| 421 |
+
stamp = _now(now)
|
| 422 |
+
found = {}
|
| 423 |
+
|
| 424 |
+
def apply(raw):
|
| 425 |
+
data = copy.deepcopy(raw) if isinstance(raw, dict) else {}
|
| 426 |
+
requests = data.setdefault("requests", {})
|
| 427 |
+
for rec in requests.values():
|
| 428 |
+
if isinstance(rec, dict) and _same(rec, me, recipients, kind, target, text, role, stamp):
|
| 429 |
+
found["record"], found["folded"] = copy.deepcopy(rec), True
|
| 430 |
+
return data
|
| 431 |
+
from core import write_execution
|
| 432 |
+
rid = write_execution.new_id()[:24]
|
| 433 |
+
rec = {"request_id": rid, "type": kind, "sender": sender, "recipients": list(recipients),
|
| 434 |
+
"target": target, "text": text,
|
| 435 |
+
"role": role if kind == "access_request" else None,
|
| 436 |
+
"state": "pending" if kind == "access_request" else "sent",
|
| 437 |
+
"created_at": stamp.isoformat(), "updated_at": stamp.isoformat(),
|
| 438 |
+
"notices": {}, "decided_by": None, "decided_at": None}
|
| 439 |
+
requests[rid] = rec
|
| 440 |
+
found["record"], found["folded"] = copy.deepcopy(rec), False
|
| 441 |
+
return data
|
| 442 |
+
|
| 443 |
+
session.runtime.update(STORE_KEY, apply, flush="sync")
|
| 444 |
+
record = found["record"]
|
| 445 |
+
if found["folded"]:
|
| 446 |
+
return _public(record, True)
|
| 447 |
+
rt, rid = session.runtime, record["request_id"]
|
| 448 |
+
notices = {}
|
| 449 |
+
for uname in record["recipients"]:
|
| 450 |
+
alerts.notify(uname, _title(record), topic="inbox", key=rid, detail=record["text"],
|
| 451 |
+
actor=sender["name"], st=rt, target=copy.deepcopy(record["target"]),
|
| 452 |
+
inbox=notice_payload(record, uname))
|
| 453 |
+
turn_id = _notice_id(rt, uname, rid)
|
| 454 |
+
if turn_id:
|
| 455 |
+
notices[uname] = turn_id
|
| 456 |
+
if notices:
|
| 457 |
+
record = update(rt, rid, lambda rec: {**rec, "notices": {**rec.get("notices", {}),
|
| 458 |
+
**notices}}) or record
|
| 459 |
+
return _public(record, False)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def send(session, *, type, to, target, text, role="view", now=None): # noqa: A002
|
| 463 |
+
"""Send one message. Returns the request, `folded: true` for a repeat, or a refusal."""
|
| 464 |
+
try:
|
| 465 |
+
return _send(session, type, to, target, text, role, now)
|
| 466 |
+
except Refused as exc:
|
| 467 |
+
return {"ok": False, "refused": str(exc)}
|
| 468 |
+
except Exception as exc: # noqa: BLE001
|
| 469 |
+
_LOG.warning("Agent message was not sent (%s)", exc.__class__.__name__)
|
| 470 |
+
return {"ok": False, "refused": UNAVAILABLE}
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def agent_message(session, args):
|
| 474 |
+
"""The `agent_message` tool."""
|
| 475 |
+
args = args if isinstance(args, dict) else {}
|
| 476 |
+
return send(session, type=str(args.get("type") or ""), to=args.get("to"),
|
| 477 |
+
target=args.get("target"), text=args.get("text"),
|
| 478 |
+
role=str(args.get("role") or "view"))
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
# ── S72-T28: a person answers an access request (C6 route only) ───────────────────────────────
|
| 482 |
+
# ⛔ No agent tool may call into this section. An agent never changes a grant with no person's
|
| 483 |
+
# click (R93). `verify_agent_inbox` walks every registered tool to prove it.
|
| 484 |
+
def _may_answer(session, ref):
|
| 485 |
+
"""R93: the owner answers a sheet, view or app. An Administrator answers a database."""
|
| 486 |
+
if ref["kind"] == "database":
|
| 487 |
+
return bool(session.admin) # only an Administrator grants a database
|
| 488 |
+
_who, owner = _answerers(session, ref)
|
| 489 |
+
if owner:
|
| 490 |
+
return owner == _lower(session.uname)
|
| 491 |
+
return bool(session.admin)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def _asker(session, record):
|
| 495 |
+
want = _lower((record.get("sender") or {}).get("username"))
|
| 496 |
+
for n, rec in agent_directory._accounts(session):
|
| 497 |
+
if str(n).strip().lower() == want:
|
| 498 |
+
return want, users._public(n, rec)
|
| 499 |
+
raise Denied(409, "asker_gone", NOT_IN_WORKSPACE)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def _with_grant(prior, user, role):
|
| 503 |
+
"""`prior` with `user` at `role`. Every other entry is copied unchanged."""
|
| 504 |
+
rows = [dict(e) for e in prior or ()]
|
| 505 |
+
for row in rows:
|
| 506 |
+
if row.get("user") == user:
|
| 507 |
+
row["role"] = role
|
| 508 |
+
return rows
|
| 509 |
+
return rows + [{"user": user, "role": role}]
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _add_grant(kind, oid, user, role, *, owner, granter, st):
|
| 513 |
+
"""Add one grant through `shares.set_grants`, guarded by `expect`, the PUT door's own CAS."""
|
| 514 |
+
from core import shares
|
| 515 |
+
held = shares.grants(kind, oid, st=st)
|
| 516 |
+
return shares.set_grants(kind, oid, _with_grant(held["entries"], user, role),
|
| 517 |
+
owner=None if held["owner"] else owner, st=st,
|
| 518 |
+
granter=granter, expect=held["entries"])
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def _approve_grant(session, ref, asker, principal, role):
|
| 522 |
+
"""Grant exactly `role` to exactly `asker` on exactly the item. Raises Denied."""
|
| 523 |
+
rt, kind, oid = session.runtime, ref["kind"], ref["oid"]
|
| 524 |
+
if kind == "app" and role != "view":
|
| 525 |
+
raise Denied(409, "unsupported_role", APP_VIEW_ONLY)
|
| 526 |
+
if kind == "database":
|
| 527 |
+
import routes_admin
|
| 528 |
+
routes_admin.grant_database_access(session, asker, oid, role)
|
| 529 |
+
return
|
| 530 |
+
if RANK[_held(session, ref, principal)] >= RANK[role]:
|
| 531 |
+
return # The asker holds this already: nothing to write.
|
| 532 |
+
if kind == "sheet":
|
| 533 |
+
from core import sheets
|
| 534 |
+
_add_grant("workbook", oid, asker, role, owner=ref.get("owner"),
|
| 535 |
+
granter=session.uname, st=rt)
|
| 536 |
+
if "access" not in ref["book"]:
|
| 537 |
+
sheets.narrow_workbook(rt, oid) # the marker `routes_sheet.share_sheet` writes too
|
| 538 |
+
elif kind == "view":
|
| 539 |
+
# The PUT door's View path: the audience and its field boundary in one transaction.
|
| 540 |
+
import routes_shares
|
| 541 |
+
from core import field_permissions, shares
|
| 542 |
+
held = shares.grants("view", oid, st=rt)
|
| 543 |
+
_topic, view, grant_topic, _keys, _owned = routes_shares._prepare_view_share(session, oid)
|
| 544 |
+
field_permissions.set_view_grants_with_boundary(
|
| 545 |
+
view, grant_topic, _with_grant(held["entries"], asker, role),
|
| 546 |
+
owner=None if held["owner"] else ref.get("owner"), granter=session.uname,
|
| 547 |
+
expect=held["entries"], st=rt)
|
| 548 |
+
else:
|
| 549 |
+
import application_registry as apps
|
| 550 |
+
app = (apps.load(rt).get("applications") or {}).get(oid) or {}
|
| 551 |
+
share = app.get("share") if isinstance(app.get("share"), dict) else {}
|
| 552 |
+
names = list(share.get("users") or ()) if share.get("mode") == "users" else []
|
| 553 |
+
apps.mutate(rt, oid, session.uname, session.admin,
|
| 554 |
+
{"share": {"mode": "users", "users": names + [asker]}}, expect=share)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def _claim(rt, request_id, state, who):
|
| 558 |
+
"""Move a pending request to `state` once. Returns `(record, claimed)`."""
|
| 559 |
+
claimed = []
|
| 560 |
+
|
| 561 |
+
def fn(rec):
|
| 562 |
+
# A store replay must report whether this invocation won the claim.
|
| 563 |
+
claimed.clear()
|
| 564 |
+
if rec.get("state") != "pending":
|
| 565 |
+
return rec
|
| 566 |
+
claimed.append(True)
|
| 567 |
+
return {**rec, "state": state, "decided_by": who, "decided_at": _now().isoformat()}
|
| 568 |
+
|
| 569 |
+
return update(rt, request_id, fn), bool(claimed)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def _close_cards(rt, record):
|
| 573 |
+
"""Rewrite each recipient's notice to the final state with no buttons."""
|
| 574 |
+
def fn(turn):
|
| 575 |
+
payload = dict(turn.get("payload") or {}, state=record["state"], actions=[])
|
| 576 |
+
return {**turn, "payload": payload}
|
| 577 |
+
|
| 578 |
+
for uname in record.get("recipients") or ():
|
| 579 |
+
turn_id = ((record.get("notices") or {}).get(uname)
|
| 580 |
+
or _notice_id(rt, uname, record["request_id"]))
|
| 581 |
+
try:
|
| 582 |
+
if turn_id:
|
| 583 |
+
assistant_log.update_turn(rt, uname, turn_id, fn)
|
| 584 |
+
except Exception as exc: # noqa: BLE001
|
| 585 |
+
_LOG.warning("Inbox card was not closed (%s)", type(exc).__name__)
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def _tell_asker(session, record):
|
| 589 |
+
"""One outcome notice to the asker. It never raises: the decision already stands."""
|
| 590 |
+
me = _lower(session.uname)
|
| 591 |
+
name = str((session.user or {}).get("name") or me)
|
| 592 |
+
text = ai_enrich.no_dashes(f"{name} approved your request." if record["state"] == "approved"
|
| 593 |
+
else f"{name} said not now.")
|
| 594 |
+
payload = dict(notice_payload(record), sender={"username": me, "name": name}, text=text)
|
| 595 |
+
try:
|
| 596 |
+
alerts.notify(record["sender"]["username"], text, topic="inbox",
|
| 597 |
+
key=record["request_id"], detail=text, actor=name, st=session.runtime,
|
| 598 |
+
target=copy.deepcopy(record.get("target")), inbox=payload)
|
| 599 |
+
except Exception as exc: # noqa: BLE001
|
| 600 |
+
_LOG.warning("Inbox outcome was not sent (%s)", type(exc).__name__)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def _unclaim(rt, request_id, state, who):
|
| 604 |
+
"""Put a claimed request back to pending, only while it still reads `state` by `who`."""
|
| 605 |
+
def fn(rec):
|
| 606 |
+
if rec.get("state") != state or rec.get("decided_by") != who:
|
| 607 |
+
return rec
|
| 608 |
+
return {**rec, "state": "pending", "decided_by": None, "decided_at": None}
|
| 609 |
+
|
| 610 |
+
return update(rt, request_id, fn)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _denied(exc):
|
| 614 |
+
"""The Denied a failed answer maps to. Every refusal stays one plain sentence."""
|
| 615 |
+
from core import shares
|
| 616 |
+
from fastapi import HTTPException
|
| 617 |
+
if isinstance(exc, Denied):
|
| 618 |
+
return exc
|
| 619 |
+
if isinstance(exc, HTTPException) and isinstance(exc.detail, dict):
|
| 620 |
+
error = exc.detail.get('error') or {}
|
| 621 |
+
return Denied(exc.status_code, error.get('code') or 'not_granted',
|
| 622 |
+
error.get('message') or NOT_GRANTED)
|
| 623 |
+
if isinstance(exc, agent_directory.DirectoryUnavailable):
|
| 624 |
+
return Denied(503, "unavailable", NOT_ANSWERED)
|
| 625 |
+
if isinstance(exc, PermissionError):
|
| 626 |
+
return Denied(403, "not_allowed", ONLY_OWNER)
|
| 627 |
+
if isinstance(exc, shares.GrantsChanged):
|
| 628 |
+
return Denied(409, "grants_changed", CHANGED)
|
| 629 |
+
_LOG.warning("Inbox request was not answered (%s)", type(exc).__name__)
|
| 630 |
+
return Denied(409, "not_granted", NOT_GRANTED)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def decide_request(session, request_id, action):
|
| 634 |
+
"""Answer one access request on a person's click (C6, R93). Returns `{"state"}`.
|
| 635 |
+
|
| 636 |
+
The decision is claimed before the grant, so a parallel click can never leave a grant under
|
| 637 |
+
a declined record. A failed grant puts the claim back.
|
| 638 |
+
"""
|
| 639 |
+
if action not in ACTIONS:
|
| 640 |
+
raise Denied(400, "bad_action", BAD_ACTION)
|
| 641 |
+
rt, me = session.runtime, _lower(session.uname)
|
| 642 |
+
record = get(rt, request_id)
|
| 643 |
+
# The store is the tenant's own, so another tenant's id is simply not here.
|
| 644 |
+
if not isinstance(record, dict) or record.get("type") != "access_request" \
|
| 645 |
+
or not isinstance(record.get("target"), dict):
|
| 646 |
+
raise Denied(404, "no_request", NO_REQUEST)
|
| 647 |
+
decided = record.get("state") in ("approved", "declined")
|
| 648 |
+
try:
|
| 649 |
+
try:
|
| 650 |
+
ref = _resolve(session, record["target"])
|
| 651 |
+
except Refused:
|
| 652 |
+
if decided and (session.admin or me == record.get("decided_by")
|
| 653 |
+
or me in (record.get("recipients") or ())):
|
| 654 |
+
return {"state": record["state"]}
|
| 655 |
+
raise Denied(404, "no_item", NOT_FOUND)
|
| 656 |
+
if not _may_answer(session, ref):
|
| 657 |
+
raise Denied(403, "not_allowed",
|
| 658 |
+
ONLY_ADMIN if ref["kind"] == "database" else ONLY_OWNER)
|
| 659 |
+
if decided:
|
| 660 |
+
return {"state": record["state"]} # A second click changes nothing.
|
| 661 |
+
asker, principal = _asker(session, record)
|
| 662 |
+
state = "approved" if action == "approve" else "declined"
|
| 663 |
+
role = record.get("role")
|
| 664 |
+
if action == 'approve' and role not in ROLES:
|
| 665 |
+
raise Denied(409, "unsupported_role", BAD_ROLE)
|
| 666 |
+
except Exception as exc: # noqa: BLE001
|
| 667 |
+
raise _denied(exc) from exc
|
| 668 |
+
final, claimed = _claim(rt, record["request_id"], state, me)
|
| 669 |
+
if not claimed or not final:
|
| 670 |
+
return {"state": (final or record).get("state")} # Another click decided first.
|
| 671 |
+
if action == "approve":
|
| 672 |
+
try:
|
| 673 |
+
_approve_grant(session, ref, asker, principal, role)
|
| 674 |
+
except Exception as exc: # noqa: BLE001
|
| 675 |
+
_unclaim(rt, record["request_id"], state, me)
|
| 676 |
+
raise _denied(exc) from exc
|
| 677 |
+
_close_cards(rt, final)
|
| 678 |
+
_tell_asker(session, final)
|
| 679 |
+
return {"state": final["state"]}
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
TOOLS = ({"name": "agent_message", "schema": SCHEMA, "fn": agent_message, "effect": "write"},)
|
api/agent_runtime.py
CHANGED
|
@@ -1,10 +1,14 @@
|
|
| 1 |
"""Server-side Assistant turns and principal-bound delete confirmation (C10)."""
|
|
|
|
| 2 |
import copy
|
| 3 |
import contextvars
|
| 4 |
import hashlib
|
|
|
|
| 5 |
import inspect
|
| 6 |
import json
|
| 7 |
import logging
|
|
|
|
|
|
|
| 8 |
import threading
|
| 9 |
import time
|
| 10 |
import uuid
|
|
@@ -18,8 +22,22 @@ import turn_control
|
|
| 18 |
import turn_audit
|
| 19 |
|
| 20 |
PENDING_TTL_S = 600
|
|
|
|
|
|
|
|
|
|
| 21 |
DOORS = {"app", "whatsapp", "slack", "wake"}
|
| 22 |
_MEMORY_BLOCK = contextvars.ContextVar("agent_memory_block", default=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
_COMPACTION_LOCKS = {}
|
| 24 |
_LOCKS_GUARD = threading.Lock()
|
| 25 |
_LOG = logging.getLogger(__name__)
|
|
@@ -110,6 +128,8 @@ def _plain(value):
|
|
| 110 |
|
| 111 |
def _result(reply="", *, refused=None, turn=None):
|
| 112 |
turn = turn or {}
|
|
|
|
|
|
|
| 113 |
return {"reply": _plain(reply), "toolCalls": turn.get("toolCalls", []),
|
| 114 |
"pendingDelete": turn.get("pendingDelete"), "artifacts": turn.get("artifacts", []),
|
| 115 |
"refused": _plain(refused) if refused else None}
|
|
@@ -203,8 +223,267 @@ def _dispatch(session, name, args):
|
|
| 203 |
entry = agent_tools.registered().get(name)
|
| 204 |
if entry is not None:
|
| 205 |
fn = entry["fn"]
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
|
| 210 |
def _owner(tenant, username):
|
|
@@ -261,23 +540,249 @@ def _summary(name, args, session=None):
|
|
| 261 |
return f"Remove {subject}."
|
| 262 |
|
| 263 |
|
| 264 |
-
def
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
entry = {"id": pid, "tool": name, "args": copy.deepcopy(args), "summary": _summary(name, args, session),
|
| 268 |
-
"tenant": session.tenant, "username": session.uname, "door": door,
|
| 269 |
-
"createdAt": now, "expiresAt": now + PENDING_TTL_S}
|
| 270 |
|
| 271 |
def update(raw):
|
| 272 |
pending = (raw or {}).get("pending", {})
|
| 273 |
pending = {key: value for key, value in pending.items() if value["expiresAt"] > now}
|
| 274 |
-
pending[
|
| 275 |
return {"pending": pending}
|
| 276 |
|
| 277 |
session.runtime.update(_pending_key(session), update, flush="sync")
|
| 278 |
return {key: entry[key] for key in ("id", "summary", "expiresAt")}
|
| 279 |
|
| 280 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
def _ref(result):
|
| 282 |
if not isinstance(result, dict):
|
| 283 |
return None
|
|
@@ -293,7 +798,9 @@ def _ref(result):
|
|
| 293 |
return ids[0] if isinstance(ids, list) and len(ids) == 1 else None
|
| 294 |
|
| 295 |
|
| 296 |
-
def _record_artifact(session, door, name, args, result):
|
|
|
|
|
|
|
| 297 |
try:
|
| 298 |
import assistant_artifacts
|
| 299 |
except ImportError:
|
|
@@ -303,6 +810,10 @@ def _record_artifact(session, door, name, args, result):
|
|
| 303 |
"view" if name.startswith("view_") else
|
| 304 |
"schedule" if name.startswith("schedule_") or name == "reminder_create" else "run")
|
| 305 |
value = result if isinstance(result, dict) else {}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
view = args.get("view") if isinstance(args.get("view"), dict) else {}
|
| 307 |
made = next((value[key] for key in ("workbook", "view", "schedule", "application")
|
| 308 |
if isinstance(value.get(key), dict)), {})
|
|
@@ -323,9 +834,13 @@ def _record_artifact(session, door, name, args, result):
|
|
| 323 |
cursor = page.get("nextCursor")
|
| 324 |
if cursor is None:
|
| 325 |
break
|
| 326 |
-
|
| 327 |
"kind": kind, "ref": str(ref) if ref is not None else None, "title": _plain(title),
|
| 328 |
-
"door": door, "toolCall": {"name": name, "args": copy.deepcopy(args)}, "createdAt": time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
|
| 330 |
|
| 331 |
def execute(session, name, args, *, door, turn):
|
|
@@ -347,21 +862,33 @@ def _execute(session, name, args, *, door, turn):
|
|
| 347 |
return {"ok": False, "error": "Evaluation turns permit read tools only."}
|
| 348 |
if not isinstance(args, dict):
|
| 349 |
raise ValueError("Tool arguments must be an object.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
if effect == "delete":
|
| 351 |
pending = _pending(session, door, name, args)
|
| 352 |
turn["pendingDelete"] = pending
|
| 353 |
call.update(ok=True, ref=pending["id"])
|
| 354 |
return {"ok": True, "pendingDelete": pending,
|
| 355 |
"message": "Nothing is removed until the user confirms this delete."}
|
| 356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
if isinstance(result, dict) and (result.get("ok") is False or result.get("refused")):
|
| 358 |
return result
|
| 359 |
call.update(ok=True, ref=_ref(result))
|
| 360 |
-
if
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
turn["artifacts"].append(artifact_id)
|
| 364 |
-
return result
|
| 365 |
except Exception as exc:
|
| 366 |
# Plugin failures are tool results too, so no tool exception escapes to a chat door.
|
| 367 |
return {"ok": False, "error": _sentence(exc)}
|
|
@@ -387,12 +914,14 @@ def cancel(rt, principal, id):
|
|
| 387 |
return False
|
| 388 |
|
| 389 |
|
| 390 |
-
def run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None, model=None
|
|
|
|
| 391 |
handle = turn_control.TurnHandle((principal["tenant"], principal["username"]), door, ())
|
| 392 |
result = None
|
| 393 |
try:
|
| 394 |
result = _run_turn(rt, principal, door, text, confirm=confirm, chat=chat,
|
| 395 |
-
context=context, model=model, audit_handle=handle
|
|
|
|
| 396 |
return result
|
| 397 |
finally:
|
| 398 |
if not handle.audit_delegated and (result or {}).get("status") != "code_received" and not (confirm is None and door in {"whatsapp", "slack"}
|
|
@@ -402,9 +931,14 @@ def run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None
|
|
| 402 |
turn_audit.write(handle, rt, result=result)
|
| 403 |
|
| 404 |
|
| 405 |
-
def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None, model=None, audit_handle=None
|
|
|
|
| 406 |
if door not in DOORS:
|
| 407 |
raise ValueError("That Assistant door is not available.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
also_as = principal.get("also_as") or []
|
| 409 |
if any(member is None for member in also_as):
|
| 410 |
return _result(refused="A member of this channel has not linked a Loopable account.")
|
|
@@ -428,14 +962,21 @@ def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=Non
|
|
| 428 |
if confirm is not None:
|
| 429 |
pid = str(confirm)
|
| 430 |
owner = _owner(session.tenant, session.uname)
|
|
|
|
|
|
|
|
|
|
| 431 |
if _foreign_id(pid, owner):
|
| 432 |
foreign = session.runtime.get("agent_pending_" + pid.split(".")[0]) or {}
|
| 433 |
-
sentence = ("Only the person who asked can confirm this
|
| 434 |
-
if pid in foreign.get("pending", {}) else
|
| 435 |
return _result(refused=sentence)
|
| 436 |
entry = _take(session, pid)
|
| 437 |
if entry is None:
|
| 438 |
-
return _result(refused=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 439 |
if entry["expiresAt"] <= time.time():
|
| 440 |
return _result(refused="That delete request expired. Ask again to delete it.")
|
| 441 |
turn = {"toolCalls": [{"name": entry["tool"], "args": entry["args"], "effect": "delete",
|
|
@@ -451,14 +992,20 @@ def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=Non
|
|
| 451 |
return _result(refused=_sentence(exc), turn=turn)
|
| 452 |
token = query._AGENT_DOOR.set(door)
|
| 453 |
memory_token = _MEMORY_BLOCK.set(memory_block(rt, principal))
|
| 454 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
try:
|
| 456 |
body = {"question": text}
|
| 457 |
if model is not None:
|
| 458 |
body["model"] = model
|
| 459 |
response = query._submit(body, session, chat=chat, also_as=also_as, door=door, audit_handle=audit_handle)
|
| 460 |
finally:
|
|
|
|
| 461 |
query._AGENT_CONTEXT.reset(context_token)
|
|
|
|
| 462 |
_MEMORY_BLOCK.reset(memory_token)
|
| 463 |
query._AGENT_DOOR.reset(token)
|
| 464 |
if response.get("status") in {"joined", "stopped", "paused", "code_received"}:
|
|
@@ -466,8 +1013,11 @@ def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=Non
|
|
| 466 |
message = response["message"]
|
| 467 |
if door == "slack":
|
| 468 |
maybe_compact(rt, session.uname, chat=chat)
|
| 469 |
-
|
| 470 |
-
|
|
|
|
|
|
|
|
|
|
| 471 |
except (external_access.ExternalAccessError, HTTPException, ValueError) as exc:
|
| 472 |
return _result(refused=_sentence(exc))
|
| 473 |
|
|
|
|
| 1 |
"""Server-side Assistant turns and principal-bound delete confirmation (C10)."""
|
| 2 |
+
import base64
|
| 3 |
import copy
|
| 4 |
import contextvars
|
| 5 |
import hashlib
|
| 6 |
+
import importlib
|
| 7 |
import inspect
|
| 8 |
import json
|
| 9 |
import logging
|
| 10 |
+
import os
|
| 11 |
+
import re
|
| 12 |
import threading
|
| 13 |
import time
|
| 14 |
import uuid
|
|
|
|
| 22 |
import turn_audit
|
| 23 |
|
| 24 |
PENDING_TTL_S = 600
|
| 25 |
+
#: R100: a change asked on WhatsApp waits this long for the user's YES.
|
| 26 |
+
CHANGE_TTL_S = 900
|
| 27 |
+
CHANGE_PREVIEW_LINES = 6
|
| 28 |
DOORS = {"app", "whatsapp", "slack", "wake"}
|
| 29 |
_MEMORY_BLOCK = contextvars.ContextVar("agent_memory_block", default=None)
|
| 30 |
+
#: The calls this WhatsApp turn holds for YES; None outside a WhatsApp model turn.
|
| 31 |
+
_HELD = contextvars.ContextVar("agent_held_change", default=None)
|
| 32 |
+
_PLACEHOLDER = re.compile(r"\bpending_(\d+)\b")
|
| 33 |
+
#: R99: the photos and PDFs this turn carries; None on a turn without files.
|
| 34 |
+
_ATTACHMENTS = contextvars.ContextVar("agent_attachments", default=None)
|
| 35 |
+
_PRODUCING_TURN = contextvars.ContextVar("agent_producing_turn", default=None)
|
| 36 |
+
_UNSET = object()
|
| 37 |
+
IMAGE_INPUT_ENV = "AIOS_ASSISTANT_IMAGE_INPUT"
|
| 38 |
+
ATTACHMENT_IMAGE_MIMES = {"image/jpeg", "image/png", "image/webp"}
|
| 39 |
+
ATTACHMENT_PDF_MIME = "application/pdf"
|
| 40 |
+
MAX_ATTACHMENTS = 4
|
| 41 |
_COMPACTION_LOCKS = {}
|
| 42 |
_LOCKS_GUARD = threading.Lock()
|
| 43 |
_LOG = logging.getLogger(__name__)
|
|
|
|
| 128 |
|
| 129 |
def _result(reply="", *, refused=None, turn=None):
|
| 130 |
turn = turn or {}
|
| 131 |
+
notes = dict.fromkeys(call["linkNote"] for call in turn.get("toolCalls", []) if call.get("linkNote"))
|
| 132 |
+
reply = " ".join([reply, *(note for note in notes if note not in reply)]).strip()
|
| 133 |
return {"reply": _plain(reply), "toolCalls": turn.get("toolCalls", []),
|
| 134 |
"pendingDelete": turn.get("pendingDelete"), "artifacts": turn.get("artifacts", []),
|
| 135 |
"refused": _plain(refused) if refused else None}
|
|
|
|
| 223 |
entry = agent_tools.registered().get(name)
|
| 224 |
if entry is not None:
|
| 225 |
fn = entry["fn"]
|
| 226 |
+
result = fn(args) if len(inspect.signature(fn).parameters) == 1 else fn(session, args)
|
| 227 |
+
else:
|
| 228 |
+
result = external_tools.dispatch(_agent_tool_context(session), name, args)
|
| 229 |
+
producing = _PRODUCING_TURN.get()
|
| 230 |
+
if producing is not None and producing[0] is session:
|
| 231 |
+
_observe_sources(session, producing[1], name, args, result)
|
| 232 |
+
return result
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _merge_sources(session, turn, sources):
|
| 236 |
+
"""Keep validated database keys, with unknown evidence sticky for the whole turn."""
|
| 237 |
+
try:
|
| 238 |
+
if not isinstance(sources, list) or any(not isinstance(key, str) or not key.strip() for key in sources):
|
| 239 |
+
raise ValueError("Unknown artifact provenance.")
|
| 240 |
+
import deps
|
| 241 |
+
also_as = turn.get("also_as") or []
|
| 242 |
+
kwargs = {"mode": "schema"}
|
| 243 |
+
if also_as:
|
| 244 |
+
kwargs["also_as"] = also_as
|
| 245 |
+
keys = list(dict.fromkeys(key.strip() for key in sources))
|
| 246 |
+
for key in keys:
|
| 247 |
+
deps.assistant_read_scope(session, key, **kwargs)
|
| 248 |
+
turn["artifactSources"] = sorted(set(turn.get("artifactSources", [])) | set(keys))
|
| 249 |
+
except Exception:
|
| 250 |
+
turn["artifactSourcesUnknown"] = True
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _turn_sources(turn):
|
| 254 |
+
if turn.get("artifactSourcesUnknown") or "artifactSources" not in turn:
|
| 255 |
+
return None
|
| 256 |
+
return copy.deepcopy(turn["artifactSources"])
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def producing_turn_sources(session, username=None):
|
| 260 |
+
"""Return caller-bound source proof for a file producer, or None when unknown."""
|
| 261 |
+
producing = _PRODUCING_TURN.get()
|
| 262 |
+
if producing is None:
|
| 263 |
+
return None
|
| 264 |
+
caller, turn = producing
|
| 265 |
+
owned = (caller is session if username is None
|
| 266 |
+
else caller.runtime is session and caller.uname == username)
|
| 267 |
+
if owned:
|
| 268 |
+
_seed_sources(caller, turn)
|
| 269 |
+
return _turn_sources(turn) if owned else None
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _argument_sources(value, depth=0):
|
| 273 |
+
if depth > 12:
|
| 274 |
+
return None
|
| 275 |
+
found = []
|
| 276 |
+
members = value.items() if isinstance(value, dict) else enumerate(value) if isinstance(value, list) else ()
|
| 277 |
+
for key, item in members:
|
| 278 |
+
if key in ("database", "sourceDatabase", "compatibleDatabases"):
|
| 279 |
+
keys = item if key == "compatibleDatabases" else [item]
|
| 280 |
+
if not isinstance(keys, list) or any(not isinstance(k, str) or not k.strip() for k in keys):
|
| 281 |
+
return None
|
| 282 |
+
found.extend(keys)
|
| 283 |
+
nested = _argument_sources(item, depth + 1)
|
| 284 |
+
if nested is None:
|
| 285 |
+
return None
|
| 286 |
+
found.extend(nested)
|
| 287 |
+
return found
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _seed_sources(session, turn):
|
| 291 |
+
if not turn.get("artifactSourcesSeeded"):
|
| 292 |
+
turn["artifactSourcesSeeded"] = True
|
| 293 |
+
if "memorySources" in turn:
|
| 294 |
+
_merge_sources(session, turn, [source.get("database") if isinstance(source, dict) else None
|
| 295 |
+
for source in turn["memorySources"]])
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def _observe_sources(session, turn, name, args, result):
|
| 299 |
+
if isinstance(result, dict) and (result.get("ok") is False or result.get("refused")):
|
| 300 |
+
return
|
| 301 |
+
_seed_sources(session, turn)
|
| 302 |
+
value = result if isinstance(result, dict) else {}
|
| 303 |
+
if "sources" in value:
|
| 304 |
+
_merge_sources(session, turn, value["sources"])
|
| 305 |
+
databases = _argument_sources(args)
|
| 306 |
+
if databases is None:
|
| 307 |
+
turn["artifactSourcesUnknown"] = True
|
| 308 |
+
databases = []
|
| 309 |
+
if isinstance(value.get("database"), str):
|
| 310 |
+
databases.append(value["database"])
|
| 311 |
+
if databases:
|
| 312 |
+
_merge_sources(session, turn, databases)
|
| 313 |
+
elif "sources" not in value and agent_tools.classify(name, args) == "read":
|
| 314 |
+
turn["artifactSourcesUnknown"] = True
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _optional_module(name):
|
| 318 |
+
try:
|
| 319 |
+
return importlib.import_module(name)
|
| 320 |
+
except ModuleNotFoundError as exc:
|
| 321 |
+
if exc.name != name:
|
| 322 |
+
raise
|
| 323 |
+
return None
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _artifact_result(session, artifact_id, result, call, turn):
|
| 327 |
+
"""Attach only the caller's stored artifact link and conservative turn provenance."""
|
| 328 |
+
artifacts = _optional_module("assistant_artifacts")
|
| 329 |
+
get = getattr(artifacts, "get", None)
|
| 330 |
+
row = get(session.runtime, session.uname, artifact_id) if get else None
|
| 331 |
+
if row is None:
|
| 332 |
+
return result
|
| 333 |
+
if "sources" in row:
|
| 334 |
+
_merge_sources(session, turn, row["sources"])
|
| 335 |
+
sources = _turn_sources(turn)
|
| 336 |
+
amazon = sources is None or any(key.startswith("ut_amzn_") for key in sources) or row.get("amazon") is True
|
| 337 |
+
# The row lookup binds this update to the caller's tenant and owner.
|
| 338 |
+
import assistant_log
|
| 339 |
+
owner = assistant_log._hash(session.runtime, session.uname)
|
| 340 |
+
seq = artifacts._seq(owner, artifact_id)
|
| 341 |
+
if seq is not None and (row.get("sources", _UNSET) != sources or row.get("amazon", _UNSET) != amazon):
|
| 342 |
+
def update(raw):
|
| 343 |
+
doc = copy.deepcopy(raw)
|
| 344 |
+
for item in doc.get("items", []):
|
| 345 |
+
if item.get("id") == artifact_id:
|
| 346 |
+
item.update(sources=copy.deepcopy(sources), amazon=amazon)
|
| 347 |
+
return doc
|
| 348 |
+
session.runtime.update(artifacts._chunk_key(owner, seq // artifacts.CHUNK_ITEMS), update, flush="sync")
|
| 349 |
+
fields = {"sources": sources, "amazon": amazon}
|
| 350 |
+
links = getattr(artifacts, "link_fields", None)
|
| 351 |
+
if links:
|
| 352 |
+
fields.update(links(row))
|
| 353 |
+
call.update(copy.deepcopy(fields))
|
| 354 |
+
return {**result, **fields} if isinstance(result, dict) else result
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _after_dispatch(session, door, name, args, result, call, turn, effect):
|
| 358 |
+
_observe_sources(session, turn, name, args, result)
|
| 359 |
+
if name == "agent_message":
|
| 360 |
+
return result
|
| 361 |
+
if name == "open_items" and isinstance(result, dict):
|
| 362 |
+
if not result.get("view"):
|
| 363 |
+
return result
|
| 364 |
+
view = _after_dispatch(session, door, "view_upsert", result["viewArgs"], result["view"],
|
| 365 |
+
call, turn, effect)
|
| 366 |
+
return {**result, **{key: view[key] for key in ("sources", "amazon", "link") if key in view}}
|
| 367 |
+
snapshot = _optional_module("artifact_snapshot")
|
| 368 |
+
snapshot_id = snapshot.capture(session, door, name, args, result, turn) if snapshot else None
|
| 369 |
+
if snapshot_id:
|
| 370 |
+
result = _artifact_result(session, snapshot_id, result, call, turn)
|
| 371 |
+
file_id = (result.get("fileId") or result.get("file_id")) if isinstance(result, dict) else None
|
| 372 |
+
artifact_id = None
|
| 373 |
+
if file_id:
|
| 374 |
+
files = _optional_module("assistant_files")
|
| 375 |
+
owned = getattr(files, "owned_metadata", None)
|
| 376 |
+
metadata = owned(session.runtime, session.uname, file_id) if owned else None
|
| 377 |
+
artifact_id = metadata.get("artifactId") if metadata else None
|
| 378 |
+
if not artifact_id and effect == "write":
|
| 379 |
+
artifact_id = _record_artifact(session, door, name, args, result, sources=_turn_sources(turn))
|
| 380 |
+
if artifact_id:
|
| 381 |
+
if artifact_id not in turn["artifacts"]:
|
| 382 |
+
turn["artifacts"].append(artifact_id)
|
| 383 |
+
result = _artifact_result(session, artifact_id, result, call, turn)
|
| 384 |
+
call["sources"] = _turn_sources(turn)
|
| 385 |
+
return result
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _offered_tools():
|
| 389 |
+
offered = set(external_tools.TOOLS)
|
| 390 |
+
try:
|
| 391 |
+
agent_tools.load_modules()
|
| 392 |
+
offered |= set(agent_tools.registered())
|
| 393 |
+
except Exception:
|
| 394 |
+
_LOG.warning("Assistant tools did not load for the door guidance.", exc_info=True)
|
| 395 |
+
return offered
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def whatsapp_guidance(offered=None):
|
| 399 |
+
"""R98 in plain words, naming only the tools this turn is offered."""
|
| 400 |
+
offered = _offered_tools() if offered is None else set(offered)
|
| 401 |
+
lines = ["You are answering on WhatsApp. Keep a short answer as plain text."]
|
| 402 |
+
if "make_xlsx" in offered:
|
| 403 |
+
lines.append("For a table over 10 rows, call make_xlsx and give its link.")
|
| 404 |
+
else:
|
| 405 |
+
lines.append("For a table over 10 rows, show the first 10 rows and say the rest is in Loopable.")
|
| 406 |
+
if "make_image" in offered:
|
| 407 |
+
lines.append("For a chart, call make_image.")
|
| 408 |
+
lines.append("After you create a Sheet, call make_image of it and give the Sheet's link.")
|
| 409 |
+
else:
|
| 410 |
+
lines.append("After you create a Sheet, give the Sheet's link.")
|
| 411 |
+
if "make_pdf" in offered:
|
| 412 |
+
lines.append("When the user asks for a PDF, call make_pdf.")
|
| 413 |
+
if "make_xlsx" in offered:
|
| 414 |
+
lines.append("When the user asks for an Excel file, call make_xlsx.")
|
| 415 |
+
lines.append("On WhatsApp a change waits for the user's YES, so plan every step, "
|
| 416 |
+
"then say in a few words what will change.")
|
| 417 |
+
return " ".join(lines)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def reads_images():
|
| 421 |
+
"""True when the setting says the Assistant model reads images (glm-4.7-flash reads text only)."""
|
| 422 |
+
# A literal name, so the env walk resolves it; IMAGE_INPUT_ENV names the same var.
|
| 423 |
+
return os.environ.get("AIOS_ASSISTANT_IMAGE_INPUT", "").strip().lower() in {"1", "true"}
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def _attachments(value):
|
| 427 |
+
"""Validate a turn's files: photos only when the model reads images, PDFs always."""
|
| 428 |
+
if value is None:
|
| 429 |
+
return None
|
| 430 |
+
if not isinstance(value, list) or not value or len(value) > MAX_ATTACHMENTS:
|
| 431 |
+
raise ValueError("A turn can carry one to four files.")
|
| 432 |
+
checked = []
|
| 433 |
+
for item in value:
|
| 434 |
+
if not isinstance(item, dict) or not isinstance(item.get("data"), bytes) or not item["data"]:
|
| 435 |
+
raise ValueError("That file could not be read.")
|
| 436 |
+
kind, mime = item.get("kind"), item.get("mime")
|
| 437 |
+
if kind == "image" and mime in ATTACHMENT_IMAGE_MIMES:
|
| 438 |
+
if not reads_images():
|
| 439 |
+
raise ValueError("I cannot read photos yet. Type what it shows, or send it as a PDF.")
|
| 440 |
+
elif not (kind == "document" and mime == ATTACHMENT_PDF_MIME):
|
| 441 |
+
raise ValueError("I can read photos and PDFs only.")
|
| 442 |
+
filename = item.get("filename") if isinstance(item.get("filename"), str) else None
|
| 443 |
+
caption = item.get("caption") if isinstance(item.get("caption"), str) else None
|
| 444 |
+
checked.append({"kind": kind, "mime": mime, "data": item["data"],
|
| 445 |
+
"filename": (filename or "").strip()[:120] or None, "caption": caption})
|
| 446 |
+
return checked
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def has_attachments():
|
| 450 |
+
"""True inside a turn that carries files."""
|
| 451 |
+
return bool(_ATTACHMENTS.get())
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def user_content(question):
|
| 455 |
+
"""The user message content: the question alone, or a content list with this turn's files."""
|
| 456 |
+
items = _ATTACHMENTS.get()
|
| 457 |
+
if not items:
|
| 458 |
+
return question
|
| 459 |
+
parts = [{"type": "text", "text": question}]
|
| 460 |
+
for item in items:
|
| 461 |
+
encoded = base64.b64encode(item["data"]).decode("ascii")
|
| 462 |
+
if item["kind"] == "image":
|
| 463 |
+
if reads_images():
|
| 464 |
+
parts.append({"type": "image_url",
|
| 465 |
+
"image_url": {"url": f"data:{item['mime']};base64,{encoded}"}})
|
| 466 |
+
else:
|
| 467 |
+
parts.append({"type": "file", "file": {
|
| 468 |
+
"filename": item["filename"] or "document.pdf",
|
| 469 |
+
"file_data": "data:application/pdf;base64," + encoded}})
|
| 470 |
+
return parts
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def _attachment_line(items):
|
| 474 |
+
named = [("a photo" if item["kind"] == "image" else "a PDF")
|
| 475 |
+
+ (f" named {item['filename']}" if item["filename"] else "") for item in items]
|
| 476 |
+
return "The user sent " + ", ".join(named) + ". Read it before you answer."
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def door_context(door, context):
|
| 480 |
+
"""The turn context: the caller's context, the door guidance on WhatsApp, and one line naming the files."""
|
| 481 |
+
caller = context if isinstance(context, str) and context else None
|
| 482 |
+
items = _ATTACHMENTS.get()
|
| 483 |
+
files = _attachment_line(items) if items else None
|
| 484 |
+
if door != "whatsapp":
|
| 485 |
+
return "\n\n".join(part for part in (caller, files) if part) or None
|
| 486 |
+
return "\n\n".join(part for part in (caller, whatsapp_guidance(), files) if part)
|
| 487 |
|
| 488 |
|
| 489 |
def _owner(tenant, username):
|
|
|
|
| 540 |
return f"Remove {subject}."
|
| 541 |
|
| 542 |
|
| 543 |
+
def _put(session, entry):
|
| 544 |
+
"""Store one owner-bound pending entry and drop the expired ones."""
|
| 545 |
+
now = entry["createdAt"]
|
|
|
|
|
|
|
|
|
|
| 546 |
|
| 547 |
def update(raw):
|
| 548 |
pending = (raw or {}).get("pending", {})
|
| 549 |
pending = {key: value for key, value in pending.items() if value["expiresAt"] > now}
|
| 550 |
+
pending[entry["id"]] = entry
|
| 551 |
return {"pending": pending}
|
| 552 |
|
| 553 |
session.runtime.update(_pending_key(session), update, flush="sync")
|
| 554 |
return {key: entry[key] for key in ("id", "summary", "expiresAt")}
|
| 555 |
|
| 556 |
|
| 557 |
+
def _pending(session, door, name, args):
|
| 558 |
+
now = time.time()
|
| 559 |
+
pid = _owner(session.tenant, session.uname) + "." + uuid.uuid4().hex
|
| 560 |
+
return _put(session, {"id": pid, "tool": name, "args": copy.deepcopy(args),
|
| 561 |
+
"summary": _summary(name, args, session),
|
| 562 |
+
"tenant": session.tenant, "username": session.uname, "door": door,
|
| 563 |
+
"createdAt": now, "expiresAt": now + PENDING_TTL_S})
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def waits_for_yes(door, name, args, effect):
|
| 567 |
+
"""R100: on WhatsApp an app write tool or any delete is held for the user's YES."""
|
| 568 |
+
if door != "whatsapp":
|
| 569 |
+
return False
|
| 570 |
+
return effect in {"write", "delete"}
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def _label(value, limit=60):
|
| 574 |
+
text = " ".join(_plain(str(value)).split()).rstrip(". ")
|
| 575 |
+
return text if len(text) <= limit else text[:limit - 3].rstrip() + "..."
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
_SHEET_PARTS = {"sheet_set_styles": "styles", "sheet_set_dimensions": "sizes",
|
| 579 |
+
"sheet_set_validation": "dropdowns", "sheet_set_freeze": "frozen rows",
|
| 580 |
+
"sheet_add_rule": "a format rule", "sheet_set_chart": "a chart",
|
| 581 |
+
"sheet_structure": "rows or columns"}
|
| 582 |
+
_PAST = {"Create": "Created", "Write": "Wrote", "Save": "Saved", "Change": "Changed",
|
| 583 |
+
"Remove": "Removed", "Add": "Added", "Bind": "Bound", "Run": "Ran", "Clear": "Cleared"}
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def _change_line(name, args):
|
| 587 |
+
"""One plain imperative line for one held write, built from its name and arguments."""
|
| 588 |
+
name = name if isinstance(name, str) else ""
|
| 589 |
+
action = args.get("action")
|
| 590 |
+
inner = args.get("arguments") if isinstance(args.get("arguments"), dict) else {}
|
| 591 |
+
tab = args.get("tab") or args.get("worksheet")
|
| 592 |
+
on_tab = (" on the new tab" if isinstance(tab, str) and _PLACEHOLDER.fullmatch(tab)
|
| 593 |
+
else f" on tab {_label(tab)}" if tab else "")
|
| 594 |
+
where = f" in {_label(args['database'])}" if args.get("database") else ""
|
| 595 |
+
if name == "sheet_create_workbook" or (name == "workbook_object" and action == "create"):
|
| 596 |
+
title = args.get("name") or inner.get("name")
|
| 597 |
+
return f"Create workbook {_label(title)}." if title else "Create a workbook."
|
| 598 |
+
if name == "sheet_add_tab" or (name == "worksheet_object" and action == "add"):
|
| 599 |
+
title = args.get("name") or inner.get("name")
|
| 600 |
+
return f"Add tab {_label(title)}." if title else "Add a tab."
|
| 601 |
+
if name == "sheet_write_cells":
|
| 602 |
+
count = len(args["cells"]) if isinstance(args.get("cells"), dict) else 0
|
| 603 |
+
return f"Write {count} cell{'' if count == 1 else 's'}{on_tab}."
|
| 604 |
+
if name == "range_object":
|
| 605 |
+
target = f"range {_label(args['range'])}" if args.get("range") else "cells"
|
| 606 |
+
return f"{'Clear' if action == 'clear' else 'Write'} {target}{on_tab}."
|
| 607 |
+
if name == "sheet_set_binding":
|
| 608 |
+
return f"Bind cell {_label(args.get('addr'))}{on_tab}."
|
| 609 |
+
if name == "sheet_save_template":
|
| 610 |
+
return f"Save template {_label(args.get('name'))}."
|
| 611 |
+
if name in _SHEET_PARTS:
|
| 612 |
+
return f"Change {_SHEET_PARTS[name]}{on_tab}."
|
| 613 |
+
if name == "view_upsert" or (name == "view_object" and action == "upsert"):
|
| 614 |
+
view = args.get("view") if isinstance(args.get("view"), dict) else {}
|
| 615 |
+
title = view.get("name") or view.get("id")
|
| 616 |
+
return f"Save view {_label(title)}." if title else "Save a view."
|
| 617 |
+
if name == "app_upsert":
|
| 618 |
+
verb = "Change" if args.get("app_id") else "Create"
|
| 619 |
+
title = args.get("name") or args.get("app_id")
|
| 620 |
+
return f"{verb} app {_label(title)}." if title else f"{verb} an app."
|
| 621 |
+
if name == "database_object":
|
| 622 |
+
record = f" on record {_label(args['record_id'])}" if args.get("record_id") is not None else ""
|
| 623 |
+
field = args.get("field") if isinstance(args.get("field"), dict) else {}
|
| 624 |
+
if action == "record_create":
|
| 625 |
+
return f"Add a record{where}."
|
| 626 |
+
if action == "record_update":
|
| 627 |
+
keys = list(args["values"]) if isinstance(args.get("values"), dict) else []
|
| 628 |
+
what = (" and ".join(_label(key) for key in keys) if 0 < len(keys) <= 3
|
| 629 |
+
else f"{len(keys)} fields" if keys else "values")
|
| 630 |
+
return f"Change {what}{record}."
|
| 631 |
+
if action == "field_create":
|
| 632 |
+
title = field.get("name") or field.get("label") or field.get("key")
|
| 633 |
+
return f"Add field {_label(title)}{where}." if title else f"Add a field{where}."
|
| 634 |
+
if action == "field_update":
|
| 635 |
+
title = args.get("field_key") or field.get("name")
|
| 636 |
+
return f"Change field {_label(title)}{where}." if title else f"Change a field{where}."
|
| 637 |
+
if name.endswith("_object"):
|
| 638 |
+
return f"Change {name.removesuffix('_object')}{on_tab}."
|
| 639 |
+
return f"Run {_label(name.replace('_', ' '))}." if name else "Run a change."
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def _change_lines(name, args, session=None):
|
| 643 |
+
"""The preview lines for one held call: a delete names its target, a batch each operation."""
|
| 644 |
+
args = args if isinstance(args, dict) else {}
|
| 645 |
+
if name == "validated_batch" and isinstance(args.get("operations"), list):
|
| 646 |
+
lines = []
|
| 647 |
+
for operation in args["operations"]:
|
| 648 |
+
if isinstance(operation, dict):
|
| 649 |
+
lines.extend(_change_lines(operation.get("name"), operation.get("arguments"), session))
|
| 650 |
+
return lines or ["Run a batch of changes."]
|
| 651 |
+
if agent_tools.classify(name, args) == "delete":
|
| 652 |
+
return [_summary(name, args, session)]
|
| 653 |
+
return [_change_line(name, args)]
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def _capped(lines):
|
| 657 |
+
shown = list(lines[:CHANGE_PREVIEW_LINES])
|
| 658 |
+
rest = len(lines) - len(shown)
|
| 659 |
+
if rest:
|
| 660 |
+
shown.append(f"And {rest} more step{'' if rest == 1 else 's'}.")
|
| 661 |
+
return shown
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def _past(line):
|
| 665 |
+
verb, _, rest = line.partition(" ")
|
| 666 |
+
return f"{_PAST[verb]} {rest}" if verb in _PAST and rest else line
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def _hold(session, name, args, effect, held, turn):
|
| 670 |
+
import assistant_write_preview
|
| 671 |
+
_seed_sources(session, turn)
|
| 672 |
+
ref = f"pending_{len(held) + 1}"
|
| 673 |
+
refs = {step["ref"]: _ref(step["preview"]["result"]) for step in held
|
| 674 |
+
if _ref(step["preview"]["result"]) is not None}
|
| 675 |
+
resolved = _fill(args, refs, len(held) + 1)
|
| 676 |
+
if _PLACEHOLDER.search(json.dumps(resolved)):
|
| 677 |
+
raise ValueError("A change can only use an earlier step's created object.")
|
| 678 |
+
preview = assistant_write_preview.prepare(session, name, resolved, prior=held)
|
| 679 |
+
_observe_sources(session, turn, name, resolved, preview["result"])
|
| 680 |
+
held.append({"tool": name, "args": copy.deepcopy(args), "effect": effect, "ref": ref,
|
| 681 |
+
"resolvedArgs": resolved, "preview": preview,
|
| 682 |
+
"context": {key: copy.deepcopy(turn[key]) for key in
|
| 683 |
+
("memorySources", "memoryEvidenceSources", "memoryCompanyRequested", "door")
|
| 684 |
+
if key in turn},
|
| 685 |
+
"lines": assistant_write_preview.lines(preview, name, resolved, session),
|
| 686 |
+
"sources": _turn_sources(turn)})
|
| 687 |
+
return ref
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def _store_change(session, door, held, *, turn=None):
|
| 691 |
+
"""Store the turn's held calls as ONE pending change, owner-bound like a delete."""
|
| 692 |
+
now = time.time()
|
| 693 |
+
proof = {}
|
| 694 |
+
for sources in [*(step.get("sources") for step in held),
|
| 695 |
+
*(call.get("sources") for call in (turn or {}).get("toolCalls", [])
|
| 696 |
+
if call.get("ok") and not call.get("held"))]:
|
| 697 |
+
_merge_sources(session, proof, sources)
|
| 698 |
+
sources = _turn_sources(proof)
|
| 699 |
+
# Every artifact made by YES belongs to the full producing turn, including late reads.
|
| 700 |
+
held = [{**step, "sources": copy.deepcopy(sources)} for step in held]
|
| 701 |
+
lines = [line for step in held for line in step["lines"]]
|
| 702 |
+
return _put(session, {"id": _owner(session.tenant, session.uname) + "." + uuid.uuid4().hex,
|
| 703 |
+
"kind": "change", "steps": copy.deepcopy(held),
|
| 704 |
+
"summary": "\n".join(_capped(lines)),
|
| 705 |
+
"tenant": session.tenant, "username": session.uname, "door": door,
|
| 706 |
+
"createdAt": now, "expiresAt": now + CHANGE_TTL_S})
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _fill(value, refs, index):
|
| 710 |
+
"""Replace each earlier step's placeholder with the real id that step made."""
|
| 711 |
+
if isinstance(value, dict):
|
| 712 |
+
return {key: _fill(item, refs, index) for key, item in value.items()}
|
| 713 |
+
if isinstance(value, list):
|
| 714 |
+
return [_fill(item, refs, index) for item in value]
|
| 715 |
+
if not isinstance(value, str):
|
| 716 |
+
return value
|
| 717 |
+
|
| 718 |
+
def swap(match):
|
| 719 |
+
step = int(match.group(1))
|
| 720 |
+
if not 0 < step < index:
|
| 721 |
+
return match.group(0)
|
| 722 |
+
if match.group(0) not in refs:
|
| 723 |
+
raise ValueError(f"Step {step} made nothing that this step can use.")
|
| 724 |
+
return str(refs[match.group(0)])
|
| 725 |
+
|
| 726 |
+
if value in refs:
|
| 727 |
+
return refs[value]
|
| 728 |
+
return _PLACEHOLDER.sub(swap, value)
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def _refusal(result):
|
| 732 |
+
for key in ("error", "refused", "message"):
|
| 733 |
+
if isinstance(result.get(key), str) and result[key].strip():
|
| 734 |
+
return _plain(result[key])
|
| 735 |
+
return "The app refused it."
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
def _apply_change(session, entry):
|
| 739 |
+
"""Run a confirmed change's steps once, in order, and stop at the first that fails."""
|
| 740 |
+
steps = entry.get("steps") or []
|
| 741 |
+
door = entry.get("door") or "whatsapp"
|
| 742 |
+
turn = {"toolCalls": [], "pendingDelete": None, "artifacts": []}
|
| 743 |
+
refs, done = {}, []
|
| 744 |
+
for index, step in enumerate(steps, 1):
|
| 745 |
+
call = {"name": step["tool"], "args": step["args"], "effect": step["effect"], "ok": False, "ref": None}
|
| 746 |
+
turn["toolCalls"].append(call)
|
| 747 |
+
try:
|
| 748 |
+
args = _fill(step["args"], refs, index)
|
| 749 |
+
call["args"] = args
|
| 750 |
+
if "sources" in step and step["sources"] is not None:
|
| 751 |
+
_merge_sources(session, turn, step["sources"])
|
| 752 |
+
elif "sources" in step:
|
| 753 |
+
turn["artifactSourcesUnknown"] = True
|
| 754 |
+
token = _PRODUCING_TURN.set((session, turn))
|
| 755 |
+
import routes_query as query
|
| 756 |
+
context_token = query._AGENT_TURN.set(step.get("context") or {})
|
| 757 |
+
door_token = query._AGENT_DOOR.set(door)
|
| 758 |
+
try:
|
| 759 |
+
import assistant_write_preview
|
| 760 |
+
if args != step.get("resolvedArgs"):
|
| 761 |
+
raise ValueError("An earlier step no longer matches this preview. Ask again.")
|
| 762 |
+
result = assistant_write_preview.apply(session, step)
|
| 763 |
+
_observe_sources(session, turn, step["tool"], args, result)
|
| 764 |
+
finally:
|
| 765 |
+
_PRODUCING_TURN.reset(token)
|
| 766 |
+
query._AGENT_TURN.reset(context_token)
|
| 767 |
+
query._AGENT_DOOR.reset(door_token)
|
| 768 |
+
reason = (_refusal(result) if isinstance(result, dict)
|
| 769 |
+
and (result.get("ok") is False or result.get("refused")) else None)
|
| 770 |
+
except Exception as exc:
|
| 771 |
+
reason = _sentence(exc)
|
| 772 |
+
if reason is not None:
|
| 773 |
+
head = f"Step {index} of {len(steps)} did not run: {reason.rstrip('. ')}."
|
| 774 |
+
tail = (" Ran before it: " + " ".join(_past(line) for line in _capped(done))
|
| 775 |
+
if done else " Nothing was changed.")
|
| 776 |
+
return _result(refused=head + tail, turn=turn)
|
| 777 |
+
ref = _ref(result)
|
| 778 |
+
call.update(ok=True, ref=ref)
|
| 779 |
+
if ref is not None:
|
| 780 |
+
refs[step["ref"]] = ref
|
| 781 |
+
_after_dispatch(session, door, step["tool"], args, result, call, turn, step["effect"])
|
| 782 |
+
done.extend(step["lines"])
|
| 783 |
+
return _result(" ".join(["Done.", *(_past(line) for line in _capped(done))]), turn=turn)
|
| 784 |
+
|
| 785 |
+
|
| 786 |
def _ref(result):
|
| 787 |
if not isinstance(result, dict):
|
| 788 |
return None
|
|
|
|
| 798 |
return ids[0] if isinstance(ids, list) and len(ids) == 1 else None
|
| 799 |
|
| 800 |
|
| 801 |
+
def _record_artifact(session, door, name, args, result, *, sources=_UNSET):
|
| 802 |
+
if name == "agent_message":
|
| 803 |
+
return None
|
| 804 |
try:
|
| 805 |
import assistant_artifacts
|
| 806 |
except ImportError:
|
|
|
|
| 810 |
"view" if name.startswith("view_") else
|
| 811 |
"schedule" if name.startswith("schedule_") or name == "reminder_create" else "run")
|
| 812 |
value = result if isinstance(result, dict) else {}
|
| 813 |
+
if sources is _UNSET:
|
| 814 |
+
proof = {}
|
| 815 |
+
_observe_sources(session, proof, name, args, result)
|
| 816 |
+
sources = _turn_sources(proof)
|
| 817 |
view = args.get("view") if isinstance(args.get("view"), dict) else {}
|
| 818 |
made = next((value[key] for key in ("workbook", "view", "schedule", "application")
|
| 819 |
if isinstance(value.get(key), dict)), {})
|
|
|
|
| 834 |
cursor = page.get("nextCursor")
|
| 835 |
if cursor is None:
|
| 836 |
break
|
| 837 |
+
artifact_id = assistant_artifacts.record(session.runtime, session.uname, {
|
| 838 |
"kind": kind, "ref": str(ref) if ref is not None else None, "title": _plain(title),
|
| 839 |
+
"door": door, "toolCall": {"name": name, "args": copy.deepcopy(args)}, "createdAt": time.time(),
|
| 840 |
+
"sources": sources, "amazon": sources is None or any(key.startswith("ut_amzn_") for key in sources)})
|
| 841 |
+
if sources is None:
|
| 842 |
+
_artifact_result(session, artifact_id, result, {}, {"artifactSourcesUnknown": True})
|
| 843 |
+
return artifact_id
|
| 844 |
|
| 845 |
|
| 846 |
def execute(session, name, args, *, door, turn):
|
|
|
|
| 862 |
return {"ok": False, "error": "Evaluation turns permit read tools only."}
|
| 863 |
if not isinstance(args, dict):
|
| 864 |
raise ValueError("Tool arguments must be an object.")
|
| 865 |
+
if waits_for_yes(door, name, args, effect):
|
| 866 |
+
held = _HELD.get()
|
| 867 |
+
if held is None:
|
| 868 |
+
return {"ok": False, "error": "On WhatsApp a change waits for the user's YES, "
|
| 869 |
+
"and this turn cannot hold one."}
|
| 870 |
+
ref = _hold(session, name, args, effect, held, turn)
|
| 871 |
+
call.update(ok=True, ref=ref, held=True)
|
| 872 |
+
return {"ok": True, "pending": True, "ref": ref, "preview": copy.deepcopy(held[-1]["lines"]),
|
| 873 |
+
"message": (f"Nothing changed yet. The user's YES applies this step. Use {ref} "
|
| 874 |
+
"wherever a later step needs the id this step creates.")}
|
| 875 |
if effect == "delete":
|
| 876 |
pending = _pending(session, door, name, args)
|
| 877 |
turn["pendingDelete"] = pending
|
| 878 |
call.update(ok=True, ref=pending["id"])
|
| 879 |
return {"ok": True, "pendingDelete": pending,
|
| 880 |
"message": "Nothing is removed until the user confirms this delete."}
|
| 881 |
+
token = _PRODUCING_TURN.set((session, turn))
|
| 882 |
+
try:
|
| 883 |
+
result = _dispatch(session, name, args)
|
| 884 |
+
finally:
|
| 885 |
+
_PRODUCING_TURN.reset(token)
|
| 886 |
if isinstance(result, dict) and (result.get("ok") is False or result.get("refused")):
|
| 887 |
return result
|
| 888 |
call.update(ok=True, ref=_ref(result))
|
| 889 |
+
if getattr(session.runtime, "preview_only", False):
|
| 890 |
+
return result
|
| 891 |
+
return _after_dispatch(session, door, name, args, result, call, turn, effect)
|
|
|
|
|
|
|
| 892 |
except Exception as exc:
|
| 893 |
# Plugin failures are tool results too, so no tool exception escapes to a chat door.
|
| 894 |
return {"ok": False, "error": _sentence(exc)}
|
|
|
|
| 914 |
return False
|
| 915 |
|
| 916 |
|
| 917 |
+
def run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None, model=None,
|
| 918 |
+
attachments=None):
|
| 919 |
handle = turn_control.TurnHandle((principal["tenant"], principal["username"]), door, ())
|
| 920 |
result = None
|
| 921 |
try:
|
| 922 |
result = _run_turn(rt, principal, door, text, confirm=confirm, chat=chat,
|
| 923 |
+
context=context, model=model, audit_handle=handle,
|
| 924 |
+
**({"attachments": attachments} if attachments is not None else {}))
|
| 925 |
return result
|
| 926 |
finally:
|
| 927 |
if not handle.audit_delegated and (result or {}).get("status") != "code_received" and not (confirm is None and door in {"whatsapp", "slack"}
|
|
|
|
| 931 |
turn_audit.write(handle, rt, result=result)
|
| 932 |
|
| 933 |
|
| 934 |
+
def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None, model=None, audit_handle=None,
|
| 935 |
+
attachments=None):
|
| 936 |
if door not in DOORS:
|
| 937 |
raise ValueError("That Assistant door is not available.")
|
| 938 |
+
try:
|
| 939 |
+
attachments = _attachments(attachments)
|
| 940 |
+
except ValueError as exc:
|
| 941 |
+
return _result(refused=str(exc))
|
| 942 |
also_as = principal.get("also_as") or []
|
| 943 |
if any(member is None for member in also_as):
|
| 944 |
return _result(refused="A member of this channel has not linked a Loopable account.")
|
|
|
|
| 962 |
if confirm is not None:
|
| 963 |
pid = str(confirm)
|
| 964 |
owner = _owner(session.tenant, session.uname)
|
| 965 |
+
# WhatsApp holds every change, deletes included, so its confirm names a change.
|
| 966 |
+
noun, gone = (("change", "That change no longer exists.") if door == "whatsapp"
|
| 967 |
+
else ("delete", "That delete request no longer exists."))
|
| 968 |
if _foreign_id(pid, owner):
|
| 969 |
foreign = session.runtime.get("agent_pending_" + pid.split(".")[0]) or {}
|
| 970 |
+
sentence = (f"Only the person who asked can confirm this {noun}."
|
| 971 |
+
if pid in foreign.get("pending", {}) else gone)
|
| 972 |
return _result(refused=sentence)
|
| 973 |
entry = _take(session, pid)
|
| 974 |
if entry is None:
|
| 975 |
+
return _result(refused=gone)
|
| 976 |
+
if entry.get("kind") == "change":
|
| 977 |
+
if entry["expiresAt"] <= time.time():
|
| 978 |
+
return _result(refused="That change expired. Ask again to make it.")
|
| 979 |
+
return _apply_change(session, entry)
|
| 980 |
if entry["expiresAt"] <= time.time():
|
| 981 |
return _result(refused="That delete request expired. Ask again to delete it.")
|
| 982 |
turn = {"toolCalls": [{"name": entry["tool"], "args": entry["args"], "effect": "delete",
|
|
|
|
| 992 |
return _result(refused=_sentence(exc), turn=turn)
|
| 993 |
token = query._AGENT_DOOR.set(door)
|
| 994 |
memory_token = _MEMORY_BLOCK.set(memory_block(rt, principal))
|
| 995 |
+
# Set before the context: door_context names the files, user_content carries them.
|
| 996 |
+
files_token = _ATTACHMENTS.set(attachments)
|
| 997 |
+
context_token = query._AGENT_CONTEXT.set(door_context(door, context))
|
| 998 |
+
held = [] if door == "whatsapp" else None
|
| 999 |
+
held_token = _HELD.set(held)
|
| 1000 |
try:
|
| 1001 |
body = {"question": text}
|
| 1002 |
if model is not None:
|
| 1003 |
body["model"] = model
|
| 1004 |
response = query._submit(body, session, chat=chat, also_as=also_as, door=door, audit_handle=audit_handle)
|
| 1005 |
finally:
|
| 1006 |
+
_HELD.reset(held_token)
|
| 1007 |
query._AGENT_CONTEXT.reset(context_token)
|
| 1008 |
+
_ATTACHMENTS.reset(files_token)
|
| 1009 |
_MEMORY_BLOCK.reset(memory_token)
|
| 1010 |
query._AGENT_DOOR.reset(token)
|
| 1011 |
if response.get("status") in {"joined", "stopped", "paused", "code_received"}:
|
|
|
|
| 1013 |
message = response["message"]
|
| 1014 |
if door == "slack":
|
| 1015 |
maybe_compact(rt, session.uname, chat=chat)
|
| 1016 |
+
result = _result(message["content"], refused=message["content"] if message.get("reason") else None,
|
| 1017 |
+
turn=message)
|
| 1018 |
+
if held and not result["refused"]:
|
| 1019 |
+
result["pendingChange"] = _store_change(session, door, held, turn=message)
|
| 1020 |
+
return result
|
| 1021 |
except (external_access.ExternalAccessError, HTTPException, ValueError) as exc:
|
| 1022 |
return _result(refused=_sentence(exc))
|
| 1023 |
|
api/agent_tools.py
CHANGED
|
@@ -8,6 +8,7 @@ import copy
|
|
| 8 |
import importlib
|
| 9 |
import json
|
| 10 |
import logging
|
|
|
|
| 11 |
|
| 12 |
from core import external_tools
|
| 13 |
|
|
@@ -69,6 +70,54 @@ def load_modules():
|
|
| 69 |
register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
|
| 70 |
except (KeyError, TypeError, ValueError) as exc:
|
| 71 |
_LOG.info("Assistant tool entry in %s was skipped (%s)", name, type(exc).__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
def _connector_setup_link(session, args):
|
|
|
|
| 8 |
import importlib
|
| 9 |
import json
|
| 10 |
import logging
|
| 11 |
+
import re
|
| 12 |
|
| 13 |
from core import external_tools
|
| 14 |
|
|
|
|
| 70 |
register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
|
| 71 |
except (KeyError, TypeError, ValueError) as exc:
|
| 72 |
_LOG.info("Assistant tool entry in %s was skipped (%s)", name, type(exc).__name__)
|
| 73 |
+
# S72-T26: the directory sits outside AGENT_TOOL_MODULES, which verify_query pins exactly.
|
| 74 |
+
# A failure here must not take every turn down.
|
| 75 |
+
try:
|
| 76 |
+
import agent_directory
|
| 77 |
+
for entry in agent_directory.TOOLS:
|
| 78 |
+
register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
|
| 79 |
+
except Exception as exc: # noqa: BLE001
|
| 80 |
+
_LOG.warning("Assistant directory tool is unavailable (%s)", type(exc).__name__)
|
| 81 |
+
# S72-T27: agent messages, outside AGENT_TOOL_MODULES for the same reason.
|
| 82 |
+
try:
|
| 83 |
+
import agent_inbox
|
| 84 |
+
for entry in agent_inbox.TOOLS:
|
| 85 |
+
register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
|
| 86 |
+
except Exception as exc: # noqa: BLE001
|
| 87 |
+
_LOG.warning("Assistant inbox tool is unavailable (%s)", type(exc).__name__)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
_NOT_A_NAME = r"(?!(?:me|us|my|our|the|a|an|what|how|who|which|when|why|where|about)\b)"
|
| 91 |
+
_DIRECTORY = tuple(re.compile(p) for p in (
|
| 92 |
+
r"^who (?:uses|is using) loopable\b",
|
| 93 |
+
r"^who(?: is| are)? (?:in|on) (?:my|our) (?:workspace|team)\b",
|
| 94 |
+
r"^who has access to \w",
|
| 95 |
+
r"^what access does \w[\w .'-]* have\b",
|
| 96 |
+
))
|
| 97 |
+
_INBOX = tuple(re.compile(p) for p in (
|
| 98 |
+
r"^(?:please )?ask " + _NOT_A_NAME + r"\w+(?: \w+)? for (?:edit |view )?access to \w",
|
| 99 |
+
r"^(?:please )?request (?:edit |view )?access to \w",
|
| 100 |
+
r"^(?:please )?tell " + _NOT_A_NAME + r"\w+(?: \w+)? (?:that|to|about|we|i|our|the|my|it)\b",
|
| 101 |
+
r"^(?:please )?ask " + _NOT_A_NAME + r"\w+(?: \w+)? (?:whether|if|about) \w",
|
| 102 |
+
))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def admitted_tools(question):
|
| 106 |
+
"""The tools a directory or inbox question admits without a database match, else empty."""
|
| 107 |
+
text = " ".join(str(question or "").casefold().replace("\u2019", "'").split()).strip(" ?.!")
|
| 108 |
+
if not text:
|
| 109 |
+
return frozenset()
|
| 110 |
+
if any(p.search(text) for p in _INBOX):
|
| 111 |
+
return frozenset({"workspace_people", "agent_message"})
|
| 112 |
+
try:
|
| 113 |
+
import agent_directory
|
| 114 |
+
if agent_directory.admits(question):
|
| 115 |
+
return frozenset({"workspace_people"})
|
| 116 |
+
except Exception: # noqa: BLE001
|
| 117 |
+
pass
|
| 118 |
+
if any(p.search(text) for p in _DIRECTORY):
|
| 119 |
+
return frozenset({"workspace_people"})
|
| 120 |
+
return frozenset()
|
| 121 |
|
| 122 |
|
| 123 |
def _connector_setup_link(session, args):
|
api/amazon_relational.py
CHANGED
|
@@ -149,7 +149,7 @@ _QUANTITY = {"quantity", "quantity_purchased", "starting_warehouse_balance",
|
|
| 149 |
|
| 150 |
|
| 151 |
def _label(col):
|
| 152 |
-
return
|
| 153 |
|
| 154 |
|
| 155 |
def _ftype(col, duck_type):
|
|
@@ -160,6 +160,8 @@ def _ftype(col, duck_type):
|
|
| 160 |
name is allowed to override. The store's `_coltype` already refuses to guess a type for text
|
| 161 |
it cannot parse; this is the presentation half of the same judgement.
|
| 162 |
"""
|
|
|
|
|
|
|
| 163 |
if any(col == s or col.endswith(s) for s in _DATEISH):
|
| 164 |
return "date"
|
| 165 |
if col in _MONEY or col.endswith(("_amount", "_fee")) or any(col.endswith(s) for s in _RATE_SUFFIX):
|
|
@@ -378,6 +380,7 @@ def _fields_for(cur, key):
|
|
| 378 |
"source": "overlay",
|
| 379 |
"default": name == pinned or name in _DEFAULT_COLUMNS or name in product,
|
| 380 |
"pinned": name == pinned,
|
|
|
|
| 381 |
}, flow="amazon_relational"))
|
| 382 |
for lookup in derived.get(name, ()):
|
| 383 |
field = {"key": lookup["key"], "label": lookup["label"], "type": "text",
|
|
@@ -525,9 +528,10 @@ def grid_source(cur, key):
|
|
| 525 |
for name, dtype in columns:
|
| 526 |
kind = _ftype(name, dtype)
|
| 527 |
expr = _quoted(name)
|
|
|
|
| 528 |
if kind in ("currency", "int"):
|
| 529 |
-
expr = f"TRY_CAST({expr} AS {'DOUBLE' if
|
| 530 |
-
cols[name] = (expr,
|
| 531 |
# S67-T30: the product lookups bind like any mirror column, so a filter (`=` a parent), a
|
| 532 |
# group (count by parent) and a sort compile against them in SQL with no per-row Python.
|
| 533 |
for lookup in lookups(cur, key, names):
|
|
|
|
| 149 |
|
| 150 |
|
| 151 |
def _label(col):
|
| 152 |
+
return connector_spec._label(col)
|
| 153 |
|
| 154 |
|
| 155 |
def _ftype(col, duck_type):
|
|
|
|
| 160 |
name is allowed to override. The store's `_coltype` already refuses to guess a type for text
|
| 161 |
it cannot parse; this is the presentation half of the same judgement.
|
| 162 |
"""
|
| 163 |
+
if col == "per_unit_volume":
|
| 164 |
+
return "int"
|
| 165 |
if any(col == s or col.endswith(s) for s in _DATEISH):
|
| 166 |
return "date"
|
| 167 |
if col in _MONEY or col.endswith(("_amount", "_fee")) or any(col.endswith(s) for s in _RATE_SUFFIX):
|
|
|
|
| 380 |
"source": "overlay",
|
| 381 |
"default": name == pinned or name in _DEFAULT_COLUMNS or name in product,
|
| 382 |
"pinned": name == pinned,
|
| 383 |
+
**({"format": {"decimals": 4}} if name == "per_unit_volume" else {}),
|
| 384 |
}, flow="amazon_relational"))
|
| 385 |
for lookup in derived.get(name, ()):
|
| 386 |
field = {"key": lookup["key"], "label": lookup["label"], "type": "text",
|
|
|
|
| 528 |
for name, dtype in columns:
|
| 529 |
kind = _ftype(name, dtype)
|
| 530 |
expr = _quoted(name)
|
| 531 |
+
fractional = kind == "currency" or name == "per_unit_volume"
|
| 532 |
if kind in ("currency", "int"):
|
| 533 |
+
expr = f"TRY_CAST({expr} AS {'DOUBLE' if fractional else 'BIGINT'})"
|
| 534 |
+
cols[name] = (expr, _number if fractional else {"int": _integer}.get(kind, _text))
|
| 535 |
# S67-T30: the product lookups bind like any mirror column, so a filter (`=` a parent), a
|
| 536 |
# group (count by parent) and a sort compile against them in SQL with no per-row Python.
|
| 537 |
for lookup in lookups(cur, key, names):
|
api/application_registry.py
CHANGED
|
@@ -3,7 +3,7 @@ from __future__ import annotations
|
|
| 3 |
|
| 4 |
import copy
|
| 5 |
import json
|
| 6 |
-
from core import write_execution
|
| 7 |
|
| 8 |
from modules.finance_apps import (finance_application as _finance_application,
|
| 9 |
finance_applications as _finance_applications,
|
|
@@ -74,6 +74,55 @@ class ApplicationError(ValueError):
|
|
| 74 |
pass
|
| 75 |
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
def template_contracts():
|
| 78 |
"""The trusted renderer contracts offered by the Application creation flow."""
|
| 79 |
return [copy.deepcopy(_TEMPLATE_CONTRACTS[kind]) for kind in APPLICATION_WIZARD_TEMPLATE_KINDS]
|
|
@@ -89,11 +138,8 @@ def finance_applications(may_open=None):
|
|
| 89 |
return _finance_applications(may_open=may_open)
|
| 90 |
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
#
|
| 94 |
-
# validate_application's governed type vocabulary.
|
| 95 |
-
# This remains true for the SEEDED six. Users may now persist their own Finance applications
|
| 96 |
-
# through templateKind, pointing to the same trusted surface without modifying those projections.
|
| 97 |
def finance_application_records(may_open=None):
|
| 98 |
"""Project the grant-filtered Finance catalogue as seeded Application records."""
|
| 99 |
return [
|
|
@@ -242,6 +288,52 @@ def may_edit(app, user, is_admin=False):
|
|
| 242 |
return bool(is_admin or (isinstance(app, dict) and app.get("createdBy") == user))
|
| 243 |
|
| 244 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
def _compat(raw):
|
| 246 |
values=[]
|
| 247 |
for item in raw if isinstance(raw, (list, tuple)) else ():
|
|
@@ -470,11 +562,8 @@ def _public(app, user, is_admin=False, *, allowed_databases=None, target_databas
|
|
| 470 |
row["starred"] = user in (app.get("starredBy") or ())
|
| 471 |
row["isDefault"] = bool(is_default)
|
| 472 |
if row.get("templateKind") == FINANCE_TEMPLATE_KIND:
|
| 473 |
-
#
|
| 474 |
-
|
| 475 |
-
row["capabilities"].update({key: False for key in (
|
| 476 |
-
"edit", "share", "delete", "duplicate", "star", "default")})
|
| 477 |
-
row["starred"] = False
|
| 478 |
row["isDefault"] = False
|
| 479 |
target_database = target_database if target_database in compatible else (compatible[0] if compatible else None)
|
| 480 |
row["openTarget"]={"kind":"application","id":row["id"],"type":row["type"],
|
|
@@ -514,14 +603,28 @@ def dependent_view_counts(runtime, database):
|
|
| 514 |
|
| 515 |
|
| 516 |
def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starred=None,
|
| 517 |
-
allowed_databases=None):
|
|
|
|
| 518 |
doc = load(runtime)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 519 |
rows=[]
|
| 520 |
for app in doc["applications"].values():
|
| 521 |
-
if
|
| 522 |
-
|
|
|
|
|
|
|
|
|
|
| 523 |
if (app.get("templateKind") != FINANCE_TEMPLATE_KIND
|
| 524 |
and not _allowed(app.get("compatibleDatabases"), allowed_databases)): continue
|
|
|
|
| 525 |
if kind and app.get("type") != kind: continue
|
| 526 |
if starred is not None and bool(user in (app.get("starredBy") or ())) != bool(starred): continue
|
| 527 |
default_key = f"{database}::{app.get('type')}" if database else ""
|
|
@@ -539,8 +642,8 @@ def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starre
|
|
| 539 |
|
| 540 |
|
| 541 |
def nav_applications(runtime, user, is_admin=False, *, may_open=None, allowed_databases=None):
|
| 542 |
-
"""The
|
| 543 |
-
|
| 544 |
"type": app.get("type"), "templateKind": app.get("templateKind"),
|
| 545 |
"deepLink": app.get("deepLink"),
|
| 546 |
"origin": "tenant",
|
|
@@ -550,8 +653,8 @@ def nav_applications(runtime, user, is_admin=False, *, may_open=None, allowed_da
|
|
| 550 |
"capabilities": app.get("capabilities"), "starred": app.get("starred"),
|
| 551 |
"isDefault": app.get("isDefault")}
|
| 552 |
for index, app in enumerate(list_apps(runtime, user, is_admin,
|
| 553 |
-
allowed_databases=allowed_databases
|
| 554 |
-
|
| 555 |
|
| 556 |
|
| 557 |
def _build_application(tenant, user, payload, *, semantic_records=None, field_contracts=None,
|
|
@@ -593,32 +696,55 @@ def create(runtime, tenant, user, payload, *, semantic_records=None, field_contr
|
|
| 593 |
tenant, user, payload, semantic_records=semantic_records, field_contracts=field_contracts,
|
| 594 |
allowed_databases=allowed_databases)
|
| 595 |
app_id = app["id"]
|
|
|
|
| 596 |
def apply(raw):
|
| 597 |
doc=_clean_doc(raw)
|
| 598 |
if len(doc["applications"])>=_MAX: raise ApplicationError("application limit reached")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
doc["applications"][app_id]=app; return doc
|
| 600 |
runtime.update(_KEY,apply)
|
| 601 |
return _public(app,user,allowed_databases=allowed_databases)
|
| 602 |
|
| 603 |
|
| 604 |
-
def
|
| 605 |
-
"""
|
| 606 |
-
from core import route_system
|
| 607 |
-
|
| 608 |
-
# list_routes() suppresses read errors; an unknown count must remain retryable at boot.
|
| 609 |
# ⛔ D-260: `runtime.get` is the LENIENT display read. A failed hub read there answers {},
|
| 610 |
# which counted as 0 routes and wrote the one-shot marker as "no_routes", so a tenant WITH
|
| 611 |
# routes never got its App. Read STRICTLY (the timeseries_retirement._read door) so a failure
|
| 612 |
-
# raises into the retryable skip
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 613 |
try:
|
| 614 |
-
|
| 615 |
-
if callable(strict):
|
| 616 |
-
route_doc = strict(route_system.STORE_KEY)
|
| 617 |
-
elif callable(getattr(runtime, "_store", None)) and callable(
|
| 618 |
-
getattr(runtime, "store_key", None)):
|
| 619 |
-
route_doc = runtime._store()._read_strict(runtime.store_key(route_system.STORE_KEY))
|
| 620 |
-
else:
|
| 621 |
-
route_doc = runtime.get(route_system.STORE_KEY)
|
| 622 |
if route_doc is None:
|
| 623 |
routes = []
|
| 624 |
elif isinstance(route_doc, dict):
|
|
@@ -668,8 +794,184 @@ def ensure_route_application(runtime, tenant):
|
|
| 668 |
return result
|
| 669 |
|
| 670 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 671 |
def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
|
| 672 |
-
allowed_databases=None, target_database=None):
|
|
|
|
| 673 |
patch=patch if isinstance(patch,dict) else {}; landed={}
|
| 674 |
immutable = sorted(set(patch) & {
|
| 675 |
"id", "tenant", "type", "templateKind", "sourceDatabase", "fieldMap", "navPlacement",
|
|
@@ -681,7 +983,7 @@ def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
|
|
| 681 |
def apply(raw):
|
| 682 |
doc=_clean_doc(raw); app=doc["applications"].get(app_id)
|
| 683 |
if not app: raise ApplicationError("application does not exist")
|
| 684 |
-
if not _allowed(app.get("compatibleDatabases"), allowed_databases):
|
| 685 |
raise ApplicationError("application does not exist")
|
| 686 |
if app.get("templateKind") in APPLICATION_TEMPLATE_KINDS and "compatibleDatabases" in patch:
|
| 687 |
raise ApplicationError("a template Application's sourceDatabase is immutable")
|
|
@@ -690,6 +992,17 @@ def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
|
|
| 690 |
if not may_read(app,user,is_admin): raise PermissionError("application is not available")
|
| 691 |
elif not may_edit(app,user,is_admin):
|
| 692 |
raise PermissionError("application belongs to another user")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 693 |
if "name" in patch:
|
| 694 |
name=" ".join(str(patch["name"] or "").split())[:120]
|
| 695 |
if not name: raise ApplicationError("application name is required")
|
|
@@ -725,30 +1038,108 @@ def duplicate(runtime, app_id, tenant, user, is_admin=False, *, semantic_records
|
|
| 725 |
field_contracts=None, allowed_databases=None):
|
| 726 |
app=load(runtime)["applications"].get(app_id)
|
| 727 |
if not may_read(app,user,is_admin): raise ApplicationError("application does not exist")
|
| 728 |
-
if not _allowed(app.get("compatibleDatabases"), allowed_databases):
|
| 729 |
raise ApplicationError("application does not exist")
|
| 730 |
payload={"type":app["type"],"name":f"{app['name']} copy",
|
| 731 |
"compatibleDatabases":app.get("compatibleDatabases"),
|
| 732 |
"semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")}
|
| 733 |
-
for key in ("templateKind", "sourceDatabase", "fieldMap", "navPlacement"):
|
| 734 |
if key in app: payload[key]=copy.deepcopy(app[key])
|
| 735 |
return create(runtime,tenant,user,payload,
|
| 736 |
semantic_records=semantic_records, field_contracts=field_contracts,
|
| 737 |
allowed_databases=allowed_databases)
|
| 738 |
|
| 739 |
|
| 740 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 741 |
def apply(raw):
|
| 742 |
doc=_clean_doc(raw); app=doc["applications"].get(app_id)
|
| 743 |
if not app: raise ApplicationError("application does not exist")
|
| 744 |
-
if not _allowed(app.get("compatibleDatabases"), allowed_databases):
|
| 745 |
raise ApplicationError("application does not exist")
|
| 746 |
if not may_edit(app,user,is_admin): raise PermissionError("application belongs to another user")
|
| 747 |
-
|
|
|
|
|
|
|
|
|
|
| 748 |
for key in list(doc["defaults"]):
|
| 749 |
if doc["defaults"][key]==app_id: doc["defaults"].pop(key)
|
| 750 |
return doc
|
| 751 |
-
runtime.update(_KEY,apply)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 752 |
|
| 753 |
|
| 754 |
def set_default(runtime, database, kind, app_id, user, is_admin=False, *, allowed_databases=None):
|
|
@@ -775,11 +1166,12 @@ def resolve_default(runtime, database, kind, user, is_admin=False, *, allowed_da
|
|
| 775 |
raise PermissionError("that database is not available")
|
| 776 |
doc=load(runtime); explicit=doc["defaults"].get(f"{database}::{kind}")
|
| 777 |
app=doc["applications"].get(explicit)
|
| 778 |
-
if app and may_read(app,user,is_admin) and database in (app.get("compatibleDatabases") or ()) and app.get("type")==kind:
|
| 779 |
return {"resolution":"explicit","application":_public(
|
| 780 |
app,user,is_admin,allowed_databases=allowed_databases,target_database=database,
|
| 781 |
is_default=True)}
|
| 782 |
-
|
|
|
|
| 783 |
matches.sort(key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
|
| 784 |
return {"resolution":"latest" if matches else "blank",
|
| 785 |
"application":_public(matches[0],user,is_admin,allowed_databases=allowed_databases,
|
|
|
|
| 3 |
|
| 4 |
import copy
|
| 5 |
import json
|
| 6 |
+
from core import shares, write_execution
|
| 7 |
|
| 8 |
from modules.finance_apps import (finance_application as _finance_application,
|
| 9 |
finance_applications as _finance_applications,
|
|
|
|
| 74 |
pass
|
| 75 |
|
| 76 |
|
| 77 |
+
#: R103: the one sentence a second App of a template is refused with. No dash: it reaches a screen.
|
| 78 |
+
APP_EXISTS_MESSAGE = "You already have this App."
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ApplicationExistsError(ApplicationError):
|
| 82 |
+
"""The caller already owns an App of this template; `existing` is its {id, name}."""
|
| 83 |
+
|
| 84 |
+
def __init__(self, existing=None):
|
| 85 |
+
super().__init__(APP_EXISTS_MESSAGE)
|
| 86 |
+
self.existing = existing
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def template_identity(app):
|
| 90 |
+
"""The template an App counts against: route, catalog or finance:<key>; None for no template."""
|
| 91 |
+
if not isinstance(app, dict):
|
| 92 |
+
return None
|
| 93 |
+
kind = str(app.get("templateKind") or "")
|
| 94 |
+
if kind == FINANCE_TEMPLATE_KIND:
|
| 95 |
+
key = str(app.get("financeKey") or "")
|
| 96 |
+
return f"{FINANCE_TEMPLATE_KIND}:{key}" if key else None
|
| 97 |
+
return kind if kind in APPLICATION_WIZARD_TEMPLATE_KINDS else None
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _own_template_app(applications, user, identity):
|
| 101 |
+
"""R103: the caller's OWN live App of `identity`; shared and retired Apps never count."""
|
| 102 |
+
if not identity:
|
| 103 |
+
return None
|
| 104 |
+
for app in applications.values():
|
| 105 |
+
if (isinstance(app, dict) and app.get("createdBy") == user
|
| 106 |
+
and app.get("retired") is not True and template_identity(app) == identity):
|
| 107 |
+
return app
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def own_template_apps(runtime, user):
|
| 112 |
+
"""{template identity: {id, name}} of the caller's own Apps, for the template picker."""
|
| 113 |
+
owned = {}
|
| 114 |
+
apps = sorted((app for app in load(runtime)["applications"].values() if isinstance(app, dict)),
|
| 115 |
+
key=lambda app: (str(app.get("createdAt") or ""), str(app.get("id") or "")))
|
| 116 |
+
for app in apps:
|
| 117 |
+
identity = template_identity(app)
|
| 118 |
+
if (identity and identity not in owned and app.get("createdBy") == user
|
| 119 |
+
and app.get("retired") is not True):
|
| 120 |
+
owned[identity] = {"id": app.get("id"), "name": app.get("name"),
|
| 121 |
+
"deepLink": app.get("deepLink"),
|
| 122 |
+
"sourceDatabase": app.get("sourceDatabase")}
|
| 123 |
+
return owned
|
| 124 |
+
|
| 125 |
+
|
| 126 |
def template_contracts():
|
| 127 |
"""The trusted renderer contracts offered by the Application creation flow."""
|
| 128 |
return [copy.deepcopy(_TEMPLATE_CONTRACTS[kind]) for kind in APPLICATION_WIZARD_TEMPLATE_KINDS]
|
|
|
|
| 138 |
return _finance_applications(may_open=may_open)
|
| 139 |
|
| 140 |
|
| 141 |
+
# R102: the App home lists no code projection. These records name the pre-wave Finance tiles, so
|
| 142 |
+
# the copy migration and routes_module_index can map their ids; nav_applications never returns them.
|
|
|
|
|
|
|
|
|
|
| 143 |
def finance_application_records(may_open=None):
|
| 144 |
"""Project the grant-filtered Finance catalogue as seeded Application records."""
|
| 145 |
return [
|
|
|
|
| 288 |
return bool(is_admin or (isinstance(app, dict) and app.get("createdBy") == user))
|
| 289 |
|
| 290 |
|
| 291 |
+
def _listed(app, user):
|
| 292 |
+
"""R102: the App home lists what the caller owns or was shared, for an Administrator too."""
|
| 293 |
+
if not isinstance(app, dict) or app.get("retired") is True:
|
| 294 |
+
return False
|
| 295 |
+
if app.get("createdBy") == user:
|
| 296 |
+
return True
|
| 297 |
+
share = app.get("share") if isinstance(app.get("share"), dict) else {}
|
| 298 |
+
return share.get("mode") == "tenant" or user in set(share.get("users") or ())
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def _is_finance(app):
|
| 302 |
+
return isinstance(app, dict) and app.get("templateKind") == FINANCE_TEMPLATE_KIND
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _finance_permission(app):
|
| 306 |
+
try:
|
| 307 |
+
return _finance_application(str(app.get("financeKey") or ""))["permissionKey"]
|
| 308 |
+
except KeyError:
|
| 309 |
+
return None
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def _account_wall(runtime, user_record):
|
| 313 |
+
"""The `deps.Session.require` predicate for one account, without a request."""
|
| 314 |
+
from core import perm_scope
|
| 315 |
+
config = getattr(getattr(runtime, "tenant", None), "config", None) or {}
|
| 316 |
+
modules = config.get("modules", "all") if isinstance(config, dict) else "all"
|
| 317 |
+
|
| 318 |
+
def may_open(key):
|
| 319 |
+
if not perm_scope.nav_may_open(user_record, key, st=runtime):
|
| 320 |
+
return False
|
| 321 |
+
return modules == "all" or str(key) in {str(item) for item in (modules or [])}
|
| 322 |
+
return may_open
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _user_wall(runtime, user):
|
| 326 |
+
"""Resolve one username's wall from the account registry; fail closed on any read error."""
|
| 327 |
+
try:
|
| 328 |
+
from core import users
|
| 329 |
+
record = (users.registry() or {}).get(user)
|
| 330 |
+
if not isinstance(record, dict) or record.get("active") is False:
|
| 331 |
+
return lambda _key: False
|
| 332 |
+
return _account_wall(runtime, users._public(user, record))
|
| 333 |
+
except Exception:
|
| 334 |
+
return lambda _key: False
|
| 335 |
+
|
| 336 |
+
|
| 337 |
def _compat(raw):
|
| 338 |
values=[]
|
| 339 |
for item in raw if isinstance(raw, (list, tuple)) else ():
|
|
|
|
| 562 |
row["starred"] = user in (app.get("starredBy") or ())
|
| 563 |
row["isDefault"] = bool(is_default)
|
| 564 |
if row.get("templateKind") == FINANCE_TEMPLATE_KIND:
|
| 565 |
+
# A Finance App is a user's own copy: owner controls apply. Defaults bind a database.
|
| 566 |
+
row["capabilities"]["default"] = False
|
|
|
|
|
|
|
|
|
|
| 567 |
row["isDefault"] = False
|
| 568 |
target_database = target_database if target_database in compatible else (compatible[0] if compatible else None)
|
| 569 |
row["openTarget"]={"kind":"application","id":row["id"],"type":row["type"],
|
|
|
|
| 603 |
|
| 604 |
|
| 605 |
def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starred=None,
|
| 606 |
+
allowed_databases=None, may_open=None):
|
| 607 |
+
"""List Applications. Unfiltered is the App home; a database filter is how a View resolves."""
|
| 608 |
doc = load(runtime)
|
| 609 |
+
walls = []
|
| 610 |
+
|
| 611 |
+
def finance_open(app):
|
| 612 |
+
# Hidden, never deleted, while the caller's wall refuses the Finance permission key.
|
| 613 |
+
if not walls:
|
| 614 |
+
walls.append(may_open if callable(may_open) else _user_wall(runtime, user))
|
| 615 |
+
key = _finance_permission(app)
|
| 616 |
+
return bool(key and walls[0](key))
|
| 617 |
+
|
| 618 |
rows=[]
|
| 619 |
for app in doc["applications"].values():
|
| 620 |
+
if database:
|
| 621 |
+
# A View resolves its App only through this read, so a retired seed stays listed here.
|
| 622 |
+
if not may_read(app,user,is_admin): continue
|
| 623 |
+
if database not in (app.get("compatibleDatabases") or ()): continue
|
| 624 |
+
elif not _listed(app, user): continue
|
| 625 |
if (app.get("templateKind") != FINANCE_TEMPLATE_KIND
|
| 626 |
and not _allowed(app.get("compatibleDatabases"), allowed_databases)): continue
|
| 627 |
+
if _is_finance(app) and not finance_open(app): continue
|
| 628 |
if kind and app.get("type") != kind: continue
|
| 629 |
if starred is not None and bool(user in (app.get("starredBy") or ())) != bool(starred): continue
|
| 630 |
default_key = f"{database}::{app.get('type')}" if database else ""
|
|
|
|
| 642 |
|
| 643 |
|
| 644 |
def nav_applications(runtime, user, is_admin=False, *, may_open=None, allowed_databases=None):
|
| 645 |
+
"""The App home read: stored records the caller owns or was shared, never a code projection."""
|
| 646 |
+
return [{"id": app["id"], "name": app.get("name"),
|
| 647 |
"type": app.get("type"), "templateKind": app.get("templateKind"),
|
| 648 |
"deepLink": app.get("deepLink"),
|
| 649 |
"origin": "tenant",
|
|
|
|
| 653 |
"capabilities": app.get("capabilities"), "starred": app.get("starred"),
|
| 654 |
"isDefault": app.get("isDefault")}
|
| 655 |
for index, app in enumerate(list_apps(runtime, user, is_admin,
|
| 656 |
+
allowed_databases=allowed_databases,
|
| 657 |
+
may_open=may_open))]
|
| 658 |
|
| 659 |
|
| 660 |
def _build_application(tenant, user, payload, *, semantic_records=None, field_contracts=None,
|
|
|
|
| 696 |
tenant, user, payload, semantic_records=semantic_records, field_contracts=field_contracts,
|
| 697 |
allowed_databases=allowed_databases)
|
| 698 |
app_id = app["id"]
|
| 699 |
+
identity = template_identity(app)
|
| 700 |
def apply(raw):
|
| 701 |
doc=_clean_doc(raw)
|
| 702 |
if len(doc["applications"])>=_MAX: raise ApplicationError("application limit reached")
|
| 703 |
+
# R103: counted on the document being written, so two concurrent creates cannot both pass.
|
| 704 |
+
held = _own_template_app(doc["applications"], user, identity)
|
| 705 |
+
if held is not None:
|
| 706 |
+
raise ApplicationExistsError({"id": held.get("id"), "name": held.get("name")})
|
| 707 |
doc["applications"][app_id]=app; return doc
|
| 708 |
runtime.update(_KEY,apply)
|
| 709 |
return _public(app,user,allowed_databases=allowed_databases)
|
| 710 |
|
| 711 |
|
| 712 |
+
def _read_strict(runtime, key):
|
| 713 |
+
"""Read one document so that a failure RAISES; the lenient `runtime.get` answers {} instead."""
|
|
|
|
|
|
|
|
|
|
| 714 |
# ⛔ D-260: `runtime.get` is the LENIENT display read. A failed hub read there answers {},
|
| 715 |
# which counted as 0 routes and wrote the one-shot marker as "no_routes", so a tenant WITH
|
| 716 |
# routes never got its App. Read STRICTLY (the timeseries_retirement._read door) so a failure
|
| 717 |
+
# raises into the retryable skip. Only a double exposing no strict door reads via get.
|
| 718 |
+
strict = getattr(runtime, "_read_strict", None)
|
| 719 |
+
if callable(strict):
|
| 720 |
+
return strict(key)
|
| 721 |
+
if callable(getattr(runtime, "_store", None)) and callable(getattr(runtime, "store_key", None)):
|
| 722 |
+
return runtime._store()._read_strict(runtime.store_key(key))
|
| 723 |
+
return runtime.get(key)
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
def ensure_route_application(runtime, tenant, *, accounts=None, wall=None):
|
| 727 |
+
"""R15: boot migrations, once per tenant, never from an Application read.
|
| 728 |
+
|
| 729 |
+
Runs the Routing seed migration, then `ensure_user_app_copies`, and folds both into one dict.
|
| 730 |
+
"""
|
| 731 |
+
result = _ensure_route_seed(runtime, tenant)
|
| 732 |
+
copies = ensure_user_app_copies(runtime, tenant, accounts=accounts, wall=wall)
|
| 733 |
+
folded = dict(result)
|
| 734 |
+
folded["userCopies"] = copies
|
| 735 |
+
note = "user copies " + copies["outcome"] + (
|
| 736 |
+
": " + copies["reason"] if copies.get("reason") else "")
|
| 737 |
+
folded["reason"] = result["reason"] + "; " + note if result.get("reason") else note
|
| 738 |
+
return folded
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def _ensure_route_seed(runtime, tenant):
|
| 742 |
+
"""R15: migrate route references once per tenant into the seeded Routing App."""
|
| 743 |
+
from core import route_system
|
| 744 |
+
|
| 745 |
+
# list_routes() suppresses read errors; an unknown count must remain retryable at boot.
|
| 746 |
try:
|
| 747 |
+
route_doc = _read_strict(runtime, route_system.STORE_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 748 |
if route_doc is None:
|
| 749 |
routes = []
|
| 750 |
elif isinstance(route_doc, dict):
|
|
|
|
| 794 |
return result
|
| 795 |
|
| 796 |
|
| 797 |
+
_COPIES = "userAppCopies"
|
| 798 |
+
_APP_INDEX_KEY = "module_index_app"
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def _active_accounts(tenant):
|
| 802 |
+
"""`[(username, public user record)]` for this tenant's active accounts; raises if unreadable."""
|
| 803 |
+
from core import users
|
| 804 |
+
if not isinstance(users.registry(), dict):
|
| 805 |
+
raise ApplicationError("the account registry is unreadable")
|
| 806 |
+
return [(name, users._public(name, record)) for name, record in users._tenant_accounts(tenant)]
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def _copy_id(tenant, old_id, username):
|
| 810 |
+
"""One stable id per (tenant, old App id, account), so a rerun cannot duplicate a copy."""
|
| 811 |
+
import hashlib
|
| 812 |
+
digest = hashlib.sha256(f"{tenant}\x1f{old_id}\x1f{username}".encode("utf-8")).hexdigest()
|
| 813 |
+
return "app_" + digest[:16]
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
def _seed_route_app(doc):
|
| 817 |
+
"""The tenant-shared Routing App the route migration seeded, or None."""
|
| 818 |
+
seed_id = ((doc.get("migrations") or {}).get("routeApplication") or {}).get("appId")
|
| 819 |
+
seed = doc["applications"].get(seed_id) if seed_id else None
|
| 820 |
+
if (isinstance(seed, dict) and seed.get("createdBy") == "loopable"
|
| 821 |
+
and (seed.get("share") or {}).get("mode") == "tenant"):
|
| 822 |
+
return seed
|
| 823 |
+
return None
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
def _move_placements(runtime, moves):
|
| 827 |
+
"""Move each account's App-home folder placement from an old App id to its copy id."""
|
| 828 |
+
doc = _read_strict(runtime, _APP_INDEX_KEY)
|
| 829 |
+
owners = (doc or {}).get("users") if isinstance(doc, dict) else None
|
| 830 |
+
if not isinstance(owners, dict):
|
| 831 |
+
return 0
|
| 832 |
+
if not any(old in ((owners.get(name) or {}).get("itemFolders") or {})
|
| 833 |
+
for name, pairs in moves.items() for old in pairs):
|
| 834 |
+
return 0
|
| 835 |
+
moved = [0]
|
| 836 |
+
|
| 837 |
+
def apply(raw):
|
| 838 |
+
state = copy.deepcopy(raw) if isinstance(raw, dict) else raw
|
| 839 |
+
buckets = state.get("users") if isinstance(state, dict) else None
|
| 840 |
+
for name, pairs in moves.items():
|
| 841 |
+
bucket = buckets.get(name) if isinstance(buckets, dict) else None
|
| 842 |
+
placed = bucket.get("itemFolders") if isinstance(bucket, dict) else None
|
| 843 |
+
if not isinstance(placed, dict):
|
| 844 |
+
continue
|
| 845 |
+
changed = False
|
| 846 |
+
for old, new in pairs.items():
|
| 847 |
+
if old in placed:
|
| 848 |
+
folder = placed.pop(old)
|
| 849 |
+
placed.setdefault(new, folder)
|
| 850 |
+
changed = True
|
| 851 |
+
moved[0] += 1
|
| 852 |
+
if changed:
|
| 853 |
+
# A client holding the old revision must reload before it writes folders again.
|
| 854 |
+
bucket["rev"] = int(bucket.get("rev") or 0) + 1
|
| 855 |
+
return state
|
| 856 |
+
runtime.update(_APP_INDEX_KEY, apply)
|
| 857 |
+
return moved[0]
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def ensure_user_app_copies(runtime, tenant, *, accounts=None, wall=None):
|
| 861 |
+
"""R102: give every account its own copy of each App it could see, once per tenant.
|
| 862 |
+
|
| 863 |
+
Finance tiles become stored Finance copies for accounts whose wall admits the permission key.
|
| 864 |
+
The seeded Routing App becomes one private copy per active account and is then retired: hidden
|
| 865 |
+
from the App home but kept, so a View holding its id still resolves. Folder placements move to
|
| 866 |
+
the copy ids. A failed read returns a retryable `skipped` and writes no marker.
|
| 867 |
+
"""
|
| 868 |
+
try:
|
| 869 |
+
current = _read_strict(runtime, _KEY)
|
| 870 |
+
if current is not None and not isinstance(current, dict):
|
| 871 |
+
raise ApplicationError("the Application registry must be an object")
|
| 872 |
+
except Exception as exc:
|
| 873 |
+
return {"outcome": "skipped", "reason": f"registry read failed: {type(exc).__name__}: {exc}"}
|
| 874 |
+
migrations = _clean_doc(current).get("migrations") or {}
|
| 875 |
+
marker = migrations.get(_COPIES)
|
| 876 |
+
if isinstance(marker, dict) and marker.get("state") == "done":
|
| 877 |
+
return {"outcome": "skipped", "reason": "user App copies already applied"}
|
| 878 |
+
if "routeApplication" not in migrations:
|
| 879 |
+
return {"outcome": "skipped", "reason": "route Application migration pending"}
|
| 880 |
+
|
| 881 |
+
if isinstance(marker, dict) and isinstance(marker.get("moves"), dict):
|
| 882 |
+
moves = copy.deepcopy(marker["moves"])
|
| 883 |
+
copies = int(marker.get("copies") or 0)
|
| 884 |
+
else:
|
| 885 |
+
try:
|
| 886 |
+
people = list(_active_accounts(tenant) if accounts is None else accounts)
|
| 887 |
+
wall = wall or (lambda record: _account_wall(runtime, record))
|
| 888 |
+
plan = []
|
| 889 |
+
for username, record in people:
|
| 890 |
+
may_open = wall(record)
|
| 891 |
+
admitted = [app for app in _finance_applications()
|
| 892 |
+
if may_open(app["permissionKey"])]
|
| 893 |
+
plan.append((str(username), admitted))
|
| 894 |
+
except Exception as exc:
|
| 895 |
+
return {"outcome": "skipped",
|
| 896 |
+
"reason": f"account read failed: {type(exc).__name__}: {exc}"}
|
| 897 |
+
if not plan:
|
| 898 |
+
return {"outcome": "skipped", "reason": "no active accounts"}
|
| 899 |
+
landed = {}
|
| 900 |
+
|
| 901 |
+
def apply(raw):
|
| 902 |
+
doc = _clean_doc(raw)
|
| 903 |
+
state = doc.setdefault("migrations", {})
|
| 904 |
+
if isinstance(state.get(_COPIES), dict):
|
| 905 |
+
landed.update(copy.deepcopy(state[_COPIES]))
|
| 906 |
+
return raw
|
| 907 |
+
now = write_execution.utcnow().isoformat()
|
| 908 |
+
seed = _seed_route_app(doc)
|
| 909 |
+
moves, made = {}, 0
|
| 910 |
+
for username, admitted in plan:
|
| 911 |
+
pairs = moves.setdefault(username, {})
|
| 912 |
+
for index, app in enumerate(_finance_applications()):
|
| 913 |
+
if app not in admitted:
|
| 914 |
+
continue
|
| 915 |
+
old_id = f"finance_{app['key']}"
|
| 916 |
+
new_id = _copy_id(tenant, old_id, username)
|
| 917 |
+
pairs[old_id] = new_id
|
| 918 |
+
if new_id in doc["applications"]:
|
| 919 |
+
continue
|
| 920 |
+
record = _build_application(
|
| 921 |
+
tenant, username,
|
| 922 |
+
{"templateKind": FINANCE_TEMPLATE_KIND, "financeKey": app["key"],
|
| 923 |
+
"name": app["navLabel"], "navPlacement": {"section": "app", "order": index}},
|
| 924 |
+
allowed_databases=set())
|
| 925 |
+
record.update(id=new_id, migratedFrom=old_id)
|
| 926 |
+
doc["applications"][new_id] = record
|
| 927 |
+
made += 1
|
| 928 |
+
if seed is not None:
|
| 929 |
+
new_id = _copy_id(tenant, seed["id"], username)
|
| 930 |
+
pairs[seed["id"]] = new_id
|
| 931 |
+
if new_id not in doc["applications"]:
|
| 932 |
+
record = copy.deepcopy(seed)
|
| 933 |
+
for key in ("retired", "retiredAt"):
|
| 934 |
+
record.pop(key, None)
|
| 935 |
+
record.update(
|
| 936 |
+
id=new_id, createdBy=username, share={"mode": "private", "users": []},
|
| 937 |
+
starredBy=[username] if username in (seed.get("starredBy") or ()) else [],
|
| 938 |
+
createdAt=now, updatedAt=now, revision=1, migratedFrom=seed["id"])
|
| 939 |
+
doc["applications"][new_id] = record
|
| 940 |
+
made += 1
|
| 941 |
+
if seed is not None:
|
| 942 |
+
seed.update(retired=True, retiredAt=now)
|
| 943 |
+
for key in [key for key, value in doc["defaults"].items() if value == seed["id"]]:
|
| 944 |
+
doc["defaults"].pop(key)
|
| 945 |
+
state[_COPIES] = {"state": "copied", "at": now, "accounts": len(plan),
|
| 946 |
+
"copies": made, "seed": seed["id"] if seed else None,
|
| 947 |
+
"moves": moves}
|
| 948 |
+
landed.update(copy.deepcopy(state[_COPIES]))
|
| 949 |
+
return doc
|
| 950 |
+
runtime.update(_KEY, apply)
|
| 951 |
+
if landed.get("state") == "done":
|
| 952 |
+
return {"outcome": "skipped", "reason": "user App copies already applied"}
|
| 953 |
+
moves, copies = landed.get("moves") or {}, int(landed.get("copies") or 0)
|
| 954 |
+
|
| 955 |
+
try:
|
| 956 |
+
moved = _move_placements(runtime, moves)
|
| 957 |
+
except Exception as exc:
|
| 958 |
+
return {"outcome": "skipped",
|
| 959 |
+
"reason": f"folder placement move failed: {type(exc).__name__}: {exc}"}
|
| 960 |
+
def finish(raw):
|
| 961 |
+
doc = _clean_doc(raw)
|
| 962 |
+
state = (doc.get("migrations") or {}).get(_COPIES)
|
| 963 |
+
if not isinstance(state, dict) or state.get("state") == "done":
|
| 964 |
+
return raw
|
| 965 |
+
state.update(state="done", moved=moved, doneAt=write_execution.utcnow().isoformat())
|
| 966 |
+
return doc
|
| 967 |
+
runtime.update(_KEY, finish)
|
| 968 |
+
return {"outcome": "copied", "copies": copies, "accounts": len(moves), "moved": moved,
|
| 969 |
+
"reason": f"{copies} copies for {len(moves)} accounts, {moved} folder placements moved"}
|
| 970 |
+
|
| 971 |
+
|
| 972 |
def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
|
| 973 |
+
allowed_databases=None, target_database=None, expect=None):
|
| 974 |
+
"""Apply a patch, optionally requiring the current share's mode and users to match `expect`."""
|
| 975 |
patch=patch if isinstance(patch,dict) else {}; landed={}
|
| 976 |
immutable = sorted(set(patch) & {
|
| 977 |
"id", "tenant", "type", "templateKind", "sourceDatabase", "fieldMap", "navPlacement",
|
|
|
|
| 983 |
def apply(raw):
|
| 984 |
doc=_clean_doc(raw); app=doc["applications"].get(app_id)
|
| 985 |
if not app: raise ApplicationError("application does not exist")
|
| 986 |
+
if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
|
| 987 |
raise ApplicationError("application does not exist")
|
| 988 |
if app.get("templateKind") in APPLICATION_TEMPLATE_KINDS and "compatibleDatabases" in patch:
|
| 989 |
raise ApplicationError("a template Application's sourceDatabase is immutable")
|
|
|
|
| 992 |
if not may_read(app,user,is_admin): raise PermissionError("application is not available")
|
| 993 |
elif not may_edit(app,user,is_admin):
|
| 994 |
raise PermissionError("application belongs to another user")
|
| 995 |
+
if expect is not None:
|
| 996 |
+
def share_state(value):
|
| 997 |
+
value = value if isinstance(value, dict) else {}
|
| 998 |
+
mode = str(value.get("mode") or "private")
|
| 999 |
+
return mode, _users(value.get("users")) if mode == "users" else []
|
| 1000 |
+
# Compare the fresh share on every store replay before changing any Application field.
|
| 1001 |
+
if share_state(app.get("share")) != share_state(expect):
|
| 1002 |
+
raise shares.GrantsChanged(
|
| 1003 |
+
'this item was shared with somebody else while you were editing, so nothing '
|
| 1004 |
+
'was saved. Reopen the sharing panel to see who has access now, then make '
|
| 1005 |
+
'your change again.')
|
| 1006 |
if "name" in patch:
|
| 1007 |
name=" ".join(str(patch["name"] or "").split())[:120]
|
| 1008 |
if not name: raise ApplicationError("application name is required")
|
|
|
|
| 1038 |
field_contracts=None, allowed_databases=None):
|
| 1039 |
app=load(runtime)["applications"].get(app_id)
|
| 1040 |
if not may_read(app,user,is_admin): raise ApplicationError("application does not exist")
|
| 1041 |
+
if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
|
| 1042 |
raise ApplicationError("application does not exist")
|
| 1043 |
payload={"type":app["type"],"name":f"{app['name']} copy",
|
| 1044 |
"compatibleDatabases":app.get("compatibleDatabases"),
|
| 1045 |
"semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")}
|
| 1046 |
+
for key in ("templateKind", "sourceDatabase", "fieldMap", "navPlacement", "financeKey"):
|
| 1047 |
if key in app: payload[key]=copy.deepcopy(app[key])
|
| 1048 |
return create(runtime,tenant,user,payload,
|
| 1049 |
semantic_records=semantic_records, field_contracts=field_contracts,
|
| 1050 |
allowed_databases=allowed_databases)
|
| 1051 |
|
| 1052 |
|
| 1053 |
+
_ANY_NAME = object()
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
def _strip_view_refs(doc, app_id):
|
| 1057 |
+
"""Remove `config.application` naming `app_id` from every View in one workspace document.
|
| 1058 |
+
|
| 1059 |
+
Walks every top-level member, reserved ones included, and each owner's trash entries.
|
| 1060 |
+
Returns the number of Views changed. Mutates `doc` in place.
|
| 1061 |
+
"""
|
| 1062 |
+
def views_of(bucket):
|
| 1063 |
+
views = bucket.get("views")
|
| 1064 |
+
yield from (views.values() if isinstance(views, dict)
|
| 1065 |
+
else views if isinstance(views, list) else ())
|
| 1066 |
+
trash = bucket.get("trash")
|
| 1067 |
+
for entry in (trash.values() if isinstance(trash, dict)
|
| 1068 |
+
else trash if isinstance(trash, list) else ()):
|
| 1069 |
+
if isinstance(entry, dict) and isinstance(entry.get("view"), dict):
|
| 1070 |
+
yield entry["view"]
|
| 1071 |
+
|
| 1072 |
+
cleared = 0
|
| 1073 |
+
for bucket in (doc.values() if isinstance(doc, dict) else ()):
|
| 1074 |
+
if not isinstance(bucket, dict):
|
| 1075 |
+
continue
|
| 1076 |
+
for view in views_of(bucket):
|
| 1077 |
+
config = view.get("config") if isinstance(view, dict) else None
|
| 1078 |
+
ref = config.get("application") if isinstance(config, dict) else None
|
| 1079 |
+
if isinstance(ref, dict) and str(ref.get("id") or "") == app_id:
|
| 1080 |
+
config.pop("application")
|
| 1081 |
+
cleared += 1
|
| 1082 |
+
return cleared
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
def clear_view_references(runtime, app_id, databases):
|
| 1086 |
+
"""D-2233: drop a deleted App's id from saved Views so each opens as a plain View.
|
| 1087 |
+
|
| 1088 |
+
Returns `(views cleared, reasons for databases not cleared)`. Never raises.
|
| 1089 |
+
"""
|
| 1090 |
+
from core.view_templates import workspace_key
|
| 1091 |
+
cleared, failed = 0, []
|
| 1092 |
+
for database in dict.fromkeys(str(value or "") for value in databases or ()):
|
| 1093 |
+
key = workspace_key(database)
|
| 1094 |
+
if not key:
|
| 1095 |
+
continue
|
| 1096 |
+
try:
|
| 1097 |
+
# A strict read: a failed read is reported, never counted as no reference.
|
| 1098 |
+
if not _strip_view_refs(copy.deepcopy(_read_strict(runtime, key)), app_id):
|
| 1099 |
+
continue
|
| 1100 |
+
count = [0]
|
| 1101 |
+
|
| 1102 |
+
def apply(raw):
|
| 1103 |
+
doc = copy.deepcopy(raw)
|
| 1104 |
+
count[0] = _strip_view_refs(doc, app_id)
|
| 1105 |
+
return doc if count[0] else raw
|
| 1106 |
+
runtime.update(key, apply)
|
| 1107 |
+
cleared += count[0]
|
| 1108 |
+
except Exception as exc:
|
| 1109 |
+
failed.append(f"{database}: {type(exc).__name__}")
|
| 1110 |
+
return cleared, failed
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
def delete(runtime, app_id, user, is_admin=False, *, allowed_databases=None,
|
| 1114 |
+
confirm_name=_ANY_NAME):
|
| 1115 |
+
"""Delete one App record. Its databases, Views and records stay; Views lose the dead id.
|
| 1116 |
+
|
| 1117 |
+
`confirm_name`, when given, must equal the stored name inside the same atomic update.
|
| 1118 |
+
"""
|
| 1119 |
+
removed = {}
|
| 1120 |
+
|
| 1121 |
def apply(raw):
|
| 1122 |
doc=_clean_doc(raw); app=doc["applications"].get(app_id)
|
| 1123 |
if not app: raise ApplicationError("application does not exist")
|
| 1124 |
+
if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
|
| 1125 |
raise ApplicationError("application does not exist")
|
| 1126 |
if not may_edit(app,user,is_admin): raise PermissionError("application belongs to another user")
|
| 1127 |
+
if confirm_name is not _ANY_NAME and (
|
| 1128 |
+
not isinstance(confirm_name, str) or confirm_name != app.get("name")):
|
| 1129 |
+
raise ApplicationError("enter the exact App name to confirm deletion")
|
| 1130 |
+
removed.update(doc["applications"].pop(app_id))
|
| 1131 |
for key in list(doc["defaults"]):
|
| 1132 |
if doc["defaults"][key]==app_id: doc["defaults"].pop(key)
|
| 1133 |
return doc
|
| 1134 |
+
runtime.update(_KEY,apply)
|
| 1135 |
+
result = {"deleted": app_id}
|
| 1136 |
+
# After the registry write: a failed clear is reported, never an undone delete.
|
| 1137 |
+
cleared, failed = clear_view_references(runtime, app_id, removed.get("compatibleDatabases"))
|
| 1138 |
+
if cleared:
|
| 1139 |
+
result["viewsCleared"] = cleared
|
| 1140 |
+
if failed:
|
| 1141 |
+
result["viewsNotCleared"] = "; ".join(failed)
|
| 1142 |
+
return result
|
| 1143 |
|
| 1144 |
|
| 1145 |
def set_default(runtime, database, kind, app_id, user, is_admin=False, *, allowed_databases=None):
|
|
|
|
| 1166 |
raise PermissionError("that database is not available")
|
| 1167 |
doc=load(runtime); explicit=doc["defaults"].get(f"{database}::{kind}")
|
| 1168 |
app=doc["applications"].get(explicit)
|
| 1169 |
+
if app and app.get("retired") is not True and may_read(app,user,is_admin) and database in (app.get("compatibleDatabases") or ()) and app.get("type")==kind:
|
| 1170 |
return {"resolution":"explicit","application":_public(
|
| 1171 |
app,user,is_admin,allowed_databases=allowed_databases,target_database=database,
|
| 1172 |
is_default=True)}
|
| 1173 |
+
# A retired seed still resolves by id but is never offered as the latest default.
|
| 1174 |
+
matches=[x for x in doc["applications"].values() if x.get("type")==kind and database in (x.get("compatibleDatabases") or ()) and may_read(x,user,is_admin) and x.get("retired") is not True]
|
| 1175 |
matches.sort(key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
|
| 1176 |
return {"resolution":"latest" if matches else "blank",
|
| 1177 |
"application":_public(matches[0],user,is_admin,allowed_databases=allowed_databases,
|
api/artifact_share.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Signed frozen artifact links enforce phone binding and Amazon sign-in (C7, R85, R86, R97)."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import base64
|
| 5 |
+
import binascii
|
| 6 |
+
import hmac
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import secrets
|
| 11 |
+
import time
|
| 12 |
+
from hashlib import sha256
|
| 13 |
+
|
| 14 |
+
import assistant_artifacts
|
| 15 |
+
import loopy_links
|
| 16 |
+
|
| 17 |
+
TTL_S = 86400
|
| 18 |
+
# A separate key derived from the session secret, so a share token never verifies as a session.
|
| 19 |
+
_KEY_LABEL = b"loopable artifact share v1"
|
| 20 |
+
_SHARE_ID = re.compile(r"[A-Za-z0-9_\-]{22}")
|
| 21 |
+
_PART = re.compile(r"[A-Za-z0-9_\-]+")
|
| 22 |
+
MAX_TOKEN = 600
|
| 23 |
+
SENT = "A new link is on its way to your WhatsApp."
|
| 24 |
+
ALREADY = "A new link was already sent to your WhatsApp."
|
| 25 |
+
STILL_OPEN = "This link still works. Open it again."
|
| 26 |
+
NOT_VALID = "This link is not valid."
|
| 27 |
+
NOT_SENT = "We could not send a new link. Ask Loopy on WhatsApp for one."
|
| 28 |
+
LINK_TEXT = "Here is your new Loopable link: {link}"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ShareRefused(ValueError):
|
| 32 |
+
"""A refused signed link with an optional normal artifact sign-in destination."""
|
| 33 |
+
|
| 34 |
+
def __init__(self, message, *, link=None):
|
| 35 |
+
super().__init__(message)
|
| 36 |
+
self.link = link
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _secret() -> bytes | None:
|
| 40 |
+
raw = os.environ.get("AIOS_SESSION_SECRET") or ""
|
| 41 |
+
return hmac.new(raw.encode("utf-8"), _KEY_LABEL, sha256).digest() if raw else None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _b64(raw: bytes) -> str:
|
| 45 |
+
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _unb64(text: str) -> bytes:
|
| 49 |
+
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _sign(key: bytes, payload: bytes) -> str:
|
| 53 |
+
return _b64(hmac.new(key, b"token:" + payload, sha256).digest())
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _phone_tag(key: bytes, phone: str) -> str:
|
| 57 |
+
return _b64(hmac.new(key, b"phone:" + phone.encode("utf-8"), sha256).digest()[:12])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _doc_key(share_id: str) -> str:
|
| 61 |
+
return f"artifact_share_{share_id}"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def needs_sign_in(row) -> bool:
|
| 65 |
+
"""Require normal sign-in for Amazon content and unknown provenance under R86."""
|
| 66 |
+
if not isinstance(row, dict):
|
| 67 |
+
return True
|
| 68 |
+
try:
|
| 69 |
+
return assistant_artifacts.c7(row)["amazon"] is not False
|
| 70 |
+
except Exception:
|
| 71 |
+
return True
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _lookup(phone):
|
| 75 |
+
import whatsapp_identity
|
| 76 |
+
return whatsapp_identity.lookup(phone)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _eligible(rt, artifact_id, phone):
|
| 80 |
+
"""Return the owner's username, or raise ShareRefused with a plain reason."""
|
| 81 |
+
if not isinstance(phone, str) or not phone:
|
| 82 |
+
raise ShareRefused("This number is not connected to Loopable.")
|
| 83 |
+
bound = _lookup(phone)
|
| 84 |
+
if not bound:
|
| 85 |
+
raise ShareRefused("This number is not connected to Loopable.")
|
| 86 |
+
tenant, owner = bound
|
| 87 |
+
if tenant != getattr(rt, "key", None):
|
| 88 |
+
raise ShareRefused("This number belongs to another workspace.")
|
| 89 |
+
row = assistant_artifacts.get(rt, owner, artifact_id)
|
| 90 |
+
if row is None:
|
| 91 |
+
raise ShareRefused("That item is not yours.")
|
| 92 |
+
if row.get("status") != "active":
|
| 93 |
+
raise ShareRefused("That item is no longer available.")
|
| 94 |
+
if needs_sign_in(row):
|
| 95 |
+
raise ShareRefused("That item requires sign in to open.", link=loopy_links.artifact_link(row["id"]))
|
| 96 |
+
if row.get("kind") not in {"snapshot", "pdf", "xlsx", "image"} or not row.get("frozen_at"):
|
| 97 |
+
raise ShareRefused("That item has no frozen content to share.")
|
| 98 |
+
return owner
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _mint(rt, artifact_id, owner, phone, key, now):
|
| 102 |
+
share_id = _b64(secrets.token_bytes(16))
|
| 103 |
+
expires = int(now) + TTL_S
|
| 104 |
+
record = {"artifact_id": artifact_id, "owner": owner, "phone": phone,
|
| 105 |
+
"expires": expires, "created": int(now)}
|
| 106 |
+
rt.update(_doc_key(share_id), lambda _raw: dict(record), flush="sync")
|
| 107 |
+
claims = {"t": rt.key, "s": share_id, "a": artifact_id, "p": _phone_tag(key, phone), "x": expires}
|
| 108 |
+
payload = json.dumps(claims, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
| 109 |
+
return f"{_b64(payload)}.{_sign(key, payload)}"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def signed_link(rt, artifact_id, *, phone, now=None):
|
| 113 |
+
"""Mint a signed link, or refuse with a normal artifact link when sign-in is required."""
|
| 114 |
+
key = _secret()
|
| 115 |
+
if key is None or loopy_links.public_base() is None:
|
| 116 |
+
return None
|
| 117 |
+
owner = _eligible(rt, artifact_id, phone)
|
| 118 |
+
token = _mint(rt, artifact_id, owner, phone, key, time.time() if now is None else now)
|
| 119 |
+
return loopy_links.shared_artifact_link(token)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _claims(token, key):
|
| 123 |
+
"""The verified claims of a token, or None for a bad shape or signature."""
|
| 124 |
+
if not isinstance(token, str) or len(token) > MAX_TOKEN or token.count(".") != 1:
|
| 125 |
+
return None
|
| 126 |
+
body, sig = token.split(".")
|
| 127 |
+
if not _PART.fullmatch(body) or not _PART.fullmatch(sig):
|
| 128 |
+
return None
|
| 129 |
+
try:
|
| 130 |
+
payload = _unb64(body)
|
| 131 |
+
except (binascii.Error, ValueError):
|
| 132 |
+
return None
|
| 133 |
+
if _b64(payload) != body:
|
| 134 |
+
return None
|
| 135 |
+
if not hmac.compare_digest(sig, _sign(key, payload)):
|
| 136 |
+
return None
|
| 137 |
+
try:
|
| 138 |
+
claims = json.loads(payload.decode("utf-8"))
|
| 139 |
+
except (UnicodeDecodeError, ValueError):
|
| 140 |
+
return None
|
| 141 |
+
shape = {"t": str, "s": str, "a": str, "p": str, "x": int}
|
| 142 |
+
if not isinstance(claims, dict) or set(claims) != set(shape) or not all(
|
| 143 |
+
isinstance(claims[name], kind) and not isinstance(claims[name], bool)
|
| 144 |
+
for name, kind in shape.items()):
|
| 145 |
+
return None
|
| 146 |
+
return claims if _SHARE_ID.fullmatch(claims["s"]) else None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _runtime(slug):
|
| 150 |
+
from harness import runtime as _rt
|
| 151 |
+
try:
|
| 152 |
+
if slug not in _rt.known_tenants():
|
| 153 |
+
return None
|
| 154 |
+
rt = _rt.get_runtime(slug)
|
| 155 |
+
except Exception:
|
| 156 |
+
return None
|
| 157 |
+
return rt if getattr(rt, "key", None) == slug else None
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def resolve(token, now=None):
|
| 161 |
+
"""Return ok, expired, sign_in or invalid; only ok carries anonymous content rights."""
|
| 162 |
+
invalid = {"state": "invalid", "rt": None, "share": None, "row": None}
|
| 163 |
+
key = _secret()
|
| 164 |
+
if key is None:
|
| 165 |
+
return invalid
|
| 166 |
+
claims = _claims(token, key)
|
| 167 |
+
if claims is None:
|
| 168 |
+
return invalid
|
| 169 |
+
rt = _runtime(claims["t"])
|
| 170 |
+
if rt is None or getattr(rt, "key", None) != claims["t"]:
|
| 171 |
+
return invalid
|
| 172 |
+
try:
|
| 173 |
+
share = rt.get(_doc_key(claims["s"]))
|
| 174 |
+
except Exception:
|
| 175 |
+
return invalid
|
| 176 |
+
if (not isinstance(share, dict) or share.get("artifact_id") != claims["a"]
|
| 177 |
+
or share.get("expires") != claims["x"] or not isinstance(share.get("phone"), str)
|
| 178 |
+
or not isinstance(share.get("owner"), str)
|
| 179 |
+
or not hmac.compare_digest(_phone_tag(key, share["phone"]), claims["p"])):
|
| 180 |
+
return invalid
|
| 181 |
+
try:
|
| 182 |
+
row = assistant_artifacts.get(rt, share["owner"], claims["a"])
|
| 183 |
+
except Exception:
|
| 184 |
+
return invalid
|
| 185 |
+
if (row is None or row.get("id") != claims["a"] or row.get("status") != "active"
|
| 186 |
+
or row.get("kind") not in {"snapshot", "pdf", "xlsx", "image"}
|
| 187 |
+
or not row.get("frozen_at")):
|
| 188 |
+
return invalid
|
| 189 |
+
now = time.time() if now is None else now
|
| 190 |
+
created = share.get("created")
|
| 191 |
+
if (not isinstance(created, int) or isinstance(created, bool)
|
| 192 |
+
or claims["x"] - created != TTL_S or now < created):
|
| 193 |
+
return invalid
|
| 194 |
+
try:
|
| 195 |
+
if _lookup(share["phone"]) != (rt.key, share["owner"]):
|
| 196 |
+
return invalid
|
| 197 |
+
except Exception:
|
| 198 |
+
return invalid
|
| 199 |
+
if needs_sign_in(row):
|
| 200 |
+
return {"state": "sign_in", "rt": rt, "share": share,
|
| 201 |
+
"row": {"id": row["id"], "status": row["status"]}}
|
| 202 |
+
if now >= claims["x"]:
|
| 203 |
+
return {"state": "expired", "rt": rt, "share": share, "row": row}
|
| 204 |
+
return {"state": "ok", "rt": rt, "share": share, "row": row}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _send(phone, text, link, *, tenant, username):
|
| 208 |
+
"""Send inside the 24 hour window as text, outside it as the approved template."""
|
| 209 |
+
import telnyx_whatsapp
|
| 210 |
+
send = getattr(telnyx_whatsapp, "send_reply", None)
|
| 211 |
+
kwargs = {"purpose": "artifact_link", "tenant": tenant, "username": username}
|
| 212 |
+
if send is not None:
|
| 213 |
+
return send(phone, text, link=link, **kwargs)
|
| 214 |
+
if telnyx_whatsapp.within_window(phone):
|
| 215 |
+
return telnyx_whatsapp.send_text(phone, text, **kwargs)
|
| 216 |
+
return telnyx_whatsapp.send_template(phone, telnyx_whatsapp.ping_template(), [text, link], **kwargs)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def request_again(token, now=None):
|
| 220 |
+
"""Send a fresh link for an expired token to the same number; return {"outcome", "message"}."""
|
| 221 |
+
now = time.time() if now is None else now
|
| 222 |
+
found = resolve(token, now)
|
| 223 |
+
if found["state"] == "ok":
|
| 224 |
+
return {"outcome": "still_open", "message": STILL_OPEN}
|
| 225 |
+
if found["state"] != "expired":
|
| 226 |
+
return {"outcome": "invalid", "message": NOT_VALID}
|
| 227 |
+
rt, share = found["rt"], found["share"]
|
| 228 |
+
share_id = _claims(token, _secret())["s"]
|
| 229 |
+
try:
|
| 230 |
+
owner = _eligible(rt, share["artifact_id"], share["phone"])
|
| 231 |
+
except ShareRefused:
|
| 232 |
+
return {"outcome": "refused", "message": NOT_VALID}
|
| 233 |
+
if owner != share["owner"]:
|
| 234 |
+
return {"outcome": "refused", "message": NOT_VALID}
|
| 235 |
+
claimed = []
|
| 236 |
+
|
| 237 |
+
def claim(raw):
|
| 238 |
+
claimed.clear()
|
| 239 |
+
raw = dict(raw or {})
|
| 240 |
+
if raw.get("renewed") is None:
|
| 241 |
+
raw["renewed"] = int(now)
|
| 242 |
+
claimed.append(True)
|
| 243 |
+
return raw
|
| 244 |
+
# One fresh link per expired token, so a visitor cannot flood the number.
|
| 245 |
+
rt.update(_doc_key(share_id), claim, flush="sync")
|
| 246 |
+
if not claimed:
|
| 247 |
+
return {"outcome": "already", "message": ALREADY}
|
| 248 |
+
try:
|
| 249 |
+
link = signed_link(rt, share["artifact_id"], phone=share["phone"], now=now)
|
| 250 |
+
delivery = _send(share["phone"], LINK_TEXT.format(link=link), link,
|
| 251 |
+
tenant=rt.key, username=owner) if link else None
|
| 252 |
+
if isinstance(delivery, dict) and delivery.get("status") in {"sandbox", "sent"}:
|
| 253 |
+
return {"outcome": "sent", "message": SENT}
|
| 254 |
+
except Exception:
|
| 255 |
+
pass
|
| 256 |
+
rt.update(_doc_key(share_id), lambda raw: {**(raw or {}), "renewed": None}, flush="sync")
|
| 257 |
+
return {"outcome": "failed", "message": NOT_SENT}
|
api/artifact_snapshot.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""S72-T68: freeze what a turn made or answered into one `snapshot` artifact (C7, R96, A3)."""
|
| 2 |
+
import copy
|
| 3 |
+
import datetime
|
| 4 |
+
import importlib
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
import re
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
import assistant_artifacts
|
| 11 |
+
|
| 12 |
+
LOG = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
ROW_LIMIT = 200
|
| 15 |
+
MAX_CONTENT_BYTES = 256 * 1024
|
| 16 |
+
MAX_SUMMED_COLUMNS = 15
|
| 17 |
+
MAX_SHEET_COLUMNS = 52
|
| 18 |
+
RECORD_TOOLS = frozenset({"query_database", "database_object"})
|
| 19 |
+
SUMMED_TYPES = frozenset({"currency", "int"})
|
| 20 |
+
OPEN_SENTENCE = "Open in Loopable to see every row."
|
| 21 |
+
_SHEET_READS = {"sheet_read_cells", "sheet_delete_tab"}
|
| 22 |
+
_OBJECT_READS = {"workbook_object": {"list", "get", "export"}, "worksheet_object": {"list", "get"},
|
| 23 |
+
"range_object": {"read"}, "calculation_object": set()}
|
| 24 |
+
_ADDR = re.compile(r"([A-Z]{1,3})([0-9]{1,7})")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _module(name):
|
| 28 |
+
"""Import a live reader by name at call time; a fixture swaps it in `sys.modules`."""
|
| 29 |
+
return importlib.import_module(name)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _query(session, database, payload):
|
| 33 |
+
return _module("routes_external")._query_database(session, database, payload)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _visible_keys(session, database):
|
| 37 |
+
"""The field keys the maker may read, from the Assistant read scope."""
|
| 38 |
+
scoped = _module("deps").assistant_read_scope(session, database, mode="schema")
|
| 39 |
+
return {field["key"] for field in scoped.get("fields") or ()
|
| 40 |
+
if isinstance(field, dict) and isinstance(field.get("key"), str)}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _authorization_scope(session, database):
|
| 44 |
+
"""Resolve current field and row authority without reading source values."""
|
| 45 |
+
from core import perm_scope
|
| 46 |
+
scoped = _module("deps").assistant_read_scope(session, database, mode="schema")
|
| 47 |
+
grant = perm_scope.assistant_entry(session.user, database) or {}
|
| 48 |
+
fields = scoped.get("fields") or ()
|
| 49 |
+
audience = False
|
| 50 |
+
if database.startswith("ut_"):
|
| 51 |
+
definitions = session.runtime.get_projection("user_tables", drop=("rows",))
|
| 52 |
+
definition = definitions.get(database) if isinstance(definitions, dict) else None
|
| 53 |
+
if not isinstance(definition, dict):
|
| 54 |
+
raise ValueError("The source definition is unavailable.")
|
| 55 |
+
audience = perm_scope.audience_declared(database, st=session.runtime, defn=definition)
|
| 56 |
+
fields = definition.get("fields") or ()
|
| 57 |
+
pool = perm_scope.derive_pool_scope(session.user, database)
|
| 58 |
+
return {"database": database,
|
| 59 |
+
"fields": sorted(field["key"] for field in scoped.get("fields") or ()
|
| 60 |
+
if isinstance(field, dict) and isinstance(field.get("key"), str)),
|
| 61 |
+
"field_types": {field["key"]: field.get("type") for field in fields
|
| 62 |
+
if isinstance(field, dict) and isinstance(field.get("key"), str)},
|
| 63 |
+
"hidden": sorted(str(key) for key in grant.get("hiddenFields") or ()),
|
| 64 |
+
"filter": copy.deepcopy(grant.get("filter")) or None,
|
| 65 |
+
"pool": list(pool), "audience": audience}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _authorization_proof(session, sources):
|
| 69 |
+
"""Bind a server-captured document to its maker, tenant and permission scopes."""
|
| 70 |
+
return {"version": 1, "tenant": session.tenant, "owner": session.uname,
|
| 71 |
+
"scopes": [_authorization_scope(session, source) for source in sources]}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def require_permission(session, sources, content):
|
| 75 |
+
"""Refuse frozen values whose current authorization cannot be proved without live rows."""
|
| 76 |
+
def refuse():
|
| 77 |
+
raise _module("deps").err(403, "assistant_forbidden",
|
| 78 |
+
"Your current permissions do not allow this snapshot.")
|
| 79 |
+
|
| 80 |
+
if sources is None or content.get("sources") != sources:
|
| 81 |
+
refuse()
|
| 82 |
+
proof = content.get("_authorization")
|
| 83 |
+
try:
|
| 84 |
+
current = _authorization_proof(session, sources)
|
| 85 |
+
except Exception:
|
| 86 |
+
refuse()
|
| 87 |
+
# Recipient membership can change independently of the rows-free permission contract.
|
| 88 |
+
if any(scope["audience"] for scope in current["scopes"]):
|
| 89 |
+
refuse()
|
| 90 |
+
if proof is not None:
|
| 91 |
+
if proof != current:
|
| 92 |
+
refuse()
|
| 93 |
+
return
|
| 94 |
+
# Legacy sheets and unknown origins cannot prove which fields supplied their displayed values.
|
| 95 |
+
if len(sources) != 1 or content.get("kind_of") not in ("records", "view", "app"):
|
| 96 |
+
refuse()
|
| 97 |
+
scope = current["scopes"][0]
|
| 98 |
+
if scope["hidden"] or scope["filter"] or any(value is not None for value in scope["pool"]):
|
| 99 |
+
refuse()
|
| 100 |
+
columns, sums = content.get("columns"), (content.get("totals") or {}).get("sum")
|
| 101 |
+
if not isinstance(columns, list) or not isinstance(sums, dict):
|
| 102 |
+
refuse()
|
| 103 |
+
visible = set(scope["fields"])
|
| 104 |
+
if (any(not isinstance(column, dict) or column.get("key") not in visible for column in columns)
|
| 105 |
+
or not set(sums).issubset(visible)):
|
| 106 |
+
refuse()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _load_view(session, database, view_id):
|
| 110 |
+
found = _module("routes_external")._view_context(session, database, {}).table.find_view(
|
| 111 |
+
view_id, prefer_owner=session.uname)
|
| 112 |
+
return found[1] if found else None
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _load_workbook(session, workbook_id):
|
| 116 |
+
book = _module("core.sheets").get_workbook(session.runtime, workbook_id)
|
| 117 |
+
routes = _module("routes_sheet")
|
| 118 |
+
routes._require_reader(session, book)
|
| 119 |
+
return routes._read_for(session, book)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _binding_readable(session, binding, book, tab):
|
| 123 |
+
"""True only when the maker can resolve this binding now."""
|
| 124 |
+
try:
|
| 125 |
+
_module("routes_sheet")._resolve_cell_binding(session, binding, book, tab.get("id"))
|
| 126 |
+
return True
|
| 127 |
+
except Exception:
|
| 128 |
+
return False
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _now():
|
| 132 |
+
return datetime.datetime.fromtimestamp(time.time(), datetime.timezone.utc).isoformat()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _text(value):
|
| 136 |
+
return value.strip() if isinstance(value, str) and value.strip() else None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _kind_of(name, args):
|
| 140 |
+
action = args.get("action")
|
| 141 |
+
if name == "query_database" or (name == "database_object" and action == "query"):
|
| 142 |
+
return "records"
|
| 143 |
+
if name.startswith("sheet_") and name not in _SHEET_READS:
|
| 144 |
+
return "sheet"
|
| 145 |
+
if name.startswith("workbook_") and name != "workbook_object":
|
| 146 |
+
return "sheet"
|
| 147 |
+
if name in _OBJECT_READS and action not in _OBJECT_READS[name] and action != "delete":
|
| 148 |
+
return "sheet"
|
| 149 |
+
if name == "view_upsert" or (name == "view_object" and action == "upsert"):
|
| 150 |
+
return "view"
|
| 151 |
+
if name == "app_upsert":
|
| 152 |
+
return "app"
|
| 153 |
+
return None
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _rows_sentence(shown, total, cause):
|
| 157 |
+
return f"Showing {shown:,} of {total:,} rows because {cause}. {OPEN_SENTENCE}"
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _totals(session, database, filters, columns):
|
| 161 |
+
"""Count every permitted row and sum the number columns, server side, over ALL rows."""
|
| 162 |
+
numeric = [col["key"] for col in columns if col.get("type") in SUMMED_TYPES]
|
| 163 |
+
notes = []
|
| 164 |
+
if len(numeric) > MAX_SUMMED_COLUMNS:
|
| 165 |
+
notes.append(f"Totals cover the first {MAX_SUMMED_COLUMNS} number columns.")
|
| 166 |
+
numeric = numeric[:MAX_SUMMED_COLUMNS]
|
| 167 |
+
base = {"limit": 1}
|
| 168 |
+
if filters:
|
| 169 |
+
base["filters"] = copy.deepcopy(filters)
|
| 170 |
+
specs = [{"fn": "count"}] + [{"fn": "sum", "field": key} for key in numeric]
|
| 171 |
+
try:
|
| 172 |
+
answer = _query(session, database, {**base, "aggregates": specs})
|
| 173 |
+
except Exception:
|
| 174 |
+
if not numeric:
|
| 175 |
+
raise
|
| 176 |
+
notes.append("Totals show the row count only because a number column holds text.")
|
| 177 |
+
answer = _query(session, database, {**base, "aggregates": [{"fn": "count"}]})
|
| 178 |
+
totals = {"count": None, "sum": {}}
|
| 179 |
+
for agg in answer.get("aggregates") or ():
|
| 180 |
+
if agg.get("fn") == "count" and agg.get("field") is None:
|
| 181 |
+
totals["count"] = agg.get("value")
|
| 182 |
+
elif agg.get("fn") == "sum":
|
| 183 |
+
totals["sum"][agg["field"]] = agg.get("value")
|
| 184 |
+
if not isinstance(totals["count"], int):
|
| 185 |
+
raise ValueError("the reader returned no row count")
|
| 186 |
+
return totals, notes
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _columns(fields, keys, visible):
|
| 190 |
+
"""Column order follows `keys`; a field hidden from the maker never becomes a column."""
|
| 191 |
+
by_key = {f["key"]: f for f in fields or () if isinstance(f, dict) and isinstance(f.get("key"), str)}
|
| 192 |
+
out = []
|
| 193 |
+
for key in keys:
|
| 194 |
+
if key in by_key and key in visible:
|
| 195 |
+
field = by_key[key]
|
| 196 |
+
out.append({"key": key, "label": _text(field.get("label")) or key, "type": field.get("type")})
|
| 197 |
+
return out
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _table_content(session, database, title, kind_of, result, filters, page_read, column_keys=None):
|
| 201 |
+
"""Build records, view or app content from one reader result."""
|
| 202 |
+
visible = _visible_keys(session, database)
|
| 203 |
+
fields = result.get("fields") or []
|
| 204 |
+
keys = column_keys if column_keys is not None else [f.get("key") for f in fields if isinstance(f, dict)]
|
| 205 |
+
columns = _columns(fields, keys, visible)
|
| 206 |
+
records = result.get("records") or []
|
| 207 |
+
rows = [[copy.deepcopy(rec.get(col["key"])) for col in columns] for rec in records[:ROW_LIMIT]]
|
| 208 |
+
totals, notes = _totals(session, database, filters, columns)
|
| 209 |
+
total = totals["count"]
|
| 210 |
+
if len(rows) < total:
|
| 211 |
+
cause = ("Loopy read only those rows" if page_read and len(records) <= ROW_LIMIT
|
| 212 |
+
else f"a snapshot keeps the first {ROW_LIMIT}")
|
| 213 |
+
notes.insert(0, _rows_sentence(len(rows), total, cause))
|
| 214 |
+
return {"title": title, "kind_of": kind_of,
|
| 215 |
+
"columns": [{"key": c["key"], "label": c["label"]} for c in columns],
|
| 216 |
+
"rows": rows, "totals": totals, "row_count": total, "shown": len(rows),
|
| 217 |
+
"notes": notes, "sources": [database]}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _record_list(session, name, args, result):
|
| 221 |
+
if (not isinstance(result, dict) or not isinstance(result.get("records"), list)
|
| 222 |
+
or result.get("groups")):
|
| 223 |
+
return None
|
| 224 |
+
database = _text(args.get("database")) or _text(result.get("database"))
|
| 225 |
+
if database is None:
|
| 226 |
+
return None
|
| 227 |
+
query = args.get("query") if name == "database_object" else args
|
| 228 |
+
filters = (query or {}).get("filters")
|
| 229 |
+
title = f"{_text(result.get('label')) or database} records"
|
| 230 |
+
return _table_content(session, database, title, "records", result, filters, True)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _view_payload(config, visible):
|
| 234 |
+
keys = config.get("visible")
|
| 235 |
+
keys = list(keys) if isinstance(keys, list) else None
|
| 236 |
+
order = [k for k in config.get("order") or () if isinstance(k, str)]
|
| 237 |
+
if keys is not None and order:
|
| 238 |
+
keys = [k for k in order if k in keys] + [k for k in keys if k not in order]
|
| 239 |
+
payload = {"limit": ROW_LIMIT}
|
| 240 |
+
if keys is not None:
|
| 241 |
+
payload["fields"] = [k for k in dict.fromkeys(keys) if k in visible]
|
| 242 |
+
sorts = [{"field": rule.get("colId"), "direction": rule.get("dir")}
|
| 243 |
+
for rule in config.get("sorts") or () if isinstance(rule, dict)]
|
| 244 |
+
if sorts:
|
| 245 |
+
payload["sorts"] = sorts[:8]
|
| 246 |
+
filters = config.get("filters")
|
| 247 |
+
if isinstance(filters, list) and filters:
|
| 248 |
+
payload["filters"] = {"conj": config.get("filterConj") or "and", "nodes": filters}
|
| 249 |
+
elif isinstance(filters, dict) and filters.get("nodes"):
|
| 250 |
+
payload["filters"] = filters
|
| 251 |
+
return payload
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _view(session, args, result):
|
| 255 |
+
database = _text(args.get("database")) or _text((result or {}).get("database"))
|
| 256 |
+
draft = args.get("view") if isinstance(args.get("view"), dict) else {}
|
| 257 |
+
view_id = _text((result or {}).get("view_id")) or _text(draft.get("id"))
|
| 258 |
+
if database is None or view_id is None:
|
| 259 |
+
return None
|
| 260 |
+
view = _load_view(session, database, view_id) or draft
|
| 261 |
+
config = view.get("config") if isinstance(view.get("config"), dict) else {}
|
| 262 |
+
payload = _view_payload(config, _visible_keys(session, database))
|
| 263 |
+
answer = _query(session, database, payload)
|
| 264 |
+
title = _text(view.get("name")) or "Saved View"
|
| 265 |
+
return _table_content(session, database, title, "view", answer, payload.get("filters"), False,
|
| 266 |
+
payload.get("fields"))
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _app(session, args, result):
|
| 270 |
+
app = (result or {}).get("application")
|
| 271 |
+
app = app if isinstance(app, dict) else {}
|
| 272 |
+
title = _text(app.get("name")) or _text(args.get("name")) or "App"
|
| 273 |
+
compatible = app.get("compatibleDatabases") or args.get("compatibleDatabases") or []
|
| 274 |
+
database = (_text(app.get("sourceDatabase")) or _text(args.get("sourceDatabase"))
|
| 275 |
+
or (_text(compatible[0]) if isinstance(compatible, list) and compatible else None))
|
| 276 |
+
if database is None:
|
| 277 |
+
return {"title": title, "kind_of": "app", "columns": [], "rows": [], "totals": {"count": 0, "sum": {}},
|
| 278 |
+
"row_count": 0, "shown": 0, "notes": ["This App reads no database."], "sources": None}
|
| 279 |
+
payload = {"limit": ROW_LIMIT}
|
| 280 |
+
field_map = app.get("fieldMap") or args.get("fieldMap")
|
| 281 |
+
if isinstance(field_map, dict) and field_map:
|
| 282 |
+
visible = _visible_keys(session, database)
|
| 283 |
+
payload["fields"] = [k for k in dict.fromkeys(field_map.values()) if k in visible]
|
| 284 |
+
answer = _query(session, database, payload)
|
| 285 |
+
return _table_content(session, database, title, "app", answer, None, False, payload.get("fields"))
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _col_index(letters):
|
| 289 |
+
n = 0
|
| 290 |
+
for ch in letters:
|
| 291 |
+
n = n * 26 + ord(ch) - 64
|
| 292 |
+
return n
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _col_name(n):
|
| 296 |
+
out = ""
|
| 297 |
+
while n:
|
| 298 |
+
n, rem = divmod(n - 1, 26)
|
| 299 |
+
out = chr(65 + rem) + out
|
| 300 |
+
return out
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _cell_shown(cell):
|
| 304 |
+
for key in ("display", "text"):
|
| 305 |
+
if isinstance(cell.get(key), str) and cell[key] != "":
|
| 306 |
+
return cell[key]
|
| 307 |
+
value = cell.get("value")
|
| 308 |
+
return "" if value is None else value
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _sheet(session, name, args, result):
|
| 312 |
+
result = result if isinstance(result, dict) else {}
|
| 313 |
+
nested = result.get("workbook") if isinstance(result.get("workbook"), dict) else {}
|
| 314 |
+
workbook_id = (_text(args.get("workbook_id")) or _text(result.get("workbook_id"))
|
| 315 |
+
or _text(nested.get("id")) or _text(result.get("id")))
|
| 316 |
+
if workbook_id is None:
|
| 317 |
+
return None
|
| 318 |
+
book = _load_workbook(session, workbook_id)
|
| 319 |
+
tabs = [tab for tab in book.get("sheets") or () if isinstance(tab, dict)]
|
| 320 |
+
if not tabs:
|
| 321 |
+
return None
|
| 322 |
+
wanted = args.get("tab") or args.get("worksheet") or result.get("tab")
|
| 323 |
+
wanted = wanted.get("id") if isinstance(wanted, dict) else wanted
|
| 324 |
+
tab = next((t for t in tabs if wanted is not None and wanted in (t.get("id"), t.get("name"))), tabs[0])
|
| 325 |
+
cells = {}
|
| 326 |
+
for addr, cell in (tab.get("cells") or {}).items():
|
| 327 |
+
match = _ADDR.fullmatch(str(addr).strip().upper())
|
| 328 |
+
if match and isinstance(cell, dict):
|
| 329 |
+
cells[(int(match.group(2)), _col_index(match.group(1)))] = cell
|
| 330 |
+
sources, unnamed, checked = set(), False, {}
|
| 331 |
+
# A displayed formula can read a binding on another tab.
|
| 332 |
+
for source_tab in tabs:
|
| 333 |
+
for cell in (source_tab.get("cells") or {}).values():
|
| 334 |
+
if not isinstance(cell, dict) or cell.get("binding") is None:
|
| 335 |
+
continue
|
| 336 |
+
binding = cell["binding"]
|
| 337 |
+
database = _text(binding.get("database")) if isinstance(binding, dict) else None
|
| 338 |
+
if database is None:
|
| 339 |
+
unnamed = True
|
| 340 |
+
else:
|
| 341 |
+
sources.add(database)
|
| 342 |
+
shown = {}
|
| 343 |
+
for at, cell in cells.items():
|
| 344 |
+
binding = cell.get("binding")
|
| 345 |
+
if binding is not None:
|
| 346 |
+
database = _text(binding.get("database")) if isinstance(binding, dict) else None
|
| 347 |
+
if database is None:
|
| 348 |
+
continue
|
| 349 |
+
memo = json.dumps(binding, sort_keys=True, default=str)
|
| 350 |
+
if memo not in checked:
|
| 351 |
+
checked[memo] = _binding_readable(session, binding, book, tab)
|
| 352 |
+
if not checked[memo]:
|
| 353 |
+
continue
|
| 354 |
+
shown[at] = copy.deepcopy(_cell_shown(cell))
|
| 355 |
+
last_row = max((r for r, _ in cells), default=0)
|
| 356 |
+
last_col = max((c for _, c in cells), default=0)
|
| 357 |
+
notes = []
|
| 358 |
+
if last_col > MAX_SHEET_COLUMNS:
|
| 359 |
+
notes.append(f"Showing the first {MAX_SHEET_COLUMNS} columns because a snapshot keeps "
|
| 360 |
+
f"{MAX_SHEET_COLUMNS} columns. Open in Loopable to see every column.")
|
| 361 |
+
width = min(last_col, MAX_SHEET_COLUMNS)
|
| 362 |
+
rows = [[shown.get((r, c), "") for c in range(1, width + 1)] for r in range(1, min(last_row, ROW_LIMIT) + 1)]
|
| 363 |
+
if last_row > ROW_LIMIT:
|
| 364 |
+
notes.insert(0, _rows_sentence(ROW_LIMIT, last_row, f"a snapshot keeps the first {ROW_LIMIT}"))
|
| 365 |
+
book_name = _text(book.get("name")) or "Sheet"
|
| 366 |
+
tab_name = _text(tab.get("name"))
|
| 367 |
+
return {"title": f"{book_name}, {tab_name}" if tab_name and len(tabs) > 1 else book_name,
|
| 368 |
+
"kind_of": "sheet",
|
| 369 |
+
"columns": [{"key": _col_name(c), "label": _col_name(c)} for c in range(1, width + 1)],
|
| 370 |
+
"rows": rows, "totals": {"count": last_row, "sum": {}}, "row_count": last_row,
|
| 371 |
+
"shown": len(rows), "notes": notes, "sources": None if unnamed else sorted(sources)}
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def _size(content):
|
| 375 |
+
return len(json.dumps(content, sort_keys=True, default=str).encode("utf-8"))
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _finish(content, frozen_at):
|
| 379 |
+
"""Apply the byte bound, join the notes and stamp the time, keeping totals over all rows."""
|
| 380 |
+
content = json.loads(json.dumps(content, default=str))
|
| 381 |
+
notes = content.pop("notes")
|
| 382 |
+
content.update(frozen_at=frozen_at, note=" ".join(notes) or None)
|
| 383 |
+
if _size(content) > MAX_CONTENT_BYTES:
|
| 384 |
+
lo, hi, rows = 0, len(content["rows"]), content["rows"]
|
| 385 |
+
notes = [n for n in notes if not re.match(r"Showing [\d,]+ of [\d,]+ rows because ", n)]
|
| 386 |
+
|
| 387 |
+
def bounded(count):
|
| 388 |
+
content["rows"] = rows[:count]
|
| 389 |
+
content["shown"] = count
|
| 390 |
+
content["note"] = " ".join([
|
| 391 |
+
_rows_sentence(count, content["row_count"],
|
| 392 |
+
f"a snapshot keeps at most {MAX_CONTENT_BYTES // 1024} KB"), *notes])
|
| 393 |
+
return _size(content) <= MAX_CONTENT_BYTES
|
| 394 |
+
|
| 395 |
+
if not bounded(0):
|
| 396 |
+
raise ValueError("Snapshot labels and totals exceed the content bound.")
|
| 397 |
+
while lo < hi:
|
| 398 |
+
mid = (lo + hi + 1) // 2
|
| 399 |
+
lo, hi = (mid, hi) if bounded(mid) else (lo, mid - 1)
|
| 400 |
+
bounded(lo)
|
| 401 |
+
return {key: content[key] for key in ("title", "kind_of", "columns", "rows", "totals", "row_count",
|
| 402 |
+
"shown", "note", "sources", "frozen_at", "_authorization")
|
| 403 |
+
if key in content}
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def _retire_earlier(rt, username, turn):
|
| 407 |
+
"""Keep one active record-list snapshot per turn."""
|
| 408 |
+
for item_id in list(turn.get("artifacts") or ()):
|
| 409 |
+
row = assistant_artifacts.get(rt, username, item_id)
|
| 410 |
+
if (row and row.get("kind") == "snapshot" and row.get("status") == "active"
|
| 411 |
+
and row.get("toolCall", {}).get("name") in RECORD_TOOLS):
|
| 412 |
+
assistant_artifacts.set_status(rt, username, item_id, "deleted")
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def capture(session, door, name, args, result, turn):
|
| 416 |
+
"""Store a frozen snapshot of this tool call when it qualifies; return its id or None. Never raises."""
|
| 417 |
+
try:
|
| 418 |
+
if (door not in assistant_artifacts.DOORS or not isinstance(name, str)
|
| 419 |
+
or not isinstance(turn, dict) or not isinstance(turn.get("artifacts"), list)):
|
| 420 |
+
return None
|
| 421 |
+
args = args if isinstance(args, dict) else {}
|
| 422 |
+
kind_of = _kind_of(name, args)
|
| 423 |
+
if kind_of is None:
|
| 424 |
+
return None
|
| 425 |
+
build = {"records": lambda: _record_list(session, name, args, result),
|
| 426 |
+
"sheet": lambda: _sheet(session, name, args, result),
|
| 427 |
+
"view": lambda: _view(session, args, result),
|
| 428 |
+
"app": lambda: _app(session, args, result)}[kind_of]
|
| 429 |
+
content = build()
|
| 430 |
+
if content is None:
|
| 431 |
+
return None
|
| 432 |
+
if content["sources"] is not None:
|
| 433 |
+
if kind_of == "sheet":
|
| 434 |
+
try:
|
| 435 |
+
content["_authorization"] = _authorization_proof(session, content["sources"])
|
| 436 |
+
except Exception:
|
| 437 |
+
pass # A blanked unreadable binding retains protected provenance.
|
| 438 |
+
else:
|
| 439 |
+
content["_authorization"] = _authorization_proof(session, content["sources"])
|
| 440 |
+
rt, username = session.runtime, session.uname
|
| 441 |
+
frozen_at = _now()
|
| 442 |
+
content = _finish(content, frozen_at)
|
| 443 |
+
ref = assistant_artifacts.store_snapshot(rt, username, content)
|
| 444 |
+
if kind_of == "records":
|
| 445 |
+
_retire_earlier(rt, username, turn)
|
| 446 |
+
item_id = assistant_artifacts.record(rt, username, {
|
| 447 |
+
"kind": "snapshot", "ref": ref, "title": content["title"], "door": door,
|
| 448 |
+
"toolCall": {"name": name, "args": copy.deepcopy(args)}, "createdAt": time.time(),
|
| 449 |
+
"sources": content["sources"], "frozen_at": frozen_at})
|
| 450 |
+
turn["artifacts"].append(item_id)
|
| 451 |
+
return item_id
|
| 452 |
+
except Exception as exc:
|
| 453 |
+
LOG.warning("snapshot not captured for %s: %s: %s", name, type(exc).__name__, exc)
|
| 454 |
+
return None
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def read(rt, artifact_id):
|
| 458 |
+
"""Return the stored artifact and its frozen content; read only those two documents."""
|
| 459 |
+
row = assistant_artifacts.get_by_id(rt, artifact_id)
|
| 460 |
+
if row is None or row.get("kind") != "snapshot" or row.get("status") == "deleted":
|
| 461 |
+
return None
|
| 462 |
+
content = assistant_artifacts.read_snapshot(rt, row)
|
| 463 |
+
if content is None:
|
| 464 |
+
return None
|
| 465 |
+
return {"artifact": assistant_artifacts.c7(row),
|
| 466 |
+
"snapshot": {key: value for key, value in content.items() if key != "_authorization"}}
|
api/assistant_artifacts.py
CHANGED
|
@@ -4,13 +4,20 @@ import datetime
|
|
| 4 |
import heapq
|
| 5 |
import json
|
| 6 |
import math
|
|
|
|
|
|
|
| 7 |
|
| 8 |
import assistant_log
|
|
|
|
| 9 |
|
| 10 |
CHUNK_ITEMS = 200
|
| 11 |
-
KINDS = {"view", "sheet", "report", "run", "query", "schedule", "pdf"}
|
|
|
|
| 12 |
DOORS = {"app", "whatsapp", "wake"}
|
| 13 |
STATUSES = {"active", "paused", "deleted"}
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
def timestamp(value):
|
|
@@ -35,6 +42,86 @@ def _chunk_key(h, n):
|
|
| 35 |
return f"assistant_artifacts_{h}_{n}"
|
| 36 |
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
def record(rt, username, item):
|
| 39 |
"""Validate and append exactly one C14 item; return its principal-bound id."""
|
| 40 |
from routes_query import _no_dashes
|
|
@@ -60,9 +147,12 @@ def record(rt, username, item):
|
|
| 60 |
at = timestamp(item.get("createdAt"))
|
| 61 |
except (TypeError, ValueError, OverflowError, OSError) as exc:
|
| 62 |
raise ValueError("An artifact needs JSON arguments and a valid creation time.") from exc
|
|
|
|
| 63 |
value = {"kind": item["kind"], "ref": ref, "title": _no_dashes(item["title"]).strip()[:200],
|
| 64 |
"door": item["door"], "toolCall": {"name": call["name"], "args": copy.deepcopy(call["args"])},
|
| 65 |
-
"createdAt": at, "status": "active"}
|
|
|
|
|
|
|
| 66 |
h = assistant_log._hash(rt, username)
|
| 67 |
allocated = []
|
| 68 |
def allocate(raw):
|
|
@@ -76,6 +166,7 @@ def record(rt, username, item):
|
|
| 76 |
rt.update(f"assistant_artifacts_{h}_index", allocate, flush="sync")
|
| 77 |
seq, n = allocated
|
| 78 |
row = {**value, "id": f"{h}.{seq}", "seq": seq}
|
|
|
|
| 79 |
def insert(raw):
|
| 80 |
existing = {entry["seq"]: entry for entry in (raw or {}).get("items", [])}
|
| 81 |
existing.setdefault(seq, row)
|
|
@@ -130,6 +221,64 @@ def get(rt, username, item_id):
|
|
| 130 |
return next((copy.deepcopy(row) for row in chunk.get("items", []) if row["id"] == item_id), None)
|
| 131 |
|
| 132 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
def set_status(rt, username, item_id, status):
|
| 134 |
if not isinstance(status, str) or status not in STATUSES:
|
| 135 |
raise ValueError("That artifact status is not available.")
|
|
|
|
| 4 |
import heapq
|
| 5 |
import json
|
| 6 |
import math
|
| 7 |
+
import re
|
| 8 |
+
import uuid
|
| 9 |
|
| 10 |
import assistant_log
|
| 11 |
+
import loopy_links
|
| 12 |
|
| 13 |
CHUNK_ITEMS = 200
|
| 14 |
+
KINDS = {"view", "sheet", "report", "run", "query", "schedule", "pdf", "xlsx", "image", "snapshot"}
|
| 15 |
+
FROZEN_KINDS = {"snapshot", "pdf", "xlsx", "image"}
|
| 16 |
DOORS = {"app", "whatsapp", "wake"}
|
| 17 |
STATUSES = {"active", "paused", "deleted"}
|
| 18 |
+
AMAZON_PREFIX = "ut_amzn_"
|
| 19 |
+
_ITEM_ID = re.compile(r"([0-9a-f]{24})\.([0-9]+)")
|
| 20 |
+
_SNAPSHOT_REF = re.compile(r"[0-9a-f]{32}")
|
| 21 |
|
| 22 |
|
| 23 |
def timestamp(value):
|
|
|
|
| 42 |
return f"assistant_artifacts_{h}_{n}"
|
| 43 |
|
| 44 |
|
| 45 |
+
def _source_keys(sources):
|
| 46 |
+
"""Return normalized database keys, or None for unknown or malformed provenance."""
|
| 47 |
+
if not isinstance(sources, list) or not all(isinstance(key, str) and key.strip() for key in sources):
|
| 48 |
+
return None
|
| 49 |
+
return [key.strip() for key in sources]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def is_amazon(sources):
|
| 53 |
+
"""R86 applies to Amazon databases and unknown or malformed provenance."""
|
| 54 |
+
keys = _source_keys(sources)
|
| 55 |
+
return keys is None or any(key.startswith(AMAZON_PREFIX) for key in keys)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _optional_text(item, field, sentence):
|
| 59 |
+
value = item.get(field)
|
| 60 |
+
if value is not None and (not isinstance(value, str) or not value.strip()):
|
| 61 |
+
raise ValueError(sentence)
|
| 62 |
+
return value.strip() if value is not None else None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _c7_inputs(item, kind, args, created_at):
|
| 66 |
+
"""Validate the optional C7 inputs and return sources, amazon, file_id, mime and frozen_at."""
|
| 67 |
+
sources = item.get("sources")
|
| 68 |
+
if sources is not None and _source_keys(sources) is None:
|
| 69 |
+
raise ValueError("Artifact sources must be a list of database names.")
|
| 70 |
+
if sources is None and kind in ("view", "query") and isinstance(args.get("database"), str) \
|
| 71 |
+
and args["database"].strip():
|
| 72 |
+
sources = [args["database"].strip()]
|
| 73 |
+
elif sources is not None:
|
| 74 |
+
sources = _source_keys(sources)
|
| 75 |
+
if "amazon" in item and not isinstance(item["amazon"], bool):
|
| 76 |
+
raise ValueError("The artifact Amazon flag must be true or false.")
|
| 77 |
+
amazon = is_amazon(sources) or item.get("amazon") is True
|
| 78 |
+
file_id = _optional_text(item, "file_id", "An artifact file id must be text.")
|
| 79 |
+
mime = _optional_text(item, "mime", "An artifact file type must be text.")
|
| 80 |
+
frozen = item.get("frozen_at")
|
| 81 |
+
try:
|
| 82 |
+
frozen = timestamp(frozen) if frozen is not None else None
|
| 83 |
+
except (TypeError, ValueError, OverflowError, OSError) as exc:
|
| 84 |
+
raise ValueError("An artifact needs a valid frozen time.") from exc
|
| 85 |
+
if frozen is None and kind in FROZEN_KINDS:
|
| 86 |
+
frozen = created_at
|
| 87 |
+
return sources, amazon, file_id, mime, frozen
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _app_database(rt, ref, args):
|
| 91 |
+
compatible = args.get("compatibleDatabases")
|
| 92 |
+
if isinstance(compatible, list) and compatible and isinstance(compatible[0], str) and compatible[0].strip():
|
| 93 |
+
return compatible[0]
|
| 94 |
+
if isinstance(args.get("sourceDatabase"), str) and args["sourceDatabase"].strip():
|
| 95 |
+
return args["sourceDatabase"]
|
| 96 |
+
try:
|
| 97 |
+
import application_registry
|
| 98 |
+
stored = application_registry.load(rt)["applications"].get(ref) or {}
|
| 99 |
+
first = (stored.get("compatibleDatabases") or [None])[0]
|
| 100 |
+
return first if isinstance(first, str) and first.strip() else None
|
| 101 |
+
except Exception:
|
| 102 |
+
# A registry read failure falls back to the artifact link.
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _link(rt, row):
|
| 107 |
+
"""The absolute link that opens this row's work, or None with no public base."""
|
| 108 |
+
kind, ref, call = row["kind"], row["ref"], row["toolCall"]
|
| 109 |
+
args = call["args"]
|
| 110 |
+
# A fixture links module can carry only the artifact builder, so a missing builder means no link.
|
| 111 |
+
build = lambda name, *values: (getattr(loopy_links, name, None) or (lambda *_: None))(*values)
|
| 112 |
+
link = None
|
| 113 |
+
if ref is not None:
|
| 114 |
+
if kind == "sheet":
|
| 115 |
+
link = build("sheet_link", ref)
|
| 116 |
+
elif kind == "view":
|
| 117 |
+
link = build("view_link", args.get("database"), ref)
|
| 118 |
+
elif kind == "query":
|
| 119 |
+
link = build("query_link", ref)
|
| 120 |
+
elif kind == "run" and call["name"] == "app_upsert":
|
| 121 |
+
link = build("application_link", ref, _app_database(rt, ref, args))
|
| 122 |
+
return link or loopy_links.artifact_link(row["id"])
|
| 123 |
+
|
| 124 |
+
|
| 125 |
def record(rt, username, item):
|
| 126 |
"""Validate and append exactly one C14 item; return its principal-bound id."""
|
| 127 |
from routes_query import _no_dashes
|
|
|
|
| 147 |
at = timestamp(item.get("createdAt"))
|
| 148 |
except (TypeError, ValueError, OverflowError, OSError) as exc:
|
| 149 |
raise ValueError("An artifact needs JSON arguments and a valid creation time.") from exc
|
| 150 |
+
sources, amazon, file_id, mime, frozen = _c7_inputs(item, item["kind"], call["args"], at)
|
| 151 |
value = {"kind": item["kind"], "ref": ref, "title": _no_dashes(item["title"]).strip()[:200],
|
| 152 |
"door": item["door"], "toolCall": {"name": call["name"], "args": copy.deepcopy(call["args"])},
|
| 153 |
+
"createdAt": at, "status": "active", "sources": sources, "amazon": amazon}
|
| 154 |
+
value.update({key: got for key, got in (("file_id", file_id), ("mime", mime), ("frozen_at", frozen))
|
| 155 |
+
if got is not None})
|
| 156 |
h = assistant_log._hash(rt, username)
|
| 157 |
allocated = []
|
| 158 |
def allocate(raw):
|
|
|
|
| 166 |
rt.update(f"assistant_artifacts_{h}_index", allocate, flush="sync")
|
| 167 |
seq, n = allocated
|
| 168 |
row = {**value, "id": f"{h}.{seq}", "seq": seq}
|
| 169 |
+
row["link"] = _link(rt, row)
|
| 170 |
def insert(raw):
|
| 171 |
existing = {entry["seq"]: entry for entry in (raw or {}).get("items", [])}
|
| 172 |
existing.setdefault(seq, row)
|
|
|
|
| 221 |
return next((copy.deepcopy(row) for row in chunk.get("items", []) if row["id"] == item_id), None)
|
| 222 |
|
| 223 |
|
| 224 |
+
def get_by_id(rt, item_id):
|
| 225 |
+
"""Read one row by its `h.seq` id alone, for a page that has no username."""
|
| 226 |
+
match = _ITEM_ID.fullmatch(item_id) if isinstance(item_id, str) else None
|
| 227 |
+
if match is None:
|
| 228 |
+
return None
|
| 229 |
+
h, seq = match.group(1), int(match.group(2))
|
| 230 |
+
chunk = rt.get(_chunk_key(h, seq // CHUNK_ITEMS)) or {}
|
| 231 |
+
return next((copy.deepcopy(row) for row in chunk.get("items", []) if row.get("id") == item_id), None)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _snapshot_key(h, ref):
|
| 235 |
+
# The content lives in its own document: a read is billed at the document's text size.
|
| 236 |
+
return f"assistant_snapshot_{h}_{ref}"
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def store_snapshot(rt, username, content):
|
| 240 |
+
"""Write one frozen snapshot content document and return its `ref`."""
|
| 241 |
+
if not isinstance(content, dict):
|
| 242 |
+
raise ValueError("A snapshot must be an object.")
|
| 243 |
+
json.dumps(content, allow_nan=False)
|
| 244 |
+
ref = uuid.uuid4().hex
|
| 245 |
+
frozen = copy.deepcopy(content)
|
| 246 |
+
rt.update(_snapshot_key(assistant_log._hash(rt, username), ref), lambda _raw: frozen, flush="sync")
|
| 247 |
+
return ref
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def read_snapshot(rt, row):
|
| 251 |
+
"""Read the content document of one snapshot row, or None; it touches no other key."""
|
| 252 |
+
if not isinstance(row, dict) or row.get("kind") != "snapshot" or not isinstance(row.get("id"), str):
|
| 253 |
+
return None
|
| 254 |
+
match, ref = _ITEM_ID.fullmatch(row["id"]), row.get("ref")
|
| 255 |
+
if match is None or not isinstance(ref, str) or not _SNAPSHOT_REF.fullmatch(ref):
|
| 256 |
+
return None
|
| 257 |
+
content = rt.get(_snapshot_key(match.group(1), ref))
|
| 258 |
+
return copy.deepcopy(content) if content else None
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def c7(row):
|
| 262 |
+
"""Project C7 with Amazon protection for unknown provenance, including malformed legacy sources."""
|
| 263 |
+
sources = _source_keys(row.get("sources"))
|
| 264 |
+
out = {"id": row["id"], "kind": row["kind"], "title": row["title"], "created_at": row["createdAt"],
|
| 265 |
+
"frozen_at": row.get("frozen_at"), "sources": sources,
|
| 266 |
+
"amazon": is_amazon(sources) or row.get("amazon", False) is not False,
|
| 267 |
+
"link": row["link"] if "link" in row else loopy_links.artifact_link(row["id"])}
|
| 268 |
+
file_id = row.get("file_id") or (row.get("ref") if row["kind"] == "pdf" else None)
|
| 269 |
+
if file_id:
|
| 270 |
+
out["file_id"] = file_id
|
| 271 |
+
if row.get("mime"):
|
| 272 |
+
out["mime"] = row["mime"]
|
| 273 |
+
return out
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def link_fields(row):
|
| 277 |
+
"""The link a tool result carries, or a plain note when no public base is set."""
|
| 278 |
+
link = (row or {}).get("link")
|
| 279 |
+
return {"link": link} if link else {"link": None, "linkNote": loopy_links.NO_LINK_NOTE}
|
| 280 |
+
|
| 281 |
+
|
| 282 |
def set_status(rt, username, item_id, status):
|
| 283 |
if not isinstance(status, str) or status not in STATUSES:
|
| 284 |
raise ValueError("That artifact status is not available.")
|
api/assistant_feed.py
CHANGED
|
@@ -12,6 +12,7 @@ from core import alerts
|
|
| 12 |
|
| 13 |
|
| 14 |
CUTOVER_KEY = "assistant_notice_cutover"
|
|
|
|
| 15 |
_LOCK = threading.RLock()
|
| 16 |
_LOG = logging.getLogger(__name__)
|
| 17 |
|
|
@@ -20,6 +21,8 @@ def _target(item):
|
|
| 20 |
if isinstance(item.get("target"), dict):
|
| 21 |
return copy.deepcopy(item["target"])
|
| 22 |
topic, key = str(item.get("topic") or ""), str(item.get("alertId") or "")
|
|
|
|
|
|
|
| 23 |
view = str(item.get("viewId") or "")
|
| 24 |
if topic == "automation" and key:
|
| 25 |
return {"module": "automation", "id": key, "tab": "runs"}
|
|
@@ -54,6 +57,53 @@ def _link(target):
|
|
| 54 |
return ""
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
def post(rt, username, item):
|
| 58 |
"""Append one notice, drop legacy unread rows once, and use the optional external door."""
|
| 59 |
if item.get("topic") == "ticket":
|
|
@@ -66,10 +116,14 @@ def post(rt, username, item):
|
|
| 66 |
fallback = {"automation": "Agents", "share": "A teammate"}.get(source, "Alerts")
|
| 67 |
sender = ai_enrich.no_dashes(item.get("actor") or fallback)
|
| 68 |
target = _target(item)
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
turn = {"role": "system", "door": "wake", "kind": "notice", "text": body,
|
| 74 |
"payload": payload, "at": item.get("at") or alerts._now_iso()}
|
| 75 |
with _LOCK:
|
|
@@ -78,13 +132,25 @@ def post(rt, username, item):
|
|
| 78 |
rt.update(CUTOVER_KEY, lambda _data: {"version": 1, "purged": True}, flush="sync")
|
| 79 |
turn_id = assistant_log.append(rt, username, turn)
|
| 80 |
turn["id"] = turn_id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
external = getattr(ping_doors, "notify_external", None)
|
|
|
|
|
|
|
|
|
|
| 82 |
if callable(external):
|
| 83 |
try:
|
| 84 |
external(rt, username, copy.deepcopy(turn))
|
| 85 |
except Exception as exc:
|
| 86 |
_LOG.warning("External notice was not delivered: %s", type(exc).__name__)
|
| 87 |
-
return turn_id
|
| 88 |
|
| 89 |
|
| 90 |
alerts.set_sink(post)
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
CUTOVER_KEY = "assistant_notice_cutover"
|
| 15 |
+
INBOX_KEYS = ("type", "request_id", "sender", "target", "text", "actions", "state")
|
| 16 |
_LOCK = threading.RLock()
|
| 17 |
_LOG = logging.getLogger(__name__)
|
| 18 |
|
|
|
|
| 21 |
if isinstance(item.get("target"), dict):
|
| 22 |
return copy.deepcopy(item["target"])
|
| 23 |
topic, key = str(item.get("topic") or ""), str(item.get("alertId") or "")
|
| 24 |
+
if topic == "inbox":
|
| 25 |
+
return None # A C6 target arrives as a dict above. A question may have none.
|
| 26 |
view = str(item.get("viewId") or "")
|
| 27 |
if topic == "automation" and key:
|
| 28 |
return {"module": "automation", "id": key, "tab": "runs"}
|
|
|
|
| 57 |
return ""
|
| 58 |
|
| 59 |
|
| 60 |
+
def _inbox_link(target):
|
| 61 |
+
"""The deep link of a C6 target `{kind, key, label}`, or "" when it has no address."""
|
| 62 |
+
if not isinstance(target, dict):
|
| 63 |
+
return ""
|
| 64 |
+
kind, key = target.get("kind"), str(target.get("key") or "")
|
| 65 |
+
pair = re.split(r"[/:]", key, maxsplit=1)
|
| 66 |
+
if not key:
|
| 67 |
+
return ""
|
| 68 |
+
if kind == "database":
|
| 69 |
+
return "#/data?" + urlencode({"database": key})
|
| 70 |
+
if kind == "view":
|
| 71 |
+
if len(pair) == 2 and all(pair):
|
| 72 |
+
return "#/data?" + urlencode({"database": pair[0], "view": pair[1]})
|
| 73 |
+
return "#/data?" + urlencode({"view": key})
|
| 74 |
+
if kind == "sheet":
|
| 75 |
+
return "#/sheet?" + urlencode({"wb": key})
|
| 76 |
+
if kind == "app" and len(pair) == 2 and all(pair):
|
| 77 |
+
# An app opens inside its database: `#/app?database=<db>&application=<id>`.
|
| 78 |
+
return "#/app?" + urlencode({"database": pair[0], "application": pair[1]})
|
| 79 |
+
return ""
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _inbox_payload(inbox, subject, body):
|
| 83 |
+
"""Exactly the C6 keys, plus title, body, link and source for the external door."""
|
| 84 |
+
payload = {key: copy.deepcopy(inbox.get(key)) for key in INBOX_KEYS}
|
| 85 |
+
sender = payload.get("sender")
|
| 86 |
+
if isinstance(sender, dict):
|
| 87 |
+
sender["name"] = ai_enrich.no_dashes(" ".join(str(sender.get("name") or "").split()))
|
| 88 |
+
payload.update(title=subject, body=body, link=_inbox_link(payload.get("target")),
|
| 89 |
+
source="inbox")
|
| 90 |
+
return payload
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _inside_window(rt, username):
|
| 94 |
+
"""True when the recipient has a WhatsApp phone inside the 24-hour window."""
|
| 95 |
+
try:
|
| 96 |
+
import telnyx_whatsapp
|
| 97 |
+
from core import users
|
| 98 |
+
record = dict(users._tenant_accounts(assistant_log._tenant_of(rt))).get(username)
|
| 99 |
+
whatsapp = record.get("whatsapp") if isinstance(record, dict) else None
|
| 100 |
+
phone = whatsapp.get("phone") if isinstance(whatsapp, dict) else None
|
| 101 |
+
return bool(phone) and bool(telnyx_whatsapp.within_window(phone))
|
| 102 |
+
except Exception as exc: # noqa: BLE001
|
| 103 |
+
_LOG.warning("WhatsApp window was not read: %s", type(exc).__name__)
|
| 104 |
+
return False
|
| 105 |
+
|
| 106 |
+
|
| 107 |
def post(rt, username, item):
|
| 108 |
"""Append one notice, drop legacy unread rows once, and use the optional external door."""
|
| 109 |
if item.get("topic") == "ticket":
|
|
|
|
| 116 |
fallback = {"automation": "Agents", "share": "A teammate"}.get(source, "Alerts")
|
| 117 |
sender = ai_enrich.no_dashes(item.get("actor") or fallback)
|
| 118 |
target = _target(item)
|
| 119 |
+
inbox = item.get("inbox") if isinstance(item.get("inbox"), dict) else None
|
| 120 |
+
if inbox is not None:
|
| 121 |
+
payload = _inbox_payload(inbox, subject, body)
|
| 122 |
+
else:
|
| 123 |
+
payload = {"title": subject, "subject": subject, "body": body, "sender": sender,
|
| 124 |
+
"target": target, "link": _link(target), "source": source,
|
| 125 |
+
"notificationId": item.get("id"), "alertId": item.get("alertId"),
|
| 126 |
+
"viewId": item.get("viewId"), "rowId": item.get("rowId")}
|
| 127 |
turn = {"role": "system", "door": "wake", "kind": "notice", "text": body,
|
| 128 |
"payload": payload, "at": item.get("at") or alerts._now_iso()}
|
| 129 |
with _LOCK:
|
|
|
|
| 132 |
rt.update(CUTOVER_KEY, lambda _data: {"version": 1, "purged": True}, flush="sync")
|
| 133 |
turn_id = assistant_log.append(rt, username, turn)
|
| 134 |
turn["id"] = turn_id
|
| 135 |
+
if getattr(rt, "preview_only", False):
|
| 136 |
+
rt.deferred_notices.append({"username": username, "turn": copy.deepcopy(turn),
|
| 137 |
+
"inside_window_only": inbox is not None})
|
| 138 |
+
return turn_id
|
| 139 |
+
deliver_external(rt, username, turn, inside_window_only=inbox is not None)
|
| 140 |
+
return turn_id
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def deliver_external(rt, username, turn, *, inside_window_only=False):
|
| 144 |
+
"""Deliver an already committed notice, including a notice held by an Assistant preview."""
|
| 145 |
external = getattr(ping_doors, "notify_external", None)
|
| 146 |
+
if inside_window_only and not _inside_window(rt, username):
|
| 147 |
+
# R108(l): an agent message reaches WhatsApp only inside the window, never as a template.
|
| 148 |
+
external = None
|
| 149 |
if callable(external):
|
| 150 |
try:
|
| 151 |
external(rt, username, copy.deepcopy(turn))
|
| 152 |
except Exception as exc:
|
| 153 |
_LOG.warning("External notice was not delivered: %s", type(exc).__name__)
|
|
|
|
| 154 |
|
| 155 |
|
| 156 |
alerts.set_sink(post)
|
api/assistant_files.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Store assistant
|
| 2 |
import base64
|
| 3 |
import copy
|
| 4 |
import hashlib
|
|
@@ -15,6 +15,9 @@ import assistant_artifacts
|
|
| 15 |
import assistant_log
|
| 16 |
|
| 17 |
MAX_TTL = 3600
|
|
|
|
|
|
|
|
|
|
| 18 |
_FILE_ID = re.compile(r"[0-9a-f]{32}")
|
| 19 |
_TENANT = re.compile(r"[a-z0-9][a-z0-9_-]{0,62}")
|
| 20 |
_TOKEN_PART = re.compile(r"[A-Za-z0-9_-]{48}")
|
|
@@ -58,7 +61,8 @@ def _key(file_id):
|
|
| 58 |
|
| 59 |
|
| 60 |
def _path(item):
|
| 61 |
-
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
def metadata(rt, file_id):
|
|
@@ -70,7 +74,7 @@ def metadata(rt, file_id):
|
|
| 70 |
or item.get("tenant") != assistant_log._tenant_of(rt)
|
| 71 |
or not isinstance(item.get("owner"), str) or not item["owner"]
|
| 72 |
or item.get("ownerHash") != assistant_log._hash(rt, item["owner"])
|
| 73 |
-
or item.get("mime")
|
| 74 |
or not isinstance(item.get("size"), int) or item["size"] < 0
|
| 75 |
or not isinstance(item.get("artifactId"), str)):
|
| 76 |
return None
|
|
@@ -94,16 +98,51 @@ def read_bytes(rt, item):
|
|
| 94 |
|
| 95 |
def _public_metadata(item):
|
| 96 |
fields = ("id", "filename", "size", "mime", "artifactId", "createdAt")
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
|
| 100 |
-
def save(rt, username, *, title, data, mime, door, tool_call):
|
| 101 |
-
"""Save one
|
| 102 |
h = assistant_log._hash(rt, username)
|
| 103 |
if not isinstance(title, str) or not title.strip():
|
| 104 |
raise ValueError("A file needs a title.")
|
| 105 |
-
if mime
|
| 106 |
-
raise ValueError("A file needs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
if not isinstance(door, str) or door not in assistant_artifacts.DOORS:
|
| 108 |
raise ValueError("That file door is not available.")
|
| 109 |
if (not isinstance(tool_call, dict) or not isinstance(tool_call.get("name"), str)
|
|
@@ -115,26 +154,29 @@ def save(rt, username, *, title, data, mime, door, tool_call):
|
|
| 115 |
file_id = secrets.token_hex(16)
|
| 116 |
item = {"id": file_id, "owner": username, "ownerHash": h,
|
| 117 |
"tenant": assistant_log._tenant_of(rt), "title": title,
|
| 118 |
-
"filename": (re.sub(r"[^A-Za-z0-9._-]+", "_", title).strip("._")[:100] or "document") + ".
|
| 119 |
"size": len(data), "mime": mime, "door": door,
|
| 120 |
"createdAt": assistant_artifacts.timestamp(time.time()),
|
| 121 |
-
"toolCall": copy.deepcopy(tool_call)}
|
| 122 |
-
_bytes_runtime(rt).upload_bytes(_path(item), bytes(data), message="Save assistant
|
| 123 |
item["artifactId"] = assistant_artifacts.record(rt, username, {
|
| 124 |
-
"kind":
|
| 125 |
-
"toolCall": tool_call, "createdAt": item["createdAt"]
|
|
|
|
|
|
|
| 126 |
rt.update(_key(file_id), lambda _raw: copy.deepcopy(item), flush="sync")
|
| 127 |
-
return {"id": file_id, "artifactId": item["artifactId"], "link": _artifact_link(item["artifactId"])
|
|
|
|
| 128 |
|
| 129 |
|
| 130 |
def created_in_turn(rt, username, since):
|
| 131 |
-
"""Return all owned
|
| 132 |
boundary = assistant_artifacts.timestamp(since)
|
| 133 |
h = assistant_log._hash(rt, username)
|
| 134 |
index = assistant_artifacts._index(rt.get(f"assistant_artifacts_{h}_index"))
|
| 135 |
items = []
|
| 136 |
for row in assistant_artifacts._rows(rt, h, index):
|
| 137 |
-
if row["kind"]
|
| 138 |
continue
|
| 139 |
item = owned_metadata(rt, username, row["ref"])
|
| 140 |
if item and item["createdAt"] >= boundary:
|
|
@@ -163,6 +205,8 @@ def capability_url(rt, file_id, ttl=MAX_TTL):
|
|
| 163 |
item = metadata(rt, file_id)
|
| 164 |
if item is None:
|
| 165 |
raise ValueError("That file does not exist.")
|
|
|
|
|
|
|
| 166 |
tenant = assistant_log._tenant_of(rt)
|
| 167 |
if not _TENANT.fullmatch(tenant):
|
| 168 |
raise ValueError("A file link needs a valid tenant.")
|
|
@@ -205,6 +249,8 @@ def resolve_capability(token):
|
|
| 205 |
item = owned_metadata(rt, entry["owner"], entry.get("fileId"))
|
| 206 |
if item is None:
|
| 207 |
return None
|
|
|
|
|
|
|
| 208 |
now = time.time()
|
| 209 |
if now < born:
|
| 210 |
return None
|
|
|
|
| 1 |
+
"""Store assistant files and durable capabilities under their tenant and owner."""
|
| 2 |
import base64
|
| 3 |
import copy
|
| 4 |
import hashlib
|
|
|
|
| 15 |
import assistant_log
|
| 16 |
|
| 17 |
MAX_TTL = 3600
|
| 18 |
+
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
| 19 |
+
IMAGE_MIME = "image/png"
|
| 20 |
+
_FORMATS = {"application/pdf": ("pdf", "pdf"), XLSX_MIME: ("xlsx", "xlsx"), IMAGE_MIME: ("png", "image")}
|
| 21 |
_FILE_ID = re.compile(r"[0-9a-f]{32}")
|
| 22 |
_TENANT = re.compile(r"[a-z0-9][a-z0-9_-]{0,62}")
|
| 23 |
_TOKEN_PART = re.compile(r"[A-Za-z0-9_-]{48}")
|
|
|
|
| 61 |
|
| 62 |
|
| 63 |
def _path(item):
|
| 64 |
+
extension = _FORMATS[item["mime"]][0]
|
| 65 |
+
return f"assistant_files/{item['ownerHash']}/{item['id']}.{extension}"
|
| 66 |
|
| 67 |
|
| 68 |
def metadata(rt, file_id):
|
|
|
|
| 74 |
or item.get("tenant") != assistant_log._tenant_of(rt)
|
| 75 |
or not isinstance(item.get("owner"), str) or not item["owner"]
|
| 76 |
or item.get("ownerHash") != assistant_log._hash(rt, item["owner"])
|
| 77 |
+
or not isinstance(item.get("mime"), str) or item["mime"] not in _FORMATS
|
| 78 |
or not isinstance(item.get("size"), int) or item["size"] < 0
|
| 79 |
or not isinstance(item.get("artifactId"), str)):
|
| 80 |
return None
|
|
|
|
| 98 |
|
| 99 |
def _public_metadata(item):
|
| 100 |
fields = ("id", "filename", "size", "mime", "artifactId", "createdAt")
|
| 101 |
+
result = {**{key: item[key] for key in fields}, "link": _artifact_link(item["artifactId"])}
|
| 102 |
+
if item["mime"] in (XLSX_MIME, IMAGE_MIME):
|
| 103 |
+
result.update(file_id=item["id"], bytes=item["size"], created_at=item["createdAt"],
|
| 104 |
+
frozen_at=item["createdAt"], sources=copy.deepcopy(item.get("sources")),
|
| 105 |
+
amazon=item.get("amazon", True))
|
| 106 |
+
return result
|
| 107 |
|
| 108 |
|
| 109 |
+
def save(rt, username, *, title, data, mime, door, tool_call, sources=None, amazon=False):
|
| 110 |
+
"""Save one file and its replayable artifact with validated source provenance."""
|
| 111 |
h = assistant_log._hash(rt, username)
|
| 112 |
if not isinstance(title, str) or not title.strip():
|
| 113 |
raise ValueError("A file needs a title.")
|
| 114 |
+
if not isinstance(mime, str) or mime not in _FORMATS or not isinstance(data, (bytes, bytearray, memoryview)):
|
| 115 |
+
raise ValueError("A file needs bytes and a supported media type.")
|
| 116 |
+
extension, kind = _FORMATS[mime]
|
| 117 |
+
import agent_runtime
|
| 118 |
+
if agent_runtime._PRODUCING_TURN.get() is not None:
|
| 119 |
+
proof = agent_runtime.producing_turn_sources(rt, username)
|
| 120 |
+
if proof is None:
|
| 121 |
+
sources = None
|
| 122 |
+
else:
|
| 123 |
+
if sources is not None and assistant_artifacts._source_keys(sources) is None:
|
| 124 |
+
raise ValueError("A file needs valid source provenance.")
|
| 125 |
+
sources = sorted(set(proof) | set(sources or []))
|
| 126 |
+
amazon = amazon or assistant_artifacts.is_amazon(sources)
|
| 127 |
+
if mime == XLSX_MIME:
|
| 128 |
+
from loopy_xlsx import MAX_BYTES
|
| 129 |
+
if len(data) > MAX_BYTES:
|
| 130 |
+
raise ValueError("Excel export exceeds the 20 MiB file limit. Filter the rows or select fewer fields and ask again. No file was stored.")
|
| 131 |
+
if sources is None:
|
| 132 |
+
raise ValueError("An Excel file needs validated source provenance. Read its sources and ask again.")
|
| 133 |
+
if mime == IMAGE_MIME:
|
| 134 |
+
from loopy_image import MAX_BYTES
|
| 135 |
+
if len(data) > MAX_BYTES:
|
| 136 |
+
raise ValueError("The image exceeds the 20 MiB limit. Select fewer fields and ask again. No file was stored.")
|
| 137 |
+
if sources is None:
|
| 138 |
+
raise ValueError("An image needs validated source provenance. Read its sources and ask again.")
|
| 139 |
+
if (sources is not None and assistant_artifacts._source_keys(sources) is None
|
| 140 |
+
or type(amazon) is not bool):
|
| 141 |
+
raise ValueError("A file needs valid source provenance and its Amazon flag.")
|
| 142 |
+
sources = list(dict.fromkeys(assistant_artifacts._source_keys(sources))) if sources is not None else None
|
| 143 |
+
amazon = amazon or assistant_artifacts.is_amazon(sources)
|
| 144 |
+
if kind not in assistant_artifacts.KINDS:
|
| 145 |
+
raise ValueError(f"{kind.capitalize()} artifacts are not available on this build. Update the artifact registry and ask again. No file was stored.")
|
| 146 |
if not isinstance(door, str) or door not in assistant_artifacts.DOORS:
|
| 147 |
raise ValueError("That file door is not available.")
|
| 148 |
if (not isinstance(tool_call, dict) or not isinstance(tool_call.get("name"), str)
|
|
|
|
| 154 |
file_id = secrets.token_hex(16)
|
| 155 |
item = {"id": file_id, "owner": username, "ownerHash": h,
|
| 156 |
"tenant": assistant_log._tenant_of(rt), "title": title,
|
| 157 |
+
"filename": (re.sub(r"[^A-Za-z0-9._-]+", "_", title).strip("._")[:100] or "document") + "." + extension,
|
| 158 |
"size": len(data), "mime": mime, "door": door,
|
| 159 |
"createdAt": assistant_artifacts.timestamp(time.time()),
|
| 160 |
+
"toolCall": copy.deepcopy(tool_call), "sources": copy.deepcopy(sources), "amazon": amazon}
|
| 161 |
+
_bytes_runtime(rt).upload_bytes(_path(item), bytes(data), message=f"Save assistant {kind.upper()}")
|
| 162 |
item["artifactId"] = assistant_artifacts.record(rt, username, {
|
| 163 |
+
"kind": kind, "ref": file_id, "title": title, "door": door,
|
| 164 |
+
"toolCall": tool_call, "createdAt": item["createdAt"],
|
| 165 |
+
"created_at": item["createdAt"], "frozen_at": item["createdAt"],
|
| 166 |
+
"sources": sources, "amazon": amazon, "file_id": file_id, "mime": mime})
|
| 167 |
rt.update(_key(file_id), lambda _raw: copy.deepcopy(item), flush="sync")
|
| 168 |
+
return {"id": file_id, "artifactId": item["artifactId"], "link": _artifact_link(item["artifactId"]),
|
| 169 |
+
"file_id": file_id, "mime": mime, "bytes": len(data)}
|
| 170 |
|
| 171 |
|
| 172 |
def created_in_turn(rt, username, since):
|
| 173 |
+
"""Return all owned file metadata created at or after the turn's start."""
|
| 174 |
boundary = assistant_artifacts.timestamp(since)
|
| 175 |
h = assistant_log._hash(rt, username)
|
| 176 |
index = assistant_artifacts._index(rt.get(f"assistant_artifacts_{h}_index"))
|
| 177 |
items = []
|
| 178 |
for row in assistant_artifacts._rows(rt, h, index):
|
| 179 |
+
if row["kind"] not in ("pdf", "xlsx", "image") or row["status"] == "deleted" or row["createdAt"] < boundary:
|
| 180 |
continue
|
| 181 |
item = owned_metadata(rt, username, row["ref"])
|
| 182 |
if item and item["createdAt"] >= boundary:
|
|
|
|
| 205 |
item = metadata(rt, file_id)
|
| 206 |
if item is None:
|
| 207 |
raise ValueError("That file does not exist.")
|
| 208 |
+
if assistant_artifacts.is_amazon(item.get("sources")) or item.get("amazon") is not False:
|
| 209 |
+
raise ValueError("Amazon files cannot use a public download link. Download the file in the app instead.")
|
| 210 |
tenant = assistant_log._tenant_of(rt)
|
| 211 |
if not _TENANT.fullmatch(tenant):
|
| 212 |
raise ValueError("A file link needs a valid tenant.")
|
|
|
|
| 249 |
item = owned_metadata(rt, entry["owner"], entry.get("fileId"))
|
| 250 |
if item is None:
|
| 251 |
return None
|
| 252 |
+
if assistant_artifacts.is_amazon(item.get("sources")) or item.get("amazon") is not False:
|
| 253 |
+
return None
|
| 254 |
now = time.time()
|
| 255 |
if now < born:
|
| 256 |
return None
|
api/assistant_log.py
CHANGED
|
@@ -6,7 +6,8 @@ turns without an ever-growing message-id index; old ids remain in payload for ra
|
|
| 6 |
import copy
|
| 7 |
import datetime
|
| 8 |
import hashlib
|
| 9 |
-
|
|
|
|
| 10 |
|
| 11 |
CHUNK_TURNS = 200
|
| 12 |
ROLES = {"user", "assistant", "system"}
|
|
@@ -14,6 +15,25 @@ DOORS = {"app", "whatsapp", "wake"}
|
|
| 14 |
KINDS = {"text", "ping", "confirm", "divider", "notice"}
|
| 15 |
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
def _tenant_of(rt):
|
| 18 |
# TenantRuntime.tenant is a Tenant object; its key is the session's tenant slug.
|
| 19 |
tenant = getattr(rt, "key", None) or getattr(rt, "tenant", None)
|
|
@@ -32,6 +52,7 @@ def _index(raw):
|
|
| 32 |
raw = raw or {}
|
| 33 |
return {"version": 1, "nextSeq": int(raw.get("nextSeq", 0)),
|
| 34 |
"chunks": copy.deepcopy(raw.get("chunks") or {}),
|
|
|
|
| 35 |
"folded": bool(raw.get("folded")), "foldedFrom": copy.deepcopy(raw.get("foldedFrom"))}
|
| 36 |
|
| 37 |
|
|
@@ -54,15 +75,45 @@ def _put_rows(rt, h, n, rows):
|
|
| 54 |
if len(existing) > CHUNK_TURNS:
|
| 55 |
raise ValueError("A conversation chunk is full.")
|
| 56 |
return {"version": 1, "turns": [existing[seq] for seq in sorted(existing)]}
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
|
| 60 |
def _ensure_fold(rt, h):
|
|
|
|
|
|
|
|
|
|
| 61 |
key = f"assistant_log_{h}_index"
|
| 62 |
-
index = _index(
|
| 63 |
if index["folded"]:
|
| 64 |
-
return index
|
| 65 |
-
old =
|
| 66 |
threads, messages = old.get("threads") or {}, old.get("messages") or {}
|
| 67 |
rows = sorted(messages.values(), key=lambda row: (
|
| 68 |
str(row.get("createdAt") or ""), 0 if row.get("role") == "user" else 1,
|
|
@@ -95,8 +146,8 @@ def _ensure_fold(rt, h):
|
|
| 95 |
for n in range((len(turns) + CHUNK_TURNS - 1) // CHUNK_TURNS)}
|
| 96 |
committed[:] = [copy.deepcopy(current)]
|
| 97 |
return current
|
| 98 |
-
|
| 99 |
-
return committed[0]
|
| 100 |
|
| 101 |
|
| 102 |
def append(rt, username, turn):
|
|
@@ -127,15 +178,19 @@ def append(rt, username, turn):
|
|
| 127 |
count = index["chunks"].get(str(n), 0)
|
| 128 |
if count >= CHUNK_TURNS:
|
| 129 |
raise ValueError("A conversation chunk is full.")
|
|
|
|
|
|
|
| 130 |
index["nextSeq"] = seq + 1
|
| 131 |
index["chunks"][str(n)] = count + 1
|
|
|
|
| 132 |
allocated[:] = [seq, n]
|
| 133 |
return index
|
| 134 |
-
#
|
| 135 |
-
|
| 136 |
seq, n = allocated
|
| 137 |
row = _turn(h, seq, value)
|
| 138 |
_put_rows(rt, h, n, [row])
|
|
|
|
| 139 |
return row["id"]
|
| 140 |
|
| 141 |
|
|
@@ -150,40 +205,52 @@ def _seq(h, turn_id):
|
|
| 150 |
return None
|
| 151 |
|
| 152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
def _newest(rt, h, index, before=None):
|
| 154 |
end = min(index["nextSeq"], before) if before is not None else index["nextSeq"]
|
| 155 |
for n in range((end - 1) // CHUNK_TURNS, -1, -1):
|
| 156 |
if not index["chunks"].get(str(n)):
|
| 157 |
continue
|
| 158 |
-
|
| 159 |
-
for row in sorted(chunk.get("turns", []), key=lambda row: row["seq"], reverse=True):
|
| 160 |
if row["seq"] < end:
|
| 161 |
yield copy.deepcopy(row)
|
| 162 |
|
| 163 |
|
| 164 |
-
|
| 165 |
-
"""
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
-
def __init__(self):
|
| 175 |
-
self.documents = {}
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
|
| 180 |
-
def update(self, key, fn, **kwargs):
|
| 181 |
-
current = self.get(key) or {}
|
| 182 |
-
changed = fn(current)
|
| 183 |
-
self.documents[key] = copy.deepcopy(current if changed is None else changed)
|
| 184 |
-
return self.get(key)
|
| 185 |
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
| 187 |
h = _hash(rt, username)
|
| 188 |
index = _ensure_fold(rt, h)
|
| 189 |
limit = max(1, min(CHUNK_TURNS, int(limit)))
|
|
@@ -210,14 +277,15 @@ def read(rt, username, *, before=None, limit=50):
|
|
| 210 |
|
| 211 |
def find(rt, username, turn_id):
|
| 212 |
"""Find a turn by C12 id, sequence, or the legacy message id in payload."""
|
|
|
|
| 213 |
h = _hash(rt, username)
|
| 214 |
index = _ensure_fold(rt, h)
|
| 215 |
seq = _seq(h, turn_id)
|
| 216 |
if seq is not None:
|
| 217 |
if seq < 0 or seq >= index["nextSeq"]:
|
| 218 |
return None
|
| 219 |
-
|
| 220 |
-
|
| 221 |
return next((row for row in _newest(rt, h, index)
|
| 222 |
if (row.get("payload") or {}).get("id") == turn_id), None)
|
| 223 |
|
|
@@ -239,7 +307,7 @@ def update_turn(rt, username, turn_id, fn):
|
|
| 239 |
current["turns"][i] = new
|
| 240 |
changed[:] = [copy.deepcopy(new)]
|
| 241 |
return current
|
| 242 |
-
|
| 243 |
return changed[0] if changed else None
|
| 244 |
|
| 245 |
|
|
@@ -247,6 +315,7 @@ def search(rt, username, query, limit=10):
|
|
| 247 |
words = str(query or "").casefold()[:1000].split()
|
| 248 |
if not words:
|
| 249 |
return []
|
|
|
|
| 250 |
h = _hash(rt, username)
|
| 251 |
index = _ensure_fold(rt, h)
|
| 252 |
limit = max(1, min(CHUNK_TURNS, int(limit)))
|
|
|
|
| 6 |
import copy
|
| 7 |
import datetime
|
| 8 |
import hashlib
|
| 9 |
+
import inspect
|
| 10 |
+
from core import freeze_notice, grid_events
|
| 11 |
|
| 12 |
CHUNK_TURNS = 200
|
| 13 |
ROLES = {"user", "assistant", "system"}
|
|
|
|
| 15 |
KINDS = {"text", "ping", "confirm", "divider", "notice"}
|
| 16 |
|
| 17 |
|
| 18 |
+
def _get(rt, key):
|
| 19 |
+
"""Bypass a process cache when the bound runtime supports fresh reads."""
|
| 20 |
+
try:
|
| 21 |
+
if "fresh" in inspect.signature(rt.get).parameters:
|
| 22 |
+
return rt.get(key, fresh=True)
|
| 23 |
+
return rt.get(key)
|
| 24 |
+
except Exception as exc:
|
| 25 |
+
raise grid_events.StoreUnavailable("Conversation store read failed.") from exc
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _update(rt, key, fn):
|
| 29 |
+
try:
|
| 30 |
+
return rt.update(key, fn, flush="sync")
|
| 31 |
+
except ValueError:
|
| 32 |
+
raise
|
| 33 |
+
except Exception as exc:
|
| 34 |
+
raise grid_events.StoreUnavailable("Conversation store write failed.") from exc
|
| 35 |
+
|
| 36 |
+
|
| 37 |
def _tenant_of(rt):
|
| 38 |
# TenantRuntime.tenant is a Tenant object; its key is the session's tenant slug.
|
| 39 |
tenant = getattr(rt, "key", None) or getattr(rt, "tenant", None)
|
|
|
|
| 52 |
raw = raw or {}
|
| 53 |
return {"version": 1, "nextSeq": int(raw.get("nextSeq", 0)),
|
| 54 |
"chunks": copy.deepcopy(raw.get("chunks") or {}),
|
| 55 |
+
"pending": copy.deepcopy(raw.get("pending") or {}),
|
| 56 |
"folded": bool(raw.get("folded")), "foldedFrom": copy.deepcopy(raw.get("foldedFrom"))}
|
| 57 |
|
| 58 |
|
|
|
|
| 75 |
if len(existing) > CHUNK_TURNS:
|
| 76 |
raise ValueError("A conversation chunk is full.")
|
| 77 |
return {"version": 1, "turns": [existing[seq] for seq in sorted(existing)]}
|
| 78 |
+
_update(rt, _chunk_key(h, n), update)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _ack(rt, h, rows):
|
| 82 |
+
committed = []
|
| 83 |
+
def finish(raw):
|
| 84 |
+
current = _index(raw)
|
| 85 |
+
for row in rows:
|
| 86 |
+
current["pending"].pop(str(row["seq"]), None)
|
| 87 |
+
committed[:] = [copy.deepcopy(current)]
|
| 88 |
+
return current
|
| 89 |
+
_update(rt, f"assistant_log_{h}_index", finish)
|
| 90 |
+
return committed[0]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _recover(rt, h, index):
|
| 94 |
+
"""Publish journalled rows before removing their durable recovery copies."""
|
| 95 |
+
rows = list(index["pending"].values())
|
| 96 |
+
if not rows:
|
| 97 |
+
return index
|
| 98 |
+
chunks = {}
|
| 99 |
+
for row in rows:
|
| 100 |
+
chunks.setdefault(row["seq"] // CHUNK_TURNS, []).append(row)
|
| 101 |
+
for n, values in chunks.items():
|
| 102 |
+
_put_rows(rt, h, n, values)
|
| 103 |
+
_ack(rt, h, rows)
|
| 104 |
+
# Keep this read's sequence boundary when other appends allocate during recovery.
|
| 105 |
+
return {**index, "pending": {}}
|
| 106 |
|
| 107 |
|
| 108 |
def _ensure_fold(rt, h):
|
| 109 |
+
available = getattr(rt, "available", None)
|
| 110 |
+
if callable(available) and not available():
|
| 111 |
+
raise grid_events.StoreUnavailable("Conversation store is unavailable.")
|
| 112 |
key = f"assistant_log_{h}_index"
|
| 113 |
+
index = _index(_get(rt, key))
|
| 114 |
if index["folded"]:
|
| 115 |
+
return _recover(rt, h, index)
|
| 116 |
+
old = _get(rt, "query_user_" + h) or {}
|
| 117 |
threads, messages = old.get("threads") or {}, old.get("messages") or {}
|
| 118 |
rows = sorted(messages.values(), key=lambda row: (
|
| 119 |
str(row.get("createdAt") or ""), 0 if row.get("role") == "user" else 1,
|
|
|
|
| 146 |
for n in range((len(turns) + CHUNK_TURNS - 1) // CHUNK_TURNS)}
|
| 147 |
committed[:] = [copy.deepcopy(current)]
|
| 148 |
return current
|
| 149 |
+
_update(rt, key, finish)
|
| 150 |
+
return _recover(rt, h, committed[0])
|
| 151 |
|
| 152 |
|
| 153 |
def append(rt, username, turn):
|
|
|
|
| 178 |
count = index["chunks"].get(str(n), 0)
|
| 179 |
if count >= CHUNK_TURNS:
|
| 180 |
raise ValueError("A conversation chunk is full.")
|
| 181 |
+
if len(index["pending"]) >= CHUNK_TURNS:
|
| 182 |
+
raise grid_events.StoreUnavailable("Conversation publication needs recovery.")
|
| 183 |
index["nextSeq"] = seq + 1
|
| 184 |
index["chunks"][str(n)] = count + 1
|
| 185 |
+
index["pending"][str(seq)] = _turn(h, seq, value)
|
| 186 |
allocated[:] = [seq, n]
|
| 187 |
return index
|
| 188 |
+
# Allocation retains the row until its chunk is durable.
|
| 189 |
+
_update(rt, f"assistant_log_{h}_index", allocate)
|
| 190 |
seq, n = allocated
|
| 191 |
row = _turn(h, seq, value)
|
| 192 |
_put_rows(rt, h, n, [row])
|
| 193 |
+
_ack(rt, h, [row])
|
| 194 |
return row["id"]
|
| 195 |
|
| 196 |
|
|
|
|
| 205 |
return None
|
| 206 |
|
| 207 |
|
| 208 |
+
def _rows(rt, h, index, n):
|
| 209 |
+
rows = (_get(rt, _chunk_key(h, n)) or {}).get("turns", [])
|
| 210 |
+
expected = set(range(n * CHUNK_TURNS, min((n + 1) * CHUNK_TURNS, index["nextSeq"])))
|
| 211 |
+
if not expected.issubset({row["seq"] for row in rows}):
|
| 212 |
+
raise grid_events.StoreUnavailable("Conversation chunk is incomplete.")
|
| 213 |
+
return rows
|
| 214 |
+
|
| 215 |
+
|
| 216 |
def _newest(rt, h, index, before=None):
|
| 217 |
end = min(index["nextSeq"], before) if before is not None else index["nextSeq"]
|
| 218 |
for n in range((end - 1) // CHUNK_TURNS, -1, -1):
|
| 219 |
if not index["chunks"].get(str(n)):
|
| 220 |
continue
|
| 221 |
+
for row in sorted(_rows(rt, h, index, n), key=lambda row: row["seq"], reverse=True):
|
|
|
|
| 222 |
if row["seq"] < end:
|
| 223 |
yield copy.deepcopy(row)
|
| 224 |
|
| 225 |
|
| 226 |
+
class _Projection:
|
| 227 |
+
"""Fold and recover read results in memory while maintenance forbids durable writes."""
|
| 228 |
+
def __init__(self, source):
|
| 229 |
+
self.source = source
|
| 230 |
+
self.key = _tenant_of(source)
|
| 231 |
+
self.documents = {}
|
| 232 |
+
|
| 233 |
+
def get(self, key):
|
| 234 |
+
return copy.deepcopy(self.documents[key] if key in self.documents else _get(self.source, key))
|
| 235 |
+
|
| 236 |
+
def available(self):
|
| 237 |
+
return getattr(self.source, "available", lambda: True)()
|
| 238 |
|
| 239 |
+
def update(self, key, fn, **kwargs):
|
| 240 |
+
current = self.get(key) or {}
|
| 241 |
+
changed = fn(current)
|
| 242 |
+
self.documents[key] = copy.deepcopy(current if changed is None else changed)
|
| 243 |
+
return self.get(key)
|
| 244 |
|
|
|
|
|
|
|
| 245 |
|
| 246 |
+
def _read_runtime(rt):
|
| 247 |
+
return _Projection(rt) if freeze_notice.enabled() and not isinstance(rt, _Projection) else rt
|
| 248 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
+
def read(rt, username, *, before=None, limit=50):
|
| 251 |
+
"""Newest page by default; each page is oldest first and its first id pages backward."""
|
| 252 |
+
if freeze_notice.enabled():
|
| 253 |
+
rt = _read_runtime(rt)
|
| 254 |
h = _hash(rt, username)
|
| 255 |
index = _ensure_fold(rt, h)
|
| 256 |
limit = max(1, min(CHUNK_TURNS, int(limit)))
|
|
|
|
| 277 |
|
| 278 |
def find(rt, username, turn_id):
|
| 279 |
"""Find a turn by C12 id, sequence, or the legacy message id in payload."""
|
| 280 |
+
rt = _read_runtime(rt)
|
| 281 |
h = _hash(rt, username)
|
| 282 |
index = _ensure_fold(rt, h)
|
| 283 |
seq = _seq(h, turn_id)
|
| 284 |
if seq is not None:
|
| 285 |
if seq < 0 or seq >= index["nextSeq"]:
|
| 286 |
return None
|
| 287 |
+
return next((copy.deepcopy(row) for row in _rows(rt, h, index, seq // CHUNK_TURNS)
|
| 288 |
+
if row["seq"] == seq), None)
|
| 289 |
return next((row for row in _newest(rt, h, index)
|
| 290 |
if (row.get("payload") or {}).get("id") == turn_id), None)
|
| 291 |
|
|
|
|
| 307 |
current["turns"][i] = new
|
| 308 |
changed[:] = [copy.deepcopy(new)]
|
| 309 |
return current
|
| 310 |
+
_update(rt, _chunk_key(h, row["seq"] // CHUNK_TURNS), update)
|
| 311 |
return changed[0] if changed else None
|
| 312 |
|
| 313 |
|
|
|
|
| 315 |
words = str(query or "").casefold()[:1000].split()
|
| 316 |
if not words:
|
| 317 |
return []
|
| 318 |
+
rt = _read_runtime(rt)
|
| 319 |
h = _hash(rt, username)
|
| 320 |
index = _ensure_fold(rt, h)
|
| 321 |
limit = max(1, min(CHUNK_TURNS, int(limit)))
|
api/assistant_memory.py
CHANGED
|
@@ -36,7 +36,8 @@ def _key(rt, username):
|
|
| 36 |
|
| 37 |
|
| 38 |
def _now():
|
| 39 |
-
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
def _document(raw):
|
|
@@ -110,16 +111,32 @@ def _capture_sources(user, sources):
|
|
| 110 |
if key not in {"bus", "bu", "businessUnit"}}, "bus": bus} for source in sources]
|
| 111 |
|
| 112 |
|
| 113 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
from core import perms
|
| 115 |
-
|
| 116 |
-
|
|
|
|
| 117 |
if door not in {"app", "whatsapp", "slack", "wake"}:
|
| 118 |
raise ValueError("That Assistant memory door is not available.")
|
|
|
|
| 119 |
sources = _sources(sources)
|
| 120 |
bus = sorted(set().union(*(_source_bus(source) for source in sources))) if sources else []
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
entry["kind"] = _kind(entry["text"], kind)
|
| 124 |
def update(raw):
|
| 125 |
doc = _document(raw)
|
|
@@ -202,7 +219,8 @@ def remember(rt, username, text, *, sources, door):
|
|
| 202 |
"""Store in the narrowest container. Slack's explicit-remember policy belongs to its door."""
|
| 203 |
if door not in {"app", "whatsapp", "slack", "wake"}:
|
| 204 |
raise ValueError("That Assistant memory door is not available.")
|
| 205 |
-
|
|
|
|
| 206 |
"door": door, "at": _now()}
|
| 207 |
entry["kind"] = _kind(entry["text"])
|
| 208 |
key = _key(rt, username)
|
|
@@ -244,11 +262,20 @@ def _forget_at(rt, key, id):
|
|
| 244 |
|
| 245 |
|
| 246 |
def forget_company(rt, principal, id):
|
|
|
|
| 247 |
from core import perms
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
|
|
|
| 251 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
return _forget_at(rt, _company_key(rt), id)
|
| 253 |
|
| 254 |
|
|
@@ -372,6 +399,25 @@ def _readable(rt, principal, sources, *, company=False):
|
|
| 372 |
return False
|
| 373 |
|
| 374 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
def recall(rt, principal, query=None, limit=20):
|
| 376 |
"""Recall the authorized union with current source access for every channel member."""
|
| 377 |
try:
|
|
@@ -389,10 +435,15 @@ def recall(rt, principal, query=None, limit=20):
|
|
| 389 |
return result
|
| 390 |
entries = [(entry, "personal", doc["tombstones"]) for entry in doc["entries"]]
|
| 391 |
entries.extend((entry, "company", company["tombstones"]) for entry in company["entries"])
|
|
|
|
|
|
|
|
|
|
| 392 |
for entry, scope, tombstones in sorted(reversed(entries), key=lambda row: _oldest(row[0]), reverse=True):
|
| 393 |
if (not isinstance(entry, dict) or not all(key in entry for key in ("id", "text", "sources", "door", "at"))
|
| 394 |
or not isinstance(entry["text"], str)):
|
| 395 |
continue
|
|
|
|
|
|
|
| 396 |
if _normalized(entry["text"]) in tombstones:
|
| 397 |
continue
|
| 398 |
if words and not all(word in str(entry.get("text", "")).casefold() for word in words):
|
|
@@ -609,7 +660,6 @@ def _principal(session):
|
|
| 609 |
def _remember(session, args):
|
| 610 |
from routes_query import _AGENT_DOOR, _AGENT_TURN
|
| 611 |
turn = _AGENT_TURN.get() or {}
|
| 612 |
-
from core import perms
|
| 613 |
scope = args.get("scope", "personal")
|
| 614 |
if scope not in {"personal", "company"}:
|
| 615 |
raise ValueError("Memory scope must be personal or company.")
|
|
@@ -628,16 +678,13 @@ def _remember(session, args):
|
|
| 628 |
if not _readable(session.runtime, principal, sources):
|
| 629 |
raise PermissionError("Your current permissions do not allow this fact's source.")
|
| 630 |
door = turn.get("door") or _AGENT_DOOR.get()
|
| 631 |
-
if requested
|
| 632 |
if not _readable(session.runtime, principal, sources, company=True):
|
| 633 |
raise PermissionError("This fact's source scope could not be proven.")
|
| 634 |
-
return _write_company(session.runtime, user, args.get("text"), sources=sources, door=door
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
result["message"] = "I remembered this only for you. Only an Administrator can share a fact with everyone."
|
| 639 |
-
turn["memoryReply"] = result["message"]
|
| 640 |
-
return result
|
| 641 |
|
| 642 |
|
| 643 |
def admits(question):
|
|
@@ -666,9 +713,14 @@ def memory_tools():
|
|
| 666 |
import agent_tools
|
| 667 |
source = {"type": "object", "properties": {"database": {"type": "string"},
|
| 668 |
"fields": {"type": "array", "items": {"type": "string"}}}, "required": ["database", "fields"]}
|
| 669 |
-
agent_tools.register("remember", {"type": "object", "description":
|
|
|
|
|
|
|
| 670 |
"properties": {"text": {"type": "string"},
|
| 671 |
"scope": {"type": "string", "enum": ["personal", "company"]},
|
|
|
|
|
|
|
|
|
|
| 672 |
"sources": {"type": "array", "items": source}}, "required": ["text"]},
|
| 673 |
_remember, effect="write")
|
| 674 |
agent_tools.register("recall_memory", {"type": "object", "description": "Search this user's readable memory.",
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def _now():
|
| 39 |
+
from core import write_execution
|
| 40 |
+
return write_execution.utcnow().isoformat()
|
| 41 |
|
| 42 |
|
| 43 |
def _document(raw):
|
|
|
|
| 111 |
if key not in {"bus", "bu", "businessUnit"}}, "bus": bus} for source in sources]
|
| 112 |
|
| 113 |
|
| 114 |
+
def _subject(value):
|
| 115 |
+
"""Normalize the model-supplied key that names what a company note is about."""
|
| 116 |
+
if value is None or value == "":
|
| 117 |
+
return None
|
| 118 |
+
subject = value.strip().lower() if isinstance(value, str) else None
|
| 119 |
+
if not subject or not re.fullmatch(r"[a-z0-9_]{1,60}", subject):
|
| 120 |
+
raise ValueError("A note subject uses only lowercase letters, digits and underscores, at most 60 characters.")
|
| 121 |
+
return subject
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _write_company(rt, user, text, *, sources, door, kind=None, subject=None):
|
| 125 |
from core import perms
|
| 126 |
+
# R105: every active member writes company notes. The author's role decides which note prevails.
|
| 127 |
+
if not isinstance(user, dict) or not isinstance(user.get("username"), str) or not user["username"]:
|
| 128 |
+
raise PermissionError("Only an active member of this workspace can share a company note.")
|
| 129 |
if door not in {"app", "whatsapp", "slack", "wake"}:
|
| 130 |
raise ValueError("That Assistant memory door is not available.")
|
| 131 |
+
subject = _subject(subject)
|
| 132 |
sources = _sources(sources)
|
| 133 |
bus = sorted(set().union(*(_source_bus(source) for source in sources))) if sources else []
|
| 134 |
+
from core import write_execution
|
| 135 |
+
entry = {"id": write_execution.new_id(), "text": _text(text), "sources": sources,
|
| 136 |
+
"door": door, "at": _now(), "scope": "company", "bus": bus, "author": user["username"],
|
| 137 |
+
"authorRole": "admin" if perms.is_admin(user) else "member"}
|
| 138 |
+
if subject:
|
| 139 |
+
entry["subject"] = subject
|
| 140 |
entry["kind"] = _kind(entry["text"], kind)
|
| 141 |
def update(raw):
|
| 142 |
doc = _document(raw)
|
|
|
|
| 219 |
"""Store in the narrowest container. Slack's explicit-remember policy belongs to its door."""
|
| 220 |
if door not in {"app", "whatsapp", "slack", "wake"}:
|
| 221 |
raise ValueError("That Assistant memory door is not available.")
|
| 222 |
+
from core import write_execution
|
| 223 |
+
entry = {"id": write_execution.new_id(), "text": _text(text), "sources": _sources(sources),
|
| 224 |
"door": door, "at": _now()}
|
| 225 |
entry["kind"] = _kind(entry["text"])
|
| 226 |
key = _key(rt, username)
|
|
|
|
| 262 |
|
| 263 |
|
| 264 |
def forget_company(rt, principal, id):
|
| 265 |
+
"""An Administrator erases any company note. Its author erases only their own."""
|
| 266 |
from core import perms
|
| 267 |
+
user = _active_writer(rt, principal)
|
| 268 |
+
entries = company_document(rt)["entries"]
|
| 269 |
+
entry = next((row for row in entries if row.get("id") == id), None)
|
| 270 |
+
if entry is None:
|
| 271 |
return False
|
| 272 |
+
if not perms.is_admin(user):
|
| 273 |
+
if entry.get("author") != user.get("username"):
|
| 274 |
+
return False
|
| 275 |
+
# Erase removes every note with the same text. A member never erases another author's note.
|
| 276 |
+
text = _normalized(entry["text"])
|
| 277 |
+
if any(_normalized(row["text"]) == text and row.get("author") != user.get("username") for row in entries):
|
| 278 |
+
return False
|
| 279 |
return _forget_at(rt, _company_key(rt), id)
|
| 280 |
|
| 281 |
|
|
|
|
| 399 |
return False
|
| 400 |
|
| 401 |
|
| 402 |
+
def _prevailing(entry):
|
| 403 |
+
"""Rank the company notes on one subject: an Administrator's note first, then the newest."""
|
| 404 |
+
return (entry.get("authorRole") == "admin", _oldest(entry))
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _superseded(entries, tombstones):
|
| 408 |
+
"""Ids of company notes that another note on the same subject overrides."""
|
| 409 |
+
groups = {}
|
| 410 |
+
for entry in entries:
|
| 411 |
+
if (isinstance(entry, dict) and isinstance(entry.get("subject"), str) and entry["subject"]
|
| 412 |
+
and isinstance(entry.get("text"), str) and _normalized(entry["text"]) not in tombstones):
|
| 413 |
+
groups.setdefault(entry["subject"], []).append(entry)
|
| 414 |
+
superseded = set()
|
| 415 |
+
for group in groups.values():
|
| 416 |
+
winner = max(group, key=_prevailing)
|
| 417 |
+
superseded.update(id(entry) for entry in group if entry is not winner)
|
| 418 |
+
return superseded
|
| 419 |
+
|
| 420 |
+
|
| 421 |
def recall(rt, principal, query=None, limit=20):
|
| 422 |
"""Recall the authorized union with current source access for every channel member."""
|
| 423 |
try:
|
|
|
|
| 435 |
return result
|
| 436 |
entries = [(entry, "personal", doc["tombstones"]) for entry in doc["entries"]]
|
| 437 |
entries.extend((entry, "company", company["tombstones"]) for entry in company["entries"])
|
| 438 |
+
# The prevailing note is chosen before the query and source filters, so a withheld winner
|
| 439 |
+
# never lets a superseded note through.
|
| 440 |
+
superseded = _superseded(company["entries"], company["tombstones"])
|
| 441 |
for entry, scope, tombstones in sorted(reversed(entries), key=lambda row: _oldest(row[0]), reverse=True):
|
| 442 |
if (not isinstance(entry, dict) or not all(key in entry for key in ("id", "text", "sources", "door", "at"))
|
| 443 |
or not isinstance(entry["text"], str)):
|
| 444 |
continue
|
| 445 |
+
if scope == "company" and id(entry) in superseded:
|
| 446 |
+
continue
|
| 447 |
if _normalized(entry["text"]) in tombstones:
|
| 448 |
continue
|
| 449 |
if words and not all(word in str(entry.get("text", "")).casefold() for word in words):
|
|
|
|
| 660 |
def _remember(session, args):
|
| 661 |
from routes_query import _AGENT_DOOR, _AGENT_TURN
|
| 662 |
turn = _AGENT_TURN.get() or {}
|
|
|
|
| 663 |
scope = args.get("scope", "personal")
|
| 664 |
if scope not in {"personal", "company"}:
|
| 665 |
raise ValueError("Memory scope must be personal or company.")
|
|
|
|
| 678 |
if not _readable(session.runtime, principal, sources):
|
| 679 |
raise PermissionError("Your current permissions do not allow this fact's source.")
|
| 680 |
door = turn.get("door") or _AGENT_DOOR.get()
|
| 681 |
+
if requested:
|
| 682 |
if not _readable(session.runtime, principal, sources, company=True):
|
| 683 |
raise PermissionError("This fact's source scope could not be proven.")
|
| 684 |
+
return _write_company(session.runtime, user, args.get("text"), sources=sources, door=door,
|
| 685 |
+
subject=args.get("subject"))
|
| 686 |
+
return {"id": remember(session.runtime, session.uname, args.get("text"), sources=sources, door=door),
|
| 687 |
+
"scope": "personal"}
|
|
|
|
|
|
|
|
|
|
| 688 |
|
| 689 |
|
| 690 |
def admits(question):
|
|
|
|
| 713 |
import agent_tools
|
| 714 |
source = {"type": "object", "properties": {"database": {"type": "string"},
|
| 715 |
"fields": {"type": "array", "items": {"type": "string"}}}, "required": ["database", "fields"]}
|
| 716 |
+
agent_tools.register("remember", {"type": "object", "description": (
|
| 717 |
+
"Remember a sourced fact. Use company scope for a fact about the business that "
|
| 718 |
+
"everyone should share, such as when the fiscal year starts. Any user can add a company note."),
|
| 719 |
"properties": {"text": {"type": "string"},
|
| 720 |
"scope": {"type": "string", "enum": ["personal", "company"]},
|
| 721 |
+
"subject": {"type": "string", "description": (
|
| 722 |
+
"A short key for what the note is about, such as fiscal_year_start. "
|
| 723 |
+
"Reuse it for a note that replaces another.")},
|
| 724 |
"sources": {"type": "array", "items": source}}, "required": ["text"]},
|
| 725 |
_remember, effect="write")
|
| 726 |
agent_tools.register("recall_memory", {"type": "object", "description": "Search this user's readable memory.",
|
api/assistant_open_items.py
CHANGED
|
@@ -70,8 +70,9 @@ def open_items(session, args):
|
|
| 70 |
assignments = sorted({username, *(str(row["assigned_to"]) for row in mine)})
|
| 71 |
if any(len(assignment) > 500 for assignment in assignments):
|
| 72 |
raise ValueError("A ticket assignment exceeds the saved View filter limit.")
|
|
|
|
| 73 |
view_args = {"database": database, "view": {
|
| 74 |
-
"id": "open_items_" +
|
| 75 |
"filters": [{"colId": "status", "op": "eq", "value": "Open"},
|
| 76 |
{"conj": "or", "children": [
|
| 77 |
{"colId": "assigned_to", "op": "eq", "value": assignment}
|
|
|
|
| 70 |
assignments = sorted({username, *(str(row["assigned_to"]) for row in mine)})
|
| 71 |
if any(len(assignment) > 500 for assignment in assignments):
|
| 72 |
raise ValueError("A ticket assignment exceeds the saved View filter limit.")
|
| 73 |
+
from core import write_execution
|
| 74 |
view_args = {"database": database, "view": {
|
| 75 |
+
"id": "open_items_" + write_execution.new_id(), "name": "Open for me", "config": {
|
| 76 |
"filters": [{"colId": "status", "op": "eq", "value": "Open"},
|
| 77 |
{"conj": "or", "children": [
|
| 78 |
{"colId": "assigned_to", "op": "eq", "value": assignment}
|
api/assistant_write_preview.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run authorized Assistant writers on a private store, then commit only their held documents.
|
| 2 |
+
|
| 3 |
+
The ordinary writer remains the permission/field/BU validator. Revalidation uses the held
|
| 4 |
+
execution clock and ids, and must reproduce the exact documents before any real write.
|
| 5 |
+
"""
|
| 6 |
+
import copy
|
| 7 |
+
import time
|
| 8 |
+
import uuid
|
| 9 |
+
|
| 10 |
+
from deps import Session
|
| 11 |
+
from core import write_execution
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _digest(value):
|
| 15 |
+
from routes_external import _json_digest
|
| 16 |
+
return _json_digest(value)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _changes(before, after, path=()):
|
| 20 |
+
"""Exact store deltas, including absent keys and list removal rather than null cells."""
|
| 21 |
+
if before == after:
|
| 22 |
+
return []
|
| 23 |
+
if isinstance(before, dict) and isinstance(after, dict):
|
| 24 |
+
changes = []
|
| 25 |
+
for key in sorted(before.keys() | after.keys()):
|
| 26 |
+
at = [*path, key]
|
| 27 |
+
if key not in after:
|
| 28 |
+
changes.append({"path": at, "remove": True})
|
| 29 |
+
elif key not in before:
|
| 30 |
+
changes.append({"path": at, "after": copy.deepcopy(after[key])})
|
| 31 |
+
else:
|
| 32 |
+
changes.extend(_changes(before[key], after[key], at))
|
| 33 |
+
return changes
|
| 34 |
+
if isinstance(before, list) and isinstance(after, list):
|
| 35 |
+
changes = []
|
| 36 |
+
for i in range(min(len(before), len(after))):
|
| 37 |
+
changes.extend(_changes(before[i], after[i], [*path, i]))
|
| 38 |
+
changes.extend({"path": [*path, i], "after": copy.deepcopy(after[i])}
|
| 39 |
+
for i in range(len(before), len(after)))
|
| 40 |
+
changes.extend({"path": [*path, i], "remove": True}
|
| 41 |
+
for i in range(len(before) - 1, len(after) - 1, -1))
|
| 42 |
+
return changes
|
| 43 |
+
return [{"path": list(path), "after": copy.deepcopy(after)}]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def project(current, document):
|
| 47 |
+
if _digest(current) != document["before_digest"]:
|
| 48 |
+
raise ValueError("The data changed after preview. Ask again to preview the change.")
|
| 49 |
+
value = copy.deepcopy(current)
|
| 50 |
+
for op in document["patch"]:
|
| 51 |
+
path = op["path"]
|
| 52 |
+
if not path:
|
| 53 |
+
value = copy.deepcopy(op["after"])
|
| 54 |
+
continue
|
| 55 |
+
parent = value
|
| 56 |
+
for key in path[:-1]:
|
| 57 |
+
parent = parent[key]
|
| 58 |
+
key = path[-1]
|
| 59 |
+
if op.get("remove"):
|
| 60 |
+
del parent[key]
|
| 61 |
+
elif isinstance(parent, list) and key == len(parent):
|
| 62 |
+
parent.append(copy.deepcopy(op["after"]))
|
| 63 |
+
else:
|
| 64 |
+
parent[key] = copy.deepcopy(op["after"])
|
| 65 |
+
if _digest(value) != document["after_digest"]:
|
| 66 |
+
raise ValueError("The held change could not be verified. Preview the change again.")
|
| 67 |
+
return value
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def prepare(session, name, args, *, prior=(), execution=None):
|
| 71 |
+
import agent_runtime
|
| 72 |
+
import routes_external as external
|
| 73 |
+
|
| 74 |
+
runtime = external._PreviewRuntime(session.runtime)
|
| 75 |
+
runtime.preview_only = True
|
| 76 |
+
runtime.deferred_notices = []
|
| 77 |
+
runtime.deferred_audits = []
|
| 78 |
+
for step in prior:
|
| 79 |
+
for key, document in step["preview"]["documents"].items():
|
| 80 |
+
runtime.put(key, project(runtime.get(key), document))
|
| 81 |
+
# Prior held steps are the starting point for this step, not part of its diff.
|
| 82 |
+
runtime._initial = copy.deepcopy(runtime._docs)
|
| 83 |
+
actor = Session(session.tenant, copy.deepcopy(session.user), copy.deepcopy(session.claims), runtime)
|
| 84 |
+
execution = execution or {"seed": uuid.uuid4().hex, "timestamp": time.time()}
|
| 85 |
+
with write_execution.replay(execution):
|
| 86 |
+
result = agent_runtime._dispatch(actor, name, copy.deepcopy(args))
|
| 87 |
+
if isinstance(result, dict) and (result.get("ok") is False or result.get("refused")):
|
| 88 |
+
raise ValueError(agent_runtime._refusal(result))
|
| 89 |
+
documents = runtime.changed()
|
| 90 |
+
diff, truncated = external._diff_documents(documents)
|
| 91 |
+
if truncated:
|
| 92 |
+
raise ValueError("The complete change is too large to preview. Split it into smaller changes.")
|
| 93 |
+
# A valid no-op still goes through the writer and may have a meaningful return value.
|
| 94 |
+
preview = {"execution": execution, "documents": {
|
| 95 |
+
key: {"before_digest": _digest(pair["before"]), "after_digest": _digest(pair["after"]),
|
| 96 |
+
"patch": _changes(pair["before"], pair["after"])}
|
| 97 |
+
for key, pair in documents.items()}, "result": result,
|
| 98 |
+
"reads": {key: _digest(value) for key, value in runtime._initial.items()}, "diff": diff,
|
| 99 |
+
"notices": runtime.deferred_notices, "audits": runtime.deferred_audits}
|
| 100 |
+
external._canonical_json(preview)
|
| 101 |
+
return preview
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def lines(preview, name, args, session):
|
| 105 |
+
import agent_runtime
|
| 106 |
+
import json
|
| 107 |
+
result = preview["result"]
|
| 108 |
+
heading = agent_runtime._change_lines(name, args, session)
|
| 109 |
+
if isinstance(result, dict):
|
| 110 |
+
if result.get("label") and (name.startswith("schedule_") or name == "reminder_create"):
|
| 111 |
+
return [f"{name.replace('_', ' ').capitalize()}: {result['label']}.",
|
| 112 |
+
result.get("message") or f"{result['inWords']} ({result['timezone']})."]
|
| 113 |
+
elif name.startswith("ticket_") and result.get("title"):
|
| 114 |
+
detail = ("Assigned to: " + result["assigned_to"] if name == "ticket_assign" else
|
| 115 |
+
"Snoozed until: " + result["snoozed_until"] if name == "ticket_snooze" else
|
| 116 |
+
"Status: " + result["status"])
|
| 117 |
+
return [f"{name.replace('_', ' ').capitalize()}: {result['title']}.", detail]
|
| 118 |
+
elif name == "remember":
|
| 119 |
+
from assistant_memory import _text
|
| 120 |
+
return ["Remember: " + _text(args.get("text")), "Scope: " + str(result.get("scope") or "company")]
|
| 121 |
+
elif name == "tool_save":
|
| 122 |
+
saved = result["saved"]
|
| 123 |
+
return ["Save tool " + saved["title"] + " for you.",
|
| 124 |
+
*(step["tool"].replace("_", " ") + ": " + json.dumps(step["args"], ensure_ascii=True)
|
| 125 |
+
for step in saved["steps"])]
|
| 126 |
+
elif name == "tool_share":
|
| 127 |
+
return ["Share tool " + args["name"] + ".", result.get("message") or "Share with the workspace."]
|
| 128 |
+
elif name == "tool_share_decide":
|
| 129 |
+
return [("Share " + result["tool"]["title"] + " with the workspace."
|
| 130 |
+
if result.get("shared") else "Decline the tool sharing request.")]
|
| 131 |
+
elif name == "agent_message":
|
| 132 |
+
return ["Send " + args["type"].replace("_", " ") + " to " + str(args.get("to") or "the item owner") + ".",
|
| 133 |
+
str(result.get("text") or args.get("text") or "")]
|
| 134 |
+
elif name == "open_items":
|
| 135 |
+
return str(result["message"]).splitlines()
|
| 136 |
+
# The held delta contains every normalized change. Show values relevant to the decision;
|
| 137 |
+
# revisions, attribution and store addresses do not help a person approve a change.
|
| 138 |
+
metadata = {"id", "rev", "schemaVersion", "created_at", "updated_at", "createdAt", "updatedAt",
|
| 139 |
+
"created_by", "updatedBy", "writes", "writesFrom", "refreshed_at", "has_access"}
|
| 140 |
+
details = []
|
| 141 |
+
def show(value):
|
| 142 |
+
if isinstance(value, dict):
|
| 143 |
+
if value.get("kind") == "literal":
|
| 144 |
+
return value.get("value")
|
| 145 |
+
return {k: show(v) for k, v in value.items() if k not in metadata}
|
| 146 |
+
return [show(v) for v in value] if isinstance(value, list) else value
|
| 147 |
+
for row in preview["diff"]:
|
| 148 |
+
path = row["path"].split("/")[1:]
|
| 149 |
+
if not path or path[-1] in metadata or path[0] == "sheet_workbooks" or "writes" in path:
|
| 150 |
+
continue
|
| 151 |
+
if name in {"sheet_create_workbook", "sheet_add_tab", "sheet_delete_tab", "view_delete", "query_view_delete", "app_delete"}:
|
| 152 |
+
continue
|
| 153 |
+
label = path[-1].replace("_", " ").capitalize()
|
| 154 |
+
if "cells" in path:
|
| 155 |
+
index = path.index("cells")
|
| 156 |
+
label = "Cell " + path[index + 1] + (" " + path[-1] if len(path) > index + 2 else "")
|
| 157 |
+
elif "rows" in path:
|
| 158 |
+
index = path.index("rows")
|
| 159 |
+
label = "Record " + path[index + 1] + (" " + label.lower() if len(path) > index + 2 else "")
|
| 160 |
+
elif "rules" in path:
|
| 161 |
+
label = "Format rule"
|
| 162 |
+
elif "charts" in path:
|
| 163 |
+
label = "Chart"
|
| 164 |
+
details.append(label + ": " + json.dumps(show(row["after"]), ensure_ascii=True))
|
| 165 |
+
return [*heading, *details]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def apply(session, step):
|
| 169 |
+
import routes_external as external
|
| 170 |
+
held = step["preview"]
|
| 171 |
+
# Every read used by the planner must still match, including permission/owner documents.
|
| 172 |
+
for key, before_digest in held["reads"].items():
|
| 173 |
+
try:
|
| 174 |
+
current = session.runtime.get(key, fresh=True)
|
| 175 |
+
except TypeError:
|
| 176 |
+
current = session.runtime.get(key)
|
| 177 |
+
if _digest(current) != before_digest:
|
| 178 |
+
raise ValueError("The data changed after preview. Ask again to preview the change.")
|
| 179 |
+
checked = prepare(session, step["tool"], step["resolvedArgs"], execution=held["execution"])
|
| 180 |
+
if any(checked[key] != held[key] for key in ("documents", "notices", "audits")):
|
| 181 |
+
raise ValueError("The data or permissions changed after preview. Ask again to preview the change.")
|
| 182 |
+
# Commit the approved plan, rather than recomputing a plan inside a live writer.
|
| 183 |
+
revisions = {key: session.runtime.revision(key) for key in held["documents"]}
|
| 184 |
+
if any(not isinstance(rev, dict) or type(rev.get("rev")) is not int for rev in revisions.values()):
|
| 185 |
+
raise ValueError("This store cannot safely confirm the preview. Nothing was changed.")
|
| 186 |
+
for key, pair in held["documents"].items():
|
| 187 |
+
def exact(current, pair=pair):
|
| 188 |
+
return project(current, pair)
|
| 189 |
+
session.runtime.update(key, exact, flush="sync", expect_rev=revisions[key]["rev"])
|
| 190 |
+
if held["notices"]:
|
| 191 |
+
import assistant_feed
|
| 192 |
+
for notice in held["notices"]:
|
| 193 |
+
assistant_feed.deliver_external(session.runtime, **notice)
|
| 194 |
+
if held["audits"]:
|
| 195 |
+
from core import audit
|
| 196 |
+
for detail in held["audits"]:
|
| 197 |
+
audit.record("external.query", session.tenant, session.uname, detail)
|
| 198 |
+
return copy.deepcopy(held["result"])
|
api/deps.py
CHANGED
|
@@ -186,8 +186,7 @@ def _assistant_tenant_allows(session: Session, database: str) -> bool:
|
|
| 186 |
|
| 187 |
|
| 188 |
def _assistant_preflight_request(session: Session, database: str, canonical_fields,
|
| 189 |
-
requested_fields, filters, *, require_explicit_grant: bool
|
| 190 |
-
permission_fields=None):
|
| 191 |
"""Refuse an unresolved grant, field or filter before a stored record is touched."""
|
| 192 |
import core.perm_scope as perm_scope
|
| 193 |
|
|
@@ -198,8 +197,7 @@ def _assistant_preflight_request(session: Session, database: str, canonical_fiel
|
|
| 198 |
visible = (perm_scope.assistant_visible_fields(canonical_fields, session.user, database)
|
| 199 |
if grant is not None else list(canonical_fields or ()))
|
| 200 |
try:
|
| 201 |
-
perm_scope.validate_assistant_filter((grant or {}).get("filter"),
|
| 202 |
-
canonical_fields if permission_fields is None else permission_fields)
|
| 203 |
_assistant_requested_fields(requested_fields, visible)
|
| 204 |
perm_scope.validate_assistant_filter(filters, visible)
|
| 205 |
except ValueError as exc:
|
|
@@ -208,7 +206,7 @@ def _assistant_preflight_request(session: Session, database: str, canonical_fiel
|
|
| 208 |
|
| 209 |
|
| 210 |
def _assistant_cached_builtin(session: Session, database: str, requested_fields=None, filters=None,
|
| 211 |
-
*, mode=None
|
| 212 |
"""The exact in-process snapshot for one built-in database, or a loud cache-miss refusal.
|
| 213 |
|
| 214 |
This intentionally reads `runtime.pool_cache` directly. Calling either route's `_pool_for`
|
|
@@ -224,29 +222,18 @@ def _assistant_cached_builtin(session: Session, database: str, requested_fields=
|
|
| 224 |
_assistant_refuse(403, "assistant_forbidden",
|
| 225 |
"your current permissions do not allow this database")
|
| 226 |
|
| 227 |
-
# Resolve the grid's permitted field contract without rows before any cache read.
|
| 228 |
# Its derived and overlay cells below must match the ordinary grid's scoped assembly.
|
| 229 |
import aios_grid
|
|
|
|
|
|
|
| 230 |
if database == "customer_data":
|
| 231 |
from routes_customers import grid_assembly
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
from routes_products import product_assembly as grid_assembly
|
| 235 |
-
grid_scope = "product"
|
| 236 |
-
grid = grid_assembly(session, scope=grid_scope, consume_corrections=False, with_rows=False)
|
| 237 |
-
fields = grid["fields"]
|
| 238 |
-
internal = grid.get("_permission_scope") or {"fields": fields, "rows": [], "row_fields": fields}
|
| 239 |
_assistant_preflight_request(session, database, fields, requested_fields, filters,
|
| 240 |
-
require_explicit_grant=True
|
| 241 |
-
for member in members:
|
| 242 |
-
try:
|
| 243 |
-
perm_scope.validate_assistant_filter(
|
| 244 |
-
(perm_scope.assistant_entry(member, database) or {}).get("filter"), internal["fields"])
|
| 245 |
-
except ValueError as exc:
|
| 246 |
-
_assistant_refuse(400, "assistant_bad_filter", str(exc))
|
| 247 |
if mode in ("schema", "query_schema"):
|
| 248 |
-
if permission_scope is not None and "_permission_scope" in grid:
|
| 249 |
-
permission_scope.update(internal)
|
| 250 |
return [], [dict(field) for field in fields], {"read": "field contract"}
|
| 251 |
|
| 252 |
team_id, agent = perm_scope.derive_pool_scope(session.user, database)
|
|
@@ -281,12 +268,15 @@ def _assistant_cached_builtin(session: Session, database: str, requested_fields=
|
|
| 281 |
or any(not isinstance(row, dict) for row in entry[1])):
|
| 282 |
_assistant_refuse(409, "assistant_snapshot_unavailable",
|
| 283 |
"this database has no app-stored snapshot for your current scope")
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
| 290 |
return rows, [dict(field) for field in fields if isinstance(field, dict)], entry[0]
|
| 291 |
|
| 292 |
|
|
@@ -751,6 +741,7 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
|
|
| 751 |
⭐ S67-T34: `mode` changes only HOW a database is read, never who may read it
|
| 752 |
(every wall below runs unchanged): "schema" returns the field contract with no row read,
|
| 753 |
"query_schema" resolves the answerable SQL fields without reading rows,
|
|
|
|
| 754 |
("aggregate", specs) adds `server_aggregates` and `total_rows` computed in SQL over every
|
| 755 |
permitted row; an optional third options dict pages SQL groups. ("page", offset, limit)
|
| 756 |
returns one SQL page plus `total_rows`. Every other
|
|
@@ -813,11 +804,10 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
|
|
| 813 |
_assistant_refuse(403, "assistant_forbidden",
|
| 814 |
"Every aggregate and grouping field must be visible to every member.")
|
| 815 |
extra = {}
|
| 816 |
-
builtin_scope = {}
|
| 817 |
_audience_defn = None # the held definition lends C16's declaration without a store read
|
| 818 |
if key in _ASSISTANT_BUILT_INS:
|
| 819 |
rows, canonical_fields, source_version = _assistant_cached_builtin(
|
| 820 |
-
session, key, fields, filters, mode=mode
|
| 821 |
label = _ASSISTANT_BUILT_INS[key]["label"]
|
| 822 |
source_kind = "runtime_cache"
|
| 823 |
elif key.startswith("ut_"):
|
|
@@ -848,6 +838,8 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
|
|
| 848 |
session, key, fields, filters, defn=_defn, lent=_lent)
|
| 849 |
source_kind = "materialised_user_table"
|
| 850 |
else:
|
|
|
|
|
|
|
| 851 |
if perm_scope.audience_declared(key, st=session.runtime, defn=_defn):
|
| 852 |
# C16 on a mirror-served table would have to run inside the SQL before counting
|
| 853 |
# and paging; filtering the returned page afterwards gives a wrong total. Refuse.
|
|
@@ -880,11 +872,10 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
|
|
| 880 |
# Spelled as membership so a third user-table source is one line, not a growing chain.
|
| 881 |
_assistant_refuse(403, "assistant_forbidden",
|
| 882 |
"your current permissions do not allow this database")
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
_assistant_refuse(400, "assistant_bad_filter", str(exc))
|
| 888 |
# ⭐ OWNER I16 — the tenant handle rides into the row wall here too, so one stored rule means
|
| 889 |
# the same thing in the Analyst's answer as it does on the grid (see
|
| 890 |
# `perm_scope._enrich_for_wall`).
|
|
@@ -900,16 +891,6 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
|
|
| 900 |
# must not make a schema description load stored cells to enrich an empty row set.
|
| 901 |
if mode in ("schema", "query_schema"):
|
| 902 |
permitted_rows = []
|
| 903 |
-
elif builtin_scope:
|
| 904 |
-
# The grid already applied the member's row wall before masking its operands.
|
| 905 |
-
permitted_rows = rows
|
| 906 |
-
if session.admin:
|
| 907 |
-
# Retain the Assistant's explicit admin grant, which the interactive grid bypasses.
|
| 908 |
-
allowed = perm_scope.assistant_apply_row_scope(
|
| 909 |
-
builtin_scope["rows"], session.user, key, builtin_scope["row_fields"],
|
| 910 |
-
st=session.runtime)
|
| 911 |
-
allowed_pids = {row.get("pid") for row in allowed}
|
| 912 |
-
permitted_rows = [row for row in permitted_rows if row.get("pid") in allowed_pids]
|
| 913 |
else:
|
| 914 |
# C16: with no grant there is no row wall, but a declared recipient list still binds
|
| 915 |
# every reader, administrators included (S68-T57).
|
|
@@ -920,23 +901,13 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
|
|
| 920 |
defn=_audience_defn))
|
| 921 |
visible = (perm_scope.assistant_visible_fields(canonical_fields, session.user, key)
|
| 922 |
if grant is not None else list(canonical_fields))
|
| 923 |
-
hidden = perm_scope.hidden_keys(session.user, key, canonical_fields, st=session.runtime)
|
| 924 |
-
visible = [field for field in visible if field.get("key") not in hidden]
|
| 925 |
if members:
|
| 926 |
hidden = set(access["hidden"])
|
| 927 |
-
member_rows = builtin_scope.get("rows", permitted_rows)
|
| 928 |
-
member_fields = builtin_scope.get("fields", canonical_fields)
|
| 929 |
for member in members:
|
| 930 |
-
hidden.update(perm_scope.hidden_keys(member, key,
|
| 931 |
if mode not in ("schema", "query_schema"):
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
st=session.runtime)
|
| 935 |
-
if builtin_scope and mode not in ("schema", "query_schema"):
|
| 936 |
-
allowed_pids = {row.get("pid") for row in member_rows}
|
| 937 |
-
permitted_rows = [row for row in permitted_rows if row.get("pid") in allowed_pids]
|
| 938 |
-
elif not builtin_scope:
|
| 939 |
-
permitted_rows = member_rows
|
| 940 |
visible = [field for field in visible if field.get("key") not in hidden]
|
| 941 |
selected_keys = _assistant_requested_fields(fields, visible)
|
| 942 |
try:
|
|
@@ -1409,16 +1380,16 @@ def require_session(request: Request, response: Response) -> Session:
|
|
| 1409 |
raise err(401, "no_session", "sign in to continue")
|
| 1410 |
claims = aios_session.read(raw)
|
| 1411 |
if not claims:
|
| 1412 |
-
raise err(401, "invalid_session", "
|
| 1413 |
user = _user_for(claims)
|
| 1414 |
if not user:
|
| 1415 |
-
raise err(401, "invalid_session", "
|
| 1416 |
try:
|
| 1417 |
rt = runtime.get_runtime(claims["t"])
|
| 1418 |
except KeyError:
|
| 1419 |
# An unknown tenant slug is a 401, not a 404: the cookie is not a valid identity for this
|
| 1420 |
# deployment, and confirming which slugs exist would answer a question we were not asked.
|
| 1421 |
-
raise err(401, "invalid_session", "
|
| 1422 |
fresh, _ = aios_session.mint(claims["t"], user["username"], int(user.get("epoch") or 0),
|
| 1423 |
absolute_expiry=claims["x"])
|
| 1424 |
aios_session.set_cookie(response, request, fresh)
|
|
@@ -1463,7 +1434,7 @@ def require_changes_session(request: Request, response: Response) -> Session | N
|
|
| 1463 |
raw = request.cookies.get(aios_session.COOKIE_NAME)
|
| 1464 |
claims = aios_session.read(raw) if raw else None
|
| 1465 |
if not claims or not str(claims.get("t") or "").strip() or not str(claims.get("u") or "").strip():
|
| 1466 |
-
raise err(401, "invalid_session", "
|
| 1467 |
return None
|
| 1468 |
|
| 1469 |
|
|
|
|
| 186 |
|
| 187 |
|
| 188 |
def _assistant_preflight_request(session: Session, database: str, canonical_fields,
|
| 189 |
+
requested_fields, filters, *, require_explicit_grant: bool):
|
|
|
|
| 190 |
"""Refuse an unresolved grant, field or filter before a stored record is touched."""
|
| 191 |
import core.perm_scope as perm_scope
|
| 192 |
|
|
|
|
| 197 |
visible = (perm_scope.assistant_visible_fields(canonical_fields, session.user, database)
|
| 198 |
if grant is not None else list(canonical_fields or ()))
|
| 199 |
try:
|
| 200 |
+
perm_scope.validate_assistant_filter((grant or {}).get("filter"), canonical_fields)
|
|
|
|
| 201 |
_assistant_requested_fields(requested_fields, visible)
|
| 202 |
perm_scope.validate_assistant_filter(filters, visible)
|
| 203 |
except ValueError as exc:
|
|
|
|
| 206 |
|
| 207 |
|
| 208 |
def _assistant_cached_builtin(session: Session, database: str, requested_fields=None, filters=None,
|
| 209 |
+
*, mode=None):
|
| 210 |
"""The exact in-process snapshot for one built-in database, or a loud cache-miss refusal.
|
| 211 |
|
| 212 |
This intentionally reads `runtime.pool_cache` directly. Calling either route's `_pool_for`
|
|
|
|
| 222 |
_assistant_refuse(403, "assistant_forbidden",
|
| 223 |
"your current permissions do not allow this database")
|
| 224 |
|
| 225 |
+
# Resolve the customer grid's permitted field contract without rows before any cache read.
|
| 226 |
# Its derived and overlay cells below must match the ordinary grid's scoped assembly.
|
| 227 |
import aios_grid
|
| 228 |
+
fields = aios_grid.FIELDS if database == "customer_data" else aios_grid.product_fields()
|
| 229 |
+
customer_grid = None
|
| 230 |
if database == "customer_data":
|
| 231 |
from routes_customers import grid_assembly
|
| 232 |
+
customer_grid = grid_assembly(session, scope="customer", consume_corrections=False, with_rows=False)
|
| 233 |
+
fields = customer_grid["fields"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
_assistant_preflight_request(session, database, fields, requested_fields, filters,
|
| 235 |
+
require_explicit_grant=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
if mode in ("schema", "query_schema"):
|
|
|
|
|
|
|
| 237 |
return [], [dict(field) for field in fields], {"read": "field contract"}
|
| 238 |
|
| 239 |
team_id, agent = perm_scope.derive_pool_scope(session.user, database)
|
|
|
|
| 268 |
or any(not isinstance(row, dict) for row in entry[1])):
|
| 269 |
_assistant_refuse(409, "assistant_snapshot_unavailable",
|
| 270 |
"this database has no app-stored snapshot for your current scope")
|
| 271 |
+
if customer_grid is not None:
|
| 272 |
+
customer_grid = grid_assembly(session, scope="customer", consume_corrections=False, with_rows=True)
|
| 273 |
+
rows = aios_grid.rows_from_pool(customer_grid["rows_src"], fields,
|
| 274 |
+
(customer_grid.get("ws") or {}).get("overlays") or {},
|
| 275 |
+
derived=customer_grid.get("derived"))
|
| 276 |
+
else:
|
| 277 |
+
import routes_products
|
| 278 |
+
product_grid = routes_products.product_assembly(session, consume_corrections=False)
|
| 279 |
+
rows = routes_products.product_rows(product_grid)
|
| 280 |
return rows, [dict(field) for field in fields if isinstance(field, dict)], entry[0]
|
| 281 |
|
| 282 |
|
|
|
|
| 741 |
⭐ S67-T34: `mode` changes only HOW a database is read, never who may read it
|
| 742 |
(every wall below runs unchanged): "schema" returns the field contract with no row read,
|
| 743 |
"query_schema" resolves the answerable SQL fields without reading rows,
|
| 744 |
+
"query_plan" uses query_schema for mirrors and the incumbent snapshot for other sources,
|
| 745 |
("aggregate", specs) adds `server_aggregates` and `total_rows` computed in SQL over every
|
| 746 |
permitted row; an optional third options dict pages SQL groups. ("page", offset, limit)
|
| 747 |
returns one SQL page plus `total_rows`. Every other
|
|
|
|
| 804 |
_assistant_refuse(403, "assistant_forbidden",
|
| 805 |
"Every aggregate and grouping field must be visible to every member.")
|
| 806 |
extra = {}
|
|
|
|
| 807 |
_audience_defn = None # the held definition lends C16's declaration without a store read
|
| 808 |
if key in _ASSISTANT_BUILT_INS:
|
| 809 |
rows, canonical_fields, source_version = _assistant_cached_builtin(
|
| 810 |
+
session, key, fields, filters, mode=mode)
|
| 811 |
label = _ASSISTANT_BUILT_INS[key]["label"]
|
| 812 |
source_kind = "runtime_cache"
|
| 813 |
elif key.startswith("ut_"):
|
|
|
|
| 838 |
session, key, fields, filters, defn=_defn, lent=_lent)
|
| 839 |
source_kind = "materialised_user_table"
|
| 840 |
else:
|
| 841 |
+
if mode == "query_plan":
|
| 842 |
+
mode = "query_schema"
|
| 843 |
if perm_scope.audience_declared(key, st=session.runtime, defn=_defn):
|
| 844 |
# C16 on a mirror-served table would have to run inside the SQL before counting
|
| 845 |
# and paging; filtering the returned page afterwards gives a wrong total. Refuse.
|
|
|
|
| 872 |
# Spelled as membership so a third user-table source is one line, not a growing chain.
|
| 873 |
_assistant_refuse(403, "assistant_forbidden",
|
| 874 |
"your current permissions do not allow this database")
|
| 875 |
+
try:
|
| 876 |
+
perm_scope.validate_assistant_filter((grant or {}).get("filter"), canonical_fields)
|
| 877 |
+
except ValueError as exc:
|
| 878 |
+
_assistant_refuse(400, "assistant_bad_filter", str(exc))
|
|
|
|
| 879 |
# ⭐ OWNER I16 — the tenant handle rides into the row wall here too, so one stored rule means
|
| 880 |
# the same thing in the Analyst's answer as it does on the grid (see
|
| 881 |
# `perm_scope._enrich_for_wall`).
|
|
|
|
| 891 |
# must not make a schema description load stored cells to enrich an empty row set.
|
| 892 |
if mode in ("schema", "query_schema"):
|
| 893 |
permitted_rows = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 894 |
else:
|
| 895 |
# C16: with no grant there is no row wall, but a declared recipient list still binds
|
| 896 |
# every reader, administrators included (S68-T57).
|
|
|
|
| 901 |
defn=_audience_defn))
|
| 902 |
visible = (perm_scope.assistant_visible_fields(canonical_fields, session.user, key)
|
| 903 |
if grant is not None else list(canonical_fields))
|
|
|
|
|
|
|
| 904 |
if members:
|
| 905 |
hidden = set(access["hidden"])
|
|
|
|
|
|
|
| 906 |
for member in members:
|
| 907 |
+
hidden.update(perm_scope.hidden_keys(member, key, canonical_fields, st=session.runtime))
|
| 908 |
if mode not in ("schema", "query_schema"):
|
| 909 |
+
permitted_rows = perm_scope.apply_row_scope(
|
| 910 |
+
permitted_rows, member, key, canonical_fields, st=session.runtime)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 911 |
visible = [field for field in visible if field.get("key") not in hidden]
|
| 912 |
selected_keys = _assistant_requested_fields(fields, visible)
|
| 913 |
try:
|
|
|
|
| 1380 |
raise err(401, "no_session", "sign in to continue")
|
| 1381 |
claims = aios_session.read(raw)
|
| 1382 |
if not claims:
|
| 1383 |
+
raise err(401, "invalid_session", "Your session ended. Sign in again.")
|
| 1384 |
user = _user_for(claims)
|
| 1385 |
if not user:
|
| 1386 |
+
raise err(401, "invalid_session", "Your session ended. Sign in again.")
|
| 1387 |
try:
|
| 1388 |
rt = runtime.get_runtime(claims["t"])
|
| 1389 |
except KeyError:
|
| 1390 |
# An unknown tenant slug is a 401, not a 404: the cookie is not a valid identity for this
|
| 1391 |
# deployment, and confirming which slugs exist would answer a question we were not asked.
|
| 1392 |
+
raise err(401, "invalid_session", "Your session ended. Sign in again.")
|
| 1393 |
fresh, _ = aios_session.mint(claims["t"], user["username"], int(user.get("epoch") or 0),
|
| 1394 |
absolute_expiry=claims["x"])
|
| 1395 |
aios_session.set_cookie(response, request, fresh)
|
|
|
|
| 1434 |
raw = request.cookies.get(aios_session.COOKIE_NAME)
|
| 1435 |
claims = aios_session.read(raw) if raw else None
|
| 1436 |
if not claims or not str(claims.get("t") or "").strip() or not str(claims.get("u") or "").strip():
|
| 1437 |
+
raise err(401, "invalid_session", "Your session ended. Sign in again.")
|
| 1438 |
return None
|
| 1439 |
|
| 1440 |
|
api/external_activity.py
CHANGED
|
@@ -26,11 +26,15 @@ def _record(session, database, outcome, code):
|
|
| 26 |
label = next((row.get("label") for row in rows if row.get("id") == key_id), "")
|
| 27 |
except external_access.ExternalAccessError:
|
| 28 |
pass
|
| 29 |
-
|
| 30 |
"key_id": key_id, "key_label": _text(label), "database": _text(database),
|
| 31 |
"outcome": outcome, "code": _text(code),
|
| 32 |
"via": _text(claims.get("external_via") or "api"),
|
| 33 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
def record_ok(session, database):
|
|
|
|
| 26 |
label = next((row.get("label") for row in rows if row.get("id") == key_id), "")
|
| 27 |
except external_access.ExternalAccessError:
|
| 28 |
pass
|
| 29 |
+
detail = {
|
| 30 |
"key_id": key_id, "key_label": _text(label), "database": _text(database),
|
| 31 |
"outcome": outcome, "code": _text(code),
|
| 32 |
"via": _text(claims.get("external_via") or "api"),
|
| 33 |
+
}
|
| 34 |
+
if getattr(session.runtime, "preview_only", False):
|
| 35 |
+
session.runtime.deferred_audits.append(detail)
|
| 36 |
+
return None
|
| 37 |
+
return audit.record("external.query", session.tenant, session.uname, detail)
|
| 38 |
|
| 39 |
|
| 40 |
def record_ok(session, database):
|
api/external_openapi.py
CHANGED
|
@@ -37,6 +37,8 @@ def _record_name(database):
|
|
| 37 |
|
| 38 |
|
| 39 |
def _field_schema(field, source_kind):
|
|
|
|
|
|
|
| 40 |
kind = _JSON_TYPE.get(field.get("type"), "string")
|
| 41 |
types = [kind]
|
| 42 |
# Materialised table writes retain numeric cells as strings; reads preserve those bytes.
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def _field_schema(field, source_kind):
|
| 40 |
+
if field.get("type") == "multiselect":
|
| 41 |
+
return {"type": ["string", "array", "null"], "items": {"type": "string"}}
|
| 42 |
kind = _JSON_TYPE.get(field.get("type"), "string")
|
| 43 |
types = [kind]
|
| 44 |
# Materialised table writes retain numeric cells as strings; reads preserve those bytes.
|
api/loopy_file_tools.py
CHANGED
|
@@ -20,8 +20,8 @@ def current_door(session=None):
|
|
| 20 |
return door
|
| 21 |
|
| 22 |
|
| 23 |
-
def read_all(session, database, *, fields=None, filters=None, sorts=None):
|
| 24 |
-
"""
|
| 25 |
import agent_runtime
|
| 26 |
from deps import err
|
| 27 |
|
|
@@ -36,15 +36,17 @@ def read_all(session, database, *, fields=None, filters=None, sorts=None):
|
|
| 36 |
raise err(400, "assistant_unknown_field", "Every requested field must be readable in this database.")
|
| 37 |
selected = list(dict.fromkeys(fields))
|
| 38 |
if not selected:
|
| 39 |
-
raise ValueError("A
|
| 40 |
payload = {"database": database, "limit": 500}
|
|
|
|
|
|
|
| 41 |
if fields is not None:
|
| 42 |
payload["fields"] = selected
|
| 43 |
if filters is not None:
|
| 44 |
payload["filters"] = copy.deepcopy(filters)
|
| 45 |
if sorts is not None:
|
| 46 |
payload["sorts"] = copy.deepcopy(sorts)
|
| 47 |
-
records, seen = [], set()
|
| 48 |
while True:
|
| 49 |
result = agent_runtime._dispatch(session, "query_database", payload)
|
| 50 |
rows, page = result.get("records"), result.get("page")
|
|
@@ -55,6 +57,27 @@ def read_all(session, database, *, fields=None, filters=None, sorts=None):
|
|
| 55 |
page_keys = [field.get("key") for field in result.get("fields", []) if isinstance(field, dict)]
|
| 56 |
if page_keys != [key for key in by_key if key in selected]:
|
| 57 |
raise err(409, "query_cursor_stale", "The readable fields changed. Ask again to read the complete list.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
records.extend({"pid": copy.deepcopy(row.get("pid")),
|
| 59 |
**{key: copy.deepcopy(row.get(key)) for key in selected}} for row in rows)
|
| 60 |
if not page["has_more"]:
|
|
@@ -66,8 +89,11 @@ def read_all(session, database, *, fields=None, filters=None, sorts=None):
|
|
| 66 |
raise ValueError("The database did not advance its readable cursor.")
|
| 67 |
seen.add(cursor)
|
| 68 |
payload = {**payload, "cursor": cursor}
|
|
|
|
|
|
|
| 69 |
return {"database": database, "label": schema.get("label") or database,
|
| 70 |
-
"fields": [copy.deepcopy(by_key[key]) for key in selected], "records": records
|
|
|
|
| 71 |
|
| 72 |
|
| 73 |
def _secure_link(link):
|
|
@@ -108,6 +134,7 @@ def make_pdf(session, args):
|
|
| 108 |
data = loopy_pdf.render_table(title, result["fields"], result["records"])
|
| 109 |
saved = assistant_files.save(session.runtime, session.uname, title=title, data=data,
|
| 110 |
mime="application/pdf", door=door,
|
|
|
|
| 111 |
tool_call={"name": "make_pdf", "args": copy.deepcopy(args)})
|
| 112 |
link = (assistant_files.capability_url(session.runtime, saved["id"])
|
| 113 |
if door == "whatsapp" else saved["link"])
|
|
@@ -124,4 +151,210 @@ def _schema():
|
|
| 124 |
"required": ["database"], "additionalProperties": False}
|
| 125 |
|
| 126 |
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
return door
|
| 21 |
|
| 22 |
|
| 23 |
+
def read_all(session, database, *, fields=None, filters=None, sorts=None, max_rows=None):
|
| 24 |
+
"""Read every permitted cursor page, refusing exports above their declared file limit."""
|
| 25 |
import agent_runtime
|
| 26 |
from deps import err
|
| 27 |
|
|
|
|
| 36 |
raise err(400, "assistant_unknown_field", "Every requested field must be readable in this database.")
|
| 37 |
selected = list(dict.fromkeys(fields))
|
| 38 |
if not selected:
|
| 39 |
+
raise ValueError("A file needs at least one readable field.")
|
| 40 |
payload = {"database": database, "limit": 500}
|
| 41 |
+
if max_rows is not None:
|
| 42 |
+
payload["aggregates"] = [{"fn": "count"}]
|
| 43 |
if fields is not None:
|
| 44 |
payload["fields"] = selected
|
| 45 |
if filters is not None:
|
| 46 |
payload["filters"] = copy.deepcopy(filters)
|
| 47 |
if sorts is not None:
|
| 48 |
payload["sorts"] = copy.deepcopy(sorts)
|
| 49 |
+
records, seen, expected = [], set(), None
|
| 50 |
while True:
|
| 51 |
result = agent_runtime._dispatch(session, "query_database", payload)
|
| 52 |
rows, page = result.get("records"), result.get("page")
|
|
|
|
| 57 |
page_keys = [field.get("key") for field in result.get("fields", []) if isinstance(field, dict)]
|
| 58 |
if page_keys != [key for key in by_key if key in selected]:
|
| 59 |
raise err(409, "query_cursor_stale", "The readable fields changed. Ask again to read the complete list.")
|
| 60 |
+
if "offset" in page and (type(page["offset"]) is not int or page["offset"] != len(records)):
|
| 61 |
+
raise ValueError("The database skipped rows. Read the complete result again. No file was stored.")
|
| 62 |
+
counts = []
|
| 63 |
+
for container in (result, page):
|
| 64 |
+
for key in ("total", "total_count", "total_rows"):
|
| 65 |
+
if key in container:
|
| 66 |
+
counts.append(container[key])
|
| 67 |
+
aggregates = [item for item in result.get("aggregates", []) if isinstance(item, dict)
|
| 68 |
+
and item.get("fn") == "count" and item.get("field") is None]
|
| 69 |
+
if max_rows is not None and len(aggregates) != 1:
|
| 70 |
+
raise ValueError("The server did not supply its row count. Read the complete result again. No file was stored.")
|
| 71 |
+
counts.extend(item.get("value") for item in aggregates)
|
| 72 |
+
for count in counts:
|
| 73 |
+
if type(count) is not int or count < 0 or expected is not None and count != expected:
|
| 74 |
+
raise ValueError("The server count changed. Read the complete result again. No file was stored.")
|
| 75 |
+
expected = count
|
| 76 |
+
if max_rows is not None and max(len(records) + len(rows), expected or 0) > max_rows:
|
| 77 |
+
raise ValueError(f"Excel export exceeds the {max_rows:,}-data-row file limit. Filter the database and ask again. No rows were exported.")
|
| 78 |
+
if max_rows is not None:
|
| 79 |
+
from loopy_xlsx import check_size
|
| 80 |
+
check_size(max(len(records) + len(rows), expected or 0) + 1, len(selected))
|
| 81 |
records.extend({"pid": copy.deepcopy(row.get("pid")),
|
| 82 |
**{key: copy.deepcopy(row.get(key)) for key in selected}} for row in rows)
|
| 83 |
if not page["has_more"]:
|
|
|
|
| 89 |
raise ValueError("The database did not advance its readable cursor.")
|
| 90 |
seen.add(cursor)
|
| 91 |
payload = {**payload, "cursor": cursor}
|
| 92 |
+
if expected is not None and len(records) != expected:
|
| 93 |
+
raise ValueError("The server count differs from the rows read. Read the complete result again. No file was stored.")
|
| 94 |
return {"database": database, "label": schema.get("label") or database,
|
| 95 |
+
"fields": [copy.deepcopy(by_key[key]) for key in selected], "records": records,
|
| 96 |
+
"total": len(records)}
|
| 97 |
|
| 98 |
|
| 99 |
def _secure_link(link):
|
|
|
|
| 134 |
data = loopy_pdf.render_table(title, result["fields"], result["records"])
|
| 135 |
saved = assistant_files.save(session.runtime, session.uname, title=title, data=data,
|
| 136 |
mime="application/pdf", door=door,
|
| 137 |
+
sources=[args["database"]], amazon=args["database"].startswith("ut_amzn_"),
|
| 138 |
tool_call={"name": "make_pdf", "args": copy.deepcopy(args)})
|
| 139 |
link = (assistant_files.capability_url(session.runtime, saved["id"])
|
| 140 |
if door == "whatsapp" else saved["link"])
|
|
|
|
| 151 |
"required": ["database"], "additionalProperties": False}
|
| 152 |
|
| 153 |
|
| 154 |
+
def _provenance(session, sources):
|
| 155 |
+
from deps import assistant_source_status
|
| 156 |
+
|
| 157 |
+
sources = list(dict.fromkeys(sources))
|
| 158 |
+
status = assistant_source_status(session, sources) if sources else {}
|
| 159 |
+
for source in sources:
|
| 160 |
+
row = status.get(source)
|
| 161 |
+
if not isinstance(row, dict) or row.get("permitted") is not True or row.get("answerable") is not True:
|
| 162 |
+
if isinstance(row, dict) and row.get("permitted") is True and row.get("reason"):
|
| 163 |
+
raise ValueError(str(row["reason"]) + ". Restore source availability and ask again. No file was stored.")
|
| 164 |
+
raise ValueError("An export source is unknown or unreadable. Restore source access or remove that binding and ask again.")
|
| 165 |
+
return sources, any(source.startswith("ut_amzn_") for source in sources)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _sheet_sources(value):
|
| 169 |
+
"""Collect database provenance from permitted cells, bindings and source metadata."""
|
| 170 |
+
found = []
|
| 171 |
+
if isinstance(value, dict):
|
| 172 |
+
if "database" in value:
|
| 173 |
+
key = value["database"]
|
| 174 |
+
if not isinstance(key, str) or not key.strip():
|
| 175 |
+
raise ValueError("A Sheet source is unknown. Repair its binding and ask again.")
|
| 176 |
+
found.append(key)
|
| 177 |
+
for member in value.values():
|
| 178 |
+
found.extend(_sheet_sources(member))
|
| 179 |
+
elif isinstance(value, list):
|
| 180 |
+
for member in value:
|
| 181 |
+
found.extend(_sheet_sources(member))
|
| 182 |
+
return found
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def read_sheet_values(session, target, *, first_only=False):
|
| 186 |
+
"""Read projected Sheet values through the caller's existing permission wall."""
|
| 187 |
+
import agent_runtime
|
| 188 |
+
from routes_sheet import read_sheet
|
| 189 |
+
|
| 190 |
+
book = read_sheet(target, tabs="meta", session=session)["workbook"]
|
| 191 |
+
tabs = []
|
| 192 |
+
selected = book.get("sheets") or []
|
| 193 |
+
if first_only:
|
| 194 |
+
selected = selected[:1]
|
| 195 |
+
for tab in selected:
|
| 196 |
+
result = agent_runtime._dispatch(session, "sheet_read_cells", {"workbook_id": target, "tab": tab["id"]})
|
| 197 |
+
if result.get("id") != book.get("id") or result.get("rev") != book.get("rev"):
|
| 198 |
+
raise ValueError("The workbook changed during export. Read the workbook again. No file was stored.")
|
| 199 |
+
if "cellCount" in tab and (type(tab["cellCount"]) is not int
|
| 200 |
+
or tab["cellCount"] != len(result["tab"].get("cells") or {})):
|
| 201 |
+
raise ValueError("The Sheet cell count differs from the cells read. Read the complete workbook again. No file was stored.")
|
| 202 |
+
tabs.append(result["tab"])
|
| 203 |
+
return book, tabs
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def make_xlsx(session, args):
|
| 207 |
+
"""Export a complete database result or the caller's permitted Sheet workbook values."""
|
| 208 |
+
import assistant_files
|
| 209 |
+
import loopy_xlsx
|
| 210 |
+
from routes_query import _no_dashes
|
| 211 |
+
|
| 212 |
+
if session.tenant != assistant_files.assistant_log._tenant_of(session.runtime):
|
| 213 |
+
raise ValueError("The export session does not belong to this workspace. Sign in again.")
|
| 214 |
+
allowed = {"database", "fields", "filters", "sorts", "workbook_id", "title"}
|
| 215 |
+
if not isinstance(args, dict) or set(args) - allowed or ("database" in args) == ("workbook_id" in args):
|
| 216 |
+
raise ValueError("Choose one database or workbook_id to make an Excel file.")
|
| 217 |
+
target = args.get("database", args.get("workbook_id"))
|
| 218 |
+
if not isinstance(target, str) or not target.strip():
|
| 219 |
+
raise ValueError("An Excel file needs a database or workbook_id.")
|
| 220 |
+
if "title" in args and (not isinstance(args["title"], str) or not args["title"].strip()):
|
| 221 |
+
raise ValueError("An Excel file needs a title.")
|
| 222 |
+
door = current_door(session)
|
| 223 |
+
_secure_link(_links().app_link("#/assistant"))
|
| 224 |
+
if "database" in args:
|
| 225 |
+
sources, amazon = _provenance(session, [target])
|
| 226 |
+
result = read_all(session, target, fields=args.get("fields"), filters=args.get("filters"),
|
| 227 |
+
sorts=args.get("sorts"), max_rows=loopy_xlsx.MAX_ROWS - 1)
|
| 228 |
+
title = _no_dashes(args.get("title") or result["label"]).strip()[:200]
|
| 229 |
+
data = loopy_xlsx.render_table(title, result["fields"], result["records"], expected_count=result["total"])
|
| 230 |
+
count = result["total"]
|
| 231 |
+
else:
|
| 232 |
+
if set(args) & {"fields", "filters", "sorts"}:
|
| 233 |
+
raise ValueError("A Sheet export uses workbook_id and title. Database filters apply only to a database export.")
|
| 234 |
+
book, tabs = read_sheet_values(session, target)
|
| 235 |
+
sources, amazon = _provenance(session, _sheet_sources(tabs) + _sheet_sources(book.get("dataOrigins", [])))
|
| 236 |
+
title = _no_dashes(args.get("title") or book.get("name") or "Sheet workbook").strip()[:200]
|
| 237 |
+
data = loopy_xlsx.render_workbook(title, tabs)
|
| 238 |
+
count = None
|
| 239 |
+
# Recheck source access after a potentially long export, before storing bytes.
|
| 240 |
+
sources, amazon = _provenance(session, sources)
|
| 241 |
+
if amazon and door == "whatsapp":
|
| 242 |
+
raise ValueError("Amazon files cannot use a public download link. Export and download the file in the app instead. No file was stored.")
|
| 243 |
+
saved = assistant_files.save(session.runtime, session.uname, title=title, data=data,
|
| 244 |
+
mime=loopy_xlsx.MIME, door=door, sources=sources, amazon=amazon,
|
| 245 |
+
tool_call={"name": "make_xlsx", "args": copy.deepcopy(args)})
|
| 246 |
+
link = assistant_files.capability_url(session.runtime, saved["id"]) if door == "whatsapp" else saved["link"]
|
| 247 |
+
return {"ok": True, "fileId": saved["id"], "file_id": saved["file_id"],
|
| 248 |
+
"mime": saved["mime"], "bytes": saved["bytes"], "link": _secure_link(link),
|
| 249 |
+
"sources": sources, "amazon": amazon, "row_count": count}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _xlsx_schema():
|
| 253 |
+
schema = _schema()
|
| 254 |
+
schema["description"] = "Make an Excel file when asked, or for a table over 10 rows. Export every matching database row or a Sheet workbook's permitted values, with a file link."
|
| 255 |
+
schema["properties"]["workbook_id"] = {"type": "string", "minLength": 1}
|
| 256 |
+
schema.pop("required")
|
| 257 |
+
schema["oneOf"] = [{"required": ["database"]}, {"required": ["workbook_id"]}]
|
| 258 |
+
return schema
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def make_image(session, args):
|
| 262 |
+
"""Make an image of a permitted table, labelled series, or first Sheet screen."""
|
| 263 |
+
import assistant_files
|
| 264 |
+
import loopy_image
|
| 265 |
+
|
| 266 |
+
if session.tenant != assistant_files.assistant_log._tenant_of(session.runtime):
|
| 267 |
+
raise ValueError("The image session does not belong to this workspace. Sign in again.")
|
| 268 |
+
common = {"kind", "title"}
|
| 269 |
+
allowed = common | {"database", "fields", "filters", "sorts", "workbook_id",
|
| 270 |
+
"label_field", "value_field", "series", "series_label"}
|
| 271 |
+
if not isinstance(args, dict) or set(args) - allowed or args.get("kind") not in ("table", "bar", "line", "sheet"):
|
| 272 |
+
raise ValueError("Choose table, bar, line, or sheet as the image kind and use its source arguments.")
|
| 273 |
+
if "title" in args and (not isinstance(args["title"], str) or not args["title"].strip()):
|
| 274 |
+
raise ValueError("An image needs a nonempty title. Add a short title and ask again.")
|
| 275 |
+
kind = args["kind"]
|
| 276 |
+
if kind == "sheet":
|
| 277 |
+
permitted, required = common | {"workbook_id"}, {"workbook_id"}
|
| 278 |
+
elif kind == "table":
|
| 279 |
+
permitted, required = common | {"database", "fields", "filters", "sorts"}, {"database"}
|
| 280 |
+
elif "database" in args:
|
| 281 |
+
permitted = common | {"database", "filters", "sorts", "label_field", "value_field", "series_label"}
|
| 282 |
+
required = {"database", "label_field", "value_field"}
|
| 283 |
+
else:
|
| 284 |
+
permitted, required = common | {"series", "series_label"}, {"series", "series_label"}
|
| 285 |
+
if set(args) - permitted or not required <= set(args):
|
| 286 |
+
raise ValueError("The image source arguments do not match its kind. Choose one database, Sheet, or labelled series and ask again.")
|
| 287 |
+
for key in (required - {"series"}) | ({"series_label"} if "series_label" in args else set()):
|
| 288 |
+
if not isinstance(args[key], str) or not args[key].strip():
|
| 289 |
+
raise ValueError(f"Image {key} must be nonempty text. Correct the source arguments and ask again.")
|
| 290 |
+
door = current_door(session)
|
| 291 |
+
_secure_link(_links().app_link("#/assistant"))
|
| 292 |
+
sources, amazon = [], False
|
| 293 |
+
count, columns = None, None
|
| 294 |
+
if kind == "sheet":
|
| 295 |
+
book, tabs = read_sheet_values(session, args["workbook_id"], first_only=True)
|
| 296 |
+
if not tabs:
|
| 297 |
+
raise ValueError("The Sheet has no readable tabs. Add a tab and ask again.")
|
| 298 |
+
sources, amazon = _provenance(session, _sheet_sources(tabs) + _sheet_sources(book.get("dataOrigins", [])))
|
| 299 |
+
title = args.get("title") or book.get("name") or "Sheet"
|
| 300 |
+
data = loopy_image.render_sheet(title, tabs[0])
|
| 301 |
+
labels, values, count, columns = loopy_image.sheet_values(tabs[0])
|
| 302 |
+
shown_rows, shown_columns = len(values), len(labels)
|
| 303 |
+
elif "database" in args:
|
| 304 |
+
sources, amazon = _provenance(session, [args["database"]])
|
| 305 |
+
fields = args.get("fields") if kind == "table" else [args["label_field"], args["value_field"]]
|
| 306 |
+
result = read_all(session, args["database"], fields=fields,
|
| 307 |
+
filters=args.get("filters"), sorts=args.get("sorts"))
|
| 308 |
+
title = args.get("title") or result["label"]
|
| 309 |
+
count = result["total"]
|
| 310 |
+
if kind == "table":
|
| 311 |
+
data = loopy_image.render_table(title, result["fields"], result["records"], expected_count=count)
|
| 312 |
+
columns = shown_columns = len(result["fields"])
|
| 313 |
+
shown_rows = min(count, loopy_image.MAX_ROWS)
|
| 314 |
+
else:
|
| 315 |
+
series = [{"label": row.get(args["label_field"]), "value": row.get(args["value_field"])} for row in result["records"]]
|
| 316 |
+
value_label = next(field.get("label") or field["key"] for field in result["fields"] if field["key"] == args["value_field"])
|
| 317 |
+
data = loopy_image.render_chart(title, series, kind=kind, series_label=args.get("series_label") or value_label)
|
| 318 |
+
shown_rows, shown_columns = count, None
|
| 319 |
+
else:
|
| 320 |
+
title = args.get("title") or "Chart"
|
| 321 |
+
data = loopy_image.render_chart(title, args["series"], kind=kind, series_label=args["series_label"])
|
| 322 |
+
count = shown_rows = len(args["series"])
|
| 323 |
+
shown_columns = None
|
| 324 |
+
sources, amazon = _provenance(session, sources)
|
| 325 |
+
if amazon and door == "whatsapp":
|
| 326 |
+
raise ValueError("Amazon images cannot use a public link. Export the image in the app instead. No file was stored.")
|
| 327 |
+
saved = assistant_files.save(session.runtime, session.uname, title=title, data=data,
|
| 328 |
+
mime=loopy_image.MIME, door=door, sources=sources, amazon=amazon,
|
| 329 |
+
tool_call={"name": "make_image", "args": copy.deepcopy(args)})
|
| 330 |
+
return {"ok": True, "fileId": saved["id"], "file_id": saved["file_id"],
|
| 331 |
+
"mime": saved["mime"], "bytes": saved["bytes"], "link": _secure_link(saved["link"]),
|
| 332 |
+
"sources": sources, "amazon": amazon, "row_count": count,
|
| 333 |
+
"column_count": columns, "shown_rows": shown_rows, "shown_columns": shown_columns}
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _image_schema():
|
| 337 |
+
schema = _schema()
|
| 338 |
+
schema["description"] = "Make a PNG of a readable table, a bar or line chart, or a Sheet's first screen. Charts are images. A new Sheet uses its link plus this image. A table over 10 rows also needs make_xlsx. Wide images preserve cell widths."
|
| 339 |
+
schema["properties"].update({
|
| 340 |
+
"kind": {"type": "string", "enum": ["table", "bar", "line", "sheet"]},
|
| 341 |
+
"workbook_id": {"type": "string", "minLength": 1},
|
| 342 |
+
"label_field": {"type": "string", "minLength": 1},
|
| 343 |
+
"value_field": {"type": "string", "minLength": 1},
|
| 344 |
+
"series_label": {"type": "string", "minLength": 1},
|
| 345 |
+
"series": {"type": "array", "minItems": 1, "maxItems": 30,
|
| 346 |
+
"items": {"type": "object", "properties": {
|
| 347 |
+
"label": {"type": "string", "minLength": 1}, "value": {"type": "number"}},
|
| 348 |
+
"required": ["label", "value"], "additionalProperties": False}}})
|
| 349 |
+
schema["required"] = ["kind"]
|
| 350 |
+
schema["oneOf"] = [
|
| 351 |
+
{"properties": {"kind": {"const": "table"}}, "required": ["database"]},
|
| 352 |
+
{"properties": {"kind": {"const": "sheet"}}, "required": ["workbook_id"]},
|
| 353 |
+
{"properties": {"kind": {"enum": ["bar", "line"]}}, "required": ["database", "label_field", "value_field"]},
|
| 354 |
+
{"properties": {"kind": {"enum": ["bar", "line"]}}, "required": ["series", "series_label"]}]
|
| 355 |
+
return schema
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
TOOLS = [{"name": "make_pdf", "schema": _schema(), "fn": make_pdf, "effect": "read"},
|
| 359 |
+
{"name": "make_xlsx", "schema": _xlsx_schema(), "fn": make_xlsx, "effect": "read"},
|
| 360 |
+
{"name": "make_image", "schema": _image_schema(), "fn": make_image, "effect": "read"}]
|
api/loopy_image.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Draw authorized values as PNG files with Inter and no browser."""
|
| 2 |
+
from collections.abc import Mapping
|
| 3 |
+
from decimal import Decimal
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import re
|
| 9 |
+
import unicodedata
|
| 10 |
+
|
| 11 |
+
MIME = "image/png"
|
| 12 |
+
MAX_ROWS = 30
|
| 13 |
+
MAX_COLUMNS = 10
|
| 14 |
+
MAX_BYTES = 20 * 1024 * 1024
|
| 15 |
+
FONT_PATH = (Path(os.environ.get("RI_DIR") or Path(__file__).resolve().parents[2] / "platform")
|
| 16 |
+
/ "static/fonts/Inter-var.woff2")
|
| 17 |
+
PURPLE = "#5433CC"
|
| 18 |
+
INK = "#202124"
|
| 19 |
+
MUTED = "#656970"
|
| 20 |
+
RULE = "#E5E7EB"
|
| 21 |
+
_ADDRESS = re.compile(r"([A-Z]{1,3})([1-9][0-9]*)\Z")
|
| 22 |
+
_NUMBER = re.compile(r"[($+\-\u00a3\u20ac]*\d[\d,]*(?:\.\d+)?[%)]*\Z")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _text(value):
|
| 26 |
+
if value is None:
|
| 27 |
+
return ""
|
| 28 |
+
if isinstance(value, bool):
|
| 29 |
+
return "Yes" if value else "No"
|
| 30 |
+
if isinstance(value, (float, Decimal)) and not math.isfinite(value):
|
| 31 |
+
raise ValueError("An image number is not finite. Correct the value and ask again.")
|
| 32 |
+
if not isinstance(value, (str, int, float, Decimal)):
|
| 33 |
+
raise ValueError("An image cell has an unsupported value. Use text or finite numbers and ask again.")
|
| 34 |
+
text = str(value).replace("\u2014", "-").replace("\u2013", "-")
|
| 35 |
+
if len(text) > 32_767:
|
| 36 |
+
raise ValueError("Image text exceeds the cell limit. Shorten the label and ask again.")
|
| 37 |
+
for char in text:
|
| 38 |
+
code = ord(char)
|
| 39 |
+
if char in "\n\r\t":
|
| 40 |
+
continue
|
| 41 |
+
if (unicodedata.category(char).startswith("C") or code >= 0x2500
|
| 42 |
+
or 0x250 <= code < 0x2000):
|
| 43 |
+
raise ValueError("Image text needs Latin characters without emoji. Replace unsupported characters and ask again.")
|
| 44 |
+
return " ".join(text.split())
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _label(value):
|
| 48 |
+
text = _text(value)
|
| 49 |
+
return text[:1] + text[1:].lower() if text.isupper() else text
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _numeric(value):
|
| 53 |
+
return (isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
|
| 54 |
+
or isinstance(value, str) and bool(_NUMBER.fullmatch(value.strip())))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _fonts():
|
| 58 |
+
from PIL import ImageFont
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
return ImageFont.truetype(str(FONT_PATH), 17), ImageFont.truetype(str(FONT_PATH), 23)
|
| 62 |
+
except OSError as exc:
|
| 63 |
+
raise ValueError("The Inter image font is missing or unreadable. Include the font and its OFL licence in deployment assets.") from exc
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _fit(draw, text, font, width):
|
| 67 |
+
if draw.textlength(text, font=font) <= width:
|
| 68 |
+
return text
|
| 69 |
+
low, high = 0, len(text)
|
| 70 |
+
while low < high:
|
| 71 |
+
middle = (low + high + 1) // 2
|
| 72 |
+
if draw.textlength(text[:middle] + "...", font=font) <= width:
|
| 73 |
+
low = middle
|
| 74 |
+
else:
|
| 75 |
+
high = middle - 1
|
| 76 |
+
return text[:low] + "..."
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _png(image, description):
|
| 80 |
+
from PIL.PngImagePlugin import PngInfo
|
| 81 |
+
|
| 82 |
+
info = PngInfo()
|
| 83 |
+
info.add_text("Description", description)
|
| 84 |
+
output = BytesIO()
|
| 85 |
+
image.save(output, format="PNG", pnginfo=info)
|
| 86 |
+
data = output.getvalue()
|
| 87 |
+
if len(data) > MAX_BYTES:
|
| 88 |
+
raise ValueError("The image exceeds the 20 MiB limit. Select fewer fields and ask again.")
|
| 89 |
+
return data
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def table_values(columns, rows, *, expected_count=None):
|
| 93 |
+
"""Prepare at most 30 rows while preserving the complete source count."""
|
| 94 |
+
if not isinstance(rows, (list, tuple)) or not isinstance(columns, (list, tuple)) or not 1 <= len(columns) <= 30:
|
| 95 |
+
raise ValueError("An image table needs 1 to 30 columns and a row list. Select readable fields and ask again.")
|
| 96 |
+
if expected_count is not None and (type(expected_count) is not int or expected_count != len(rows)):
|
| 97 |
+
raise ValueError("The image source count differs from the rows read. Read the complete result and ask again.")
|
| 98 |
+
fields = [dict(column) if isinstance(column, Mapping) else {"key": column} for column in columns]
|
| 99 |
+
if any(not isinstance(field.get("key"), str) or not field["key"] for field in fields):
|
| 100 |
+
raise ValueError("An image column needs a field key. Choose readable fields and ask again.")
|
| 101 |
+
labels = [_label(field.get("label") or field["key"]) for field in fields]
|
| 102 |
+
prepared = []
|
| 103 |
+
for row in rows[:MAX_ROWS]:
|
| 104 |
+
if isinstance(row, Mapping):
|
| 105 |
+
values = [row.get(field["key"]) for field in fields]
|
| 106 |
+
elif isinstance(row, (list, tuple)) and len(row) == len(fields):
|
| 107 |
+
values = row
|
| 108 |
+
else:
|
| 109 |
+
raise ValueError("An image row does not match its columns. Correct the source and ask again.")
|
| 110 |
+
prepared.append([(_text(value), _numeric(value)) for value in values])
|
| 111 |
+
return labels, prepared, len(rows)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _draw_table(title, labels, rows, footer, *, row_numbers=False):
|
| 115 |
+
from PIL import Image, ImageDraw
|
| 116 |
+
|
| 117 |
+
font, heading = _fonts()
|
| 118 |
+
measure = ImageDraw.Draw(Image.new("RGB", (1, 1)))
|
| 119 |
+
widths = []
|
| 120 |
+
for index, label in enumerate(labels):
|
| 121 |
+
longest = max([measure.textlength(label, font=font),
|
| 122 |
+
*(measure.textlength(row[index][0], font=font) for row in rows)])
|
| 123 |
+
widths.append(max(100, min(230, math.ceil(longest) + 24)))
|
| 124 |
+
gutter = 42 if row_numbers else 0
|
| 125 |
+
widths[-1] += max(0, 390 - (sum(widths) + 32 + gutter))
|
| 126 |
+
width = sum(widths) + 32 + gutter
|
| 127 |
+
height = 132 + 38 * len(rows)
|
| 128 |
+
image = Image.new("RGB", (width, height), "white")
|
| 129 |
+
draw = ImageDraw.Draw(image)
|
| 130 |
+
title = _label(title)
|
| 131 |
+
if not title:
|
| 132 |
+
raise ValueError("An image needs a title. Add a short title and ask again.")
|
| 133 |
+
draw.text((16, 18), _fit(draw, title, heading, width - 32), font=heading, fill=INK)
|
| 134 |
+
x = 16 + gutter
|
| 135 |
+
for label, cell_width in zip(labels, widths):
|
| 136 |
+
draw.text((x + 12, 70), _fit(draw, label, font, cell_width - 24), font=font, fill=MUTED, anchor="lm")
|
| 137 |
+
x += cell_width
|
| 138 |
+
draw.line((16, 89, width - 16, 89), fill=RULE)
|
| 139 |
+
for index, row in enumerate(rows):
|
| 140 |
+
y, x = 108 + 38 * index, 16 + gutter
|
| 141 |
+
if row_numbers:
|
| 142 |
+
draw.text((16 + gutter - 10, y), str(index + 1), font=font, fill=MUTED, anchor="rm")
|
| 143 |
+
for (text, numeric), cell_width in zip(row, widths):
|
| 144 |
+
fitted = _fit(draw, text, font, cell_width - 24)
|
| 145 |
+
draw.text((x + cell_width - 12 if numeric else x + 12, y), fitted,
|
| 146 |
+
font=font, fill=INK, anchor="rm" if numeric else "lm", features=["tnum"])
|
| 147 |
+
x += cell_width
|
| 148 |
+
draw.line((16, y + 19, width - 16, y + 19), fill=RULE)
|
| 149 |
+
draw.text((16, height - 24), _fit(draw, footer, font, width - 32), font=font, fill=MUTED, anchor="lm")
|
| 150 |
+
return _png(image, footer)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def render_table(title, columns, rows, *, expected_count=None):
|
| 154 |
+
"""Draw a full-width table with right-aligned numbers and an accurate cut line."""
|
| 155 |
+
labels, values, total = table_values(columns, rows, expected_count=expected_count)
|
| 156 |
+
footer = f"Showing {len(values)} of {total} rows" if total > MAX_ROWS else f"{total} rows"
|
| 157 |
+
return _draw_table(title, labels, values, footer)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def sheet_values(tab):
|
| 161 |
+
"""Read the first screen of an already authorized, projected Sheet tab."""
|
| 162 |
+
if not isinstance(tab, Mapping) or not isinstance(tab.get("cells", {}), Mapping):
|
| 163 |
+
raise ValueError("The Sheet has no readable cells. Read its permitted values and ask again.")
|
| 164 |
+
values, extent_row, extent_col = {}, 0, 0
|
| 165 |
+
for address, cell in tab.get("cells", {}).items():
|
| 166 |
+
match = _ADDRESS.fullmatch(address) if isinstance(address, str) else None
|
| 167 |
+
if not match or not isinstance(cell, Mapping):
|
| 168 |
+
raise ValueError("A Sheet cell is invalid. Repair its address and ask again.")
|
| 169 |
+
col = 0
|
| 170 |
+
for char in match[1]:
|
| 171 |
+
col = col * 26 + ord(char) - 64
|
| 172 |
+
row = int(match[2])
|
| 173 |
+
extent_row, extent_col = max(extent_row, row), max(extent_col, col)
|
| 174 |
+
if row > MAX_ROWS or col > MAX_COLUMNS:
|
| 175 |
+
continue
|
| 176 |
+
binding = cell.get("binding") or {}
|
| 177 |
+
if isinstance(binding, Mapping) and (binding.get("mode") == "view" or binding.get("kind") == "view"):
|
| 178 |
+
raise ValueError("A placed View has no safe image cell value. Export its readable database instead.")
|
| 179 |
+
if cell.get("refusal") or cell.get("state") in ("refused", "stale"):
|
| 180 |
+
raise ValueError("A Sheet value needs refresh or permission. Refresh its readable sources and ask again.")
|
| 181 |
+
if cell.get("kind") in ("bound", "formula") and "value" not in cell:
|
| 182 |
+
raise ValueError("A Sheet calculation has no authorized value. Refresh the Sheet and ask again.")
|
| 183 |
+
value = None if cell.get("kind") == "empty" else cell.get("value", cell.get("text"))
|
| 184 |
+
_text(value)
|
| 185 |
+
display = cell.get("display", value) if value is not None else None
|
| 186 |
+
values[row, col] = (_text(display), _numeric(value))
|
| 187 |
+
rows, cols = min(MAX_ROWS, max(1, extent_row)), min(MAX_COLUMNS, max(1, extent_col))
|
| 188 |
+
return ([chr(65 + index) for index in range(cols)],
|
| 189 |
+
[[values.get((row, col), ("", False)) for col in range(1, cols + 1)] for row in range(1, rows + 1)],
|
| 190 |
+
extent_row, extent_col)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def render_sheet(title, tab):
|
| 194 |
+
"""Draw the first 30 rows and 10 columns without shrinking readable cells."""
|
| 195 |
+
labels, values, rows, cols = sheet_values(tab)
|
| 196 |
+
footer = (f"Showing {len(values)} of {rows} rows, {len(labels)} of {cols} columns"
|
| 197 |
+
if rows else "No populated cells. Limit: 30 rows, 10 columns")
|
| 198 |
+
return _draw_table(title, labels, values, footer, row_numbers=True)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def chart_values(series):
|
| 202 |
+
if not isinstance(series, (list, tuple)) or not 1 <= len(series) <= MAX_ROWS:
|
| 203 |
+
raise ValueError("A chart needs 1 to 30 labelled points. Filter or aggregate the series and ask again.")
|
| 204 |
+
points = []
|
| 205 |
+
for point in series:
|
| 206 |
+
if not isinstance(point, Mapping) or set(point) != {"label", "value"}:
|
| 207 |
+
raise ValueError("Each chart point needs label and value. Correct the series and ask again.")
|
| 208 |
+
label, value = point["label"], point["value"]
|
| 209 |
+
if not isinstance(label, str) or not _text(label) or isinstance(value, bool) or not isinstance(value, (int, float, Decimal)):
|
| 210 |
+
raise ValueError("A chart point needs a text label and a number. Correct the series and ask again.")
|
| 211 |
+
try:
|
| 212 |
+
value = float(value)
|
| 213 |
+
except (OverflowError, ValueError) as exc:
|
| 214 |
+
raise ValueError("A chart number is outside the supported range. Use finite numbers and ask again.") from exc
|
| 215 |
+
if not math.isfinite(value) or abs(value) > 1e100:
|
| 216 |
+
raise ValueError("A chart number is outside the supported range. Use finite numbers below 1e100 and ask again.")
|
| 217 |
+
points.append((_text(label), value))
|
| 218 |
+
return points
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def render_chart(title, series, *, kind="bar", series_label="Series"):
|
| 222 |
+
"""Draw a labelled purple series on one axis, including negative and zero values."""
|
| 223 |
+
points = chart_values(series)
|
| 224 |
+
if kind not in ("bar", "line") or not isinstance(series_label, str) or not _text(series_label):
|
| 225 |
+
raise ValueError("A chart needs bar or line and a series label. Correct the chart arguments and ask again.")
|
| 226 |
+
from PIL import Image, ImageDraw
|
| 227 |
+
|
| 228 |
+
font, heading = _fonts()
|
| 229 |
+
width, height = max(390, 96 + 72 * len(points)), 410
|
| 230 |
+
image = Image.new("RGB", (width, height), "white")
|
| 231 |
+
draw = ImageDraw.Draw(image)
|
| 232 |
+
title = _label(title)
|
| 233 |
+
if not title:
|
| 234 |
+
raise ValueError("An image needs a title. Add a short title and ask again.")
|
| 235 |
+
draw.text((16, 18), _fit(draw, title, heading, width - 32), font=heading, fill=INK)
|
| 236 |
+
draw.line((16, 67, 34, 67), fill=PURPLE, width=4)
|
| 237 |
+
draw.text((42, 67), _fit(draw, _label(series_label), font, width - 58), font=font, fill=INK, anchor="lm")
|
| 238 |
+
low, high = min(0, *(value for _, value in points)), max(0, *(value for _, value in points))
|
| 239 |
+
if low == high:
|
| 240 |
+
low, high = -1, 1
|
| 241 |
+
else:
|
| 242 |
+
span = high - low
|
| 243 |
+
low, high = low - span * .12, high + span * .12
|
| 244 |
+
ticks = [low + (high - low) * index / 4 for index in range(5)]
|
| 245 |
+
tick_labels = [format(value, ".3g") for value in ticks]
|
| 246 |
+
left = max(66, math.ceil(max(draw.textlength(label, font=font) for label in tick_labels)) + 26)
|
| 247 |
+
top, bottom, right = 102, 310, width - 20
|
| 248 |
+
def y(value):
|
| 249 |
+
return bottom - (value - low) / (high - low) * (bottom - top)
|
| 250 |
+
for tick, label in zip(ticks, tick_labels):
|
| 251 |
+
draw.line((left, y(tick), right, y(tick)), fill=RULE)
|
| 252 |
+
draw.text((left - 10, y(tick)), label, font=font, fill=MUTED, anchor="rm", features=["tnum"])
|
| 253 |
+
zero = y(0)
|
| 254 |
+
draw.line((left, top, left, bottom), fill=MUTED)
|
| 255 |
+
draw.line((left, zero, right, zero), fill=MUTED)
|
| 256 |
+
step = (right - left) / len(points)
|
| 257 |
+
positions = []
|
| 258 |
+
for index, (label, value) in enumerate(points):
|
| 259 |
+
x, py = left + (index + .5) * step, y(value)
|
| 260 |
+
positions.append((x, py))
|
| 261 |
+
if kind == "bar":
|
| 262 |
+
draw.rectangle((x - step * .28, min(zero, py), x + step * .28, max(zero, py)), fill=PURPLE)
|
| 263 |
+
draw.text((x, bottom + 24), _fit(draw, label, font, step - 8), font=font, fill=INK, anchor="mm")
|
| 264 |
+
draw.text((x, py - 13 if value >= 0 else py + 15), format(value, ".4g"), font=font, fill=INK, anchor="mm", features=["tnum"])
|
| 265 |
+
if kind == "line":
|
| 266 |
+
if len(positions) > 1:
|
| 267 |
+
draw.line(positions, fill=PURPLE, width=3)
|
| 268 |
+
for x, py in positions:
|
| 269 |
+
draw.ellipse((x - 4, py - 4, x + 4, py + 4), fill=PURPLE)
|
| 270 |
+
footer = f"{len(points)} labelled points"
|
| 271 |
+
draw.text((16, height - 24), footer, font=font, fill=MUTED, anchor="lm")
|
| 272 |
+
return _png(image, footer)
|
api/loopy_links.py
CHANGED
|
@@ -44,6 +44,60 @@ def artifact_link(item_id: str) -> str | None:
|
|
| 44 |
return app_link("#/artifacts?item=" + quote(str(item_id), safe=""))
|
| 45 |
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
def absolutize_text(text: str) -> str:
|
| 48 |
"""Expand standalone app fragments while preserving existing absolute URLs."""
|
| 49 |
base = public_base()
|
|
|
|
| 44 |
return app_link("#/artifacts?item=" + quote(str(item_id), safe=""))
|
| 45 |
|
| 46 |
|
| 47 |
+
_SHARE_TOKEN = re.compile(r"[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def shared_artifact_link(token) -> str | None:
|
| 51 |
+
"""Build the signed read-only page link `{base}/a/<token>` (C7, R85)."""
|
| 52 |
+
base = public_base()
|
| 53 |
+
if base is None or not isinstance(token, str) or _SHARE_TOKEN.fullmatch(token) is None:
|
| 54 |
+
return None
|
| 55 |
+
return base + "/a/" + token
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
NO_LINK_NOTE = "Links are not set up on this server yet, so this has no link."
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _value(value) -> str | None:
|
| 62 |
+
"""Encode one route value as a query value, or None when it is empty."""
|
| 63 |
+
text = "" if value is None or isinstance(value, bool) else str(value).strip()
|
| 64 |
+
return quote(text, safe="") if text else None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _route(path: str, *pairs, optional=()) -> str | None:
|
| 68 |
+
"""Build an absolute link when every required value is present."""
|
| 69 |
+
values = [(name, _value(value)) for name, value in pairs]
|
| 70 |
+
if any(encoded is None for _, encoded in values):
|
| 71 |
+
return None
|
| 72 |
+
values += [(name, encoded) for name, encoded in ((n, _value(v)) for n, v in optional) if encoded]
|
| 73 |
+
return app_link(path + "?" + "&".join(f"{name}={encoded}" for name, encoded in values))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def sheet_link(workbook_id, tab=None) -> str | None:
|
| 77 |
+
"""Link to a Sheet workbook, matching the client sheetAddressHash."""
|
| 78 |
+
return _route("#/sheet", ("wb", workbook_id), optional=(("tab", tab),))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def view_link(database, view_id) -> str | None:
|
| 82 |
+
"""Link to a saved View, matching the client dataAddressHash."""
|
| 83 |
+
return _route("#/data", ("database", database), ("view", view_id))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def application_link(app_id, database) -> str | None:
|
| 87 |
+
"""Link to an App, matching the client appPathHash (the database is required)."""
|
| 88 |
+
return _route("#/app", ("database", database), ("application", app_id))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def records_link(database, view_id=None) -> str | None:
|
| 92 |
+
"""Link to a database record list, optionally opened on one View."""
|
| 93 |
+
return _route("#/data", ("database", database), optional=(("view", view_id),))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def query_link(view_id) -> str | None:
|
| 97 |
+
"""Link to a saved Query answer."""
|
| 98 |
+
return _route("#/query", ("view", view_id))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
def absolutize_text(text: str) -> str:
|
| 102 |
"""Expand standalone app fragments while preserving existing absolute URLs."""
|
| 103 |
base = public_base()
|
api/loopy_skill_tools.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
|
| 4 |
def skill_list(session, args):
|
|
@@ -18,7 +18,110 @@ def skill_read(session, args):
|
|
| 18 |
return read_skill(session, args["key"].strip())
|
| 19 |
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
TOOLS = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
{"name": "skill_list", "effect": "read", "fn": skill_list,
|
| 23 |
"schema": {"type": "object", "description": "List the connector and app skills you can read in this workspace.",
|
| 24 |
"properties": {}, "additionalProperties": False}},
|
|
@@ -26,4 +129,9 @@ TOOLS = [
|
|
| 26 |
"schema": {"type": "object", "description": "Read the steps for a skill from your current skill list.",
|
| 27 |
"properties": {"key": {"type": "string", "minLength": 1}},
|
| 28 |
"required": ["key"], "additionalProperties": False}},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
]
|
|
|
|
| 1 |
+
"""Assistant tools for the caller's code-held procedures and saved tools."""
|
| 2 |
|
| 3 |
|
| 4 |
def skill_list(session, args):
|
|
|
|
| 18 |
return read_skill(session, args["key"].strip())
|
| 19 |
|
| 20 |
|
| 21 |
+
def database_notes(session, args):
|
| 22 |
+
from loopy_skills import database_notes as notes
|
| 23 |
+
|
| 24 |
+
if (not isinstance(args, dict) or set(args) != {"database"}
|
| 25 |
+
or not isinstance(args["database"], str) or not args["database"].strip()):
|
| 26 |
+
raise ValueError("Choose a database key from the database list.")
|
| 27 |
+
return notes(session, args["database"].strip())
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _tool_name(args, *keys):
|
| 31 |
+
if not isinstance(args, dict) or set(args) - set(keys) or not isinstance(args.get("name"), str):
|
| 32 |
+
raise ValueError("Choose a saved tool name from tool_list.")
|
| 33 |
+
return args["name"].strip()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _refusal(fn):
|
| 37 |
+
"""Return a store refusal as a tool result, so the model can tell the user why."""
|
| 38 |
+
from loopy_tool_store import ToolRefusal
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
return fn()
|
| 42 |
+
except ToolRefusal as exc:
|
| 43 |
+
return {"ok": False, "error": str(exc)}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def tool_save(session, args):
|
| 47 |
+
import routes_query
|
| 48 |
+
from loopy_tool_store import save
|
| 49 |
+
|
| 50 |
+
if not isinstance(args, dict):
|
| 51 |
+
raise ValueError("Give the tool a name, a title and its steps.")
|
| 52 |
+
door = routes_query._AGENT_DOOR.get()
|
| 53 |
+
return _refusal(lambda: {"ok": True, "saved": save(session, args, door=door),
|
| 54 |
+
"message": "Saved for you. Ask to share it if the workspace should use it."})
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def tool_list(session, args):
|
| 58 |
+
from loopy_tool_store import pending_shares, visible
|
| 59 |
+
|
| 60 |
+
if not isinstance(args, dict) or args:
|
| 61 |
+
raise ValueError("List saved tools without arguments.")
|
| 62 |
+
mine, shared = visible(session)
|
| 63 |
+
return {"personal": mine, "workspace": shared, "shareRequests": pending_shares(session)}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def tool_run(session, args):
|
| 67 |
+
import routes_query
|
| 68 |
+
from loopy_tool_store import run
|
| 69 |
+
|
| 70 |
+
name = _tool_name(args, "name")
|
| 71 |
+
turn = routes_query._AGENT_TURN.get() or {}
|
| 72 |
+
return _refusal(lambda: run(session, name, door=routes_query._AGENT_DOOR.get(), handle=turn.get("handle")))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def tool_share(session, args):
|
| 76 |
+
from loopy_tool_store import request_share
|
| 77 |
+
|
| 78 |
+
name = _tool_name(args, "name")
|
| 79 |
+
return _refusal(lambda: request_share(session, name))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def tool_share_decide(session, args):
|
| 83 |
+
from loopy_tool_store import decide_share
|
| 84 |
+
|
| 85 |
+
if (not isinstance(args, dict) or set(args) != {"request", "decision"}
|
| 86 |
+
or not isinstance(args["request"], str) or args["decision"] not in ("yes", "no")):
|
| 87 |
+
raise ValueError("Give the share request id and the Administrator's yes or no.")
|
| 88 |
+
return _refusal(lambda: decide_share(session, args["request"].strip(), args["decision"] == "yes"))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
_STEP = {"type": "object", "properties": {
|
| 92 |
+
"tool": {"type": "string", "minLength": 1,
|
| 93 |
+
"description": "An existing read tool, for example query_database for a query recipe."},
|
| 94 |
+
"args": {"type": "object", "description": "The arguments for that tool, as you would call it."}},
|
| 95 |
+
"required": ["tool", "args"], "additionalProperties": False}
|
| 96 |
+
_NAME = {"type": "string", "pattern": "^[a-z0-9_]{1,40}$"}
|
| 97 |
+
|
| 98 |
TOOLS = [
|
| 99 |
+
{"name": "tool_save", "effect": "write", "fn": tool_save,
|
| 100 |
+
"schema": {"type": "object",
|
| 101 |
+
"description": ("Save a named tool for the user: the read steps and query recipes of an answer. "
|
| 102 |
+
"Use it when the user asks to save an answer as a tool. It runs no code."),
|
| 103 |
+
"properties": {"name": _NAME, "title": {"type": "string", "maxLength": 80},
|
| 104 |
+
"description": {"type": "string", "maxLength": 300},
|
| 105 |
+
"steps": {"type": "array", "minItems": 1, "maxItems": 12, "items": _STEP}},
|
| 106 |
+
"required": ["name", "title", "steps"], "additionalProperties": False}},
|
| 107 |
+
{"name": "tool_list", "effect": "read", "fn": tool_list,
|
| 108 |
+
"schema": {"type": "object",
|
| 109 |
+
"description": "List your saved tools, the workspace tools you can use, and share requests for an Administrator.",
|
| 110 |
+
"properties": {}, "additionalProperties": False}},
|
| 111 |
+
{"name": "tool_run", "effect": "read", "fn": tool_run,
|
| 112 |
+
"schema": {"type": "object",
|
| 113 |
+
"description": "Run a saved tool by name and return each step's result. Use it when a question matches a saved tool.",
|
| 114 |
+
"properties": {"name": _NAME}, "required": ["name"], "additionalProperties": False}},
|
| 115 |
+
{"name": "tool_share", "effect": "write", "fn": tool_share,
|
| 116 |
+
"schema": {"type": "object",
|
| 117 |
+
"description": "Ask to share one of your saved tools with the workspace. An Administrator must say yes.",
|
| 118 |
+
"properties": {"name": _NAME}, "required": ["name"], "additionalProperties": False}},
|
| 119 |
+
{"name": "tool_share_decide", "effect": "write", "fn": tool_share_decide,
|
| 120 |
+
"schema": {"type": "object",
|
| 121 |
+
"description": "Record an Administrator's yes or no to a share request. Ask the user first.",
|
| 122 |
+
"properties": {"request": {"type": "string", "minLength": 1},
|
| 123 |
+
"decision": {"type": "string", "enum": ["yes", "no"]}},
|
| 124 |
+
"required": ["request", "decision"], "additionalProperties": False}},
|
| 125 |
{"name": "skill_list", "effect": "read", "fn": skill_list,
|
| 126 |
"schema": {"type": "object", "description": "List the connector and app skills you can read in this workspace.",
|
| 127 |
"properties": {}, "additionalProperties": False}},
|
|
|
|
| 129 |
"schema": {"type": "object", "description": "Read the steps for a skill from your current skill list.",
|
| 130 |
"properties": {"key": {"type": "string", "minLength": 1}},
|
| 131 |
"required": ["key"], "additionalProperties": False}},
|
| 132 |
+
{"name": "database_notes", "effect": "read", "fn": database_notes,
|
| 133 |
+
"schema": {"type": "object",
|
| 134 |
+
"description": "Read what one row is, the key fields, joins, scope rules and known traps for a database before you query it.",
|
| 135 |
+
"properties": {"database": {"type": "string", "minLength": 1}},
|
| 136 |
+
"required": ["database"], "additionalProperties": False}},
|
| 137 |
]
|
api/loopy_skills.py
CHANGED
|
@@ -97,6 +97,98 @@ def list_skills(session):
|
|
| 97 |
for record in SKILLS if record["applies_when"](session)]
|
| 98 |
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
def read_skill(session, key):
|
| 101 |
"""Recheck access and return an exact procedure with only installed tool names."""
|
| 102 |
import agent_tools
|
|
@@ -113,10 +205,24 @@ def read_skill(session, key):
|
|
| 113 |
steps = list(record["steps"])
|
| 114 |
if not tools:
|
| 115 |
steps = ["This skill's tools are not available in this build. Try again after they are installed."]
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
|
| 119 |
def prompt_index(session):
|
| 120 |
"""Return the permissioned one-line skill index for the system prompt."""
|
| 121 |
labels = [f"{record['key']} ({record['title']})" for record in list_skills(session)]
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
for record in SKILLS if record["applies_when"](session)]
|
| 98 |
|
| 99 |
|
| 100 |
+
#: Skill key to its knowledge pack file in platform/model/knowledge. A new source adds one row.
|
| 101 |
+
KNOWLEDGE_PACKS = {"odoo": "odoo.yml", "amazon": "amazon.yml"}
|
| 102 |
+
_PACK_CACHE = {}
|
| 103 |
+
#: A connection-namespaced key is `<base><SEP><connection id>`, as odoo_relational.CONNECTION_SEP.
|
| 104 |
+
_CONNECTION_SEP = "__"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def knowledge_dir():
|
| 108 |
+
"""Return platform/model/knowledge, found beside the `core` package in every layout."""
|
| 109 |
+
from pathlib import Path
|
| 110 |
+
|
| 111 |
+
import core
|
| 112 |
+
|
| 113 |
+
# `core` is a namespace package: it has a __path__ and no __file__.
|
| 114 |
+
dirs = [Path(p).resolve().parent / "model" / "knowledge" for p in core.__path__]
|
| 115 |
+
return next((d for d in dirs if d.is_dir()), dirs[0])
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def load_pack(skill_key):
|
| 119 |
+
"""Return one source's parsed knowledge pack, read once per process, or None if unmapped."""
|
| 120 |
+
name = KNOWLEDGE_PACKS.get(skill_key)
|
| 121 |
+
if name is None:
|
| 122 |
+
return None
|
| 123 |
+
if skill_key not in _PACK_CACHE:
|
| 124 |
+
import yaml
|
| 125 |
+
|
| 126 |
+
with open(knowledge_dir() / name, encoding="utf-8") as handle:
|
| 127 |
+
_PACK_CACHE[skill_key] = yaml.safe_load(handle)
|
| 128 |
+
return _PACK_CACHE[skill_key]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def pack_base_key(pack, key):
|
| 132 |
+
"""Return the pack's entry key for a database key, its generated prefix, or None."""
|
| 133 |
+
databases = pack.get("databases") or {}
|
| 134 |
+
prefix = (pack.get("generated_tables") or {}).get("prefix")
|
| 135 |
+
base, sep, cid = key.rpartition(_CONNECTION_SEP)
|
| 136 |
+
for candidate in ((key, base) if sep and cid else (key,)):
|
| 137 |
+
if candidate in databases:
|
| 138 |
+
return candidate
|
| 139 |
+
if prefix and candidate.startswith(prefix):
|
| 140 |
+
return prefix
|
| 141 |
+
return None
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _openable(session, keys):
|
| 145 |
+
"""Return the subset of database keys this caller may read now."""
|
| 146 |
+
from deps import assistant_source_status
|
| 147 |
+
|
| 148 |
+
status = assistant_source_status(session, list(keys) if keys is not None else None)
|
| 149 |
+
return {key for key, value in status.items()
|
| 150 |
+
if (keys is None or key in keys) and value.get("permitted") and _opens(session, key)}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def pack_for(pack, openable):
|
| 154 |
+
"""Return the pack's scope, pack traps and only the entries an openable key maps to."""
|
| 155 |
+
entries, generated = {}, None
|
| 156 |
+
prefix = (pack.get("generated_tables") or {}).get("prefix")
|
| 157 |
+
for key in sorted(openable):
|
| 158 |
+
base = pack_base_key(pack, key)
|
| 159 |
+
if base is None:
|
| 160 |
+
continue
|
| 161 |
+
if base == prefix:
|
| 162 |
+
generated = pack["generated_tables"]
|
| 163 |
+
else:
|
| 164 |
+
entries[base] = pack["databases"][base]
|
| 165 |
+
knowledge = {"scope": pack.get("scope") or {}, "traps": list(pack.get("traps") or ()),
|
| 166 |
+
"databases": entries}
|
| 167 |
+
if generated is not None:
|
| 168 |
+
knowledge["generated_tables"] = generated
|
| 169 |
+
return knowledge
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def database_notes(session, database):
|
| 173 |
+
"""Return one database's notes with its source's scope and traps, if the caller can open it."""
|
| 174 |
+
from deps import err
|
| 175 |
+
|
| 176 |
+
for skill_key in KNOWLEDGE_PACKS:
|
| 177 |
+
pack = load_pack(skill_key)
|
| 178 |
+
base = pack_base_key(pack, database)
|
| 179 |
+
if base is None:
|
| 180 |
+
continue
|
| 181 |
+
if not (_connected(session, pack.get("connector") or skill_key)
|
| 182 |
+
and database in _openable(session, [database])):
|
| 183 |
+
break
|
| 184 |
+
knowledge = pack_for(pack, {database})
|
| 185 |
+
notes = knowledge["databases"].get(base) or knowledge.get("generated_tables")
|
| 186 |
+
return {"source": skill_key, "database": database, "notes": notes,
|
| 187 |
+
"scope": knowledge["scope"], "traps": knowledge["traps"]}
|
| 188 |
+
raise err(404, "database_notes_unavailable",
|
| 189 |
+
"Notes for that database are not available for your current permissions and connections.")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
def read_skill(session, key):
|
| 193 |
"""Recheck access and return an exact procedure with only installed tool names."""
|
| 194 |
import agent_tools
|
|
|
|
| 205 |
steps = list(record["steps"])
|
| 206 |
if not tools:
|
| 207 |
steps = ["This skill's tools are not available in this build. Try again after they are installed."]
|
| 208 |
+
result = {"key": record["key"], "title": record["title"], "steps": steps, "tools": tools}
|
| 209 |
+
pack = load_pack(key)
|
| 210 |
+
if pack is not None:
|
| 211 |
+
result["knowledge"] = pack_for(pack, _openable(session, None))
|
| 212 |
+
return result
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
#: The prompt_index sentence that sends the agent to a source's notes first.
|
| 216 |
+
NOTES_SENTENCE = ("Before you query a source's database, read its notes with database_notes "
|
| 217 |
+
"or that source's skill.")
|
| 218 |
|
| 219 |
|
| 220 |
def prompt_index(session):
|
| 221 |
"""Return the permissioned one-line skill index for the system prompt."""
|
| 222 |
labels = [f"{record['key']} ({record['title']})" for record in list_skills(session)]
|
| 223 |
+
index = "Skills you can read: " + (", ".join(labels) if labels else "none") + "."
|
| 224 |
+
index = index + " " + NOTES_SENTENCE if labels else index
|
| 225 |
+
from loopy_tool_store import prompt_lines
|
| 226 |
+
|
| 227 |
+
tools = prompt_lines(session)
|
| 228 |
+
return index + "\n" + tools if tools else index
|
api/loopy_tool_store.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Saved Assistant tools: named read-only steps, kept per user and shared on an Administrator's yes (R88).
|
| 2 |
+
|
| 3 |
+
A saved tool runs no code. Each step is an existing read tool call with its arguments, and a query
|
| 4 |
+
recipe is a `query_database` step. Every step runs as the caller, through `agent_runtime.execute`.
|
| 5 |
+
Tool creation and the share inbox have no screen (R81): both live in the chat.
|
| 6 |
+
"""
|
| 7 |
+
import copy
|
| 8 |
+
import json
|
| 9 |
+
import re
|
| 10 |
+
import secrets
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
|
| 13 |
+
#: One per-tenant document: `{"users": {username: {name: tool}}, "workspace": {name: tool}}`.
|
| 14 |
+
STORE_KEY = "loopy_saved_tools"
|
| 15 |
+
#: Share requests reuse the harness proposal record under this reserved id. No agent has it, so
|
| 16 |
+
#: the harness routes refuse it with 404 at `agent_wall`.
|
| 17 |
+
SHARE_AGENT = "loopy:tools"
|
| 18 |
+
SHARE_KIND = "tool_share"
|
| 19 |
+
NAME_RE = re.compile(r"[a-z0-9_]{1,40}")
|
| 20 |
+
MAX_STEPS = 12
|
| 21 |
+
MAX_ARGS_BYTES = 8 * 1024
|
| 22 |
+
MAX_TITLE = 80
|
| 23 |
+
MAX_DESCRIPTION = 300
|
| 24 |
+
MAX_USER_TOOLS = 50
|
| 25 |
+
MAX_WORKSPACE_TOOLS = 100
|
| 26 |
+
MAX_STEP_RESULT_CHARS = 3000
|
| 27 |
+
#: Read tools that are not a data read: they mint links or touch the tool store itself.
|
| 28 |
+
_NOT_SAVEABLE = {"confirm_change", "connector_setup_link"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ToolRefusal(ValueError):
|
| 32 |
+
"""A saved tool request the store refuses, with a plain sentence for the user."""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _now():
|
| 36 |
+
from core import write_execution
|
| 37 |
+
return write_execution.utcnow().isoformat(timespec="seconds")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _is_admin(session):
|
| 41 |
+
import core.perms as perms
|
| 42 |
+
|
| 43 |
+
return bool(perms.is_admin(session.user))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _doc(runtime):
|
| 47 |
+
raw = runtime.get(STORE_KEY) or {}
|
| 48 |
+
raw = raw if isinstance(raw, dict) else {}
|
| 49 |
+
users = raw.get("users") if isinstance(raw.get("users"), dict) else {}
|
| 50 |
+
workspace = raw.get("workspace") if isinstance(raw.get("workspace"), dict) else {}
|
| 51 |
+
return {"users": users, "workspace": workspace}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _available_tools():
|
| 55 |
+
import agent_tools
|
| 56 |
+
from core import external_tools
|
| 57 |
+
|
| 58 |
+
agent_tools.load_modules()
|
| 59 |
+
return set(external_tools.TOOLS) | set(agent_tools.registered())
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def step_databases(value, found=None):
|
| 63 |
+
"""Every `database` string named anywhere in a step's arguments."""
|
| 64 |
+
found = set() if found is None else found
|
| 65 |
+
if isinstance(value, dict):
|
| 66 |
+
for key, item in value.items():
|
| 67 |
+
if key == "database" and isinstance(item, str) and item.strip():
|
| 68 |
+
found.add(item.strip())
|
| 69 |
+
else:
|
| 70 |
+
step_databases(item, found)
|
| 71 |
+
elif isinstance(value, list):
|
| 72 |
+
for item in value:
|
| 73 |
+
step_databases(item, found)
|
| 74 |
+
return found
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def unreadable(session, databases):
|
| 78 |
+
"""The databases in this set that the caller cannot read now."""
|
| 79 |
+
if not databases:
|
| 80 |
+
return set()
|
| 81 |
+
from loopy_skills import _openable
|
| 82 |
+
|
| 83 |
+
return set(databases) - _openable(session, sorted(databases))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _check_step(step, available):
|
| 87 |
+
"""Return one clean step, or raise ToolRefusal for a step a saved tool may not hold."""
|
| 88 |
+
import agent_tools
|
| 89 |
+
|
| 90 |
+
if not isinstance(step, dict) or set(step) - {"tool", "args"} or not isinstance(step.get("tool"), str):
|
| 91 |
+
raise ToolRefusal("Each step needs a tool name and its arguments.")
|
| 92 |
+
name, args = step["tool"].strip(), step.get("args") if step.get("args") is not None else {}
|
| 93 |
+
if not isinstance(args, dict):
|
| 94 |
+
raise ToolRefusal(f"The arguments for step {name} must be an object.")
|
| 95 |
+
if name in _NOT_SAVEABLE or name.startswith("tool_"):
|
| 96 |
+
raise ToolRefusal(f"A saved tool cannot use {name}.")
|
| 97 |
+
if name not in available:
|
| 98 |
+
raise ToolRefusal(f"There is no tool called {name}.")
|
| 99 |
+
if agent_tools.classify(name, args) != "read":
|
| 100 |
+
raise ToolRefusal(f"A saved tool only reads. The step {name} would change or remove data.")
|
| 101 |
+
try:
|
| 102 |
+
size = len(json.dumps(args, allow_nan=False, ensure_ascii=False).encode("utf-8"))
|
| 103 |
+
except (TypeError, ValueError):
|
| 104 |
+
raise ToolRefusal(f"The arguments for step {name} must be plain values.")
|
| 105 |
+
if size > MAX_ARGS_BYTES:
|
| 106 |
+
raise ToolRefusal(f"The arguments for step {name} are over {MAX_ARGS_BYTES // 1024} KB.")
|
| 107 |
+
return {"tool": name, "args": copy.deepcopy(args)}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def clean(session, raw):
|
| 111 |
+
"""Validate a tool from the model. Databases come from the steps, never from the model."""
|
| 112 |
+
if not isinstance(raw, dict):
|
| 113 |
+
raise ToolRefusal("A saved tool needs a name, a title and its steps.")
|
| 114 |
+
name = str(raw.get("name") or "").strip()
|
| 115 |
+
if not NAME_RE.fullmatch(name):
|
| 116 |
+
raise ToolRefusal("A tool name uses 1 to 40 lowercase letters, digits or underscores.")
|
| 117 |
+
title = " ".join(str(raw.get("title") or "").split())[:MAX_TITLE] or name.replace("_", " ")
|
| 118 |
+
description = " ".join(str(raw.get("description") or "").split())[:MAX_DESCRIPTION]
|
| 119 |
+
steps = raw.get("steps")
|
| 120 |
+
if not isinstance(steps, list) or not 1 <= len(steps) <= MAX_STEPS:
|
| 121 |
+
raise ToolRefusal(f"A saved tool has 1 to {MAX_STEPS} steps.")
|
| 122 |
+
available = _available_tools()
|
| 123 |
+
steps = [_check_step(step, available) for step in steps]
|
| 124 |
+
databases = set()
|
| 125 |
+
for step in steps:
|
| 126 |
+
step_databases(step["args"], databases)
|
| 127 |
+
blocked = unreadable(session, databases)
|
| 128 |
+
if blocked:
|
| 129 |
+
raise ToolRefusal("You cannot read " + ", ".join(sorted(blocked)) + ", so a tool cannot use it.")
|
| 130 |
+
return {"name": name, "title": title, "description": description, "steps": steps,
|
| 131 |
+
"databases": sorted(databases)}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def public(tool, scope):
|
| 135 |
+
return {"name": tool["name"], "title": tool.get("title") or "", "description": tool.get("description") or "",
|
| 136 |
+
"scope": scope, "owner": tool.get("owner") or "", "version": int(tool.get("version") or 1),
|
| 137 |
+
"databases": list(tool.get("databases") or ()), "steps": copy.deepcopy(tool.get("steps") or []),
|
| 138 |
+
**({"approvedBy": tool["approvedBy"]} if tool.get("approvedBy") else {})}
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _put(tools, tool, cap, **extra):
|
| 142 |
+
"""Store one tool in a name map in place, bumping the version of an existing name."""
|
| 143 |
+
prior = tools.get(tool["name"]) if isinstance(tools.get(tool["name"]), dict) else None
|
| 144 |
+
if prior is None and len(tools) >= cap:
|
| 145 |
+
raise ToolRefusal(f"There are already {cap} saved tools here. Remove one before you add another.")
|
| 146 |
+
now = _now()
|
| 147 |
+
stored = {**copy.deepcopy(tool), **extra, "version": int((prior or {}).get("version") or 0) + 1,
|
| 148 |
+
"createdAt": (prior or {}).get("createdAt") or now, "updatedAt": now}
|
| 149 |
+
tools[tool["name"]] = stored
|
| 150 |
+
return stored
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _execute_steps(session, steps, *, door, handle=None):
|
| 154 |
+
"""Run read steps as the caller and return `(results, error)`; error names the first failed step."""
|
| 155 |
+
import agent_runtime
|
| 156 |
+
|
| 157 |
+
turn = {"toolCalls": [], "pendingDelete": None, "artifacts": [], "handle": handle}
|
| 158 |
+
results, error = [], None
|
| 159 |
+
for number, step in enumerate(steps, 1):
|
| 160 |
+
result = agent_runtime.execute(session, step["tool"], step["args"], door=door, turn=turn)
|
| 161 |
+
if isinstance(result, dict) and result.get("stopped"):
|
| 162 |
+
return None, "stopped"
|
| 163 |
+
ok = bool(turn["toolCalls"][-1].get("ok"))
|
| 164 |
+
if not ok and error is None:
|
| 165 |
+
reason = result.get("error") if isinstance(result, dict) else None
|
| 166 |
+
error = f"Step {number} ({step['tool']}) failed: {reason or 'the tool refused it'}"
|
| 167 |
+
text = json.dumps(result, default=str, ensure_ascii=False)
|
| 168 |
+
if len(text) > MAX_STEP_RESULT_CHARS:
|
| 169 |
+
result = {"truncated": True, "text": text[:MAX_STEP_RESULT_CHARS]}
|
| 170 |
+
results.append({"tool": step["tool"], "args": copy.deepcopy(step["args"]), "ok": ok, "result": result})
|
| 171 |
+
return results, error
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def save(session, raw, *, door="app"):
|
| 175 |
+
"""Try the steps as the caller, then save the tool for the caller at once. The same name is a new version."""
|
| 176 |
+
tool = clean(session, raw)
|
| 177 |
+
_results, error = _execute_steps(session, tool["steps"], door=door)
|
| 178 |
+
if error:
|
| 179 |
+
raise ToolRefusal(f"{error.rstrip('.')}. The tool was not saved. Fix that step and save again.")
|
| 180 |
+
saved = {}
|
| 181 |
+
|
| 182 |
+
def update(current):
|
| 183 |
+
saved.clear()
|
| 184 |
+
doc = _doc_from(current)
|
| 185 |
+
mine = dict(doc["users"].get(session.uname) or {})
|
| 186 |
+
saved.update(_put(mine, tool, MAX_USER_TOOLS, owner=session.uname))
|
| 187 |
+
doc["users"][session.uname] = mine
|
| 188 |
+
return doc
|
| 189 |
+
|
| 190 |
+
session.runtime.update(STORE_KEY, update, flush="sync")
|
| 191 |
+
return public(saved, "personal")
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _doc_from(current):
|
| 195 |
+
raw = copy.deepcopy(current) if isinstance(current, dict) else {}
|
| 196 |
+
return {"users": dict(raw.get("users") or {}), "workspace": dict(raw.get("workspace") or {})}
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def find(session, name):
|
| 200 |
+
"""The caller's own tool by name, else a workspace tool, with its scope, or (None, None)."""
|
| 201 |
+
doc = _doc(session.runtime)
|
| 202 |
+
mine = (doc["users"].get(session.uname) or {}).get(name)
|
| 203 |
+
if isinstance(mine, dict):
|
| 204 |
+
return mine, "personal"
|
| 205 |
+
shared = doc["workspace"].get(name)
|
| 206 |
+
if isinstance(shared, dict):
|
| 207 |
+
return shared, "workspace"
|
| 208 |
+
return None, None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def visible(session):
|
| 212 |
+
"""The caller's tools and the workspace tools whose databases the caller can read."""
|
| 213 |
+
doc = _doc(session.runtime)
|
| 214 |
+
mine = [public(tool, "personal") for _n, tool in sorted((doc["users"].get(session.uname) or {}).items())
|
| 215 |
+
if isinstance(tool, dict)]
|
| 216 |
+
shared = [tool for _n, tool in sorted(doc["workspace"].items()) if isinstance(tool, dict)]
|
| 217 |
+
blocked = unreadable(session, {db for tool in shared for db in tool.get("databases") or ()})
|
| 218 |
+
shared = [public(tool, "workspace") for tool in shared if not blocked & set(tool.get("databases") or ())]
|
| 219 |
+
return mine, shared
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def run(session, name, *, door, handle=None):
|
| 223 |
+
"""Run each step as the caller. Refuse the whole tool if any database is unreadable."""
|
| 224 |
+
tool, scope = find(session, name)
|
| 225 |
+
if tool is None:
|
| 226 |
+
raise ToolRefusal(f"You have no saved tool called {name}.")
|
| 227 |
+
available = _available_tools()
|
| 228 |
+
steps = [_check_step(step, available) for step in tool.get("steps") or ()]
|
| 229 |
+
databases = set()
|
| 230 |
+
for step in steps:
|
| 231 |
+
step_databases(step["args"], databases)
|
| 232 |
+
blocked = unreadable(session, databases)
|
| 233 |
+
if blocked:
|
| 234 |
+
raise ToolRefusal(f"You cannot read {', '.join(sorted(blocked))}, so the tool {name} cannot run for you.")
|
| 235 |
+
results, error = _execute_steps(session, steps, door=door, handle=handle)
|
| 236 |
+
if error == "stopped":
|
| 237 |
+
return {"ok": False, "stopped": True}
|
| 238 |
+
out = {"name": name, "title": tool.get("title") or "", "scope": scope,
|
| 239 |
+
"version": int(tool.get("version") or 1), "steps": results}
|
| 240 |
+
# A failed step makes the whole run fail, so the model reports the cause and invents no number.
|
| 241 |
+
return {"ok": False, "error": error.rstrip(".") + ". Report this to the user.", **out} if error else out
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _share_rows(runtime):
|
| 245 |
+
import routes_agent_harness as harness
|
| 246 |
+
|
| 247 |
+
return {pid: row for pid, row in harness._proposal_rows(runtime, SHARE_AGENT).items()
|
| 248 |
+
if isinstance(row, dict) and row.get("kind") == SHARE_KIND}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def pending_shares(session):
|
| 252 |
+
"""Share requests that wait for an Administrator's yes. Empty for a member."""
|
| 253 |
+
if not _is_admin(session):
|
| 254 |
+
return []
|
| 255 |
+
rows = [row for row in _share_rows(session.runtime).values() if row.get("status") in {"pending", "approving"}]
|
| 256 |
+
rows.sort(key=lambda row: str(row.get("created") or ""))
|
| 257 |
+
return [{"request": row["id"], "tool": (row.get("tool") or {}).get("name") or "",
|
| 258 |
+
"title": (row.get("tool") or {}).get("title") or "", "requestedBy": row.get("requestedBy") or "",
|
| 259 |
+
"databases": list((row.get("tool") or {}).get("databases") or ()),
|
| 260 |
+
"steps": copy.deepcopy((row.get("tool") or {}).get("steps") or [])} for row in rows]
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def publish(runtime, tool, *, requested_by, approved_by):
|
| 264 |
+
"""Copy a tool to the workspace with who asked and who said yes."""
|
| 265 |
+
published = {}
|
| 266 |
+
|
| 267 |
+
def update(current):
|
| 268 |
+
published.clear()
|
| 269 |
+
doc = _doc_from(current)
|
| 270 |
+
shared = dict(doc["workspace"])
|
| 271 |
+
published.update(_put(shared, tool, MAX_WORKSPACE_TOOLS, owner=requested_by,
|
| 272 |
+
approvedBy=approved_by, approvedAt=_now()))
|
| 273 |
+
doc["workspace"] = shared
|
| 274 |
+
return doc
|
| 275 |
+
|
| 276 |
+
runtime.update(STORE_KEY, update, flush="sync")
|
| 277 |
+
return public(published, "workspace")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def request_share(session, name):
|
| 281 |
+
"""An Administrator shares at once. A member's request waits for an Administrator's yes."""
|
| 282 |
+
import routes_agent_harness as harness
|
| 283 |
+
|
| 284 |
+
doc = _doc(session.runtime)
|
| 285 |
+
tool = (doc["users"].get(session.uname) or {}).get(name)
|
| 286 |
+
if not isinstance(tool, dict):
|
| 287 |
+
raise ToolRefusal(f"You have no saved tool called {name} to share.")
|
| 288 |
+
snapshot = clean(session, tool)
|
| 289 |
+
if _is_admin(session):
|
| 290 |
+
return {"shared": True, "tool": publish(session.runtime, snapshot, requested_by=session.uname,
|
| 291 |
+
approved_by=session.uname)}
|
| 292 |
+
for row in _share_rows(session.runtime).values():
|
| 293 |
+
if (row.get("status") in {"pending", "approving"} and row.get("requestedBy") == session.uname
|
| 294 |
+
and (row.get("tool") or {}).get("name") == name):
|
| 295 |
+
return {"shared": False, "request": row["id"],
|
| 296 |
+
"message": "This tool already waits for an Administrator's yes."}
|
| 297 |
+
from core import write_execution
|
| 298 |
+
row = {"id": "ts_" + write_execution.new_id()[:16], "agent": SHARE_AGENT, "kind": SHARE_KIND,
|
| 299 |
+
"path": "tools/" + name, "summary": snapshot["title"], "tool": snapshot, "status": "pending",
|
| 300 |
+
"requestedBy": session.uname, "created": _now()}
|
| 301 |
+
try:
|
| 302 |
+
harness._store_proposal(session.runtime, SHARE_AGENT, row)
|
| 303 |
+
except ValueError:
|
| 304 |
+
raise ToolRefusal("Too many share requests are waiting. Ask an Administrator to decide them first.")
|
| 305 |
+
return {"shared": False, "request": row["id"],
|
| 306 |
+
"message": "An Administrator must say yes in the chat before the workspace can use this tool."}
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def decide_share(session, request_id, approve):
|
| 310 |
+
"""An Administrator's yes copies the tool to the workspace. A no rejects the request."""
|
| 311 |
+
import routes_agent_harness as harness
|
| 312 |
+
|
| 313 |
+
if not _is_admin(session):
|
| 314 |
+
raise ToolRefusal("Only an Administrator can decide a share request.")
|
| 315 |
+
row = _share_rows(session.runtime).get(str(request_id))
|
| 316 |
+
if row is None:
|
| 317 |
+
raise ToolRefusal("There is no share request with that id.")
|
| 318 |
+
if not approve:
|
| 319 |
+
rejected = harness._set_proposal_status(session.runtime, SHARE_AGENT, request_id, "pending", {
|
| 320 |
+
"status": "rejected", "rejectedBy": session.uname, "rejectedAt": _now()})
|
| 321 |
+
if not rejected:
|
| 322 |
+
raise ToolRefusal("That share request no longer waits for a decision.")
|
| 323 |
+
return {"shared": False, "request": request_id, "status": "rejected"}
|
| 324 |
+
if row.get("status") == "pending":
|
| 325 |
+
row = harness._set_proposal_status(session.runtime, SHARE_AGENT, request_id, "pending",
|
| 326 |
+
{"status": "approving", "approvedBy": session.uname}) or {}
|
| 327 |
+
if row.get("status") != "approving":
|
| 328 |
+
raise ToolRefusal("That share request no longer waits for a decision.")
|
| 329 |
+
tool = publish(session.runtime, row["tool"], requested_by=row.get("requestedBy") or "",
|
| 330 |
+
approved_by=row.get("approvedBy") or session.uname)
|
| 331 |
+
harness._set_proposal_status(session.runtime, SHARE_AGENT, request_id, "approving",
|
| 332 |
+
{"status": "approved", "approvedAt": _now()})
|
| 333 |
+
return {"shared": True, "request": request_id, "status": "approved", "tool": tool}
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def prompt_lines(session):
|
| 337 |
+
"""At most two short system prompt lines: saved tool names, and an Administrator's share inbox."""
|
| 338 |
+
lines = []
|
| 339 |
+
try:
|
| 340 |
+
mine, shared = visible(session)
|
| 341 |
+
names = [f"{tool['name']} ({tool['title']})" for tool in [*mine, *shared][:12]]
|
| 342 |
+
if names:
|
| 343 |
+
lines.append(("Saved tools: " + ", ".join(names))[:400] + ". Use tool_run when a question matches one.")
|
| 344 |
+
waiting = pending_shares(session)[:6]
|
| 345 |
+
if waiting:
|
| 346 |
+
asks = [f"{row['request']} ({row['tool']} from {row['requestedBy']})" for row in waiting]
|
| 347 |
+
lines.append(("Share requests waiting for your yes: " + ", ".join(asks))[:400]
|
| 348 |
+
+ ". Ask the user before you call tool_share_decide.")
|
| 349 |
+
except Exception: # noqa: BLE001
|
| 350 |
+
return ""
|
| 351 |
+
return "\n".join(lines)
|
api/loopy_xlsx.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Render authorized table and Sheet values as Excel workbooks without formulas."""
|
| 2 |
+
from collections.abc import Mapping
|
| 3 |
+
from datetime import date, datetime, timezone
|
| 4 |
+
from decimal import Decimal
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
| 11 |
+
MAX_ROWS = 100_000
|
| 12 |
+
MAX_CELLS = 1_000_000
|
| 13 |
+
MAX_BYTES = 20 * 1024 * 1024
|
| 14 |
+
_ADDRESS = re.compile(r"([A-Z]{1,3})([1-9][0-9]*)\Z")
|
| 15 |
+
_ILLEGAL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def check_size(rows, columns, *, cells=None):
|
| 19 |
+
if rows > MAX_ROWS or columns > 16_384 or (cells if cells is not None else rows * columns) > MAX_CELLS:
|
| 20 |
+
raise ValueError(
|
| 21 |
+
f"Excel export exceeds the file limit ({MAX_ROWS:,} rows, {MAX_CELLS:,} cells, "
|
| 22 |
+
"16,384 columns). Filter the database or export smaller workbooks. No rows were exported.")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _value(value, field=None):
|
| 26 |
+
# Formula-shaped source strings remain unchanged, even in a date column.
|
| 27 |
+
if isinstance(value, str) and value.startswith(("=", "+", "-", "@")):
|
| 28 |
+
if len(value) > 32_767 or _ILLEGAL.search(value):
|
| 29 |
+
raise ValueError("A cell exceeds Excel's text limits. Shorten or clean that cell and ask again. No text was cut.")
|
| 30 |
+
return value
|
| 31 |
+
kind = (field or {}).get("type")
|
| 32 |
+
if isinstance(value, str) and value and kind in ("date", "datetime"):
|
| 33 |
+
try:
|
| 34 |
+
value = (date.fromisoformat(value) if kind == "date"
|
| 35 |
+
else datetime.fromisoformat(value.replace("Z", "+00:00")))
|
| 36 |
+
except ValueError as exc:
|
| 37 |
+
raise ValueError("A date could not be exported. Correct its value and ask again.") from exc
|
| 38 |
+
if isinstance(value, datetime) and value.tzinfo is not None:
|
| 39 |
+
value = value.astimezone(timezone.utc).replace(tzinfo=None)
|
| 40 |
+
if isinstance(value, Decimal):
|
| 41 |
+
value = float(value)
|
| 42 |
+
if isinstance(value, float) and not math.isfinite(value):
|
| 43 |
+
raise ValueError("A number is not finite. Correct its value and ask again.")
|
| 44 |
+
if isinstance(value, (dict, list, tuple)):
|
| 45 |
+
value = json.dumps(value, ensure_ascii=False, allow_nan=False)
|
| 46 |
+
if value is not None and not isinstance(value, (str, int, float, bool, date, datetime)):
|
| 47 |
+
raise ValueError("A cell has an unsupported value. Correct it and ask again.")
|
| 48 |
+
if isinstance(value, str) and (len(value) > 32_767 or _ILLEGAL.search(value)):
|
| 49 |
+
raise ValueError("A cell exceeds Excel's text limits. Shorten or clean that cell and ask again. No text was cut.")
|
| 50 |
+
return value
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _cell(worksheet, value, field=None):
|
| 54 |
+
from openpyxl.cell import WriteOnlyCell
|
| 55 |
+
|
| 56 |
+
cell = WriteOnlyCell(worksheet, value=_value(value, field))
|
| 57 |
+
if isinstance(cell.value, str):
|
| 58 |
+
cell.data_type = "s"
|
| 59 |
+
return cell
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _output(book):
|
| 63 |
+
output = BytesIO()
|
| 64 |
+
book.save(output)
|
| 65 |
+
data = output.getvalue()
|
| 66 |
+
if len(data) > MAX_BYTES:
|
| 67 |
+
raise ValueError("Excel export exceeds the 20 MiB file limit. Select fewer fields or filter the rows and ask again. No file was stored.")
|
| 68 |
+
return data
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def render_table(title, columns, rows, *, expected_count=None):
|
| 72 |
+
"""Write a header and every row, preserving typed values and literal strings."""
|
| 73 |
+
from openpyxl import Workbook
|
| 74 |
+
|
| 75 |
+
if expected_count is not None and (type(expected_count) is not int or expected_count != len(rows)):
|
| 76 |
+
raise ValueError("The server count differs from the rows read. Read the complete result again. No file was stored.")
|
| 77 |
+
if not columns:
|
| 78 |
+
raise ValueError("An Excel table needs at least one readable column.")
|
| 79 |
+
check_size(len(rows) + 1, len(columns))
|
| 80 |
+
fields = [column if isinstance(column, Mapping) else {"key": column, "label": column} for column in columns]
|
| 81 |
+
prepared = []
|
| 82 |
+
for row in rows:
|
| 83 |
+
values = [row.get(field["key"]) for field in fields] if isinstance(row, Mapping) else list(row)
|
| 84 |
+
if len(values) != len(fields):
|
| 85 |
+
raise ValueError("An Excel row must match its columns. Read the complete result again.")
|
| 86 |
+
prepared.append([_value(value, field) for value, field in zip(values, fields)])
|
| 87 |
+
labels = [_value(field.get("label") or field["key"]) for field in fields]
|
| 88 |
+
book = Workbook(write_only=True)
|
| 89 |
+
book.properties.title = title
|
| 90 |
+
tab = book.create_sheet("Data")
|
| 91 |
+
tab.freeze_panes = "A2"
|
| 92 |
+
tab.append([_cell(tab, value) for value in labels])
|
| 93 |
+
for values in prepared:
|
| 94 |
+
tab.append([_cell(tab, value) for value in values])
|
| 95 |
+
return _output(book)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def render_workbook(title, tabs):
|
| 99 |
+
"""Write permitted Sheet values at their original addresses, without formulas or bindings."""
|
| 100 |
+
from openpyxl import Workbook
|
| 101 |
+
|
| 102 |
+
if not tabs:
|
| 103 |
+
raise ValueError("The Sheet workbook has no readable tabs.")
|
| 104 |
+
prepared, total_rows, total_cells, names = [], 0, 0, set()
|
| 105 |
+
for tab in tabs:
|
| 106 |
+
name = tab.get("name")
|
| 107 |
+
if (not isinstance(name, str) or not name or len(name) > 31
|
| 108 |
+
or re.search(r"[\\/*?:\[\]]", name) or name.lower() in names):
|
| 109 |
+
raise ValueError("A Sheet tab name is not valid in Excel. Rename the tab and ask again.")
|
| 110 |
+
names.add(name.lower())
|
| 111 |
+
cells, max_row, max_col = {}, 0, 0
|
| 112 |
+
for address, cell in (tab.get("cells") or {}).items():
|
| 113 |
+
match = _ADDRESS.fullmatch(address) if isinstance(address, str) else None
|
| 114 |
+
if not match or not isinstance(cell, dict):
|
| 115 |
+
raise ValueError("A Sheet cell is invalid. Repair the workbook and ask again.")
|
| 116 |
+
col = 0
|
| 117 |
+
for char in match[1]:
|
| 118 |
+
col = col * 26 + ord(char) - 64
|
| 119 |
+
row = int(match[2])
|
| 120 |
+
check_size(row, col)
|
| 121 |
+
binding = cell.get("binding") or {}
|
| 122 |
+
if isinstance(binding, dict) and (binding.get("mode") == "view" or binding.get("kind") == "view"):
|
| 123 |
+
raise ValueError("A placed View cannot be exported as a cached cell. Export its database through the query tool and ask again.")
|
| 124 |
+
if cell.get("refusal") or cell.get("state") in ("refused", "stale"):
|
| 125 |
+
raise ValueError("A Sheet value needs refresh or permission. Refresh the workbook with readable sources and ask again.")
|
| 126 |
+
if cell.get("kind") in ("bound", "formula") and "value" not in cell:
|
| 127 |
+
raise ValueError("A Sheet calculation has no value. Refresh the workbook and ask again.")
|
| 128 |
+
value = None if cell.get("kind") == "empty" else cell.get("value", cell.get("text"))
|
| 129 |
+
cells[(row, col)] = _value(value)
|
| 130 |
+
max_row, max_col = max(max_row, row), max(max_col, col)
|
| 131 |
+
total_rows += max_row
|
| 132 |
+
total_cells += max_row * max_col
|
| 133 |
+
check_size(total_rows, max_col, cells=total_cells)
|
| 134 |
+
prepared.append((name, cells, max_row, max_col))
|
| 135 |
+
book = Workbook(write_only=True)
|
| 136 |
+
book.properties.title = title
|
| 137 |
+
for name, cells, rows, cols in prepared:
|
| 138 |
+
tab = book.create_sheet(name)
|
| 139 |
+
for row in range(1, rows + 1):
|
| 140 |
+
tab.append([_cell(tab, cells.get((row, col))) for col in range(1, cols + 1)])
|
| 141 |
+
return _output(book)
|
api/main.py
CHANGED
|
@@ -489,6 +489,8 @@ app.include_router(routes_query.router) # R1 / C5 — E's router, A's line
|
|
| 489 |
# ⚠ `verify_api::section_w23_mounts` asserts this path in `app.openapi()["paths"]`, so its four
|
| 490 |
# EXPECTED reds should now go GREEN. A red here after this line means the mount broke, not the gate.
|
| 491 |
app.include_router(routes_publish.router) # R5 / C2 — C's router, A's line (the publish door)
|
|
|
|
|
|
|
| 492 |
# ⛔ NOT BEHIND `module_gate("product_data")`, WHICH IS THE WHOLE REASON IT IS A SECOND ASSET DOOR.
|
| 493 |
# `routes_assets.py` gates EVERY one of its routes on that module, so a connector logo served from
|
| 494 |
# there would 403 for any account without the product-data grant — i.e. the Connectors directory
|
|
|
|
| 489 |
# ⚠ `verify_api::section_w23_mounts` asserts this path in `app.openapi()["paths"]`, so its four
|
| 490 |
# EXPECTED reds should now go GREEN. A red here after this line means the mount broke, not the gate.
|
| 491 |
app.include_router(routes_publish.router) # R5 / C2 — C's router, A's line (the publish door)
|
| 492 |
+
import routes_shared_artifact
|
| 493 |
+
app.include_router(routes_shared_artifact.router)
|
| 494 |
# ⛔ NOT BEHIND `module_gate("product_data")`, WHICH IS THE WHOLE REASON IT IS A SECOND ASSET DOOR.
|
| 495 |
# `routes_assets.py` gates EVERY one of its routes on that module, so a connector logo served from
|
| 496 |
# there would 403 for any account without the product-data grant — i.e. the Connectors directory
|
api/meta_relational.py
CHANGED
|
@@ -116,7 +116,7 @@ _MONEY = {"spend", "social_spend", "cpc", "cpm", "cpp", "amount_spent", "balance
|
|
| 116 |
|
| 117 |
|
| 118 |
def _label(col):
|
| 119 |
-
return
|
| 120 |
|
| 121 |
|
| 122 |
def _ftype(col, duck_type):
|
|
|
|
| 116 |
|
| 117 |
|
| 118 |
def _label(col):
|
| 119 |
+
return connector_spec._label(col)
|
| 120 |
|
| 121 |
|
| 122 |
def _ftype(col, duck_type):
|
api/model_router.py
CHANGED
|
@@ -1,24 +1,11 @@
|
|
| 1 |
-
"""
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
-
import json
|
| 5 |
-
import math
|
| 6 |
import re
|
| 7 |
-
import threading
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
|
| 10 |
-
import providers
|
| 11 |
-
|
| 12 |
-
RECEIPT_PATH = Path(__file__).resolve().parents[2] / "platform/evals/router_receipt.json"
|
| 13 |
-
MEASURED_KINDS = {"total", "list", "view"}
|
| 14 |
-
OPEN_PROVIDERS = {"groq", "cerebras", "openrouter"}
|
| 15 |
-
PASS_MARGIN = 5
|
| 16 |
-
_RECEIPT_LOCK = threading.Lock()
|
| 17 |
-
_receipt_cache = None
|
| 18 |
|
| 19 |
|
| 20 |
def classify_turn(question, dock=None):
|
| 21 |
-
"""
|
| 22 |
if dock is not None:
|
| 23 |
if not isinstance(dock, dict) or dock.get("surface") not in {"data", "sheet", "automation", "field"}:
|
| 24 |
return "other"
|
|
@@ -44,76 +31,3 @@ def classify_turn(question, dock=None):
|
|
| 44 |
and re.search(r"\b(?:total|sum|average|count|how many|how much|revenue|margin|return rate|what share|balance|expense)\b", text)):
|
| 45 |
return "total"
|
| 46 |
return "other"
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def load_receipt():
|
| 50 |
-
"""Cache receipt bytes until their file identity or timestamps change."""
|
| 51 |
-
global _receipt_cache
|
| 52 |
-
path = Path(RECEIPT_PATH)
|
| 53 |
-
with _RECEIPT_LOCK:
|
| 54 |
-
try:
|
| 55 |
-
stat = path.stat()
|
| 56 |
-
signature = (str(path), stat.st_dev, stat.st_ino, stat.st_mtime_ns, stat.st_ctime_ns, stat.st_size)
|
| 57 |
-
except OSError:
|
| 58 |
-
signature = (str(path), None)
|
| 59 |
-
if _receipt_cache is None or _receipt_cache[0] != signature:
|
| 60 |
-
try:
|
| 61 |
-
receipt = json.loads(path.read_text(encoding="utf-8")) if signature[-1] is not None else None
|
| 62 |
-
except (OSError, ValueError, UnicodeError):
|
| 63 |
-
receipt = None
|
| 64 |
-
_receipt_cache = (signature, receipt if isinstance(receipt, dict) else None)
|
| 65 |
-
return _receipt_cache[1]
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def _score(value):
|
| 69 |
-
if type(value) not in (int, float):
|
| 70 |
-
return False
|
| 71 |
-
try:
|
| 72 |
-
return math.isfinite(value) and 0 <= value <= 100
|
| 73 |
-
except OverflowError:
|
| 74 |
-
return False
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def provider_order(kind, receipt):
|
| 78 |
-
"""Allow only the scored open pin followed by Anthropic, or Anthropic alone."""
|
| 79 |
-
fallback = ["anthropic"]
|
| 80 |
-
if not isinstance(kind, str) or kind not in MEASURED_KINDS or not isinstance(receipt, dict):
|
| 81 |
-
return fallback
|
| 82 |
-
if type(receipt.get("schema")) is not int or receipt["schema"] != 1 or receipt.get("margin") != PASS_MARGIN:
|
| 83 |
-
return fallback
|
| 84 |
-
kinds = receipt.get("kinds")
|
| 85 |
-
row = kinds.get(kind) if isinstance(kinds, dict) else None
|
| 86 |
-
if not isinstance(row, dict) or row.get("status") != "measured" or row.get("passed") is not True:
|
| 87 |
-
return fallback
|
| 88 |
-
open_score, claude_score = row.get("openScore"), row.get("claudeScore")
|
| 89 |
-
if not _score(open_score) or not _score(claude_score) or open_score < claude_score - PASS_MARGIN:
|
| 90 |
-
return fallback
|
| 91 |
-
name, model = row.get("provider"), row.get("model")
|
| 92 |
-
if not isinstance(name, str) or name not in OPEN_PROVIDERS or not isinstance(model, str) or not model:
|
| 93 |
-
return fallback
|
| 94 |
-
pin = providers.LLM_PROVIDERS.get(name)
|
| 95 |
-
if pin is None or pin.model != model or row.get("route") != name:
|
| 96 |
-
return fallback
|
| 97 |
-
reference = receipt.get("reference")
|
| 98 |
-
claude = providers.LLM_PROVIDERS.get("anthropic")
|
| 99 |
-
if (not isinstance(reference, dict) or claude is None or reference.get("provider") != "anthropic"
|
| 100 |
-
or reference.get("model") != claude.model or reference.get("status") != "measured"):
|
| 101 |
-
return fallback
|
| 102 |
-
ref_kinds = reference.get("kinds")
|
| 103 |
-
ref = ref_kinds.get(kind) if isinstance(ref_kinds, dict) else None
|
| 104 |
-
if (not isinstance(ref, dict) or ref.get("provider") != "anthropic" or ref.get("model") != claude.model
|
| 105 |
-
or ref.get("status") != "measured" or not _score(ref.get("score")) or ref["score"] != claude_score):
|
| 106 |
-
return fallback
|
| 107 |
-
candidates = receipt.get("candidates")
|
| 108 |
-
if not isinstance(candidates, list):
|
| 109 |
-
return fallback
|
| 110 |
-
for candidate in candidates:
|
| 111 |
-
if not isinstance(candidate, dict) or (candidate.get("provider"), candidate.get("model")) != (name, model):
|
| 112 |
-
continue
|
| 113 |
-
measured = candidate.get("kinds")
|
| 114 |
-
measured = measured.get(kind) if isinstance(measured, dict) else None
|
| 115 |
-
if (isinstance(measured, dict) and (measured.get("provider"), measured.get("model")) == (name, model)
|
| 116 |
-
and measured.get("status") == "measured" and _score(measured.get("score"))
|
| 117 |
-
and measured["score"] == open_score):
|
| 118 |
-
return [name, "anthropic"]
|
| 119 |
-
return fallback
|
|
|
|
| 1 |
+
"""Classify an Assistant turn for its audit kind. Provider choice lives in `providers.llm_chain`."""
|
| 2 |
from __future__ import annotations
|
| 3 |
|
|
|
|
|
|
|
| 4 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
def classify_turn(question, dock=None):
|
| 8 |
+
"""Name a turn total, list, view, write or other from its question and dock."""
|
| 9 |
if dock is not None:
|
| 10 |
if not isinstance(dock, dict) or dock.get("surface") not in {"data", "sheet", "automation", "field"}:
|
| 11 |
return "other"
|
|
|
|
| 31 |
and re.search(r"\b(?:total|sum|average|count|how many|how much|revenue|margin|return rate|what share|balance|expense)\b", text)):
|
| 32 |
return "total"
|
| 33 |
return "other"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/odoo_purchasing.py
CHANGED
|
@@ -38,6 +38,89 @@ def _date(value):
|
|
| 38 |
return str(value or "")[:10]
|
| 39 |
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def _fields(items):
|
| 42 |
return [{"source": "overlay", "default": True,
|
| 43 |
"automation": {"flowId": "odoo_relational", "preset": True}, **field} for field in items]
|
|
@@ -56,7 +139,7 @@ def order_fields():
|
|
| 56 |
{"key": "currency", "label": "Currency", "type": "text"},
|
| 57 |
{"key": "amount_untaxed", "label": "Untaxed amount", "type": "currency", "agg": "sum"},
|
| 58 |
{"key": "amount_total", "label": "Total amount", "type": "currency", "agg": "sum"},
|
| 59 |
-
])
|
| 60 |
|
| 61 |
|
| 62 |
def line_fields():
|
|
@@ -83,7 +166,7 @@ def line_fields():
|
|
| 83 |
{"key": "price_unit", "label": "Unit price", "type": "currency"},
|
| 84 |
{"key": "price_subtotal", "label": "Untaxed amount", "type": "currency", "agg": "sum"},
|
| 85 |
{"key": "planned_date", "label": "Planned date", "type": "date"},
|
| 86 |
-
])
|
| 87 |
|
| 88 |
|
| 89 |
def source_specs():
|
|
@@ -98,7 +181,8 @@ def source_specs():
|
|
| 98 |
"where": CONFIRMED, "id": "po.id",
|
| 99 |
"cols": {**common, "odoo_id": ("po.id", _id), "order_date": ("po.date_order", _date),
|
| 100 |
"amount_untaxed": ("po.amount_untaxed", _number),
|
| 101 |
-
"amount_total": ("po.amount_total", _number)
|
|
|
|
| 102 |
},
|
| 103 |
LINES_KEY: {
|
| 104 |
"from_sql": "(purchase_order_line pol JOIN purchase_order po ON po.id = pol.order_id "
|
|
@@ -112,7 +196,8 @@ def source_specs():
|
|
| 112 |
"standard_price": ("pp.standard_price", _number), "category": ("pp.categ_name", _text),
|
| 113 |
"qty": ("pol.product_uom_qty", _number), "purchase_qty": ("pol.product_qty", _number),
|
| 114 |
"received_qty": ("pol.qty_received", _number), "price_unit": ("pol.price_unit", _number),
|
| 115 |
-
"price_subtotal": ("pol.price_subtotal", _number), "planned_date": ("pol.date_planned", _date)
|
|
|
|
| 116 |
},
|
| 117 |
}
|
| 118 |
|
|
@@ -186,3 +271,46 @@ def validate(client, cur=None, month="2026-06"):
|
|
| 186 |
and abs(totals[ORDERS_KEY][0] - totals[LINES_KEY][1]) <= 0.01,
|
| 187 |
"observation": plane})
|
| 188 |
return checks
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
return str(value or "")[:10]
|
| 39 |
|
| 40 |
|
| 41 |
+
def _int(value):
|
| 42 |
+
return int(value or 0)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _html(value):
|
| 46 |
+
import html
|
| 47 |
+
import re
|
| 48 |
+
return " ".join(html.unescape(re.sub(r"<[^>]*>", " ", str(value or ""))).split())
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
_CASTS = {"text": _text, "html": _html, "date": _date, "num": _number, "int": _int}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _af(key, label, ftype, odoo, ref, how="text", agg=None):
|
| 55 |
+
"""One audited column (S72-T43, R107). Same shape as `odoo_relational._af`."""
|
| 56 |
+
return {"key": key, "label": label, "type": ftype, "odoo": odoo, "ref": ref, "how": how,
|
| 57 |
+
"agg": agg, "desc": None}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
#: S72-T43 / R107: the audited Odoo fields, read only, hidden by default.
|
| 61 |
+
AUDIT_FIELDS = {
|
| 62 |
+
ORDERS_KEY: (
|
| 63 |
+
_af("created_on", "Created on", "date", "purchase.order.create_date", "po.create_date",
|
| 64 |
+
"date"),
|
| 65 |
+
_af("expected_arrival", "Expected arrival", "date", "purchase.order.date_planned",
|
| 66 |
+
"po.date_planned", "date"),
|
| 67 |
+
_af("arrived_on", "Arrived on", "date", "purchase.order.effective_date",
|
| 68 |
+
"po.effective_date", "date"),
|
| 69 |
+
_af("procurement_group", "Procurement group", "text", "purchase.order.group_id",
|
| 70 |
+
"po.group_name"),
|
| 71 |
+
_af("bill_count", "Bill count", "int", "purchase.order.invoice_count",
|
| 72 |
+
"po.invoice_count", "int"),
|
| 73 |
+
_af("billing_status", "Billing status", "text", "purchase.order.invoice_status",
|
| 74 |
+
"po.invoice_status"),
|
| 75 |
+
_af("terms", "Terms and conditions", "text", "purchase.order.notes", "po.notes", "html"),
|
| 76 |
+
_af("vendor_reference", "Vendor reference", "text", "purchase.order.partner_ref",
|
| 77 |
+
"po.partner_ref"),
|
| 78 |
+
_af("payment_terms", "Payment terms", "text", "purchase.order.payment_term_id",
|
| 79 |
+
"po.payment_term_name"),
|
| 80 |
+
_af("deliver_to", "Deliver to", "text", "purchase.order.picking_type_id",
|
| 81 |
+
"po.picking_type_name"),
|
| 82 |
+
_af("receipt_status", "Receipt status", "text", "purchase.order.receipt_status",
|
| 83 |
+
"po.receipt_status"),
|
| 84 |
+
_af("buyer", "Buyer", "text", "purchase.order.user_id", "po.user_name"),
|
| 85 |
+
),
|
| 86 |
+
LINES_KEY: (
|
| 87 |
+
_af("created_on", "Created on", "date", "purchase.order.line.create_date",
|
| 88 |
+
"pol.create_date", "date"),
|
| 89 |
+
_af("description", "Description", "text", "purchase.order.line.name", "pol.name"),
|
| 90 |
+
_af("price_total", "Total with tax", "currency", "purchase.order.line.price_total",
|
| 91 |
+
"pol.price_total", "num", "sum"),
|
| 92 |
+
_af("packaging", "Packaging", "text", "purchase.order.line.product_packaging_id",
|
| 93 |
+
"pol.product_packaging_name"),
|
| 94 |
+
_af("packaging_qty", "Packaging quantity", "int",
|
| 95 |
+
"purchase.order.line.product_packaging_qty", "pol.product_packaging_qty", "num",
|
| 96 |
+
"sum"),
|
| 97 |
+
_af("billed_qty", "Billed quantity", "int", "purchase.order.line.qty_invoiced",
|
| 98 |
+
"pol.qty_invoiced", "num", "sum"),
|
| 99 |
+
_af("received_qty_method", "Received quantity method", "text",
|
| 100 |
+
"purchase.order.line.qty_received_method", "pol.qty_received_method"),
|
| 101 |
+
_af("qty_to_bill", "Quantity to bill", "int", "purchase.order.line.qty_to_invoice",
|
| 102 |
+
"pol.qty_to_invoice", "num", "sum"),
|
| 103 |
+
_af("total_billed", "Total billed", "currency", "purchase.order.line.total_invoiced",
|
| 104 |
+
"pol.total_invoiced", "num", "sum"),
|
| 105 |
+
),
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _audit_presets(key):
|
| 110 |
+
out = []
|
| 111 |
+
for entry in AUDIT_FIELDS[key]:
|
| 112 |
+
field = {"key": entry["key"], "label": entry["label"], "type": entry["type"],
|
| 113 |
+
"default": False}
|
| 114 |
+
if entry["agg"]:
|
| 115 |
+
field["agg"] = entry["agg"]
|
| 116 |
+
out.append(field)
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _audit_cols(key):
|
| 121 |
+
return {entry["key"]: (entry["ref"], _CASTS[entry["how"]]) for entry in AUDIT_FIELDS[key]}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
def _fields(items):
|
| 125 |
return [{"source": "overlay", "default": True,
|
| 126 |
"automation": {"flowId": "odoo_relational", "preset": True}, **field} for field in items]
|
|
|
|
| 139 |
{"key": "currency", "label": "Currency", "type": "text"},
|
| 140 |
{"key": "amount_untaxed", "label": "Untaxed amount", "type": "currency", "agg": "sum"},
|
| 141 |
{"key": "amount_total", "label": "Total amount", "type": "currency", "agg": "sum"},
|
| 142 |
+
] + _audit_presets(ORDERS_KEY))
|
| 143 |
|
| 144 |
|
| 145 |
def line_fields():
|
|
|
|
| 166 |
{"key": "price_unit", "label": "Unit price", "type": "currency"},
|
| 167 |
{"key": "price_subtotal", "label": "Untaxed amount", "type": "currency", "agg": "sum"},
|
| 168 |
{"key": "planned_date", "label": "Planned date", "type": "date"},
|
| 169 |
+
] + _audit_presets(LINES_KEY))
|
| 170 |
|
| 171 |
|
| 172 |
def source_specs():
|
|
|
|
| 181 |
"where": CONFIRMED, "id": "po.id",
|
| 182 |
"cols": {**common, "odoo_id": ("po.id", _id), "order_date": ("po.date_order", _date),
|
| 183 |
"amount_untaxed": ("po.amount_untaxed", _number),
|
| 184 |
+
"amount_total": ("po.amount_total", _number),
|
| 185 |
+
**_audit_cols(ORDERS_KEY)},
|
| 186 |
},
|
| 187 |
LINES_KEY: {
|
| 188 |
"from_sql": "(purchase_order_line pol JOIN purchase_order po ON po.id = pol.order_id "
|
|
|
|
| 196 |
"standard_price": ("pp.standard_price", _number), "category": ("pp.categ_name", _text),
|
| 197 |
"qty": ("pol.product_uom_qty", _number), "purchase_qty": ("pol.product_qty", _number),
|
| 198 |
"received_qty": ("pol.qty_received", _number), "price_unit": ("pol.price_unit", _number),
|
| 199 |
+
"price_subtotal": ("pol.price_subtotal", _number), "planned_date": ("pol.date_planned", _date),
|
| 200 |
+
**_audit_cols(LINES_KEY)},
|
| 201 |
},
|
| 202 |
}
|
| 203 |
|
|
|
|
| 271 |
and abs(totals[ORDERS_KEY][0] - totals[LINES_KEY][1]) <= 0.01,
|
| 272 |
"observation": plane})
|
| 273 |
return checks
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def validate_audit_totals(client, cur, start, end, id_window=None, keys=None):
|
| 277 |
+
"""S72-T43: each audited purchasing total ties to an Odoo read_group sum.
|
| 278 |
+
`odoo_relational.validate` calls it, so this module's own `validate` keeps its five legs.
|
| 279 |
+
|
| 280 |
+
`start`/`end` bound the confirmation date, end exclusive. `id_window` (lo, hi) narrows both
|
| 281 |
+
sides to one id range. Without a cursor the leg reads Odoo rows, never the mirror.
|
| 282 |
+
"""
|
| 283 |
+
checks = []
|
| 284 |
+
plane = "mirror" if cur is not None else "live_rows"
|
| 285 |
+
for key, model in ((ORDERS_KEY, "purchase.order"), (LINES_KEY, "purchase.order.line")):
|
| 286 |
+
sums = [e for e in AUDIT_FIELDS[key] if e["agg"] == "sum"]
|
| 287 |
+
if not sums or (keys is not None and key not in keys):
|
| 288 |
+
continue
|
| 289 |
+
prefix = "order_id." if key == LINES_KEY else ""
|
| 290 |
+
domain = [(prefix + "state", "in", ["purchase", "done"]),
|
| 291 |
+
(prefix + "date_approve", ">=", start), (prefix + "date_approve", "<", end)]
|
| 292 |
+
spec = source_specs()[key]
|
| 293 |
+
where, params = spec["where"] + " AND po.date_approve >= ? AND po.date_approve < ?", [start, end]
|
| 294 |
+
if id_window:
|
| 295 |
+
domain += [("id", ">=", id_window[0]), ("id", "<=", id_window[1])]
|
| 296 |
+
where += f" AND {spec['id']} >= ? AND {spec['id']} <= ?"
|
| 297 |
+
params += list(id_window)
|
| 298 |
+
for entry in sums:
|
| 299 |
+
field = entry["odoo"].rpartition(".")[2]
|
| 300 |
+
name = "audit total " + key + " " + entry["key"]
|
| 301 |
+
try:
|
| 302 |
+
if cur is None:
|
| 303 |
+
_count, total = _row_totals(client, model, domain, field)
|
| 304 |
+
else:
|
| 305 |
+
total = float(cur.execute(
|
| 306 |
+
"SELECT COALESCE(SUM(" + spec["cols"][entry["key"]][0] + "), 0) FROM "
|
| 307 |
+
+ spec["from_sql"] + " WHERE " + where, params).fetchone()[0])
|
| 308 |
+
groups = client.read_group(model, domain, [field + ":sum"], ["create_uid"],
|
| 309 |
+
lazy=False)
|
| 310 |
+
summary = math.fsum(float(row.get(field) or 0) for row in groups)
|
| 311 |
+
checks.append({"check": name, "observation": plane,
|
| 312 |
+
"ok": math.isfinite(total) and abs(total - summary) <= 0.01})
|
| 313 |
+
except Exception as exc: # noqa: BLE001
|
| 314 |
+
checks.append({"check": name, "ok": False, "error_type": type(exc).__name__,
|
| 315 |
+
"observation": plane})
|
| 316 |
+
return checks
|
api/odoo_relational.py
CHANGED
|
@@ -179,6 +179,592 @@ def _refreshed_field():
|
|
| 179 |
"default": False, "description": "When this row was last reconciled against Odoo."}
|
| 180 |
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
def shipment_fields():
|
| 183 |
"""Outgoing pickings, with elapsed delivery time measured at actual completion."""
|
| 184 |
return [_preset({"source": "overlay", **field}) for field in (
|
|
@@ -204,7 +790,7 @@ def shipment_fields():
|
|
| 204 |
"default": True, "description": "Elapsed days from the sale order date to the actual "
|
| 205 |
"shipment completion. Blank when either date is missing."},
|
| 206 |
_refreshed_field(),
|
| 207 |
-
)]
|
| 208 |
|
| 209 |
|
| 210 |
def agent_fields():
|
|
@@ -276,7 +862,7 @@ def account_fields():
|
|
| 276 |
"description": "Ticked for the expense family - the same predicate the semantic layer's "
|
| 277 |
"gl_lines topic uses, so this column and that topic cannot disagree."},
|
| 278 |
_refreshed_field(),
|
| 279 |
-
)]
|
| 280 |
|
| 281 |
|
| 282 |
def vendor_fields():
|
|
@@ -325,7 +911,7 @@ def vendor_fields():
|
|
| 325 |
{"key": "bills", "label": "Bills", "type": "link", "source": "overlay", "default": True,
|
| 326 |
"link": {"table": BILLS_KEY, "on": VENDOR_JOIN_KEY, "from": VENDOR_JOIN_KEY}},
|
| 327 |
_refreshed_field(),
|
| 328 |
-
)]
|
| 329 |
|
| 330 |
|
| 331 |
def bill_fields():
|
|
@@ -363,7 +949,7 @@ def bill_fields():
|
|
| 363 |
"default": False,
|
| 364 |
"link": {"table": VENDORS_KEY, "on": VENDOR_JOIN_KEY, "from": VENDOR_JOIN_KEY}},
|
| 365 |
_refreshed_field(),
|
| 366 |
-
)]
|
| 367 |
|
| 368 |
|
| 369 |
def invoice_fields():
|
|
@@ -510,7 +1096,7 @@ def invoice_fields():
|
|
| 510 |
"default": False,
|
| 511 |
"link": {"table": ORDERS_KEY, "on": "order_no", "from": "origin_order"}},
|
| 512 |
_refreshed_field(),
|
| 513 |
-
)]
|
| 514 |
|
| 515 |
|
| 516 |
def order_fields():
|
|
@@ -553,7 +1139,7 @@ def order_fields():
|
|
| 553 |
"default": True,
|
| 554 |
"link": {"table": INVOICES_KEY, "on": "origin_order", "from": "order_no"}},
|
| 555 |
_refreshed_field(),
|
| 556 |
-
)]
|
| 557 |
|
| 558 |
|
| 559 |
# ═════════════════════════════════════════════════════════════════════════════════════════════
|
|
@@ -652,7 +1238,7 @@ def order_line_fields():
|
|
| 652 |
{"key": "state", "label": "State", "type": "select", "source": "overlay",
|
| 653 |
"default": False, "options": ["sale", "done"]},
|
| 654 |
_scope_field(),
|
| 655 |
-
)]
|
| 656 |
|
| 657 |
|
| 658 |
def gl_line_fields():
|
|
@@ -719,7 +1305,7 @@ def gl_line_fields():
|
|
| 719 |
{"key": "parent_state", "label": "Entry state", "type": "select", "source": "overlay",
|
| 720 |
"default": True, "options": ["draft", "posted", "cancel"]},
|
| 721 |
_scope_field(),
|
| 722 |
-
)]
|
| 723 |
|
| 724 |
|
| 725 |
def _stock_product_fields():
|
|
@@ -757,7 +1343,7 @@ def stock_move_fields():
|
|
| 757 |
{"key": "picking_id", "label": "Odoo picking id", "type": "int", "default": False}]
|
| 758 |
+ _stock_location_fields("source_location", "Source location")
|
| 759 |
+ _stock_location_fields("destination_location", "Destination location")
|
| 760 |
-
)]
|
| 761 |
|
| 762 |
|
| 763 |
def stock_valuation_fields():
|
|
@@ -771,7 +1357,7 @@ def stock_valuation_fields():
|
|
| 771 |
{"key": "stock_move_id", "label": "Odoo stock move id", "type": "int", "default": False}]
|
| 772 |
+ _stock_location_fields("source_location", "Source location")
|
| 773 |
+ _stock_location_fields("destination_location", "Destination location")
|
| 774 |
-
)]
|
| 775 |
|
| 776 |
|
| 777 |
def stock_quant_fields():
|
|
@@ -782,7 +1368,7 @@ def stock_quant_fields():
|
|
| 782 |
+ [{"key": "qty", "label": "On hand", "type": "int", "agg": "sum", "default": True},
|
| 783 |
{"key": "reserved_qty", "label": "Reserved quantity", "type": "int",
|
| 784 |
"agg": "sum", "default": True}]
|
| 785 |
-
)]
|
| 786 |
|
| 787 |
|
| 788 |
def product_fields():
|
|
@@ -1809,7 +2395,7 @@ def read_accounts(cur):
|
|
| 1809 |
"account_type": t,
|
| 1810 |
"is_expense": "1" if t in ("expense", "expense_depreciation") else "",
|
| 1811 |
})
|
| 1812 |
-
return out
|
| 1813 |
|
| 1814 |
|
| 1815 |
_VENDOR_DOCS = "state = 'posted' AND move_type IN ('in_invoice','in_refund')"
|
|
@@ -1841,7 +2427,7 @@ def read_bills(cur):
|
|
| 1841 |
"payment_state": str(pay or ""),
|
| 1842 |
"move_type": str(mtype or ""),
|
| 1843 |
})
|
| 1844 |
-
return out
|
| 1845 |
|
| 1846 |
|
| 1847 |
def read_vendors(cur):
|
|
@@ -1896,7 +2482,7 @@ def read_vendors(cur):
|
|
| 1896 |
"city": str(city or ""),
|
| 1897 |
"zip": str(zipc or ""),
|
| 1898 |
})
|
| 1899 |
-
return out
|
| 1900 |
|
| 1901 |
|
| 1902 |
def customers_from(invoice_rows):
|
|
@@ -3419,7 +4005,8 @@ def stock_source_specs():
|
|
| 3419 |
**_stock_location_cols("source_location", "sl", "sm.location_id"),
|
| 3420 |
**_stock_location_cols("destination_location", "sd", "sm.location_dest_id"),
|
| 3421 |
}
|
| 3422 |
-
|
|
|
|
| 3423 |
STOCK_MOVES_KEY: {
|
| 3424 |
"from_sql": "(stock_move sm LEFT JOIN product_product pp ON pp.id = sm.product_id"
|
| 3425 |
+ locations + ")",
|
|
@@ -3450,7 +4037,7 @@ def stock_source_specs():
|
|
| 3450 |
"reserved_qty": ("sq.reserved_quantity", _stock_number)},
|
| 3451 |
"optional": ({**no_ancestry, "without": {"cols": {"location_fba": blank_fba}}},),
|
| 3452 |
},
|
| 3453 |
-
}
|
| 3454 |
|
| 3455 |
|
| 3456 |
def _stock_period(date_from, date_to, field):
|
|
@@ -3562,6 +4149,93 @@ def validate_wholesale_summary(client, cur):
|
|
| 3562 |
'error_type': type(exc).__name__}]
|
| 3563 |
|
| 3564 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3565 |
def validate(client, cur=None, date_from="2025-07-01", date_to="2026-06-30"):
|
| 3566 |
"""Read-only stock reconciliation, using the caller's own Odoo client and optional mirror.
|
| 3567 |
|
|
@@ -3665,6 +4339,7 @@ def validate(client, cur=None, date_from="2025-07-01", date_to="2026-06-30"):
|
|
| 3665 |
"error_type": type(exc).__name__, "observation": plane})
|
| 3666 |
checks.extend(validate_customer_rollups(client, cur))
|
| 3667 |
checks.extend(validate_wholesale_summary(client, cur))
|
|
|
|
| 3668 |
return checks
|
| 3669 |
|
| 3670 |
|
|
|
|
| 179 |
"default": False, "description": "When this row was last reconciled against Odoo."}
|
| 180 |
|
| 181 |
|
| 182 |
+
# ═════════════════════════════════════════════════════════════════════════════════════════════
|
| 183 |
+
# S72-T43 / R107: THE AUDITED ODOO FIELDS ("All filled fields, you strike").
|
| 184 |
+
# ═════════════════════════════════════════════════════════════════════════════════════════════
|
| 185 |
+
# One entry per added column, from the `add` rows of `platform/model/audit/field-audit.md`.
|
| 186 |
+
# An entry is read only: a preset over a mirror column, never a write path to Odoo.
|
| 187 |
+
# Three layers carry a field: the mirror entity (`AUDIT_MIRROR_ADDITIONS`, amended into
|
| 188 |
+
# `harness.datastore.ENTITIES`), the grid projection (`merge_audit_cols`) and the preset here.
|
| 189 |
+
|
| 190 |
+
def _af(key, label, ftype, odoo, ref, how="text", agg=None, desc=None):
|
| 191 |
+
"""One audited column: preset key and label, Odoo `model.field`, mirror `alias.column`."""
|
| 192 |
+
return {"key": key, "label": label, "type": ftype, "odoo": odoo, "ref": ref, "how": how,
|
| 193 |
+
"agg": agg, "desc": desc}
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _audit_text(value):
|
| 197 |
+
return "" if value is None else str(value)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _audit_html(value):
|
| 201 |
+
import html as _html
|
| 202 |
+
import re as _re
|
| 203 |
+
return " ".join(_html.unescape(_re.sub(r"<[^>]*>", " ", str(value or ""))).split())
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _audit_number(value):
|
| 207 |
+
return float(value or 0.0)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _audit_int(value):
|
| 211 |
+
return int(value or 0)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _audit_flag(value):
|
| 215 |
+
return "1" if value else ""
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _audit_pct(value):
|
| 219 |
+
return "" if value is None else round(float(value), 2)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
_AUDIT_CASTS = {"text": _audit_text, "html": _audit_html, "date": lambda v: _as_date(v),
|
| 223 |
+
"num": _audit_number, "int": _audit_int, "flag": _audit_flag, "pct": _audit_pct,
|
| 224 |
+
"agent_sum": _audit_number, "agent_names": _audit_text,
|
| 225 |
+
"agent_first": lambda v: _as_date(v), "agent_all": _audit_flag,
|
| 226 |
+
"m2m_names": _audit_text}
|
| 227 |
+
|
| 228 |
+
#: Commission lines fold onto their invoice. `am` is the invoices grid's own alias.
|
| 229 |
+
_AUDIT_AGENT_SQL = {
|
| 230 |
+
"agent_sum": "(SELECT SUM(x.{c}) FROM account_invoice_line_agent x WHERE x.invoice_id = am.id)",
|
| 231 |
+
"agent_names": ("(SELECT string_agg(DISTINCT x.{c}, ', ' ORDER BY x.{c}) "
|
| 232 |
+
"FROM account_invoice_line_agent x WHERE x.invoice_id = am.id)"),
|
| 233 |
+
"agent_first": "(SELECT min(x.{c}) FROM account_invoice_line_agent x WHERE x.invoice_id = am.id)",
|
| 234 |
+
"agent_all": ("(SELECT bool_and(COALESCE(x.{c}, FALSE)) FROM account_invoice_line_agent x "
|
| 235 |
+
"WHERE x.invoice_id = am.id)"),
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
_INVOICE_AUDIT = (
|
| 239 |
+
_af("amount_total", "Total", "currency", "account.move.amount_total", "am.amount_total",
|
| 240 |
+
"num", "sum"),
|
| 241 |
+
_af("amount_total_signed", "Total signed", "currency", "account.move.amount_total_signed",
|
| 242 |
+
"am.amount_total_signed", "num", "sum"),
|
| 243 |
+
_af("amount_total_currency", "Total in document currency", "currency",
|
| 244 |
+
"account.move.amount_total_in_currency_signed", "am.amount_total_in_currency_signed",
|
| 245 |
+
"num", "sum"),
|
| 246 |
+
_af("untaxed_amount", "Untaxed amount", "currency", "account.move.amount_untaxed",
|
| 247 |
+
"am.amount_untaxed", "num", "sum", "Unsigned. A refund shows as a positive amount."),
|
| 248 |
+
_af("commercial_partner", "Commercial entity", "text",
|
| 249 |
+
"account.move.commercial_partner_id", "am.commercial_partner_name"),
|
| 250 |
+
_af("commission_total", "Commission total", "currency", "account.move.commission_total",
|
| 251 |
+
"am.commission_total", "num", "sum"),
|
| 252 |
+
_af("created_on", "Created on", "date", "account.move.create_date", "am.create_date", "date"),
|
| 253 |
+
_af("accounting_date", "Accounting date", "date", "account.move.date", "am.date", "date"),
|
| 254 |
+
_af("payment_terms", "Payment terms", "text", "account.move.invoice_payment_term_id",
|
| 255 |
+
"am.invoice_payment_term_name"),
|
| 256 |
+
_af("salesperson", "Salesperson", "text", "account.move.invoice_user_id",
|
| 257 |
+
"am.invoice_user_name"),
|
| 258 |
+
_af("sent", "Sent", "checkbox", "account.move.is_move_sent", "am.is_move_sent", "flag"),
|
| 259 |
+
_af("journal", "Journal", "text", "account.move.journal_id", "am.journal_name"),
|
| 260 |
+
_af("terms", "Terms and conditions", "text", "account.move.narration", "am.narration", "html"),
|
| 261 |
+
_af("delivery_address", "Delivery address", "text", "account.move.partner_shipping_id",
|
| 262 |
+
"am.partner_shipping_name"),
|
| 263 |
+
_af("payment_reference", "Payment reference", "text", "account.move.payment_reference",
|
| 264 |
+
"am.payment_reference"),
|
| 265 |
+
_af("reference", "Reference", "text", "account.move.ref", "am.ref"),
|
| 266 |
+
_af("sales_team", "Sales team", "text", "account.move.team_id", "am.team_name"),
|
| 267 |
+
_af("commission_amount", "Agent commission", "currency",
|
| 268 |
+
"account.invoice.line.agent.amount", "ail.amount", "agent_sum", "sum",
|
| 269 |
+
"The sum of this invoice's agent commission lines."),
|
| 270 |
+
_af("commission_plan", "Commission plan", "text",
|
| 271 |
+
"account.invoice.line.agent.commission_id", "ail.commission_name", "agent_names"),
|
| 272 |
+
_af("commission_recorded_on", "Commission recorded on", "date",
|
| 273 |
+
"account.invoice.line.agent.create_date", "ail.create_date", "agent_first"),
|
| 274 |
+
_af("commission_settled", "Commission settled", "checkbox",
|
| 275 |
+
"account.invoice.line.agent.settled", "ail.settled", "agent_all",
|
| 276 |
+
"Ticked when every agent line on this invoice is settled."),
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
#: Bills read `account_move` unaliased. The sales-only fields stay on invoices.
|
| 280 |
+
_BILL_AUDIT = tuple(
|
| 281 |
+
{**entry, "ref": entry["ref"].split(".", 1)[1]} for entry in _INVOICE_AUDIT
|
| 282 |
+
if entry["key"] in ("amount_total", "amount_total_signed", "amount_total_currency",
|
| 283 |
+
"untaxed_amount", "commercial_partner", "created_on", "accounting_date",
|
| 284 |
+
"payment_terms", "journal", "terms", "payment_reference", "reference"))
|
| 285 |
+
|
| 286 |
+
_GL_LINE_AUDIT = (
|
| 287 |
+
_af("account_root", "Account root", "text", "account.move.line.account_root_id",
|
| 288 |
+
"aml.account_root_name"),
|
| 289 |
+
_af("amount_currency", "Amount in currency", "currency", "account.move.line.amount_currency",
|
| 290 |
+
"aml.amount_currency", "num", "sum"),
|
| 291 |
+
_af("created_on", "Created on", "date", "account.move.line.create_date", "aml.create_date",
|
| 292 |
+
"date"),
|
| 293 |
+
_af("due_date", "Due date", "date", "account.move.line.date_maturity", "aml.date_maturity",
|
| 294 |
+
"date"),
|
| 295 |
+
_af("reconcile_match", "Reconcile match", "text", "account.move.line.full_reconcile_id",
|
| 296 |
+
"aml.full_reconcile_name"),
|
| 297 |
+
_af("journal", "Journal", "text", "account.move.line.journal_id", "aml.journal_name"),
|
| 298 |
+
_af("matching_number", "Matching number", "text", "account.move.line.matching_number",
|
| 299 |
+
"aml.matching_number"),
|
| 300 |
+
_af("label", "Label", "text", "account.move.line.name", "aml.name"),
|
| 301 |
+
_af("payment", "Payment", "text", "account.move.line.payment_id", "aml.payment_name"),
|
| 302 |
+
_af("price_subtotal", "Subtotal", "currency", "account.move.line.price_subtotal",
|
| 303 |
+
"aml.price_subtotal", "num", "sum"),
|
| 304 |
+
_af("price_total", "Total", "currency", "account.move.line.price_total", "aml.price_total",
|
| 305 |
+
"num", "sum"),
|
| 306 |
+
_af("price_unit", "Unit price", "currency", "account.move.line.price_unit",
|
| 307 |
+
"aml.price_unit", "num"),
|
| 308 |
+
_af("uom", "Unit of measure", "text", "account.move.line.product_uom_id",
|
| 309 |
+
"aml.product_uom_name"),
|
| 310 |
+
_af("quantity", "Quantity", "int", "account.move.line.quantity", "aml.quantity", "num", "sum"),
|
| 311 |
+
_af("reconciled", "Reconciled", "checkbox", "account.move.line.reconciled", "aml.reconciled",
|
| 312 |
+
"flag"),
|
| 313 |
+
_af("reference", "Reference", "text", "account.move.line.ref", "aml.ref"),
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
_ACCOUNT_AUDIT = (
|
| 317 |
+
_af("created_on", "Created on", "date", "account.account.create_date", "create_date", "date"),
|
| 318 |
+
_af("deprecated", "Deprecated", "checkbox", "account.account.deprecated", "deprecated",
|
| 319 |
+
"flag"),
|
| 320 |
+
_af("carry_forward", "Balance carried forward", "checkbox",
|
| 321 |
+
"account.account.include_initial_balance", "include_initial_balance", "flag"),
|
| 322 |
+
_af("internal_group", "Internal group", "text", "account.account.internal_group",
|
| 323 |
+
"internal_group"),
|
| 324 |
+
_af("allows_reconcile", "Allows reconciliation", "checkbox", "account.account.reconcile",
|
| 325 |
+
"reconcile", "flag"),
|
| 326 |
+
_af("account_root", "Account root", "text", "account.account.root_id", "root_name"),
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
_ORDER_AUDIT = (
|
| 330 |
+
_af("amount_total", "Total", "currency", "sale.order.amount_total", "amount_total", "num",
|
| 331 |
+
"sum"),
|
| 332 |
+
_af("delivery_method", "Delivery method", "text", "sale.order.carrier_id", "carrier_name"),
|
| 333 |
+
_af("commission_total", "Commission total", "currency", "sale.order.commission_total",
|
| 334 |
+
"commission_total", "num", "sum"),
|
| 335 |
+
_af("created_on", "Created on", "date", "sale.order.create_date", "create_date", "date"),
|
| 336 |
+
_af("delivered_on", "Delivered on", "date", "sale.order.effective_date", "effective_date",
|
| 337 |
+
"date"),
|
| 338 |
+
_af("margin", "Margin $", "currency", "sale.order.margin", "margin", "num", "sum"),
|
| 339 |
+
_af("margin_percent", "Margin %", "pct", "sale.order.margin_percent", "margin_percent",
|
| 340 |
+
"pct"),
|
| 341 |
+
_af("terms", "Terms and conditions", "text", "sale.order.note", "note", "html"),
|
| 342 |
+
_af("online_payment_basis", "Online payment basis", "text",
|
| 343 |
+
"sale.order.online_payment_based_on", "online_payment_based_on"),
|
| 344 |
+
_af("invoice_address", "Invoice address", "text", "sale.order.partner_invoice_id",
|
| 345 |
+
"partner_invoice_name"),
|
| 346 |
+
_af("delivery_address", "Delivery address", "text", "sale.order.partner_shipping_id",
|
| 347 |
+
"partner_shipping_name"),
|
| 348 |
+
_af("payment_terms", "Payment terms", "text", "sale.order.payment_term_id",
|
| 349 |
+
"payment_term_name"),
|
| 350 |
+
_af("shipping_policy", "Shipping policy", "text", "sale.order.picking_policy",
|
| 351 |
+
"picking_policy"),
|
| 352 |
+
_af("procurement_group", "Procurement group", "text", "sale.order.procurement_group_id",
|
| 353 |
+
"procurement_group_name"),
|
| 354 |
+
_af("recompute_delivery", "Recompute delivery cost", "checkbox",
|
| 355 |
+
"sale.order.recompute_delivery_price", "recompute_delivery_price", "flag"),
|
| 356 |
+
_af("online_signature", "Online signature", "checkbox", "sale.order.require_signature",
|
| 357 |
+
"require_signature", "flag"),
|
| 358 |
+
_af("salesperson", "Salesperson", "text", "sale.order.user_id", "user_name"),
|
| 359 |
+
_af("warehouse", "Warehouse", "text", "sale.order.warehouse_id", "warehouse_name"),
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
_ORDER_LINE_AUDIT = (
|
| 363 |
+
_af("commission_free", "Commission free", "checkbox", "sale.order.line.commission_free",
|
| 364 |
+
"sol.commission_free", "flag"),
|
| 365 |
+
_af("created_on", "Created on", "date", "sale.order.line.create_date", "sol.create_date",
|
| 366 |
+
"date"),
|
| 367 |
+
_af("lead_days", "Lead time days", "int", "sale.order.line.customer_lead",
|
| 368 |
+
"sol.customer_lead", "num"),
|
| 369 |
+
_af("invoice_status", "Invoice status", "text", "sale.order.line.invoice_status",
|
| 370 |
+
"sol.invoice_status"),
|
| 371 |
+
_af("delivery_line", "Delivery line", "checkbox", "sale.order.line.is_delivery",
|
| 372 |
+
"sol.is_delivery", "flag"),
|
| 373 |
+
_af("margin_percent", "Margin %", "pct", "sale.order.line.margin_percent",
|
| 374 |
+
"sol.margin_percent", "pct"),
|
| 375 |
+
_af("description", "Description", "text", "sale.order.line.name", "sol.name"),
|
| 376 |
+
_af("packaging_price", "Packaging price", "currency", "sale.order.line.packaging_price",
|
| 377 |
+
"sol.packaging_price", "num"),
|
| 378 |
+
_af("price_reduce", "Discounted unit price", "currency", "sale.order.line.price_reduce",
|
| 379 |
+
"sol.price_reduce", "num"),
|
| 380 |
+
_af("price_reduce_taxexcl", "Discounted unit price before tax", "currency",
|
| 381 |
+
"sale.order.line.price_reduce_taxexcl", "sol.price_reduce_taxexcl", "num"),
|
| 382 |
+
_af("price_reduce_taxinc", "Discounted unit price with tax", "currency",
|
| 383 |
+
"sale.order.line.price_reduce_taxinc", "sol.price_reduce_taxinc", "num"),
|
| 384 |
+
_af("price_total", "Line total with tax", "currency", "sale.order.line.price_total",
|
| 385 |
+
"sol.price_total", "num", "sum"),
|
| 386 |
+
_af("price_unit", "Unit price", "currency", "sale.order.line.price_unit", "sol.price_unit",
|
| 387 |
+
"num"),
|
| 388 |
+
_af("packaging", "Packaging", "text", "sale.order.line.product_packaging_id",
|
| 389 |
+
"sol.product_packaging_name"),
|
| 390 |
+
_af("packaging_qty", "Packaging quantity", "int", "sale.order.line.product_packaging_qty",
|
| 391 |
+
"sol.product_packaging_qty", "num", "sum"),
|
| 392 |
+
_af("uom", "Unit of measure", "text", "sale.order.line.product_uom", "sol.product_uom_name"),
|
| 393 |
+
_af("qty_delivered", "Delivered quantity", "int", "sale.order.line.qty_delivered",
|
| 394 |
+
"sol.qty_delivered", "num", "sum"),
|
| 395 |
+
_af("delivered_qty_method", "Delivered quantity method", "text",
|
| 396 |
+
"sale.order.line.qty_delivered_method", "sol.qty_delivered_method"),
|
| 397 |
+
_af("qty_invoiced", "Invoiced quantity", "int", "sale.order.line.qty_invoiced",
|
| 398 |
+
"sol.qty_invoiced", "num", "sum"),
|
| 399 |
+
_af("qty_to_invoice", "Quantity to invoice", "int", "sale.order.line.qty_to_invoice",
|
| 400 |
+
"sol.qty_to_invoice", "num", "sum"),
|
| 401 |
+
_af("salesperson", "Salesperson", "text", "sale.order.line.salesman_id",
|
| 402 |
+
"sol.salesman_name"),
|
| 403 |
+
_af("untaxed_invoiced", "Untaxed invoiced", "currency",
|
| 404 |
+
"sale.order.line.untaxed_amount_invoiced", "sol.untaxed_amount_invoiced", "num", "sum"),
|
| 405 |
+
_af("untaxed_to_invoice", "Untaxed to invoice", "currency",
|
| 406 |
+
"sale.order.line.untaxed_amount_to_invoice", "sol.untaxed_amount_to_invoice", "num",
|
| 407 |
+
"sum"),
|
| 408 |
+
_af("untaxed_to_invoice_credit", "Untaxed to invoice for credit limit", "currency",
|
| 409 |
+
"sale.order.line.untaxed_amount_to_invoice_credit_limit",
|
| 410 |
+
"sol.untaxed_amount_to_invoice_credit_limit", "num", "sum"),
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
_VENDOR_AUDIT = (
|
| 414 |
+
_af("notes", "Notes", "text", "res.partner.comment", "p.comment", "html"),
|
| 415 |
+
_af("company_name", "Company name", "text", "res.partner.commercial_company_name",
|
| 416 |
+
"p.commercial_company_name"),
|
| 417 |
+
_af("commercial_partner", "Commercial entity", "text", "res.partner.commercial_partner_id",
|
| 418 |
+
"p.commercial_partner_name"),
|
| 419 |
+
_af("customer_rank", "Customer rank", "int", "res.partner.customer_rank", "p.customer_rank",
|
| 420 |
+
"int"),
|
| 421 |
+
_af("dba", "Doing business as", "text", "res.partner.dba_id", "p.dba_name"),
|
| 422 |
+
_af("invoice_age_limit", "Invoice age limit on", "checkbox",
|
| 423 |
+
"res.partner.enable_max_invoice_age", "p.enable_max_invoice_age", "flag"),
|
| 424 |
+
_af("reminders", "Reminders", "text", "res.partner.followup_reminder_type",
|
| 425 |
+
"p.followup_reminder_type"),
|
| 426 |
+
_af("is_company", "Company", "checkbox", "res.partner.is_company", "p.is_company", "flag"),
|
| 427 |
+
_af("max_invoice_age", "Max invoice age", "int", "res.partner.max_invoice_age",
|
| 428 |
+
"p.max_invoice_age", "int"),
|
| 429 |
+
_af("online_payment", "Online payment", "checkbox", "res.partner.online_payment",
|
| 430 |
+
"p.online_payment", "flag"),
|
| 431 |
+
_af("parent_company", "Related company", "text", "res.partner.parent_id", "p.parent_name"),
|
| 432 |
+
_af("sales_warning", "Sales warning", "text", "res.partner.sale_warn", "p.sale_warn"),
|
| 433 |
+
_af("supplier_rank", "Supplier rank", "int", "res.partner.supplier_rank", "p.supplier_rank",
|
| 434 |
+
"int"),
|
| 435 |
+
_af("sales_team", "Sales team", "text", "res.partner.team_id", "p.team_name"),
|
| 436 |
+
_af("address_type", "Address type", "text", "res.partner.type", "p.type"),
|
| 437 |
+
_af("timezone", "Timezone", "text", "res.partner.tz", "p.tz"),
|
| 438 |
+
_af("hubspot_company_id", "HubSpot company ID", "text", "res.partner.x_hubspot_company_id",
|
| 439 |
+
"p.x_hubspot_company_id"),
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
_SHIPMENT_AUDIT = (
|
| 443 |
+
_af("delivery_barcodes", "Delivery barcodes", "text",
|
| 444 |
+
"stock.picking.antsroute_delivery_barcodes", "sp.antsroute_delivery_barcodes"),
|
| 445 |
+
_af("delivery_comment", "Delivery comment", "text",
|
| 446 |
+
"stock.picking.antsroute_delivery_comment", "sp.antsroute_delivery_comment"),
|
| 447 |
+
_af("delivered_on", "Delivered on", "date", "stock.picking.antsroute_delivery_date",
|
| 448 |
+
"sp.antsroute_delivery_date", "date"),
|
| 449 |
+
_af("driver", "Driver", "text", "stock.picking.antsroute_delivery_driver",
|
| 450 |
+
"sp.antsroute_delivery_driver"),
|
| 451 |
+
_af("delivery_result", "Delivery status", "text", "stock.picking.antsroute_delivery_status",
|
| 452 |
+
"sp.antsroute_delivery_status"),
|
| 453 |
+
_af("vehicle_plate", "Vehicle plate", "text",
|
| 454 |
+
"stock.picking.antsroute_delivery_vehicle_plate", "sp.antsroute_delivery_vehicle_plate"),
|
| 455 |
+
_af("delivery_photos", "Delivery photos", "int", "stock.picking.antsroute_nb_delivery_photo",
|
| 456 |
+
"sp.antsroute_nb_delivery_photo", "int"),
|
| 457 |
+
_af("shipping_value", "Shipping value", "currency", "stock.picking.antsroute_shipping_value",
|
| 458 |
+
"sp.antsroute_shipping_value", "num", "sum"),
|
| 459 |
+
_af("backorder_of", "Backorder of", "text", "stock.picking.backorder_id",
|
| 460 |
+
"sp.backorder_name"),
|
| 461 |
+
_af("carrier", "Carrier", "text", "stock.picking.carrier_id", "sp.carrier_name"),
|
| 462 |
+
_af("created_on", "Created on", "date", "stock.picking.create_date", "sp.create_date", "date"),
|
| 463 |
+
_af("currency", "Currency", "text", "stock.picking.currency_id", "sp.currency_name"),
|
| 464 |
+
_af("picking_date", "Picking date", "date", "stock.picking.date", "sp.date", "date"),
|
| 465 |
+
_af("deadline", "Deadline", "date", "stock.picking.date_deadline", "sp.date_deadline", "date"),
|
| 466 |
+
_af("procurement_group", "Procurement group", "text", "stock.picking.group_id",
|
| 467 |
+
"sp.group_name"),
|
| 468 |
+
_af("locked", "Locked", "checkbox", "stock.picking.is_locked", "sp.is_locked", "flag"),
|
| 469 |
+
_af("destination_location", "Destination location", "text", "stock.picking.location_dest_id",
|
| 470 |
+
"sp.location_dest_name"),
|
| 471 |
+
_af("source_location", "Source location", "text", "stock.picking.location_id",
|
| 472 |
+
"sp.location_name"),
|
| 473 |
+
_af("shipping_policy", "Shipping policy", "text", "stock.picking.move_type", "sp.move_type"),
|
| 474 |
+
_af("operation_type", "Operation type", "text", "stock.picking.picking_type_id",
|
| 475 |
+
"sp.picking_type_name"),
|
| 476 |
+
_af("priority", "Priority", "text", "stock.picking.priority", "sp.priority"),
|
| 477 |
+
_af("sent_to_carrier", "Sent to carrier", "date", "stock.picking.sent_to_carrier",
|
| 478 |
+
"sp.sent_to_carrier", "date"),
|
| 479 |
+
_af("uses_antsroute", "Uses AntsRoute", "checkbox", "stock.picking.use_antsroute",
|
| 480 |
+
"sp.use_antsroute", "flag"),
|
| 481 |
+
_af("responsible", "Responsible", "text", "stock.picking.user_id", "sp.user_name"),
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
_STOCK_MOVE_AUDIT = (
|
| 485 |
+
_af("created_on", "Created on", "date", "stock.move.create_date", "sm.create_date", "date"),
|
| 486 |
+
_af("deadline", "Deadline", "date", "stock.move.date_deadline", "sm.date_deadline", "date"),
|
| 487 |
+
_af("picking_description", "Picking description", "text", "stock.move.description_picking",
|
| 488 |
+
"sm.description_picking"),
|
| 489 |
+
_af("fulfillment_status", "Fulfillment status", "text", "stock.move.fulfillment_status_id",
|
| 490 |
+
"sm.fulfillment_status_name"),
|
| 491 |
+
_af("procurement_group", "Procurement group", "text", "stock.move.group_id", "sm.group_name"),
|
| 492 |
+
_af("inventory_adjustment", "Inventory adjustment", "checkbox", "stock.move.is_inventory",
|
| 493 |
+
"sm.is_inventory", "flag"),
|
| 494 |
+
_af("source_document", "Source document", "text", "stock.move.origin", "sm.origin"),
|
| 495 |
+
_af("destination_address", "Destination address", "text", "stock.move.partner_id",
|
| 496 |
+
"sm.partner_name"),
|
| 497 |
+
_af("operation_type", "Operation type", "text", "stock.move.picking_type_id",
|
| 498 |
+
"sm.picking_type_name"),
|
| 499 |
+
_af("priority", "Priority", "text", "stock.move.priority", "sm.priority"),
|
| 500 |
+
_af("supply_method", "Supply method", "text", "stock.move.procure_method",
|
| 501 |
+
"sm.procure_method"),
|
| 502 |
+
_af("packaging", "Packaging", "text", "stock.move.product_packaging_id",
|
| 503 |
+
"sm.product_packaging_name"),
|
| 504 |
+
_af("real_qty", "Quantity in product units", "int", "stock.move.product_qty",
|
| 505 |
+
"sm.product_qty", "num", "sum"),
|
| 506 |
+
_af("demand_qty", "Demand", "int", "stock.move.product_uom_qty", "sm.product_uom_qty", "num",
|
| 507 |
+
"sum"),
|
| 508 |
+
_af("propagate_cancel", "Propagate cancel", "checkbox", "stock.move.propagate_cancel",
|
| 509 |
+
"sm.propagate_cancel", "flag"),
|
| 510 |
+
_af("reference", "Reference", "text", "stock.move.reference", "sm.reference"),
|
| 511 |
+
_af("reserve_on", "Reserve on", "date", "stock.move.reservation_date", "sm.reservation_date",
|
| 512 |
+
"date"),
|
| 513 |
+
_af("stock_rule", "Stock rule", "text", "stock.move.rule_id", "sm.rule_name"),
|
| 514 |
+
_af("sale_line", "Sale line", "text", "stock.move.sale_line_id", "sm.sale_line_name"),
|
| 515 |
+
_af("warehouse", "Warehouse", "text", "stock.move.warehouse_id", "sm.warehouse_name"),
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
_STOCK_VALUATION_AUDIT = (
|
| 519 |
+
_af("journal_entry", "Journal entry", "text", "stock.valuation.layer.account_move_id",
|
| 520 |
+
"svl.account_move_name"),
|
| 521 |
+
_af("description", "Description", "text", "stock.valuation.layer.description",
|
| 522 |
+
"svl.description"),
|
| 523 |
+
_af("unit_cost", "Unit value", "currency", "stock.valuation.layer.unit_cost",
|
| 524 |
+
"svl.unit_cost", "num"),
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
#: `stock.location` has no database of its own. A quant names one location, so its fields land
|
| 528 |
+
#: here through the grid's `sl` join.
|
| 529 |
+
_STOCK_QUANT_AUDIT = (
|
| 530 |
+
_af("created_on", "Created on", "date", "stock.quant.create_date", "sq.create_date", "date"),
|
| 531 |
+
_af("incoming_date", "Incoming date", "date", "stock.quant.in_date", "sq.in_date", "date"),
|
| 532 |
+
_af("count_date", "Scheduled count date", "date", "stock.quant.inventory_date",
|
| 533 |
+
"sq.inventory_date", "date"),
|
| 534 |
+
_af("count_difference", "Count difference", "int", "stock.quant.inventory_diff_quantity",
|
| 535 |
+
"sq.inventory_diff_quantity", "num", "sum"),
|
| 536 |
+
_af("package", "Package", "text", "stock.quant.package_id", "sq.package_name"),
|
| 537 |
+
_af("warehouse", "Warehouse", "text", "stock.quant.warehouse_id", "sq.warehouse_name"),
|
| 538 |
+
_af("custom_warehouse", "Custom warehouse", "text", "stock.quant.x_warehouse_id",
|
| 539 |
+
"sq.x_warehouse_name"),
|
| 540 |
+
_af("location_active", "Location active", "checkbox", "stock.location.active", "sl.active",
|
| 541 |
+
"flag"),
|
| 542 |
+
_af("location_barcode", "Location barcode", "text", "stock.location.barcode", "sl.barcode"),
|
| 543 |
+
_af("location_company", "Location company", "text", "stock.location.company_id",
|
| 544 |
+
"sl.company_name"),
|
| 545 |
+
_af("location_created_on", "Location created on", "date", "stock.location.create_date",
|
| 546 |
+
"sl.create_date", "date"),
|
| 547 |
+
_af("location_last_count", "Location last counted", "date",
|
| 548 |
+
"stock.location.last_inventory_date", "sl.last_inventory_date", "date"),
|
| 549 |
+
_af("parent_location", "Parent location", "text", "stock.location.location_id",
|
| 550 |
+
"sl.location_name"),
|
| 551 |
+
_af("location_name", "Location short name", "text", "stock.location.name", "sl.name"),
|
| 552 |
+
_af("location_warehouse", "Location warehouse", "text", "stock.location.warehouse_id",
|
| 553 |
+
"sl.warehouse_name"),
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
#: Grid key -> audited columns. Purchasing declares its own in `odoo_purchasing`.
|
| 557 |
+
AUDIT_FIELDS = {
|
| 558 |
+
INVOICES_KEY: _INVOICE_AUDIT, BILLS_KEY: _BILL_AUDIT, GL_LINES_KEY: _GL_LINE_AUDIT,
|
| 559 |
+
ACCOUNTS_KEY: _ACCOUNT_AUDIT, ORDERS_KEY: _ORDER_AUDIT, ORDER_LINES_KEY: _ORDER_LINE_AUDIT,
|
| 560 |
+
VENDORS_KEY: _VENDOR_AUDIT, SHIPMENTS_KEY: _SHIPMENT_AUDIT,
|
| 561 |
+
STOCK_MOVES_KEY: _STOCK_MOVE_AUDIT, STOCK_VALUATION_KEY: _STOCK_VALUATION_AUDIT,
|
| 562 |
+
STOCK_QUANT_KEY: _STOCK_QUANT_AUDIT,
|
| 563 |
+
}
|
| 564 |
+
AUDIT_M2M_TABLES = {
|
| 565 |
+
'account.account.tag_ids': 'account_account_tag',
|
| 566 |
+
'sale.order.fulfillment_status_ids': 'fulfillment_status',
|
| 567 |
+
'stock.picking.fulfillment_status_ids': 'fulfillment_status',
|
| 568 |
+
}
|
| 569 |
+
for _key, _entry in (
|
| 570 |
+
(ACCOUNTS_KEY, _af('account_tags', 'Account tags', 'text', 'account.account.tag_ids',
|
| 571 |
+
'tag_ids', 'm2m_names')),
|
| 572 |
+
(ORDERS_KEY, _af('fulfillment_statuses', 'Fulfillment statuses', 'text',
|
| 573 |
+
'sale.order.fulfillment_status_ids', 'so.fulfillment_status_ids', 'm2m_names')),
|
| 574 |
+
(SHIPMENTS_KEY, _af('fulfillment_statuses', 'Fulfillment statuses', 'text',
|
| 575 |
+
'stock.picking.fulfillment_status_ids', 'sp.fulfillment_status_ids', 'm2m_names')),
|
| 576 |
+
):
|
| 577 |
+
AUDIT_FIELDS[_key] += (_entry,)
|
| 578 |
+
|
| 579 |
+
#: Audit add rows that no database shows yet, with the cause. Standing rule 1: reported.
|
| 580 |
+
AUDIT_NOT_LANDED = {}
|
| 581 |
+
|
| 582 |
+
#: Odoo model -> mirror entity, for the audited columns.
|
| 583 |
+
AUDIT_ENTITY = {
|
| 584 |
+
"account.move": "account_move", "account.move.line": "account_move_line",
|
| 585 |
+
"account.invoice.line.agent": "account_invoice_line_agent",
|
| 586 |
+
"account.account": "account_account", "sale.order": "sale_order",
|
| 587 |
+
"sale.order.line": "sale_order_line", "res.partner": "res_partner",
|
| 588 |
+
"stock.picking": "stock_picking", "stock.move": "stock_move",
|
| 589 |
+
"stock.location": "stock_location", "stock.valuation.layer": "stock_valuation_layer",
|
| 590 |
+
"stock.quant": "stock_quant", "purchase.order": "purchase_order",
|
| 591 |
+
"purchase.order.line": "purchase_order_line",
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _audit_entries(key=None):
|
| 596 |
+
"""Every audited entry, relational and purchasing, optionally for one grid key."""
|
| 597 |
+
from odoo_purchasing import AUDIT_FIELDS as purchasing
|
| 598 |
+
table = {**AUDIT_FIELDS, **purchasing}
|
| 599 |
+
if key is not None:
|
| 600 |
+
return tuple(table.get(base_table_key(key), ()))
|
| 601 |
+
return table
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def _audit_split(odoo):
|
| 605 |
+
"""`model.field` -> (model, field). The field never holds a dot."""
|
| 606 |
+
model, _, field = odoo.rpartition(".")
|
| 607 |
+
return model, field
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def audit_fields(key):
|
| 611 |
+
"""The audited presets one grid adds. Hidden by default, one click away in the picker."""
|
| 612 |
+
out = []
|
| 613 |
+
for entry in _audit_entries(key):
|
| 614 |
+
field = {"key": entry["key"], "label": entry["label"], "type": entry["type"],
|
| 615 |
+
"source": "overlay", "default": False}
|
| 616 |
+
if entry.get("agg"):
|
| 617 |
+
field["agg"] = entry["agg"]
|
| 618 |
+
if entry.get("desc"):
|
| 619 |
+
field["description"] = entry["desc"]
|
| 620 |
+
out.append(_preset(field))
|
| 621 |
+
return out
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def audit_projection(entry):
|
| 625 |
+
"""(sql, cast, dependency) for one entry. `dependency` is (alias or table, column) for a
|
| 626 |
+
computed expression, which `_degrade` cannot check, and None for a bare column."""
|
| 627 |
+
how, ref = entry["how"], entry["ref"]
|
| 628 |
+
alias, _, col = ref.rpartition(".")
|
| 629 |
+
cast = _AUDIT_CASTS[how]
|
| 630 |
+
if how == 'm2m_names':
|
| 631 |
+
table = AUDIT_M2M_TABLES[entry['odoo']]
|
| 632 |
+
# A missing linked name makes the cell unknown; neither IDs nor a partial set
|
| 633 |
+
# pretend to be a complete name list. Empty relations naturally stay blank.
|
| 634 |
+
sql = (f"(SELECT CASE WHEN count(*) = count(NULLIF(trim(n.name), '')) "
|
| 635 |
+
f"THEN string_agg(DISTINCT n.name, ', ' ORDER BY n.name) ELSE NULL END "
|
| 636 |
+
f"FROM json_each({ref}) j LEFT JOIN {table} n "
|
| 637 |
+
f"ON n.id = TRY_CAST(j.value AS BIGINT))")
|
| 638 |
+
return sql, cast, (alias, col)
|
| 639 |
+
if how in _AUDIT_AGENT_SQL:
|
| 640 |
+
return _AUDIT_AGENT_SQL[how].format(c=col), cast, ("account_invoice_line_agent", col)
|
| 641 |
+
if how == "pct":
|
| 642 |
+
return f"ROUND({ref} * 100, 2)", cast, (alias, col)
|
| 643 |
+
return ref, cast, None
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def merge_audit_cols(sources):
|
| 647 |
+
"""GRID_SOURCES with the audited columns merged in. Pure: input specs are not mutated.
|
| 648 |
+
|
| 649 |
+
A computed column also gains an `optional` entry, so a mirror that lacks its column serves
|
| 650 |
+
a blank cell rather than a Binder error. Idempotent: a merged spec merges to itself.
|
| 651 |
+
"""
|
| 652 |
+
out = dict(sources or {})
|
| 653 |
+
for key, spec in list(out.items()):
|
| 654 |
+
entries = _audit_entries(key) if isinstance(spec, dict) and "cols" in spec else ()
|
| 655 |
+
if not entries:
|
| 656 |
+
continue
|
| 657 |
+
aliases = dict(spec.get("tables") or {})
|
| 658 |
+
if spec.get("table"):
|
| 659 |
+
aliases.setdefault("", spec["table"])
|
| 660 |
+
cols = dict(spec["cols"])
|
| 661 |
+
optional = list(spec.get("optional") or ())
|
| 662 |
+
for entry in entries:
|
| 663 |
+
if entry["key"] in cols:
|
| 664 |
+
continue
|
| 665 |
+
sql, cast, dep = audit_projection(entry)
|
| 666 |
+
cols[entry["key"]] = (sql, cast)
|
| 667 |
+
if dep is not None:
|
| 668 |
+
need = (aliases.get(dep[0], dep[0]), dep[1])
|
| 669 |
+
needs = (need,)
|
| 670 |
+
if entry['how'] == 'm2m_names':
|
| 671 |
+
table = AUDIT_M2M_TABLES[entry['odoo']]
|
| 672 |
+
needs += ((table, 'id'), (table, 'name'))
|
| 673 |
+
for requirement in needs:
|
| 674 |
+
degrade = {"absent": (requirement,),
|
| 675 |
+
"without": {"cols": {entry["key"]: ("NULL", cast)}}}
|
| 676 |
+
if degrade not in optional:
|
| 677 |
+
optional.append(degrade)
|
| 678 |
+
merged = {**spec, "cols": cols}
|
| 679 |
+
if optional:
|
| 680 |
+
merged["optional"] = tuple(optional)
|
| 681 |
+
out[key] = merged
|
| 682 |
+
return out
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
#: Materialised grids read their audited columns beside their reader's own SQL.
|
| 686 |
+
#: key -> (FROM, alias, id column, WHERE). The WHERE matches the reader's population.
|
| 687 |
+
def _audit_materialised(key):
|
| 688 |
+
return {
|
| 689 |
+
VENDORS_KEY: ("res_partner p", "p", "p.id",
|
| 690 |
+
f"p.id IN (SELECT partner_id FROM account_move WHERE {_VENDOR_DOCS} "
|
| 691 |
+
"AND partner_id IS NOT NULL)"),
|
| 692 |
+
BILLS_KEY: ("account_move", "", "id", f"{_VENDOR_DOCS} AND partner_id IS NOT NULL"),
|
| 693 |
+
ACCOUNTS_KEY: ("account_account", "", "id", ""),
|
| 694 |
+
}.get(key)
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
def _audit_enrich(cur, key, rows):
|
| 698 |
+
"""Add the audited columns to a materialised reader's rows. A column the mirror lacks reads
|
| 699 |
+
blank. No query runs when the mirror has none of them."""
|
| 700 |
+
shape = _audit_materialised(key)
|
| 701 |
+
entries = _audit_entries(key)
|
| 702 |
+
if not shape or not entries or not rows:
|
| 703 |
+
return rows
|
| 704 |
+
frm, alias, id_col, where = shape
|
| 705 |
+
have = columns(cur, frm.split()[0])
|
| 706 |
+
exprs, present = [], False
|
| 707 |
+
for entry in entries:
|
| 708 |
+
sql, cast, _dep = audit_projection(entry)
|
| 709 |
+
col = entry["ref"].rpartition(".")[2]
|
| 710 |
+
naming = AUDIT_M2M_TABLES.get(entry['odoo'])
|
| 711 |
+
if col.lower() in have and (not naming or {'id', 'name'} <= columns(cur, naming)):
|
| 712 |
+
exprs.append(sql)
|
| 713 |
+
present = True
|
| 714 |
+
else:
|
| 715 |
+
exprs.append("NULL")
|
| 716 |
+
values = {}
|
| 717 |
+
if present:
|
| 718 |
+
sql = (f"SELECT {id_col} AS audit_row_id, {', '.join(exprs)} FROM {frm}"
|
| 719 |
+
+ (f" WHERE {where}" if where else ""))
|
| 720 |
+
values = {str(r[0]): r[1:] for r in cur.execute(sql).fetchall()}
|
| 721 |
+
for row in rows:
|
| 722 |
+
got = values.get(str(row.get("_id")), (None,) * len(entries))
|
| 723 |
+
for entry, value in zip(entries, got):
|
| 724 |
+
row[entry["key"]] = _AUDIT_CASTS[entry["how"]](value)
|
| 725 |
+
return rows
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def audit_mirror_types():
|
| 729 |
+
"""{"bool"|"int"|"numeric": sorted Odoo field names} the mirror must type."""
|
| 730 |
+
kinds = {"flag": "bool", "agent_all": "bool", "int": "int", "num": "numeric",
|
| 731 |
+
"pct": "numeric", "agent_sum": "numeric"}
|
| 732 |
+
out = {"bool": set(), "int": set(), "numeric": set()}
|
| 733 |
+
for entries in _audit_entries().values():
|
| 734 |
+
for entry in entries:
|
| 735 |
+
kind = kinds.get(entry["how"])
|
| 736 |
+
if kind:
|
| 737 |
+
out[kind].add(_audit_split(entry["odoo"])[1])
|
| 738 |
+
return {kind: sorted(names) for kind, names in out.items()}
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def audit_mirror_additions():
|
| 742 |
+
"""{entity: [Odoo field, ...]} in declaration order: the fields the audited columns read."""
|
| 743 |
+
out = {}
|
| 744 |
+
for entries in _audit_entries().values():
|
| 745 |
+
for entry in entries:
|
| 746 |
+
if entry['how'] == 'm2m_names':
|
| 747 |
+
continue
|
| 748 |
+
model, field = _audit_split(entry["odoo"])
|
| 749 |
+
names = out.setdefault(AUDIT_ENTITY[model], [])
|
| 750 |
+
if field not in names:
|
| 751 |
+
names.append(field)
|
| 752 |
+
return out
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
def audit_mirror_entity(entity, base):
|
| 756 |
+
"""`base` (a `datastore.ENTITIES` spec) with the audited fields declared and backfilled."""
|
| 757 |
+
spec = {**base, "fields": list(base["fields"])}
|
| 758 |
+
added = [f for f in audit_mirror_additions().get(entity, ()) if f not in spec["fields"]]
|
| 759 |
+
if not added:
|
| 760 |
+
return dict(base)
|
| 761 |
+
tail = ["write_date"] if "write_date" in spec["fields"] else []
|
| 762 |
+
spec["fields"] = [f for f in spec["fields"] if f != "write_date"] + added + tail
|
| 763 |
+
backfill = list(base.get("backfill_fields") or [])
|
| 764 |
+
spec["backfill_fields"] = backfill + [f for f in added if f not in backfill]
|
| 765 |
+
return spec
|
| 766 |
+
|
| 767 |
+
|
| 768 |
def shipment_fields():
|
| 769 |
"""Outgoing pickings, with elapsed delivery time measured at actual completion."""
|
| 770 |
return [_preset({"source": "overlay", **field}) for field in (
|
|
|
|
| 790 |
"default": True, "description": "Elapsed days from the sale order date to the actual "
|
| 791 |
"shipment completion. Blank when either date is missing."},
|
| 792 |
_refreshed_field(),
|
| 793 |
+
)] + audit_fields(SHIPMENTS_KEY)
|
| 794 |
|
| 795 |
|
| 796 |
def agent_fields():
|
|
|
|
| 862 |
"description": "Ticked for the expense family - the same predicate the semantic layer's "
|
| 863 |
"gl_lines topic uses, so this column and that topic cannot disagree."},
|
| 864 |
_refreshed_field(),
|
| 865 |
+
)] + audit_fields(ACCOUNTS_KEY)
|
| 866 |
|
| 867 |
|
| 868 |
def vendor_fields():
|
|
|
|
| 911 |
{"key": "bills", "label": "Bills", "type": "link", "source": "overlay", "default": True,
|
| 912 |
"link": {"table": BILLS_KEY, "on": VENDOR_JOIN_KEY, "from": VENDOR_JOIN_KEY}},
|
| 913 |
_refreshed_field(),
|
| 914 |
+
)] + audit_fields(VENDORS_KEY)
|
| 915 |
|
| 916 |
|
| 917 |
def bill_fields():
|
|
|
|
| 949 |
"default": False,
|
| 950 |
"link": {"table": VENDORS_KEY, "on": VENDOR_JOIN_KEY, "from": VENDOR_JOIN_KEY}},
|
| 951 |
_refreshed_field(),
|
| 952 |
+
)] + audit_fields(BILLS_KEY)
|
| 953 |
|
| 954 |
|
| 955 |
def invoice_fields():
|
|
|
|
| 1096 |
"default": False,
|
| 1097 |
"link": {"table": ORDERS_KEY, "on": "order_no", "from": "origin_order"}},
|
| 1098 |
_refreshed_field(),
|
| 1099 |
+
)] + audit_fields(INVOICES_KEY)
|
| 1100 |
|
| 1101 |
|
| 1102 |
def order_fields():
|
|
|
|
| 1139 |
"default": True,
|
| 1140 |
"link": {"table": INVOICES_KEY, "on": "origin_order", "from": "order_no"}},
|
| 1141 |
_refreshed_field(),
|
| 1142 |
+
)] + audit_fields(ORDERS_KEY)
|
| 1143 |
|
| 1144 |
|
| 1145 |
# ═════════════════════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 1238 |
{"key": "state", "label": "State", "type": "select", "source": "overlay",
|
| 1239 |
"default": False, "options": ["sale", "done"]},
|
| 1240 |
_scope_field(),
|
| 1241 |
+
)] + audit_fields(ORDER_LINES_KEY)
|
| 1242 |
|
| 1243 |
|
| 1244 |
def gl_line_fields():
|
|
|
|
| 1305 |
{"key": "parent_state", "label": "Entry state", "type": "select", "source": "overlay",
|
| 1306 |
"default": True, "options": ["draft", "posted", "cancel"]},
|
| 1307 |
_scope_field(),
|
| 1308 |
+
)] + audit_fields(GL_LINES_KEY)
|
| 1309 |
|
| 1310 |
|
| 1311 |
def _stock_product_fields():
|
|
|
|
| 1343 |
{"key": "picking_id", "label": "Odoo picking id", "type": "int", "default": False}]
|
| 1344 |
+ _stock_location_fields("source_location", "Source location")
|
| 1345 |
+ _stock_location_fields("destination_location", "Destination location")
|
| 1346 |
+
)] + audit_fields(STOCK_MOVES_KEY)
|
| 1347 |
|
| 1348 |
|
| 1349 |
def stock_valuation_fields():
|
|
|
|
| 1357 |
{"key": "stock_move_id", "label": "Odoo stock move id", "type": "int", "default": False}]
|
| 1358 |
+ _stock_location_fields("source_location", "Source location")
|
| 1359 |
+ _stock_location_fields("destination_location", "Destination location")
|
| 1360 |
+
)] + audit_fields(STOCK_VALUATION_KEY)
|
| 1361 |
|
| 1362 |
|
| 1363 |
def stock_quant_fields():
|
|
|
|
| 1368 |
+ [{"key": "qty", "label": "On hand", "type": "int", "agg": "sum", "default": True},
|
| 1369 |
{"key": "reserved_qty", "label": "Reserved quantity", "type": "int",
|
| 1370 |
"agg": "sum", "default": True}]
|
| 1371 |
+
)] + audit_fields(STOCK_QUANT_KEY)
|
| 1372 |
|
| 1373 |
|
| 1374 |
def product_fields():
|
|
|
|
| 2395 |
"account_type": t,
|
| 2396 |
"is_expense": "1" if t in ("expense", "expense_depreciation") else "",
|
| 2397 |
})
|
| 2398 |
+
return _audit_enrich(cur, ACCOUNTS_KEY, out)
|
| 2399 |
|
| 2400 |
|
| 2401 |
_VENDOR_DOCS = "state = 'posted' AND move_type IN ('in_invoice','in_refund')"
|
|
|
|
| 2427 |
"payment_state": str(pay or ""),
|
| 2428 |
"move_type": str(mtype or ""),
|
| 2429 |
})
|
| 2430 |
+
return _audit_enrich(cur, BILLS_KEY, out)
|
| 2431 |
|
| 2432 |
|
| 2433 |
def read_vendors(cur):
|
|
|
|
| 2482 |
"city": str(city or ""),
|
| 2483 |
"zip": str(zipc or ""),
|
| 2484 |
})
|
| 2485 |
+
return _audit_enrich(cur, VENDORS_KEY, out)
|
| 2486 |
|
| 2487 |
|
| 2488 |
def customers_from(invoice_rows):
|
|
|
|
| 4005 |
**_stock_location_cols("source_location", "sl", "sm.location_id"),
|
| 4006 |
**_stock_location_cols("destination_location", "sd", "sm.location_dest_id"),
|
| 4007 |
}
|
| 4008 |
+
# S72-T43: the audited columns merge here, so the stock bindings and presets stay equal.
|
| 4009 |
+
return merge_audit_cols({
|
| 4010 |
STOCK_MOVES_KEY: {
|
| 4011 |
"from_sql": "(stock_move sm LEFT JOIN product_product pp ON pp.id = sm.product_id"
|
| 4012 |
+ locations + ")",
|
|
|
|
| 4037 |
"reserved_qty": ("sq.reserved_quantity", _stock_number)},
|
| 4038 |
"optional": ({**no_ancestry, "without": {"cols": {"location_fba": blank_fba}}},),
|
| 4039 |
},
|
| 4040 |
+
})
|
| 4041 |
|
| 4042 |
|
| 4043 |
def _stock_period(date_from, date_to, field):
|
|
|
|
| 4149 |
'error_type': type(exc).__name__}]
|
| 4150 |
|
| 4151 |
|
| 4152 |
+
_POSTED_OUT = [("state", "=", "posted"), ("move_type", "in", ["out_invoice", "out_refund"]),
|
| 4153 |
+
("partner_id", "!=", False)]
|
| 4154 |
+
_POSTED_IN = [("state", "=", "posted"), ("move_type", "in", ["in_invoice", "in_refund"]),
|
| 4155 |
+
("partner_id", "!=", False)]
|
| 4156 |
+
|
| 4157 |
+
#: S72-T43 total legs: grid key -> (model, population domain, Odoo date field, mirror date SQL,
|
| 4158 |
+
#: datetime?). The date bounds both sides to the validation period. Quants are a snapshot.
|
| 4159 |
+
_AUDIT_TOTAL_SCOPE = {
|
| 4160 |
+
INVOICES_KEY: ("account.move", _POSTED_OUT, "invoice_date", "am.invoice_date", False),
|
| 4161 |
+
BILLS_KEY: ("account.move", _POSTED_IN, "invoice_date", "invoice_date", False),
|
| 4162 |
+
ORDERS_KEY: ("sale.order", [("state", "in", ["sale", "done"]), ("partner_id", "!=", False)],
|
| 4163 |
+
"date_order", "date_order", True),
|
| 4164 |
+
ORDER_LINES_KEY: ("sale.order.line", [("order_id.state", "in", ["sale", "done"]),
|
| 4165 |
+
("order_id.partner_id", "!=", False)],
|
| 4166 |
+
"order_id.date_order", "so.date_order", True),
|
| 4167 |
+
GL_LINES_KEY: ("account.move.line", [], "date", "aml.date", False),
|
| 4168 |
+
SHIPMENTS_KEY: ("stock.picking", [("picking_type_code", "=", "outgoing")],
|
| 4169 |
+
"scheduled_date", "sp.scheduled_date", True),
|
| 4170 |
+
STOCK_MOVES_KEY: ("stock.move", [], "date", "sm.date", True),
|
| 4171 |
+
STOCK_QUANT_KEY: ("stock.quant", [("location_id.usage", "=", "internal")], None, None, False),
|
| 4172 |
+
}
|
| 4173 |
+
|
| 4174 |
+
#: A total read from a child model reaches the grid's population through this many2one.
|
| 4175 |
+
_AUDIT_PARENT = {"account.invoice.line.agent": "invoice_id"}
|
| 4176 |
+
|
| 4177 |
+
|
| 4178 |
+
def validate_audit_totals(client, cur, date_from="2025-07-01", date_to="2026-06-30",
|
| 4179 |
+
id_window=None, keys=None):
|
| 4180 |
+
"""S72-T43 / rule 8: every audited total ties its mirror sum to an Odoo read_group sum.
|
| 4181 |
+
|
| 4182 |
+
`id_window` (lo, hi) narrows both sides to one id range of the grid's own row id, and `keys`
|
| 4183 |
+
to some grids. Needs the mirror: without a cursor it returns no legs. Output carries no totals.
|
| 4184 |
+
"""
|
| 4185 |
+
import math
|
| 4186 |
+
if cur is None:
|
| 4187 |
+
return []
|
| 4188 |
+
import routes_odoo_tables as door
|
| 4189 |
+
checks = []
|
| 4190 |
+
for key, (model, domain, odoo_date, sql_date, stamp) in _AUDIT_TOTAL_SCOPE.items():
|
| 4191 |
+
if keys is not None and key not in keys:
|
| 4192 |
+
continue
|
| 4193 |
+
sums = [entry for entry in AUDIT_FIELDS[key] if entry.get("agg") == "sum"]
|
| 4194 |
+
lo, hi = ((date_from + " 00:00:00", date_to + " 23:59:59") if stamp
|
| 4195 |
+
else (date_from, date_to))
|
| 4196 |
+
for entry in sums:
|
| 4197 |
+
name = "audit total " + key + " " + entry["key"]
|
| 4198 |
+
try:
|
| 4199 |
+
spec = door._source_for(cur, key)
|
| 4200 |
+
if not spec:
|
| 4201 |
+
raise Refused("the mirror has no binding for " + key)
|
| 4202 |
+
expr = (spec["cols"].get(entry["key"]) or audit_projection(entry))[0]
|
| 4203 |
+
terms, params = [spec.get("where") or ""], []
|
| 4204 |
+
if odoo_date:
|
| 4205 |
+
terms.append(f"{sql_date} >= ? AND {sql_date} <= ?")
|
| 4206 |
+
params += [lo, hi]
|
| 4207 |
+
if id_window:
|
| 4208 |
+
terms.append(f"{spec['id']} >= ? AND {spec['id']} <= ?")
|
| 4209 |
+
params += list(id_window)
|
| 4210 |
+
where = " AND ".join("(" + t + ")" for t in terms if t)
|
| 4211 |
+
total = cur.execute(
|
| 4212 |
+
f"SELECT COALESCE(SUM({expr}), 0) FROM {spec.get('from_sql') or spec['table']}"
|
| 4213 |
+
+ (f" WHERE {where}" if where else ""), params).fetchone()[0]
|
| 4214 |
+
odoo_domain = list(domain) + ([(odoo_date, ">=", lo), (odoo_date, "<=", hi)]
|
| 4215 |
+
if odoo_date else [])
|
| 4216 |
+
odoo_domain += ([("id", ">=", id_window[0]), ("id", "<=", id_window[1])]
|
| 4217 |
+
if id_window else [])
|
| 4218 |
+
child, field = _audit_split(entry["odoo"])
|
| 4219 |
+
if child != model:
|
| 4220 |
+
parent = _AUDIT_PARENT[child]
|
| 4221 |
+
odoo_domain = [(parent if f == "id" else parent + "." + f, op, value)
|
| 4222 |
+
for f, op, value in odoo_domain]
|
| 4223 |
+
groups = client.read_group(child, odoo_domain, [field + ":sum"], ["create_uid"],
|
| 4224 |
+
lazy=False)
|
| 4225 |
+
summary = math.fsum(float(row.get(field) or 0.0) for row in groups)
|
| 4226 |
+
total = float(total or 0.0)
|
| 4227 |
+
error = abs(total - summary) / abs(summary) if summary else None
|
| 4228 |
+
checks.append({"check": name, "observation": "mirror", "relative_error": error,
|
| 4229 |
+
"ok": math.isfinite(total) and abs(total - summary) <= 0.01})
|
| 4230 |
+
except Exception as exc: # noqa: BLE001
|
| 4231 |
+
checks.append({"check": name, "ok": False, "error_type": type(exc).__name__,
|
| 4232 |
+
"observation": "mirror"})
|
| 4233 |
+
from odoo_purchasing import validate_audit_totals as purchasing_totals
|
| 4234 |
+
end = (_dt.date.fromisoformat(date_to) + _dt.timedelta(days=1)).isoformat()
|
| 4235 |
+
checks.extend(purchasing_totals(client, cur, date_from, end, id_window=id_window, keys=keys))
|
| 4236 |
+
return checks
|
| 4237 |
+
|
| 4238 |
+
|
| 4239 |
def validate(client, cur=None, date_from="2025-07-01", date_to="2026-06-30"):
|
| 4240 |
"""Read-only stock reconciliation, using the caller's own Odoo client and optional mirror.
|
| 4241 |
|
|
|
|
| 4339 |
"error_type": type(exc).__name__, "observation": plane})
|
| 4340 |
checks.extend(validate_customer_rollups(client, cur))
|
| 4341 |
checks.extend(validate_wholesale_summary(client, cur))
|
| 4342 |
+
checks.extend(validate_audit_totals(client, cur, date_from, date_to))
|
| 4343 |
return checks
|
| 4344 |
|
| 4345 |
|
api/provider_limits.py
CHANGED
|
@@ -3,7 +3,8 @@ import time
|
|
| 3 |
|
| 4 |
RETRY_WAITS = (20, 40, 60)
|
| 5 |
RESUMED_MESSAGE = "Loopy was paused by a provider limit and picked this up again."
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
class RetryStopped(Exception):
|
|
|
|
| 3 |
|
| 4 |
RETRY_WAITS = (20, 40, 60)
|
| 5 |
RESUMED_MESSAGE = "Loopy was paused by a provider limit and picked this up again."
|
| 6 |
+
#: The C2 `provider_limited` sentence: a limited provider pauses the turn and it resumes.
|
| 7 |
+
PAUSED_MESSAGE = "The model is busy. Your answer resumes shortly."
|
| 8 |
|
| 9 |
|
| 10 |
class RetryStopped(Exception):
|
api/providers.py
CHANGED
|
@@ -376,6 +376,13 @@ class LlmProvider:
|
|
| 376 |
#: which is a different body, a different auth header and a different result shape.
|
| 377 |
wire: str
|
| 378 |
caps: dict = field(default_factory=dict)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
|
| 380 |
def configured(self) -> bool:
|
| 381 |
return bool((os.environ.get(self.env) or "").strip())
|
|
@@ -385,10 +392,10 @@ class LlmProvider:
|
|
| 385 |
return bool(cap and cap.capable and self.configured())
|
| 386 |
|
| 387 |
|
| 388 |
-
#:
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
#:
|
| 392 |
LLM_PROVIDERS: dict[str, LlmProvider] = {
|
| 393 |
"anthropic": LlmProvider(
|
| 394 |
name="anthropic", label="Anthropic", env="ANTHROPIC_API_KEY",
|
|
@@ -461,7 +468,7 @@ LLM_PROVIDERS: dict[str, LlmProvider] = {
|
|
| 461 |
"openrouter": LlmProvider(
|
| 462 |
name="openrouter", label="OpenRouter", env="OPENROUTER_API_KEY",
|
| 463 |
url="https://openrouter.ai/api/v1/chat/completions",
|
| 464 |
-
model="
|
| 465 |
caps={
|
| 466 |
# ⭐ MEASURED 2026-08-19, W37-T39 (was "DECLARED, not measured"): HTTP 200 with a typed
|
| 467 |
# `tool_calls` block. So on the OpenAI wire BOTH reachable rungs tool-call cleanly, and
|
|
@@ -473,7 +480,8 @@ LLM_PROVIDERS: dict[str, LlmProvider] = {
|
|
| 473 |
}),
|
| 474 |
}
|
| 475 |
|
| 476 |
-
|
|
|
|
| 477 |
|
| 478 |
|
| 479 |
def mark_no_credit(name, seconds=None):
|
|
@@ -515,12 +523,11 @@ def llm_chain(capability="llm_tool_calling"):
|
|
| 515 |
turn cannot be spent discovering it (the `chain()` rule, one layer up).
|
| 516 |
2. `no_credit()` — R4's skip. A provider that told us its balance is empty is passed over
|
| 517 |
until the memo expires.
|
| 518 |
-
3. the ORDER itself
|
| 519 |
-
|
| 520 |
-
carries for the scraping side.
|
| 521 |
"""
|
| 522 |
raw = (os.environ.get("AIOS_LLM_ORDER") or "").strip()
|
| 523 |
-
names = [x.strip() for x in raw.split(",") if x.strip()] or list(LLM_DEFAULT_ORDER)
|
| 524 |
return [LLM_PROVIDERS[n] for n in names
|
| 525 |
if n in LLM_PROVIDERS and LLM_PROVIDERS[n].can(capability) and not no_credit(n)]
|
| 526 |
|
|
@@ -754,7 +761,7 @@ def llm_status(capability="llm_tool_calling"):
|
|
| 754 |
p = LLM_PROVIDERS[name]
|
| 755 |
cap = p.caps.get(capability)
|
| 756 |
rows.append({
|
| 757 |
-
"provider": p.name, "label": p.label, "model": p.
|
| 758 |
"configured": p.configured(),
|
| 759 |
"toolCalling": bool((p.caps.get("llm_tool_calling") or Capability(False)).capable),
|
| 760 |
"jsonMode": bool((p.caps.get("llm_json_mode") or Capability(False)).capable),
|
|
|
|
| 376 |
#: which is a different body, a different auth header and a different result shape.
|
| 377 |
wire: str
|
| 378 |
caps: dict = field(default_factory=dict)
|
| 379 |
+
#: Env var that overrides `model`, read at call time. Blank or unset uses `model`.
|
| 380 |
+
model_env: str = ""
|
| 381 |
+
|
| 382 |
+
def current_model(self) -> str:
|
| 383 |
+
"""The model id a call sends and an audit names: `model_env` when set, else `model`."""
|
| 384 |
+
override = (os.environ.get(self.model_env) or "").strip() if self.model_env else ""
|
| 385 |
+
return override or self.model
|
| 386 |
|
| 387 |
def configured(self) -> bool:
|
| 388 |
return bool((os.environ.get(self.env) or "").strip())
|
|
|
|
| 392 |
return bool(cap and cap.capable and self.configured())
|
| 393 |
|
| 394 |
|
| 395 |
+
#: The cheapest OpenRouter model that reached 17 of 26 on the assistant eval (S72-T21).
|
| 396 |
+
OPENROUTER_DEFAULT_MODEL = "z-ai/glm-4.7-flash"
|
| 397 |
+
|
| 398 |
+
#: Every declared provider. Only the names in `LLM_DEFAULT_ORDER` are ever called (R116).
|
| 399 |
LLM_PROVIDERS: dict[str, LlmProvider] = {
|
| 400 |
"anthropic": LlmProvider(
|
| 401 |
name="anthropic", label="Anthropic", env="ANTHROPIC_API_KEY",
|
|
|
|
| 468 |
"openrouter": LlmProvider(
|
| 469 |
name="openrouter", label="OpenRouter", env="OPENROUTER_API_KEY",
|
| 470 |
url="https://openrouter.ai/api/v1/chat/completions",
|
| 471 |
+
model=OPENROUTER_DEFAULT_MODEL, model_env="AIOS_OPENROUTER_MODEL", wire="openai",
|
| 472 |
caps={
|
| 473 |
# ⭐ MEASURED 2026-08-19, W37-T39 (was "DECLARED, not measured"): HTTP 200 with a typed
|
| 474 |
# `tool_calls` block. So on the OpenAI wire BOTH reachable rungs tool-call cleanly, and
|
|
|
|
| 480 |
}),
|
| 481 |
}
|
| 482 |
|
| 483 |
+
#: Every Assistant turn goes through OpenRouter and no other provider is called (R116).
|
| 484 |
+
LLM_DEFAULT_ORDER = ("openrouter",)
|
| 485 |
|
| 486 |
|
| 487 |
def mark_no_credit(name, seconds=None):
|
|
|
|
| 523 |
turn cannot be spent discovering it (the `chain()` rule, one layer up).
|
| 524 |
2. `no_credit()` — R4's skip. A provider that told us its balance is empty is passed over
|
| 525 |
until the memo expires.
|
| 526 |
+
3. the ORDER itself. `AIOS_LLM_ORDER` may reorder or drop names in `LLM_DEFAULT_ORDER`
|
| 527 |
+
and never adds one, so an env value cannot bring a retired provider back (R116).
|
|
|
|
| 528 |
"""
|
| 529 |
raw = (os.environ.get("AIOS_LLM_ORDER") or "").strip()
|
| 530 |
+
names = [x.strip() for x in raw.split(",") if x.strip() in LLM_DEFAULT_ORDER] or list(LLM_DEFAULT_ORDER)
|
| 531 |
return [LLM_PROVIDERS[n] for n in names
|
| 532 |
if n in LLM_PROVIDERS and LLM_PROVIDERS[n].can(capability) and not no_credit(n)]
|
| 533 |
|
|
|
|
| 761 |
p = LLM_PROVIDERS[name]
|
| 762 |
cap = p.caps.get(capability)
|
| 763 |
rows.append({
|
| 764 |
+
"provider": p.name, "label": p.label, "model": p.current_model(), "wire": p.wire,
|
| 765 |
"configured": p.configured(),
|
| 766 |
"toolCalling": bool((p.caps.get("llm_tool_calling") or Capability(False)).capable),
|
| 767 |
"jsonMode": bool((p.caps.get("llm_json_mode") or Capability(False)).capable),
|
api/routes_admin.py
CHANGED
|
@@ -2436,6 +2436,155 @@ def _sync_database_shares(session, uname, before, after):
|
|
| 2436 |
raise err(409, "shares_changed", "Database sharing changed. Save access again.") from exc
|
| 2437 |
|
| 2438 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2439 |
@router.put("/admin/users/{username}/perms")
|
| 2440 |
def put_perms(username: str, body: dict = Body(default=None),
|
| 2441 |
session: Session = Depends(admin_gate)):
|
|
|
|
| 2436 |
raise err(409, "shares_changed", "Database sharing changed. Save access again.") from exc
|
| 2437 |
|
| 2438 |
|
| 2439 |
+
def _set_database_request_share(session, key, entries, held, snapshot):
|
| 2440 |
+
"""Keep share provenance and metadata behind a fresh synchronous CAS."""
|
| 2441 |
+
import copy
|
| 2442 |
+
from core import shares
|
| 2443 |
+
|
| 2444 |
+
class BoundStore:
|
| 2445 |
+
def get(self, name):
|
| 2446 |
+
return session.runtime.get(name, fresh=True)
|
| 2447 |
+
|
| 2448 |
+
def update(self, name, fn, flush='async'):
|
| 2449 |
+
def guarded(data):
|
| 2450 |
+
current = (data.get('database') or {}).get(key)
|
| 2451 |
+
if current != snapshot:
|
| 2452 |
+
raise shares.GrantsChanged('Database sharing changed during approval.')
|
| 2453 |
+
before = copy.deepcopy(current or {})
|
| 2454 |
+
result = fn(data)
|
| 2455 |
+
after = (result.get('database') or {}).get(key)
|
| 2456 |
+
if after is not None:
|
| 2457 |
+
prior_rows = {row['user']: row for row in before.get('entries') or ()}
|
| 2458 |
+
after['entries'] = [{**prior_rows.get(row['user'], {}), **row}
|
| 2459 |
+
for row in after['entries']]
|
| 2460 |
+
result['database'][key] = {**before, **after}
|
| 2461 |
+
return result
|
| 2462 |
+
return session.runtime.update(name, guarded, flush='sync')
|
| 2463 |
+
|
| 2464 |
+
return shares.set_grants('database', key, entries, st=BoundStore(),
|
| 2465 |
+
granter=session.uname, expect=held['entries'])
|
| 2466 |
+
|
| 2467 |
+
|
| 2468 |
+
def grant_database_access(session, username, database, role):
|
| 2469 |
+
"""Grant one supported database role with account CAS and guarded share compensation."""
|
| 2470 |
+
import copy
|
| 2471 |
+
from core import perm_scope, shares, user_tables
|
| 2472 |
+
|
| 2473 |
+
admin_gate(session)
|
| 2474 |
+
uname = str(username or '').strip().lower()
|
| 2475 |
+
key = str(database or '').strip()
|
| 2476 |
+
is_table = key.startswith(user_tables.KEY_PREFIX)
|
| 2477 |
+
if role not in ('view', 'edit') or (not is_table and role != 'view'):
|
| 2478 |
+
raise err(409, 'unsupported_role', 'This database supports only viewing access.')
|
| 2479 |
+
tenant = str(session.runtime.tenant.slug).strip().lower()
|
| 2480 |
+
if _tenant_of(session.user) != tenant:
|
| 2481 |
+
raise err(403, 'forbidden', 'Database access could not be granted.')
|
| 2482 |
+
# Read the account store strictly rather than the directory's fail-silent projection.
|
| 2483 |
+
reg = store.get('users', fresh=True)
|
| 2484 |
+
actor, rec = (reg or {}).get(session.uname), (reg or {}).get(uname)
|
| 2485 |
+
if (not isinstance(actor, dict) or actor.get('role') != 'admin'
|
| 2486 |
+
or not actor.get('active', True) or _tenant_of(actor) != tenant):
|
| 2487 |
+
raise err(403, 'forbidden', 'Database access could not be granted.')
|
| 2488 |
+
if (not isinstance(rec, dict) or not rec.get('active', True) or _tenant_of(rec) != tenant):
|
| 2489 |
+
raise err(404, 'no_such_user', 'That account is not active in this workspace.')
|
| 2490 |
+
if uname == session.uname:
|
| 2491 |
+
raise err(400, 'self_perms', 'Ask another administrator to change your access.')
|
| 2492 |
+
governed = {m['key'] for m in _perm_modules(session)}
|
| 2493 |
+
if key not in governed:
|
| 2494 |
+
raise err(404, 'no_database', 'That database is not available in this workspace.')
|
| 2495 |
+
principal = users._public(uname, rec)
|
| 2496 |
+
if perm_scope.may_read(principal, key, st=session.runtime) and (
|
| 2497 |
+
role == 'view' or user_tables.may_edit_database(key, uname, False, st=session.runtime)):
|
| 2498 |
+
return {'username': uname, 'database': key, 'role': role}
|
| 2499 |
+
expected = users.database_access_state(rec)
|
| 2500 |
+
prior = copy.deepcopy((rec.get('perms') or {}).get(key))
|
| 2501 |
+
candidate = dict(prior or {}, access=True)
|
| 2502 |
+
cleaned = _clean_perms({key: candidate}, governed_keys=governed,
|
| 2503 |
+
session=session, stored=rec.get('perms'))
|
| 2504 |
+
folded = _fold_legacy_scope(rec, cleaned)
|
| 2505 |
+
_guard_bu_widening(rec, folded, False)
|
| 2506 |
+
# Validation may prune retired fields. This click changes access, so retain stored walls.
|
| 2507 |
+
if folded[key].get('filter') != cleaned[key].get('filter'):
|
| 2508 |
+
candidate['filter'] = folded[key]['filter']
|
| 2509 |
+
|
| 2510 |
+
bucket = (session.runtime.get(shares.SHARES_KEY, fresh=True) or {}) if is_table else {}
|
| 2511 |
+
held = shares.grants('database', key, st=user_tables.lend(
|
| 2512 |
+
session.runtime, **{shares.SHARES_KEY: bucket})) if is_table else None
|
| 2513 |
+
snapshot = copy.deepcopy((bucket.get('database') or {}).get(key)) if is_table else None
|
| 2514 |
+
if is_table and role == 'view':
|
| 2515 |
+
definition = user_tables.get_one(key, session.runtime) or {}
|
| 2516 |
+
if uname in (held['owner'], definition.get('createdBy')):
|
| 2517 |
+
raise err(409, 'unsupported_role', 'An administrator must review the database owner access.')
|
| 2518 |
+
proposed = None
|
| 2519 |
+
if held is not None:
|
| 2520 |
+
proposed = copy.deepcopy(held['entries'])
|
| 2521 |
+
for row in proposed:
|
| 2522 |
+
if row['user'] == uname:
|
| 2523 |
+
row['role'] = role
|
| 2524 |
+
break
|
| 2525 |
+
else:
|
| 2526 |
+
proposed.append({'user': uname, 'role': role, 'by': session.uname})
|
| 2527 |
+
|
| 2528 |
+
def compensate_share():
|
| 2529 |
+
if held is None or proposed == held['entries']:
|
| 2530 |
+
return
|
| 2531 |
+
bucket_now = session.runtime.get(shares.SHARES_KEY, fresh=True) or {}
|
| 2532 |
+
current = shares.grants('database', key, st=user_tables.lend(
|
| 2533 |
+
session.runtime, **{shares.SHARES_KEY: bucket_now}))
|
| 2534 |
+
ours = [row for row in proposed if row['user'] == uname]
|
| 2535 |
+
target = [row for row in current['entries'] if row['user'] == uname]
|
| 2536 |
+
old = [row for row in held['entries'] if row['user'] == uname]
|
| 2537 |
+
if target == old:
|
| 2538 |
+
return
|
| 2539 |
+
if target != ours:
|
| 2540 |
+
raise err(409, 'compensation_conflict', 'Database sharing changed. Ask an administrator to review access.')
|
| 2541 |
+
restored = [item for row in current['entries']
|
| 2542 |
+
for item in (old if row['user'] == uname else [row])]
|
| 2543 |
+
# Keep other principals' fresh grants. Never restore an old whole share list.
|
| 2544 |
+
_set_database_request_share(session, key, restored, current,
|
| 2545 |
+
copy.deepcopy((bucket_now.get('database') or {}).get(key)))
|
| 2546 |
+
|
| 2547 |
+
account_attempted = False
|
| 2548 |
+
result = None
|
| 2549 |
+
try:
|
| 2550 |
+
if held is not None and proposed != held['entries']:
|
| 2551 |
+
# Sharing comes first so an enabled view request cannot inherit an old edit grant.
|
| 2552 |
+
_set_database_request_share(session, key, proposed, held, snapshot)
|
| 2553 |
+
account_attempted = True
|
| 2554 |
+
result = users.set_database_access(uname, key, candidate, actor=session.uname,
|
| 2555 |
+
tenant=tenant, expect=expected,
|
| 2556 |
+
legacy_filter=(candidate.get('filter') if
|
| 2557 |
+
folded[key].get('filter') != cleaned[key].get('filter') else None))
|
| 2558 |
+
if result.get('status') != 'updated':
|
| 2559 |
+
code = result.get('status')
|
| 2560 |
+
raise err(409 if code == 'conflict' else 403, 'permissions_changed',
|
| 2561 |
+
'Account access changed. Request access again.')
|
| 2562 |
+
if held is not None:
|
| 2563 |
+
current = shares.grants('database', key, st=session.runtime)
|
| 2564 |
+
if ([row for row in current['entries'] if row['user'] == uname]
|
| 2565 |
+
!= [row for row in proposed if row['user'] == uname]):
|
| 2566 |
+
raise shares.GrantsChanged('Database sharing changed during approval.')
|
| 2567 |
+
except Exception:
|
| 2568 |
+
# A store can report failure after committing. Undo only our exact account transition.
|
| 2569 |
+
try:
|
| 2570 |
+
if account_attempted and (result is None or result.get('status') == 'updated'):
|
| 2571 |
+
fresh = store.get('users', fresh=True) or {}
|
| 2572 |
+
current = fresh.get(uname) or {}
|
| 2573 |
+
intended = copy.deepcopy(expected)
|
| 2574 |
+
intended['perms'] = dict(expected.get('perms') or {}, **{key: candidate})
|
| 2575 |
+
if ((current.get('perms') or {}).get(key) == candidate and intended != expected):
|
| 2576 |
+
restored = users.set_database_access(
|
| 2577 |
+
uname, key, prior, actor=session.uname, tenant=tenant,
|
| 2578 |
+
expect=users.database_access_state(current), restore=expected)
|
| 2579 |
+
if restored.get('status') != 'updated':
|
| 2580 |
+
raise err(409, 'compensation_conflict',
|
| 2581 |
+
'Account access changed. Ask an administrator to review access.')
|
| 2582 |
+
finally:
|
| 2583 |
+
compensate_share()
|
| 2584 |
+
raise
|
| 2585 |
+
return {'username': uname, 'database': key, 'role': role}
|
| 2586 |
+
|
| 2587 |
+
|
| 2588 |
@router.put("/admin/users/{username}/perms")
|
| 2589 |
def put_perms(username: str, body: dict = Body(default=None),
|
| 2590 |
session: Session = Depends(admin_gate)):
|
api/routes_applications.py
CHANGED
|
@@ -134,10 +134,10 @@ def reconcile_finance_fact(fact_key: str, bu: str | None = None,
|
|
| 134 |
|
| 135 |
@nav_router.get("/nav/applications")
|
| 136 |
def list_nav_applications(session: Session = Depends(require_session)):
|
| 137 |
-
"""
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
"""
|
| 142 |
if not session.runtime.available():
|
| 143 |
raise err(503, "store_unavailable", "the tenant store is unavailable")
|
|
|
|
| 134 |
|
| 135 |
@nav_router.get("/nav/applications")
|
| 136 |
def list_nav_applications(session: Session = Depends(require_session)):
|
| 137 |
+
"""The App home: stored Applications this session owns or was shared (R102).
|
| 138 |
|
| 139 |
+
No code projection rides here. A stored Finance copy is listed while this session's wall
|
| 140 |
+
admits its permission key.
|
| 141 |
"""
|
| 142 |
if not session.runtime.available():
|
| 143 |
raise err(503, "store_unavailable", "the tenant store is unavailable")
|
api/routes_assets.py
CHANGED
|
@@ -82,6 +82,27 @@ def application_access_context(session, databases, *, strict=False):
|
|
| 82 |
return allowed, records
|
| 83 |
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
def _application_databases(runtime, application_id=None):
|
| 86 |
doc = applications.load(runtime)
|
| 87 |
if application_id:
|
|
@@ -104,7 +125,8 @@ def application_index(database: str = "", type: str = "", starred: bool | None =
|
|
| 104 |
_application_error(exc)
|
| 105 |
return {"applications": applications.list_apps(
|
| 106 |
session.runtime, session.uname, session.admin, database=database or None,
|
| 107 |
-
kind=type or None, starred=starred, allowed_databases=allowed
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
@router.post("/applications", status_code=201)
|
|
@@ -126,6 +148,10 @@ def create_application(body: dict = Body(default=None),
|
|
| 126 |
def update_application(application_id: str, body: dict = Body(default=None),
|
| 127 |
session: Session = Depends(require_session)):
|
| 128 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
current = _application_databases(session.runtime, application_id)
|
| 130 |
if not current:
|
| 131 |
raise applications.ApplicationError("application does not exist")
|
|
@@ -149,6 +175,10 @@ def update_application(application_id: str, body: dict = Body(default=None),
|
|
| 149 |
def duplicate_application(application_id: str,
|
| 150 |
session: Session = Depends(require_session)):
|
| 151 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
current = _application_databases(session.runtime, application_id)
|
| 153 |
if not current:
|
| 154 |
raise applications.ApplicationError("application does not exist")
|
|
@@ -164,29 +194,18 @@ def duplicate_application(application_id: str,
|
|
| 164 |
def delete_application(application_id: str, body: dict = Body(default=None),
|
| 165 |
session: Session = Depends(require_session)):
|
| 166 |
try:
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
# A refusal below never reaches persistence, even if its name changed mid-request.
|
| 180 |
-
deleted = delete(raw)
|
| 181 |
-
app = raw["applications"][application_id]
|
| 182 |
-
if not isinstance(confirm_name, str) or confirm_name != app.get("name"):
|
| 183 |
-
raise applications.ApplicationError("enter the exact App name to confirm deletion")
|
| 184 |
-
return deleted
|
| 185 |
-
|
| 186 |
-
return session.runtime.update(key, confirmed)
|
| 187 |
-
|
| 188 |
-
return applications.delete(NameConfirmedDelete(), application_id, session.uname, session.admin,
|
| 189 |
-
allowed_databases=allowed)
|
| 190 |
except (applications.ApplicationError, PermissionError) as exc:
|
| 191 |
_application_error(exc)
|
| 192 |
|
|
|
|
| 82 |
return allowed, records
|
| 83 |
|
| 84 |
|
| 85 |
+
def _session_wall(session):
|
| 86 |
+
"""The `routes_applications._may_open` session wall, as a one-argument predicate."""
|
| 87 |
+
from routes_applications import _may_open
|
| 88 |
+
return lambda key: _may_open(session, key)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def finance_access(session, application_id):
|
| 92 |
+
"""True for a stored Finance copy this session's wall admits; False for any other App.
|
| 93 |
+
|
| 94 |
+
A Finance copy binds no database, so the database wall does not apply to it. One the wall
|
| 95 |
+
refuses is hidden from the App home, so its doors answer "does not exist".
|
| 96 |
+
"""
|
| 97 |
+
app = applications.load(session.runtime)["applications"].get(application_id)
|
| 98 |
+
if not applications._is_finance(app):
|
| 99 |
+
return False
|
| 100 |
+
key = applications._finance_permission(app)
|
| 101 |
+
if not key or not _session_wall(session)(key):
|
| 102 |
+
raise applications.ApplicationError("application does not exist")
|
| 103 |
+
return True
|
| 104 |
+
|
| 105 |
+
|
| 106 |
def _application_databases(runtime, application_id=None):
|
| 107 |
doc = applications.load(runtime)
|
| 108 |
if application_id:
|
|
|
|
| 125 |
_application_error(exc)
|
| 126 |
return {"applications": applications.list_apps(
|
| 127 |
session.runtime, session.uname, session.admin, database=database or None,
|
| 128 |
+
kind=type or None, starred=starred, allowed_databases=allowed,
|
| 129 |
+
may_open=_session_wall(session))}
|
| 130 |
|
| 131 |
|
| 132 |
@router.post("/applications", status_code=201)
|
|
|
|
| 148 |
def update_application(application_id: str, body: dict = Body(default=None),
|
| 149 |
session: Session = Depends(require_session)):
|
| 150 |
try:
|
| 151 |
+
if finance_access(session, application_id):
|
| 152 |
+
return {"application": applications.mutate(
|
| 153 |
+
session.runtime, application_id, session.uname, session.admin, body,
|
| 154 |
+
allowed_databases=set())}
|
| 155 |
current = _application_databases(session.runtime, application_id)
|
| 156 |
if not current:
|
| 157 |
raise applications.ApplicationError("application does not exist")
|
|
|
|
| 175 |
def duplicate_application(application_id: str,
|
| 176 |
session: Session = Depends(require_session)):
|
| 177 |
try:
|
| 178 |
+
if finance_access(session, application_id):
|
| 179 |
+
return {"application": applications.duplicate(
|
| 180 |
+
session.runtime, application_id, session.tenant, session.uname, session.admin,
|
| 181 |
+
allowed_databases=set())}
|
| 182 |
current = _application_databases(session.runtime, application_id)
|
| 183 |
if not current:
|
| 184 |
raise applications.ApplicationError("application does not exist")
|
|
|
|
| 194 |
def delete_application(application_id: str, body: dict = Body(default=None),
|
| 195 |
session: Session = Depends(require_session)):
|
| 196 |
try:
|
| 197 |
+
# A Finance copy binds no database: only its owner and the session wall gate it.
|
| 198 |
+
if finance_access(session, application_id):
|
| 199 |
+
allowed = set()
|
| 200 |
+
else:
|
| 201 |
+
current = _application_databases(session.runtime, application_id)
|
| 202 |
+
allowed, _ = application_access_context(session, current)
|
| 203 |
+
if not allowed:
|
| 204 |
+
raise applications.ApplicationError("application does not exist")
|
| 205 |
+
# The name check runs inside the registry's atomic update, after its permission gate.
|
| 206 |
+
return applications.delete(session.runtime, application_id, session.uname, session.admin,
|
| 207 |
+
allowed_databases=allowed,
|
| 208 |
+
confirm_name=(body or {}).get("confirmName"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
except (applications.ApplicationError, PermissionError) as exc:
|
| 210 |
_application_error(exc)
|
| 211 |
|
api/routes_assistant_memory.py
CHANGED
|
@@ -3,6 +3,16 @@ from fastapi import APIRouter, Depends
|
|
| 3 |
|
| 4 |
from deps import Session, err, module_gate, require_session
|
| 5 |
import assistant_memory
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
router = APIRouter(prefix="/api/v1/assistant", dependencies=[Depends(module_gate("analyst"))])
|
| 8 |
|
|
@@ -12,10 +22,14 @@ def erase_memory(id: str, session: Session = Depends(require_session)):
|
|
| 12 |
"""Return the same refusal for a missing id and another user's id."""
|
| 13 |
if not session.runtime.available():
|
| 14 |
raise err(503, "store_unavailable", "The tenant store is unavailable.")
|
|
|
|
| 15 |
deleted = assistant_memory.forget(session.runtime, session.uname, id)
|
| 16 |
-
if not deleted
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
if not deleted:
|
| 20 |
raise err(404, "assistant_memory_not_found", "That memory entry was not found.")
|
| 21 |
return {"deleted": True}
|
|
@@ -23,7 +37,8 @@ def erase_memory(id: str, session: Session = Depends(require_session)):
|
|
| 23 |
|
| 24 |
@router.post("/memory/{id}/promote")
|
| 25 |
def promote_memory(id: str, session: Session = Depends(require_session)):
|
| 26 |
-
|
|
|
|
| 27 |
raise err(403, "forbidden", "Only an Administrator can share a company fact.")
|
| 28 |
if not session.runtime.available():
|
| 29 |
raise err(503, "store_unavailable", "The tenant store is unavailable.")
|
|
@@ -32,6 +47,8 @@ def promote_memory(id: str, session: Session = Depends(require_session)):
|
|
| 32 |
"tenant": session.tenant, "username": session.uname}, id)
|
| 33 |
except PermissionError as exc:
|
| 34 |
raise err(403, "forbidden", str(exc)) from exc
|
|
|
|
|
|
|
| 35 |
except ValueError as exc:
|
| 36 |
raise err(409, "assistant_memory_source_unproven", str(exc)) from exc
|
| 37 |
if entry is None:
|
|
|
|
| 3 |
|
| 4 |
from deps import Session, err, module_gate, require_session
|
| 5 |
import assistant_memory
|
| 6 |
+
from core import external_access
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _active(session):
|
| 10 |
+
if session.tenant != session.runtime.key:
|
| 11 |
+
raise err(403, "forbidden", "This account is unavailable in this workspace.")
|
| 12 |
+
try:
|
| 13 |
+
return external_access.resolve_active_user(session.uname, session.tenant)
|
| 14 |
+
except external_access.ExternalAccessError as exc:
|
| 15 |
+
raise err(403, "forbidden", "This account is unavailable in this workspace.") from exc
|
| 16 |
|
| 17 |
router = APIRouter(prefix="/api/v1/assistant", dependencies=[Depends(module_gate("analyst"))])
|
| 18 |
|
|
|
|
| 22 |
"""Return the same refusal for a missing id and another user's id."""
|
| 23 |
if not session.runtime.available():
|
| 24 |
raise err(503, "store_unavailable", "The tenant store is unavailable.")
|
| 25 |
+
_active(session)
|
| 26 |
deleted = assistant_memory.forget(session.runtime, session.uname, id)
|
| 27 |
+
if not deleted:
|
| 28 |
+
try:
|
| 29 |
+
deleted = assistant_memory.forget_company(session.runtime, {
|
| 30 |
+
"tenant": session.tenant, "username": session.uname}, id)
|
| 31 |
+
except external_access.ExternalAccessError as exc:
|
| 32 |
+
raise err(403, "forbidden", "This account is unavailable in this workspace.") from exc
|
| 33 |
if not deleted:
|
| 34 |
raise err(404, "assistant_memory_not_found", "That memory entry was not found.")
|
| 35 |
return {"deleted": True}
|
|
|
|
| 37 |
|
| 38 |
@router.post("/memory/{id}/promote")
|
| 39 |
def promote_memory(id: str, session: Session = Depends(require_session)):
|
| 40 |
+
from core import perms
|
| 41 |
+
if not perms.is_admin(_active(session)):
|
| 42 |
raise err(403, "forbidden", "Only an Administrator can share a company fact.")
|
| 43 |
if not session.runtime.available():
|
| 44 |
raise err(503, "store_unavailable", "The tenant store is unavailable.")
|
|
|
|
| 47 |
"tenant": session.tenant, "username": session.uname}, id)
|
| 48 |
except PermissionError as exc:
|
| 49 |
raise err(403, "forbidden", str(exc)) from exc
|
| 50 |
+
except external_access.ExternalAccessError as exc:
|
| 51 |
+
raise err(403, "forbidden", "This account is unavailable in this workspace.") from exc
|
| 52 |
except ValueError as exc:
|
| 53 |
raise err(409, "assistant_memory_source_unproven", str(exc)) from exc
|
| 54 |
if entry is None:
|
api/routes_connectors.py
CHANGED
|
@@ -2684,6 +2684,53 @@ def odoo_status(connection_id: str = None, session: Session = Depends(require_se
|
|
| 2684 |
"receipt": receipt}
|
| 2685 |
|
| 2686 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2687 |
@router.get("/connectors/{connector_key}/sync")
|
| 2688 |
def connector_sync_status(connector_key: str, connection_id: str = None,
|
| 2689 |
session: Session = Depends(require_session)):
|
|
@@ -2693,7 +2740,12 @@ def connector_sync_status(connector_key: str, connection_id: str = None,
|
|
| 2693 |
f"{connector_key} is not registered for connector sync")
|
| 2694 |
row = (connector_sync.job_summary(_connection_jobs(session.runtime, connector_key, connection_id))
|
| 2695 |
or connector_sync.read(session.runtime, connector_key, connection_id))
|
| 2696 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2697 |
|
| 2698 |
|
| 2699 |
@router.post("/connectors/{connector_key}/sync/now")
|
|
|
|
| 2684 |
"receipt": receipt}
|
| 2685 |
|
| 2686 |
|
| 2687 |
+
def _daily_completed_sync(rt, connector_key):
|
| 2688 |
+
"""Read completed mirror markers; never create a mirror or contact a provider."""
|
| 2689 |
+
if connector_key == "amazon_sp":
|
| 2690 |
+
import connectors_amazon as cx
|
| 2691 |
+
try:
|
| 2692 |
+
states = cx.sync_state(rt, rt.key)
|
| 2693 |
+
except cx.AmazonStatusSafetyError as refused:
|
| 2694 |
+
states = dict(getattr(refused, "safe_status", None) or {})
|
| 2695 |
+
except Exception:
|
| 2696 |
+
return None, False
|
| 2697 |
+
if not isinstance(states, dict):
|
| 2698 |
+
return None, False
|
| 2699 |
+
rows = [row for row in states.values() if isinstance(row, dict) and not row.get("declared")]
|
| 2700 |
+
stamps = [_sync_stamp(row.get("lastSuccess")) for row in rows]
|
| 2701 |
+
stamps = [stamp for stamp in stamps if stamp]
|
| 2702 |
+
if stamps:
|
| 2703 |
+
return max(stamps, key=datetime.fromisoformat), True
|
| 2704 |
+
# This is the existing reader's explicit unreadable-mirror outcome, not a never-run fact.
|
| 2705 |
+
unknown = any(str(row.get("unknownCause") or "").startswith(
|
| 2706 |
+
"This container has no readable sync status.") for row in rows)
|
| 2707 |
+
return None, bool(rows) and not unknown
|
| 2708 |
+
if connector_key == "meta_ads":
|
| 2709 |
+
from pathlib import Path
|
| 2710 |
+
from harness import datastore
|
| 2711 |
+
import duckdb
|
| 2712 |
+
|
| 2713 |
+
def read(cursor):
|
| 2714 |
+
row = cursor.execute("SELECT phase, updated_at FROM _sync_state WHERE entity = ?",
|
| 2715 |
+
["meta"]).fetchone()
|
| 2716 |
+
if row is None or row[0] != "done":
|
| 2717 |
+
return None, True
|
| 2718 |
+
stamp = _sync_stamp(row[1])
|
| 2719 |
+
return stamp, stamp is not None
|
| 2720 |
+
|
| 2721 |
+
try:
|
| 2722 |
+
path = Path(getattr(rt, "datastore_path", None) or datastore.path_for(rt.key))
|
| 2723 |
+
if not path.is_file():
|
| 2724 |
+
return None, False
|
| 2725 |
+
if path.resolve() == Path(datastore.DB_PATH).resolve():
|
| 2726 |
+
return read(datastore.ro_cursor())
|
| 2727 |
+
with duckdb.connect(str(path), read_only=True) as cursor:
|
| 2728 |
+
return read(cursor)
|
| 2729 |
+
except Exception:
|
| 2730 |
+
return None, False
|
| 2731 |
+
return None, False
|
| 2732 |
+
|
| 2733 |
+
|
| 2734 |
@router.get("/connectors/{connector_key}/sync")
|
| 2735 |
def connector_sync_status(connector_key: str, connection_id: str = None,
|
| 2736 |
session: Session = Depends(require_session)):
|
|
|
|
| 2740 |
f"{connector_key} is not registered for connector sync")
|
| 2741 |
row = (connector_sync.job_summary(_connection_jobs(session.runtime, connector_key, connection_id))
|
| 2742 |
or connector_sync.read(session.runtime, connector_key, connection_id))
|
| 2743 |
+
answer = _sync_payload(connector_key, connection_id, row)
|
| 2744 |
+
if connector_key in ("amazon_sp", "meta_ads"):
|
| 2745 |
+
completed, known = _daily_completed_sync(session.runtime, connector_key)
|
| 2746 |
+
answer.update(schedule="daily", lastCompletedAt=completed,
|
| 2747 |
+
lastCompletedKnown=known, canSync=bool(session.admin))
|
| 2748 |
+
return _safe_connector_status(connector_key, answer)
|
| 2749 |
|
| 2750 |
|
| 2751 |
@router.post("/connectors/{connector_key}/sync/now")
|
api/routes_customers.py
CHANGED
|
@@ -193,7 +193,6 @@ def _pool_for(rt, team_id, agent):
|
|
| 193 |
import routes_keychain
|
| 194 |
|
| 195 |
key = ("pool", team_id, agent)
|
| 196 |
-
|
| 197 |
if routes_keychain.odoo_paused(rt):
|
| 198 |
hit = rt.pool_cache.get(key)
|
| 199 |
if hit:
|
|
@@ -206,6 +205,12 @@ def _pool_for(rt, team_id, agent):
|
|
| 206 |
"this data source is paused and no snapshot exists for your scope. "
|
| 207 |
"An admin can resume it under Settings → Connectors")
|
| 208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
def _build():
|
| 210 |
# ⚠ THE SCOPE GOES INTO THE BUILDER. `pool(agent_name, team_id)` is the same reconciled
|
| 211 |
# builder the Streamlit page uses — passing the scope here is what makes the isolation a
|
|
@@ -517,6 +522,7 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 517 |
with_rows: bool = True, needed=None):
|
| 518 |
"""C2: one wall- and revision-scoped memo for customer, product and stored envelopes."""
|
| 519 |
global grid_assembly_shared
|
|
|
|
| 520 |
rt = session.runtime
|
| 521 |
needed = None if needed is None else frozenset(str(key) for key in needed)
|
| 522 |
if build is None:
|
|
@@ -539,7 +545,9 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 539 |
separators=(",", ":"), default=str),
|
| 540 |
_wall_stamp(session, table_key) if memoable else None, pool_stamp(),
|
| 541 |
("full" if needed is None else ("columns", tuple(sorted(needed))))
|
| 542 |
-
if with_rows else "fields"
|
|
|
|
|
|
|
| 543 |
if not memoable:
|
| 544 |
result = ((*prefix, json.dumps(None)), {})
|
| 545 |
return result
|
|
@@ -882,8 +890,6 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
|
|
| 882 |
# HIDDEN. So an unthreaded `st` UNDER-shares (a grantee cannot see their own column) rather
|
| 883 |
# than over-shares — visible and reportable, but still wrong, and `visible_fields`' own note
|
| 884 |
# requires the two calls to agree about it.
|
| 885 |
-
# Internal wall inputs stay outside workspace, fields and all public row projections.
|
| 886 |
-
permission_scope = {"fields": fields, "rows": rows_src, "row_fields": aios_grid.FIELDS}
|
| 887 |
hidden = perm_scope.hidden_keys(session.user, MODULE, fields, st=rt)
|
| 888 |
if hidden:
|
| 889 |
fields = [f for f in fields if f.get("key") not in hidden]
|
|
@@ -994,7 +1000,6 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
|
|
| 994 |
for pid, cells in _ovc.items()}
|
| 995 |
return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
|
| 996 |
"fields": fields, "views": views, "lists": lists, "derived": derived,
|
| 997 |
-
"_permission_scope": permission_scope,
|
| 998 |
"measures": measures, "measure_sets": measure_sets, "today": today,
|
| 999 |
"team_id": team_id, "routes": normalized_routes, "zones": normalized_zones}
|
| 1000 |
|
|
|
|
| 193 |
import routes_keychain
|
| 194 |
|
| 195 |
key = ("pool", team_id, agent)
|
|
|
|
| 196 |
if routes_keychain.odoo_paused(rt):
|
| 197 |
hit = rt.pool_cache.get(key)
|
| 198 |
if hit:
|
|
|
|
| 205 |
"this data source is paused and no snapshot exists for your scope. "
|
| 206 |
"An admin can resume it under Settings → Connectors")
|
| 207 |
|
| 208 |
+
hit = rt.pool_cache.get(key)
|
| 209 |
+
if hit and not cl.pool_has_audit(hit[1]):
|
| 210 |
+
# New columns refresh an active source. A frozen snapshot remains the last read of
|
| 211 |
+
# this exact scope; newly declared attributes stay unknown until the source resumes.
|
| 212 |
+
rt.pool_cache.pop(key, None)
|
| 213 |
+
|
| 214 |
def _build():
|
| 215 |
# ⚠ THE SCOPE GOES INTO THE BUILDER. `pool(agent_name, team_id)` is the same reconciled
|
| 216 |
# builder the Streamlit page uses — passing the scope here is what makes the isolation a
|
|
|
|
| 522 |
with_rows: bool = True, needed=None):
|
| 523 |
"""C2: one wall- and revision-scoped memo for customer, product and stored envelopes."""
|
| 524 |
global grid_assembly_shared
|
| 525 |
+
import aios_grid
|
| 526 |
rt = session.runtime
|
| 527 |
needed = None if needed is None else frozenset(str(key) for key in needed)
|
| 528 |
if build is None:
|
|
|
|
| 545 |
separators=(",", ":"), default=str),
|
| 546 |
_wall_stamp(session, table_key) if memoable else None, pool_stamp(),
|
| 547 |
("full" if needed is None else ("columns", tuple(sorted(needed))))
|
| 548 |
+
if with_rows else "fields",
|
| 549 |
+
hashlib.sha256(json.dumps(aios_grid.FIELDS, sort_keys=True,
|
| 550 |
+
default=str).encode()).hexdigest())
|
| 551 |
if not memoable:
|
| 552 |
result = ((*prefix, json.dumps(None)), {})
|
| 553 |
return result
|
|
|
|
| 890 |
# HIDDEN. So an unthreaded `st` UNDER-shares (a grantee cannot see their own column) rather
|
| 891 |
# than over-shares — visible and reportable, but still wrong, and `visible_fields`' own note
|
| 892 |
# requires the two calls to agree about it.
|
|
|
|
|
|
|
| 893 |
hidden = perm_scope.hidden_keys(session.user, MODULE, fields, st=rt)
|
| 894 |
if hidden:
|
| 895 |
fields = [f for f in fields if f.get("key") not in hidden]
|
|
|
|
| 1000 |
for pid, cells in _ovc.items()}
|
| 1001 |
return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
|
| 1002 |
"fields": fields, "views": views, "lists": lists, "derived": derived,
|
|
|
|
| 1003 |
"measures": measures, "measure_sets": measure_sets, "today": today,
|
| 1004 |
"team_id": team_id, "routes": normalized_routes, "zones": normalized_zones}
|
| 1005 |
|
api/routes_external.py
CHANGED
|
@@ -144,6 +144,9 @@ class _PreviewRuntime:
|
|
| 144 |
def get_many(self, names):
|
| 145 |
return {str(name): self.get(name) for name in names or ()}
|
| 146 |
|
|
|
|
|
|
|
|
|
|
| 147 |
def get_projections(self, names, drop=(), timeout_s=None):
|
| 148 |
return {str(name): self.get_projection(name, drop=drop) for name in names or ()}
|
| 149 |
|
|
@@ -2937,7 +2940,7 @@ def _tool_context(session: Session, *, preview=False) -> external_tools.ToolCont
|
|
| 2937 |
view_event=lambda kind, args: _view_event(session, kind, args),
|
| 2938 |
view_share_preview=lambda args: _view_share_preview(session, args),
|
| 2939 |
app_upsert=lambda args: _application_upsert(session, args),
|
| 2940 |
-
#
|
| 2941 |
app_delete=lambda args: routes_assets.delete_application(
|
| 2942 |
args["app_id"], {"confirmName": args["confirmName"]}, session),
|
| 2943 |
database_object=lambda args: (_plan_database_write(session, args)
|
|
@@ -3280,9 +3283,7 @@ def _mcp_guide(session: Session) -> str:
|
|
| 3280 |
lines = ["# Loopable guide", "", f"Signed in as {session.uname}.", "", MCP_INSTRUCTIONS, "",
|
| 3281 |
"## Your databases", "",
|
| 3282 |
"Call describe_database with a key below for its fields before you query it.", ""]
|
| 3283 |
-
|
| 3284 |
-
rows = [row for row in _resolve_external_scope(session) if row["permitted"]
|
| 3285 |
-
and external_access.database_allowed(key_databases, row["database"])]
|
| 3286 |
for row in rows:
|
| 3287 |
note = "" if row["answerable"] else f" Not queryable right now: {_markdown_inline(row['reason'])}"
|
| 3288 |
lines.append(f"- `{row['database']}`: {_markdown_inline(row['label'])}.{note}")
|
|
|
|
| 144 |
def get_many(self, names):
|
| 145 |
return {str(name): self.get(name) for name in names or ()}
|
| 146 |
|
| 147 |
+
def get_entry(self, name, entry):
|
| 148 |
+
return copy.deepcopy((self.get(name) or {}).get(entry))
|
| 149 |
+
|
| 150 |
def get_projections(self, names, drop=(), timeout_s=None):
|
| 151 |
return {str(name): self.get_projection(name, drop=drop) for name in names or ()}
|
| 152 |
|
|
|
|
| 2940 |
view_event=lambda kind, args: _view_event(session, kind, args),
|
| 2941 |
view_share_preview=lambda args: _view_share_preview(session, args),
|
| 2942 |
app_upsert=lambda args: _application_upsert(session, args),
|
| 2943 |
+
# The registry delete checks confirmName atomically.
|
| 2944 |
app_delete=lambda args: routes_assets.delete_application(
|
| 2945 |
args["app_id"], {"confirmName": args["confirmName"]}, session),
|
| 2946 |
database_object=lambda args: (_plan_database_write(session, args)
|
|
|
|
| 3283 |
lines = ["# Loopable guide", "", f"Signed in as {session.uname}.", "", MCP_INSTRUCTIONS, "",
|
| 3284 |
"## Your databases", "",
|
| 3285 |
"Call describe_database with a key below for its fields before you query it.", ""]
|
| 3286 |
+
rows = [row for row in _resolve_external_scope(session) if row["permitted"]]
|
|
|
|
|
|
|
| 3287 |
for row in rows:
|
| 3288 |
note = "" if row["answerable"] else f" Not queryable right now: {_markdown_inline(row['reason'])}"
|
| 3289 |
lines.append(f"- `{row['database']}`: {_markdown_inline(row['label'])}.{note}")
|
api/routes_files.py
CHANGED
|
@@ -24,8 +24,9 @@ def _response(rt, item):
|
|
| 24 |
raise err(503, "file_unavailable", "This file could not be read.") from exc
|
| 25 |
if data is None:
|
| 26 |
raise _unknown()
|
| 27 |
-
|
| 28 |
-
|
|
|
|
| 29 |
"Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff"})
|
| 30 |
|
| 31 |
|
|
|
|
| 24 |
raise err(503, "file_unavailable", "This file could not be read.") from exc
|
| 25 |
if data is None:
|
| 26 |
raise _unknown()
|
| 27 |
+
disposition = "attachment" if item["mime"] == assistant_files.XLSX_MIME else "inline"
|
| 28 |
+
return Response(content=data, media_type=item["mime"], headers={
|
| 29 |
+
"Content-Disposition": f'{disposition}; filename="{item["filename"]}"',
|
| 30 |
"Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff"})
|
| 31 |
|
| 32 |
|
api/routes_module_index.py
CHANGED
|
@@ -66,13 +66,8 @@ def _readable_ids(module, session):
|
|
| 66 |
# only listed items, so an unverifiable placement renders no tile. Use local voice
|
| 67 |
# records, never audience-option assembly, just to verify placement ids.
|
| 68 |
if module == "app":
|
| 69 |
-
# S67-T38 (O24): the App home also renders the seeded Finance projections, so the wall
|
| 70 |
-
# admits their ids through the SAME grant filter /nav/applications uses. Never ungated:
|
| 71 |
-
# a Finance card the session cannot open is not placeable.
|
| 72 |
stored = {row["id"] for row in routes_assets.application_index(session=session)["applications"]}
|
| 73 |
-
|
| 74 |
-
may_open=lambda permission: _may_open(session, permission))
|
| 75 |
-
return stored | {row["id"] for row in finance}
|
| 76 |
# ⭐⭐ W62-T17 — THE ID-ONLY ACCESSOR THIS COMMENT USED TO ASK FOR NOW EXISTS. It read
|
| 77 |
# *"all_definitions omits synthetic field/Odoo agents. Keep the complete automation list until
|
| 78 |
# it has an id-only accessor"*, and the whole Agents rail payload was being built to answer a
|
|
|
|
| 66 |
# only listed items, so an unverifiable placement renders no tile. Use local voice
|
| 67 |
# records, never audience-option assembly, just to verify placement ids.
|
| 68 |
if module == "app":
|
|
|
|
|
|
|
|
|
|
| 69 |
stored = {row["id"] for row in routes_assets.application_index(session=session)["applications"]}
|
| 70 |
+
return stored
|
|
|
|
|
|
|
| 71 |
# ⭐⭐ W62-T17 — THE ID-ONLY ACCESSOR THIS COMMENT USED TO ASK FOR NOW EXISTS. It read
|
| 72 |
# *"all_definitions omits synthetic field/Odoo agents. Keep the complete automation list until
|
| 73 |
# it has an id-only accessor"*, and the whole Agents rail payload was being built to answer a
|
api/routes_nav.py
CHANGED
|
@@ -10,7 +10,10 @@ The full rule set — archived is invisible to everyone, `group_only` rows are e
|
|
| 10 |
`prefs.json` Library preference is deliberately NOT applied — is documented on
|
| 11 |
`core.perms.nav_pages`, which is where it belongs: one place, both callers.
|
| 12 |
"""
|
|
|
|
|
|
|
| 13 |
import time
|
|
|
|
| 14 |
|
| 15 |
from fastapi import APIRouter, Body, Depends
|
| 16 |
|
|
@@ -1072,6 +1075,86 @@ def save_nav_prefs(body: dict = Body(default=None),
|
|
| 1072 |
return {"prefs": clean}
|
| 1073 |
|
| 1074 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1075 |
def _schema_means(key: str) -> dict:
|
| 1076 |
"""`{field_key: the agent's semantic definition}` for a database, or `{}` when there is none.
|
| 1077 |
|
|
@@ -1395,6 +1478,8 @@ def create_nav_application(body: dict = Body(default=None),
|
|
| 1395 |
allowed_databases={source})
|
| 1396 |
except PermissionError as exc:
|
| 1397 |
raise err(403, "forbidden", str(exc))
|
|
|
|
|
|
|
| 1398 |
except application_registry.ApplicationError as exc:
|
| 1399 |
raise err(400, "bad_application", str(exc))
|
| 1400 |
except Exception:
|
|
|
|
| 10 |
`prefs.json` Library preference is deliberately NOT applied — is documented on
|
| 11 |
`core.perms.nav_pages`, which is where it belongs: one place, both callers.
|
| 12 |
"""
|
| 13 |
+
import json
|
| 14 |
+
import re
|
| 15 |
import time
|
| 16 |
+
from datetime import datetime, timezone
|
| 17 |
|
| 18 |
from fastapi import APIRouter, Body, Depends
|
| 19 |
|
|
|
|
| 1075 |
return {"prefs": clean}
|
| 1076 |
|
| 1077 |
|
| 1078 |
+
#: S72 C5: one user's small JSON preferences by key. A separate bucket from `nav_prefs`, so a
|
| 1079 |
+
#: keyed write never rewrites the folder picture. Shape: {uname: {key: {"value", "updated_at"}}}.
|
| 1080 |
+
_NAV_USER_PREFS_KEY = "nav_user_prefs"
|
| 1081 |
+
_USER_PREF_KEY_RE = re.compile(r"[a-z][a-z0-9_.:-]{0,79}")
|
| 1082 |
+
_MAX_USER_PREF_BYTES = 8192
|
| 1083 |
+
#: A full bucket refuses a NEW key loudly; it never evicts another key to make room.
|
| 1084 |
+
_MAX_USER_PREFS = 64
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
def _user_pref_key(key):
|
| 1088 |
+
key = str(key or "")
|
| 1089 |
+
if not _USER_PREF_KEY_RE.fullmatch(key):
|
| 1090 |
+
raise err(400, "pref_key_invalid", "That preference name is not valid.")
|
| 1091 |
+
return key
|
| 1092 |
+
|
| 1093 |
+
|
| 1094 |
+
def _user_pref_bytes(value):
|
| 1095 |
+
return len(json.dumps(value, separators=(",", ":"), ensure_ascii=False).encode("utf-8"))
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
def _user_pref_now():
|
| 1099 |
+
"""A UTC ISO instant with a Z suffix, never naive local time."""
|
| 1100 |
+
return datetime.fromtimestamp(_now(), timezone.utc).isoformat().replace("+00:00", "Z")
|
| 1101 |
+
|
| 1102 |
+
|
| 1103 |
+
@router.get("/nav/prefs/{key}")
|
| 1104 |
+
def get_user_pref(key: str, session: Session = Depends(require_session)):
|
| 1105 |
+
"""C5: this user's stored value for one preference key, or 404 when unset."""
|
| 1106 |
+
key = _user_pref_key(key)
|
| 1107 |
+
try:
|
| 1108 |
+
bucket = (session.runtime.get(_NAV_USER_PREFS_KEY) or {}).get(session.uname) or {}
|
| 1109 |
+
except Exception:
|
| 1110 |
+
raise err(503, "store_unavailable", "Your saved preferences could not be loaded.")
|
| 1111 |
+
row = bucket.get(key) if isinstance(bucket, dict) else None
|
| 1112 |
+
if not isinstance(row, dict) or "value" not in row:
|
| 1113 |
+
raise err(404, "pref_not_set", "That preference is not saved yet.")
|
| 1114 |
+
return {"key": key, "value": row.get("value"), "updated_at": row.get("updated_at")}
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
@router.put("/nav/prefs/{key}")
|
| 1118 |
+
def put_user_pref(key: str, body: dict = Body(default=None),
|
| 1119 |
+
session: Session = Depends(require_session)):
|
| 1120 |
+
"""C5: replace this user's value for one preference key, up to 8 KB of JSON."""
|
| 1121 |
+
key = _user_pref_key(key)
|
| 1122 |
+
if not isinstance(body, dict) or "value" not in body:
|
| 1123 |
+
raise err(400, "bad_request", "Send the preference as a value.")
|
| 1124 |
+
value = body.get("value")
|
| 1125 |
+
size = _user_pref_bytes(value)
|
| 1126 |
+
if size > _MAX_USER_PREF_BYTES:
|
| 1127 |
+
raise err(400, "pref_too_large",
|
| 1128 |
+
f"That preference is {size} bytes and the limit is {_MAX_USER_PREF_BYTES}. Nothing was saved.")
|
| 1129 |
+
stamp, uname = _user_pref_now(), session.uname
|
| 1130 |
+
from core import freeze_notice
|
| 1131 |
+
if freeze_notice.enabled():
|
| 1132 |
+
return {"key": key, "value": value, "updated_at": stamp}
|
| 1133 |
+
if not session.runtime.available():
|
| 1134 |
+
raise err(503, "store_unavailable", "The tenant store is unavailable. Nothing was saved.")
|
| 1135 |
+
full = False
|
| 1136 |
+
|
| 1137 |
+
def _up(data):
|
| 1138 |
+
nonlocal full
|
| 1139 |
+
data = data if isinstance(data, dict) else {}
|
| 1140 |
+
mine = dict(data.get(uname) or {}) if isinstance(data.get(uname), dict) else {}
|
| 1141 |
+
if key not in mine and len(mine) >= _MAX_USER_PREFS:
|
| 1142 |
+
full = True
|
| 1143 |
+
return data
|
| 1144 |
+
mine[key] = {"value": value, "updated_at": stamp}
|
| 1145 |
+
data[uname] = mine
|
| 1146 |
+
return data
|
| 1147 |
+
|
| 1148 |
+
try:
|
| 1149 |
+
session.runtime.update(_NAV_USER_PREFS_KEY, _up)
|
| 1150 |
+
except Exception:
|
| 1151 |
+
raise err(503, "store_unavailable", "The store refused the write. Nothing was saved.")
|
| 1152 |
+
if full:
|
| 1153 |
+
raise err(409, "prefs_full",
|
| 1154 |
+
f"Your account already keeps {_MAX_USER_PREFS} saved preferences. Nothing was saved.")
|
| 1155 |
+
return {"key": key, "value": value, "updated_at": stamp}
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
def _schema_means(key: str) -> dict:
|
| 1159 |
"""`{field_key: the agent's semantic definition}` for a database, or `{}` when there is none.
|
| 1160 |
|
|
|
|
| 1478 |
allowed_databases={source})
|
| 1479 |
except PermissionError as exc:
|
| 1480 |
raise err(403, "forbidden", str(exc))
|
| 1481 |
+
except application_registry.ApplicationExistsError as exc:
|
| 1482 |
+
raise err(400, "app_exists", str(exc), {"existing": exc.existing})
|
| 1483 |
except application_registry.ApplicationError as exc:
|
| 1484 |
raise err(400, "bad_application", str(exc))
|
| 1485 |
except Exception:
|
api/routes_odoo_tables.py
CHANGED
|
@@ -1106,6 +1106,8 @@ def _odoo_sources():
|
|
| 1106 |
GRID_SOURCES.update(rel.stock_source_specs())
|
| 1107 |
GRID_SOURCES.update(rel.purchase_source_specs())
|
| 1108 |
GRID_SOURCES[rel.SHIPMENTS_KEY] = rel.shipment_source_spec()
|
|
|
|
|
|
|
| 1109 |
for key, spec in GRID_SOURCES.items():
|
| 1110 |
if key in rel.READ_THROUGH_KEYS:
|
| 1111 |
spec["mirror_only"] = True
|
|
|
|
| 1106 |
GRID_SOURCES.update(rel.stock_source_specs())
|
| 1107 |
GRID_SOURCES.update(rel.purchase_source_specs())
|
| 1108 |
GRID_SOURCES[rel.SHIPMENTS_KEY] = rel.shipment_source_spec()
|
| 1109 |
+
# S72-T43 / R107: the audited Odoo columns. Their presets are declared in `odoo_relational`.
|
| 1110 |
+
GRID_SOURCES = rel.merge_audit_cols(GRID_SOURCES)
|
| 1111 |
for key, spec in GRID_SOURCES.items():
|
| 1112 |
if key in rel.READ_THROUGH_KEYS:
|
| 1113 |
spec["mirror_only"] = True
|
api/routes_products.py
CHANGED
|
@@ -504,8 +504,6 @@ def _compute_product_assembly(session: Session, scope: str = "product", storage_
|
|
| 504 |
projected.append(item)
|
| 505 |
fields = list(fields) + projected
|
| 506 |
|
| 507 |
-
# Internal wall inputs stay outside workspace, fields and all public row projections.
|
| 508 |
-
permission_scope = {"fields": fields, "rows": rows_src, "row_fields": fields_base}
|
| 509 |
hidden = perm_scope.hidden_keys(session.user, MODULE, fields, st=session.runtime)
|
| 510 |
if hidden:
|
| 511 |
fields = [f for f in fields if f.get("key") not in hidden]
|
|
@@ -577,7 +575,6 @@ def _compute_product_assembly(session: Session, scope: str = "product", storage_
|
|
| 577 |
for field in fields]
|
| 578 |
return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
|
| 579 |
"fields": fields, "views": views, "lists": lists,
|
| 580 |
-
"_permission_scope": permission_scope,
|
| 581 |
"derived": derived,
|
| 582 |
"measures": measures, "measure_sets": measure_sets, "today": today,
|
| 583 |
"team_id": team_id}
|
|
@@ -597,9 +594,7 @@ def products(session: Session = Depends(module_gate(MODULE)), related: str = Non
|
|
| 597 |
import modules.product_data as pd
|
| 598 |
|
| 599 |
g = product_assembly(session, consume_corrections=not bool(related))
|
| 600 |
-
rows =
|
| 601 |
-
g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
|
| 602 |
-
rows = _seed_image(_seed_shared(rows, g["rows_src"], g["fields"]), g["fields"])
|
| 603 |
from core import user_tables as _zones
|
| 604 |
rows = _zones.zone_cells("product_data", rows, allowed_row_ids=g["pids"],
|
| 605 |
st=session.runtime)
|
|
@@ -706,6 +701,14 @@ def patch_product(pid: int, body: dict = Body(default=None),
|
|
| 706 |
PRODUCT_IMAGE_KEY = "image"
|
| 707 |
|
| 708 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 709 |
def _seed_shared(rows, rows_src, fields):
|
| 710 |
"""W30-T36 — the supplier master as a per-render DEFAULT for the four SHARED columns.
|
| 711 |
|
|
|
|
| 504 |
projected.append(item)
|
| 505 |
fields = list(fields) + projected
|
| 506 |
|
|
|
|
|
|
|
| 507 |
hidden = perm_scope.hidden_keys(session.user, MODULE, fields, st=session.runtime)
|
| 508 |
if hidden:
|
| 509 |
fields = [f for f in fields if f.get("key") not in hidden]
|
|
|
|
| 575 |
for field in fields]
|
| 576 |
return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
|
| 577 |
"fields": fields, "views": views, "lists": lists,
|
|
|
|
| 578 |
"derived": derived,
|
| 579 |
"measures": measures, "measure_sets": measure_sets, "today": today,
|
| 580 |
"team_id": team_id}
|
|
|
|
| 594 |
import modules.product_data as pd
|
| 595 |
|
| 596 |
g = product_assembly(session, consume_corrections=not bool(related))
|
| 597 |
+
rows = product_rows(g)
|
|
|
|
|
|
|
| 598 |
from core import user_tables as _zones
|
| 599 |
rows = _zones.zone_cells("product_data", rows, allowed_row_ids=g["pids"],
|
| 600 |
st=session.runtime)
|
|
|
|
| 701 |
PRODUCT_IMAGE_KEY = "image"
|
| 702 |
|
| 703 |
|
| 704 |
+
def product_rows(assembly):
|
| 705 |
+
"""The grid and Assistant share the same permissioned overlay/default projection."""
|
| 706 |
+
import aios_grid
|
| 707 |
+
rows = aios_grid.rows_from_pool(assembly["rows_src"], assembly["fields"],
|
| 708 |
+
assembly["ws"].get("overlays"), derived=assembly["derived"])
|
| 709 |
+
return _seed_image(_seed_shared(rows, assembly["rows_src"], assembly["fields"]), assembly["fields"])
|
| 710 |
+
|
| 711 |
+
|
| 712 |
def _seed_shared(rows, rows_src, fields):
|
| 713 |
"""W30-T36 — the supplier master as a per-render DEFAULT for the four SHARED columns.
|
| 714 |
|
api/routes_query.py
CHANGED
|
@@ -10,9 +10,11 @@ import csv
|
|
| 10 |
import datetime as _dt
|
| 11 |
import base64
|
| 12 |
import hashlib
|
|
|
|
| 13 |
import hmac
|
| 14 |
import io
|
| 15 |
import json
|
|
|
|
| 16 |
import os
|
| 17 |
import re
|
| 18 |
import dash_norm
|
|
@@ -28,7 +30,36 @@ import turn_audit
|
|
| 28 |
import provider_limits
|
| 29 |
import provider_stream
|
| 30 |
|
| 31 |
-
from fastapi import APIRouter, Body, Depends, Response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
from deps import (Session, assistant_read_scope, assistant_source_status, err,
|
| 34 |
module_gate, require_session)
|
|
@@ -62,7 +93,7 @@ from deps import (Session, assistant_read_scope, assistant_source_status, err,
|
|
| 62 |
#: `analyst` grant. One entry, and adding a second is a decision somebody has to write down here.
|
| 63 |
SESSION_ONLY_PATHS = ("/api/v1/query/formula-catalogue",)
|
| 64 |
|
| 65 |
-
_analyst = APIRouter(prefix="/api/v1", dependencies=[Depends(module_gate("analyst"))])
|
| 66 |
_session_only = APIRouter(prefix="/api/v1")
|
| 67 |
#: ⚠ REBOUND AT THE BOTTOM OF THIS FILE to the ungated parent that `main.py` mounts. Until then it
|
| 68 |
#: is the gated router, which is what keeps every `@router.` decorator below a gated door.
|
|
@@ -97,6 +128,121 @@ QUERY_DRAFT_ADMIN = "This database has no approved fields yet. Pick the ones thi
|
|
| 97 |
QUERY_DRAFT_MEMBER = "This database has no approved fields yet. Pick the ones you need and your administrators will be asked to approve them."
|
| 98 |
QUERY_DRAFT_SENT = "Sent to your administrators. Ask again once one of them approves."
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
def _draft_approved_line(name, date):
|
| 102 |
return f"Approved by {_no_dashes(name)} on {str(date)[:10]}."
|
|
@@ -257,7 +403,15 @@ def _new_id(prefix):
|
|
| 257 |
|
| 258 |
def model_choices():
|
| 259 |
"""Choices are stable even when one is not configured, so explicit means explicit."""
|
| 260 |
-
return [MODEL_AUTO, *
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
|
| 263 |
def _ladder_drift():
|
|
@@ -338,17 +492,13 @@ def model_status():
|
|
| 338 |
|
| 339 |
|
| 340 |
def _providers(model=MODEL_AUTO):
|
| 341 |
-
"""
|
| 342 |
-
requested =
|
| 343 |
chain = prov.llm_chain("llm_tool_calling")
|
| 344 |
if requested != MODEL_AUTO:
|
| 345 |
chain = [p for p in chain if p.name == requested]
|
| 346 |
-
else:
|
| 347 |
-
order = model_router.provider_order((_AGENT_TURN.get() or {}).get("turnKind", "other"),
|
| 348 |
-
model_router.load_receipt())
|
| 349 |
-
chain = [p for name in order for p in chain if p.name == name]
|
| 350 |
return [{"name": p.name, "label": p.label, "env": p.env, "url": p.url,
|
| 351 |
-
"model": p.
|
| 352 |
|
| 353 |
|
| 354 |
def _model_identity(provider):
|
|
@@ -448,6 +598,7 @@ def _spec_schema(field_keys):
|
|
| 448 |
"filters": {"type": "array", "items": {"type": "object", "properties": {
|
| 449 |
"colId": col, "op": {"type": "string", "enum": sorted(_grid().FILTER_OPS)},
|
| 450 |
"value": {"type": "string"},
|
|
|
|
| 451 |
"values": {"type": "array", "items": {"type": "string"}},
|
| 452 |
"rhs": {"type": "object", "properties": {
|
| 453 |
"kind": {"type": "string", "enum": ["field"]}, "colId": col,
|
|
@@ -462,7 +613,7 @@ def _spec_schema(field_keys):
|
|
| 462 |
}, "required": ["colId", "dir"]}},
|
| 463 |
"groupBy": col,
|
| 464 |
"aggregation": {"type": "object", "properties": {
|
| 465 |
-
"op": {"type": "string", "enum": ["count", "sum", "avg", "min", "max"]},
|
| 466 |
"field": col,
|
| 467 |
}, "required": ["op"]},
|
| 468 |
"stackField": col,
|
|
@@ -570,6 +721,23 @@ carries what. Every number you state comes from build_view over the snapshot abo
|
|
| 570 |
|
| 571 |
def _system_prompt(snapshot):
|
| 572 |
fields = snapshot["fields"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
cols = json.dumps([{"key": field["key"], "label": field.get("label", field["key"]),
|
| 574 |
"type": field.get("type", "text")} for field in fields], separators=(",", ":"))
|
| 575 |
return f"""You are the assistant inside this product, talking with one person about exactly one
|
|
@@ -577,9 +745,12 @@ database they already have permission to read. Reply in plain prose, and keep it
|
|
| 577 |
|
| 578 |
DATABASE: {snapshot['database']}
|
| 579 |
SNAPSHOT VERSION: {json.dumps(snapshot['source_version'], default=str)}
|
| 580 |
-
PERMISSION-FILTERED RECORD COUNT: {
|
| 581 |
FIELDS: {cols}
|
| 582 |
VIEW KINDS: {", ".join(QUERY_KINDS)}
|
|
|
|
|
|
|
|
|
|
| 583 |
|
| 584 |
You may answer in words alone, and you may ask ONE short question back when the request is
|
| 585 |
ambiguous: which field is meant, which period, whether they want every record or a narrower set.
|
|
@@ -591,9 +762,11 @@ not call it to explain something, to confirm something, or to ask your question.
|
|
| 591 |
it you may also write one sentence saying what you built.
|
| 592 |
|
| 593 |
Inside build_view: choose visible fields, supported filters and an optional aggregation. Use count
|
| 594 |
-
for record counts
|
| 595 |
every number from this exact snapshot. Never write SQL, invent fields, or name another database.
|
| 596 |
Return kind=refused with one plain sentence if the database cannot answer.
|
|
|
|
|
|
|
| 597 |
|
| 598 |
To compare one column against ANOTHER column rather than a typed value, give the filter an rhs of
|
| 599 |
{{"kind":"field","colId":"<other field>"}} and omit value. That is how you express questions like
|
|
@@ -796,7 +969,7 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
|
|
| 796 |
signature change. An omitted session is COUNTED in ``usage_ledger.UNATTRIBUTED`` and reported
|
| 797 |
to an admin, never dropped.
|
| 798 |
"""
|
| 799 |
-
requested =
|
| 800 |
if requested not in model_choices():
|
| 801 |
return None, f"the selected model ({requested or model}) is unavailable", None, "model_unavailable"
|
| 802 |
import agent_runtime
|
|
@@ -811,12 +984,21 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
|
|
| 811 |
tools.extend(agent_runtime.tool_specs(session, snapshot=snapshot))
|
| 812 |
if turn.get("openWork"):
|
| 813 |
tools = [tool for tool in tools if tool["function"]["name"] == "open_items"]
|
|
|
|
|
|
|
| 814 |
if turn.get("memoryOnly"):
|
| 815 |
tools = [tool for tool in tools if tool["function"]["name"] in {"remember", "recall_memory"}]
|
|
|
|
|
|
|
| 816 |
prompt = (_system_prompt(snapshot) if snapshot is not None else
|
| 817 |
"You are the Loopable Assistant. Use tools for facts. Writes run at once. Deletes need the user's yes.")
|
| 818 |
if turn.get("context"):
|
| 819 |
prompt += "\n\n" + turn["context"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 820 |
if turn.get("channel") and not turn.get("memoryOnly"):
|
| 821 |
prompt += "\nThis is a shared channel. Only build_view over this snapshot is available."
|
| 822 |
if session is not None:
|
|
@@ -830,7 +1012,7 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
|
|
| 830 |
prompt += "\n\n" + memory
|
| 831 |
messages = [{"role": "system", "content": _no_dashes(prompt)},
|
| 832 |
*(history or []),
|
| 833 |
-
{"role": "user", "content": question}]
|
| 834 |
turn["intentTexts"] = [question]
|
| 835 |
chosen = None
|
| 836 |
offered = {tool["function"]["name"] for tool in tools}
|
|
@@ -923,7 +1105,12 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
|
|
| 923 |
result = {"ok": False, "error": "New instructions arrived. Reconsider this tool before executing it."}
|
| 924 |
elif name not in offered or session is None:
|
| 925 |
result = {"ok": False, "error": "That tool is not available for this conversation."}
|
| 926 |
-
elif
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 927 |
import assistant_open_items
|
| 928 |
if turn.get("handle") is not None:
|
| 929 |
with turn["handle"].execution() as allowed:
|
|
@@ -940,6 +1127,13 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
|
|
| 940 |
reconsider = True
|
| 941 |
else:
|
| 942 |
result = agent_runtime.execute(session, name, args, door=_AGENT_DOOR.get(), turn=turn)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 943 |
if isinstance(result, dict) and result.get("stopped"):
|
| 944 |
return None, None, provider, "stopped"
|
| 945 |
content = json.dumps(result, default=str, ensure_ascii=False)
|
|
@@ -959,6 +1153,7 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
|
|
| 959 |
after_attempt=None, input_token_bound=None, output_token_bound=None):
|
| 960 |
"""The provider ladder runs before the first response; subsequent steps pin that provider."""
|
| 961 |
|
|
|
|
| 962 |
priced = before_attempt is not None or after_attempt is not None
|
| 963 |
if priced:
|
| 964 |
from core import login_run
|
|
@@ -977,23 +1172,9 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
|
|
| 977 |
if chosen:
|
| 978 |
providers = [provider for provider in providers if provider["name"] == chosen]
|
| 979 |
if not providers:
|
| 980 |
-
#
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
# sentence is how the owner ended up reading `HTTP 402` to find out which.
|
| 984 |
-
broke = [row for row in prov.llm_status() if row["outOfCredit"]]
|
| 985 |
-
if requested != MODEL_AUTO:
|
| 986 |
-
row = next((r for r in prov.llm_status() if r["provider"] == requested), None)
|
| 987 |
-
if row and row["outOfCredit"]:
|
| 988 |
-
sentence = f"{row['label']} is out of credit, so it cannot answer right now"
|
| 989 |
-
else:
|
| 990 |
-
sentence = f"the selected model ({requested}) is unavailable"
|
| 991 |
-
return None, sentence, None, "model_unavailable"
|
| 992 |
-
if broke:
|
| 993 |
-
names = ", ".join(row["label"] for row in broke)
|
| 994 |
-
return (None, f"every model this deployment can reach is out of credit ({names}). "
|
| 995 |
-
f"Top one up and it will answer again", None, "no_credit")
|
| 996 |
-
return None, "the assistant is not configured on this deployment", None, "not_configured"
|
| 997 |
|
| 998 |
import requests
|
| 999 |
|
|
@@ -1029,7 +1210,7 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
|
|
| 1029 |
def pause():
|
| 1030 |
if not turn.get("providerPaused"):
|
| 1031 |
turn["providerPaused"] = True
|
| 1032 |
-
provider_stream.emit("paused", {"message": provider_limits.PAUSED_MESSAGE})
|
| 1033 |
if turn.get("handle") is not None and session is not None:
|
| 1034 |
turn_audit.write(turn["handle"], session.runtime, result={"status": "paused"})
|
| 1035 |
|
|
@@ -1111,11 +1292,11 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
|
|
| 1111 |
continue
|
| 1112 |
except provider_limits.RetryExhausted:
|
| 1113 |
turn["providerLimitExhausted"] = True
|
| 1114 |
-
return None,
|
| 1115 |
except Exception as exc: # noqa: BLE001
|
| 1116 |
if priced:
|
| 1117 |
raise
|
| 1118 |
-
trouble.append(f"
|
| 1119 |
continue
|
| 1120 |
|
| 1121 |
if response.status_code == 400 and provider["wire"] == "openai":
|
|
@@ -1133,8 +1314,7 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
|
|
| 1133 |
# it instead of paying the round trip again.
|
| 1134 |
if prov.is_credit_failure(response.status_code, response.text):
|
| 1135 |
prov.mark_no_credit(provider["name"])
|
| 1136 |
-
trouble.append(
|
| 1137 |
-
response.text))
|
| 1138 |
continue
|
| 1139 |
|
| 1140 |
try:
|
|
@@ -1146,7 +1326,7 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
|
|
| 1146 |
_book(provider, body)
|
| 1147 |
spec, said, refused = read(body)
|
| 1148 |
if refused:
|
| 1149 |
-
trouble.append(
|
| 1150 |
continue
|
| 1151 |
if spec is not None:
|
| 1152 |
# The prose rides ALONG with the view when the model wrote both, so the reader gets
|
|
@@ -1154,21 +1334,21 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
|
|
| 1154 |
return spec, said, provider["name"], None
|
| 1155 |
if said:
|
| 1156 |
return None, said, provider["name"], None
|
|
|
|
|
|
|
|
|
|
| 1157 |
# ⚠ Neither a call nor a word is a FAILED turn, not a silent one: falling through to
|
| 1158 |
# the next provider is right, and swallowing it as an empty answer would show the
|
| 1159 |
# reader a blank reply [[empty-answer-vs-unfinished-answer]].
|
| 1160 |
-
trouble.append(
|
| 1161 |
except provider_stream.StreamFailure as exc:
|
| 1162 |
_book(provider, exc.body)
|
| 1163 |
-
return None,
|
| 1164 |
except Exception as exc: # noqa: BLE001
|
| 1165 |
-
trouble.append(f"
|
| 1166 |
-
f"({type(exc).__name__})")
|
| 1167 |
if requested != MODEL_AUTO:
|
| 1168 |
-
return (None,
|
| 1169 |
-
|
| 1170 |
-
return (None, "the assistant could not be reached just now: "
|
| 1171 |
-
+ ("; ".join(trouble) if trouble else "no provider answered"),
|
| 1172 |
None, "provider_unreachable")
|
| 1173 |
|
| 1174 |
|
|
@@ -1185,10 +1365,10 @@ def _validate(spec, fields):
|
|
| 1185 |
if kind in QUERY_EXCLUDED or kind not in QUERY_KINDS:
|
| 1186 |
return None, "that kind of view cannot be built from this question", "unsupported_kind"
|
| 1187 |
|
| 1188 |
-
named =
|
| 1189 |
for item in spec.get("filters") or ():
|
| 1190 |
if isinstance(item, dict) and item.get("colId"):
|
| 1191 |
-
named
|
| 1192 |
# ⛔ THE RIGHT-HAND COLUMN IS A COLUMN AND MUST FACE THE SAME `missing` CHECK. Collecting
|
| 1193 |
# only the left side is what makes D-229 possible one layer down: `clean_filter_tree` does
|
| 1194 |
# NOT drop a leaf whose field-rhs names a column that does not exist — it keeps the leaf,
|
|
@@ -1198,21 +1378,25 @@ def _validate(spec, fields):
|
|
| 1198 |
# Naming it here turns that into the ordinary "this database does not have: X" refusal.
|
| 1199 |
rhs = item.get("rhs") if isinstance(item, dict) else None
|
| 1200 |
if isinstance(rhs, dict) and rhs.get("colId"):
|
| 1201 |
-
named
|
| 1202 |
for item in spec.get("sorts") or ():
|
| 1203 |
if isinstance(item, dict) and item.get("colId"):
|
| 1204 |
-
named
|
| 1205 |
for key in ("groupBy", "stackField", "dateField", "colorField", "sizeField"):
|
| 1206 |
if spec.get(key):
|
| 1207 |
-
named
|
| 1208 |
raw_aggregation = spec.get("aggregation") or {"op": "count"}
|
| 1209 |
if isinstance(raw_aggregation, dict) and raw_aggregation.get("field"):
|
| 1210 |
-
named
|
| 1211 |
-
missing = sorted(named - keys)
|
| 1212 |
if missing:
|
| 1213 |
return None, "this database does not have: " + ", ".join(missing), "unknown_columns"
|
| 1214 |
|
| 1215 |
visible = [str(key) for key in (spec.get("visible") or ()) if str(key) in keys][:MAX_VISIBLE]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1216 |
if not visible:
|
| 1217 |
return None, "that question did not name any fields to show", "no_columns"
|
| 1218 |
raw_filters = [item for item in (spec.get("filters") or ()) if isinstance(item, dict)]
|
|
@@ -1229,6 +1413,12 @@ def _validate(spec, fields):
|
|
| 1229 |
# `_clean_rhs` rule). Both doors, because the two catch different causes and the cost of
|
| 1230 |
# missing this one is a wrong answer that looks right.
|
| 1231 |
for sent, kept in zip(raw_filters, filters):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1232 |
if sent.get("rhs") and not kept.get("rhs"):
|
| 1233 |
return None, "that column cannot be compared against another column", "rhs_dropped"
|
| 1234 |
# D-658: an empty multi-value leaf survives cleaning but narrows no records.
|
|
@@ -1239,11 +1429,12 @@ def _validate(spec, fields):
|
|
| 1239 |
aggregation = raw_aggregation if isinstance(raw_aggregation, dict) else {}
|
| 1240 |
op = str(aggregation.get("op") or "").lower()
|
| 1241 |
field = aggregation.get("field")
|
| 1242 |
-
if op not in {"count", "sum", "avg", "min", "max"}:
|
| 1243 |
return None, "the assistant gave an unsupported aggregation", "bad_aggregation"
|
| 1244 |
if op == "count":
|
| 1245 |
field = None
|
| 1246 |
-
elif field not in keys or
|
|
|
|
| 1247 |
return None, "that aggregation needs one visible numeric field", "bad_aggregation"
|
| 1248 |
|
| 1249 |
display = {"mode": kind}
|
|
@@ -1320,6 +1511,12 @@ def _numeric_result(view, records):
|
|
| 1320 |
aggregation = view["aggregation"]
|
| 1321 |
if aggregation["op"] == "count":
|
| 1322 |
return {"label": "Matching records", "value": len(records), "contributing_record_count": len(records)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1323 |
values = []
|
| 1324 |
for record in records:
|
| 1325 |
try:
|
|
@@ -1687,14 +1884,13 @@ def _sources(body, target, session):
|
|
| 1687 |
sources = list(dict.fromkeys(item for item in sources if item))
|
| 1688 |
if target not in sources:
|
| 1689 |
sources.insert(0, target)
|
| 1690 |
-
# Source chips
|
| 1691 |
-
# The model still receives ONLY `target`'s snapshot below; these calls do not pass a second
|
| 1692 |
-
# source to it and D's helper refuses cache misses, mirrors and unshared databases.
|
| 1693 |
for source in sources:
|
| 1694 |
-
assistant_read_scope(session, source, fields=[], filters=None)
|
| 1695 |
return sources
|
| 1696 |
|
| 1697 |
|
|
|
|
| 1698 |
def _submit(body, session, chat=None, *, also_as=(), door="app", audit_handle=None):
|
| 1699 |
# C10 currently sets the door context; the explicit keyword is also the C12 consumer seam.
|
| 1700 |
door = _AGENT_DOOR.get() if door == "app" else door
|
|
@@ -1717,7 +1913,7 @@ def _submit(body, session, chat=None, *, also_as=(), door="app", audit_handle=No
|
|
| 1717 |
"toolCalls": [], "pendingDelete": None, "artifacts": [], "view": None, "citations": []}
|
| 1718 |
context_hint = assistant_dock.context_of(body, session)
|
| 1719 |
dock = assistant_dock.payload_context(body["dock"]) if context_hint is not None else None
|
| 1720 |
-
selected_model =
|
| 1721 |
if not question:
|
| 1722 |
raise err(400, "bad_request", "no question was asked")
|
| 1723 |
if len(question) > MAX_QUESTION:
|
|
@@ -1749,17 +1945,36 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1749 |
target = (dock.get("database", "") if dock is not None else
|
| 1750 |
str((replay or {}).get("database") or body.get("database") or body.get("scope") or "").strip())
|
| 1751 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1752 |
import assistant_open_items
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1753 |
open_work = (dock is None and not target and replay is None and not also_as and door != "slack"
|
| 1754 |
and assistant_open_items.admits(question))
|
| 1755 |
memory_only = dock is None and not target and replay is None and assistant_memory.admits(question)
|
| 1756 |
-
routed = _route(session, question) if dock is None and not open_work and not memory_only and not target and replay is None else {
|
| 1757 |
"database": target, "auto": False, "alternatives": []}
|
| 1758 |
target = routed["database"]
|
| 1759 |
-
route_refusal = (None if dock is not None or open_work or memory_only else
|
| 1760 |
QUERY_NO_SOURCE_MATCHED if not target and replay is None else routed.get("refusal"))
|
| 1761 |
|
| 1762 |
-
# Snapshot turns
|
| 1763 |
scope_reader = assistant_read_scope
|
| 1764 |
scope_extra = {}
|
| 1765 |
if also_as:
|
|
@@ -1770,8 +1985,11 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1770 |
scope_reader = deps.assistant_read_scope
|
| 1771 |
scope_extra["also_as"] = also_as
|
| 1772 |
snapshot = (scope_reader(session, target, fields=None,
|
| 1773 |
-
filters=(replay or {}).get("filters", body.get("filters")),
|
|
|
|
| 1774 |
if dock is None and target and not route_refusal else None)
|
|
|
|
|
|
|
| 1775 |
sources = (list(dict.fromkeys(key for key in
|
| 1776 |
[target, *(dock.get("databases") or []), *(body.get("sources") or [])] if key))
|
| 1777 |
if dock is not None else
|
|
@@ -1794,8 +2012,13 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1794 |
"also_as": list(also_as), "door": door, "turnKind": model_router.classify_turn(question, dock),
|
| 1795 |
"handle": handle, "dock": dock}
|
| 1796 |
handle.audit_turn = turn
|
|
|
|
|
|
|
|
|
|
| 1797 |
if open_work:
|
| 1798 |
turn["openWork"] = True
|
|
|
|
|
|
|
| 1799 |
if memory_only:
|
| 1800 |
turn["memoryOnly"] = True
|
| 1801 |
turn["memoryCompanyRequested"] = assistant_memory.company_requested(question)
|
|
@@ -1832,9 +2055,36 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1832 |
_AGENT_TURN.reset(token)
|
| 1833 |
if reason == "stopped":
|
| 1834 |
return turn_control.envelope(handle, "stopped")
|
|
|
|
|
|
|
| 1835 |
view, refusal, refusal_code = (_validate(spec, snapshot["fields"])
|
| 1836 |
if spec is not None and snapshot is not None else (None, said, reason))
|
| 1837 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1838 |
# Injected callers and non-model refusals also seal their completion against joins.
|
| 1839 |
if handle.stopped or handle.cancel_requested.is_set():
|
| 1840 |
return turn_control.envelope(handle, "stopped")
|
|
@@ -1842,9 +2092,11 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1842 |
if handle.close() == "stopped":
|
| 1843 |
return turn_control.envelope(handle, "stopped")
|
| 1844 |
|
| 1845 |
-
if turn.get("memoryReply"):
|
| 1846 |
-
#
|
| 1847 |
said, refusal = turn["memoryReply"], turn["memoryReply"]
|
|
|
|
|
|
|
| 1848 |
|
| 1849 |
artifact = None
|
| 1850 |
citation = None
|
|
@@ -1853,7 +2105,7 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1853 |
raise err(400, "query_limit", f"you already have {len(state['views'])} Query artefacts")
|
| 1854 |
view_id = _new_id("query")
|
| 1855 |
citation_id = _new_id("citation")
|
| 1856 |
-
numeric = _numeric_result(view, _view_records(snapshot, view))
|
| 1857 |
citation = _citation(citation_id, snapshot, view, numeric, view_id)
|
| 1858 |
if not _citation_complete(citation):
|
| 1859 |
raise RuntimeError("Query refused to persist an incomplete numeric citation")
|
|
@@ -1894,7 +2146,8 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1894 |
"targetDatabase": target, "requestedModel": selected_model, "model": provider, "turnKind": turn["turnKind"],
|
| 1895 |
"routedTo": routed,
|
| 1896 |
**_model_identity(provider),
|
| 1897 |
-
"reason": refusal_code, "
|
|
|
|
| 1898 |
"provenance": _answer_provenance(artifact),
|
| 1899 |
"citationIds": artifact["citationIds"] if artifact else [], "numeric": artifact["numeric"] if artifact else None,
|
| 1900 |
"toolCalls": turn["toolCalls"], "pendingDelete": turn["pendingDelete"], "artifacts": turn["artifacts"],
|
|
@@ -1927,7 +2180,11 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1927 |
if door != "slack" and not session.runtime.available():
|
| 1928 |
raise err(503, "store_unavailable", "the tenant store is unavailable; no chat was saved")
|
| 1929 |
if door != "slack":
|
|
|
|
|
|
|
| 1930 |
for message in (user_message, assistant_message):
|
|
|
|
|
|
|
| 1931 |
assistant_log.append(session.runtime, session.uname, {
|
| 1932 |
"role": message["role"], "door": door, "kind": "text", "text": message["content"],
|
| 1933 |
"at": now, "payload": {key: value for key, value in message.items()
|
|
@@ -1935,14 +2192,21 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
|
|
| 1935 |
if artifact:
|
| 1936 |
session.runtime.update(_namespace_key(session), update, flush="async")
|
| 1937 |
import agent_runtime
|
| 1938 |
-
|
|
|
|
| 1939 |
thread = {"id": thread_id, "title": "Conversation", "createdAt": now, "updatedAt": now,
|
| 1940 |
"sources": sources, "model": selected_model, "activeViewId": artifact["id"] if artifact else None}
|
| 1941 |
-
|
| 1942 |
-
|
| 1943 |
-
|
| 1944 |
-
|
| 1945 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1946 |
|
| 1947 |
|
| 1948 |
@router.post("/query/chat")
|
|
@@ -1950,7 +2214,34 @@ def submit_chat(body: dict = Body(default=None), session: Session = Depends(requ
|
|
| 1950 |
return _submit(body, session)
|
| 1951 |
|
| 1952 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1953 |
@router.get("/assistant/log")
|
|
|
|
| 1954 |
def conversation_log(before: str = None, limit: int = 50,
|
| 1955 |
session: Session = Depends(require_session)):
|
| 1956 |
try:
|
|
@@ -2099,7 +2390,8 @@ def list_artifacts(cursor: str = None, limit: int = 50, session: Session = Depen
|
|
| 2099 |
next_cursor = base64.urlsafe_b64encode(json.dumps([
|
| 2100 |
assistant_log._hash(session.runtime, session.uname), last["createdAt"], last["id"]]).encode()).decode()
|
| 2101 |
return {"items": [{key: row[key] for key in (
|
| 2102 |
-
"id", "kind", "title", "door", "createdAt", "ref", "status", "toolCall", "actions")}
|
|
|
|
| 2103 |
"nextCursor": next_cursor}
|
| 2104 |
|
| 2105 |
|
|
@@ -2117,6 +2409,26 @@ def _artifact_item(session, item_id):
|
|
| 2117 |
return item
|
| 2118 |
|
| 2119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2120 |
def _replay_artifact(session, item, *, name=None, args=None):
|
| 2121 |
import agent_runtime
|
| 2122 |
call = item["toolCall"]
|
|
@@ -2825,21 +3137,70 @@ def _tool_plan(question, body, snapshot, session):
|
|
| 2825 |
"""Use the existing governed planner only when a channel did not supply typed artifacts."""
|
| 2826 |
artifact_keys = {"view", "filters", "sorts", "group", "hiddenFields", "aggregation", "kind"}
|
| 2827 |
if any(key in body for key in artifact_keys):
|
| 2828 |
-
return _tool_spec(body, [field["key"] for field in snapshot.get("fields") or ()]), None, None
|
| 2829 |
-
selected_model =
|
| 2830 |
if selected_model not in model_choices():
|
| 2831 |
raise err(400, "unknown_model", "that model is not available in Query")
|
| 2832 |
spec, said, provider, reason = _call_model(
|
| 2833 |
question, snapshot, model=selected_model, chat=None, history=None, session=session)
|
| 2834 |
if spec is None:
|
| 2835 |
-
return None, (said or "Query could not build an answer"), provider
|
| 2836 |
-
return spec, said, provider
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2837 |
|
| 2838 |
|
| 2839 |
@router.post("/query/tool")
|
|
|
|
| 2840 |
def governed_query(body: dict = Body(default=None),
|
| 2841 |
session: Session = Depends(require_session)):
|
| 2842 |
-
"""
|
| 2843 |
body = body if isinstance(body, dict) else {}
|
| 2844 |
database = str(body.get("database") or "").strip()
|
| 2845 |
question = " ".join(str(body.get("prompt") or body.get("question") or "").split())
|
|
@@ -2854,8 +3215,11 @@ def governed_query(body: dict = Body(default=None),
|
|
| 2854 |
_semantic_authorize(session, database, require_answerable=not routed["auto"])
|
| 2855 |
route_refusal = QUERY_NO_SOURCE_MATCHED if not database else routed.get("refusal")
|
| 2856 |
if route_refusal:
|
| 2857 |
-
|
| 2858 |
-
|
|
|
|
|
|
|
|
|
|
| 2859 |
records = _semantic_records(session, database)
|
| 2860 |
if not routed["auto"]:
|
| 2861 |
from harness import semantic as sem
|
|
@@ -2877,25 +3241,52 @@ def governed_query(body: dict = Body(default=None),
|
|
| 2877 |
selected = [semantic_rt.require_approved(records, database, key) for key in requested]
|
| 2878 |
except semantic_rt.SemanticError as exc:
|
| 2879 |
raise err(403, "semantic_field_unapproved", str(exc))
|
| 2880 |
-
snapshot = assistant_read_scope(session, database, fields=requested, filters=None)
|
|
|
|
| 2881 |
snapshot = _semantic_answer_snapshot(snapshot, records)
|
|
|
|
|
|
|
| 2882 |
snapshot, formulas = _tool_formula_snapshot(body, snapshot, requested)
|
| 2883 |
-
spec, planned_wording, provider = _tool_plan(question, body, snapshot, session)
|
| 2884 |
if spec is None:
|
| 2885 |
-
|
| 2886 |
-
|
| 2887 |
-
|
|
|
|
|
|
|
|
|
|
| 2888 |
view, refusal, refusal_code = _validate(spec, snapshot.get("fields") or selected)
|
| 2889 |
if view is None:
|
| 2890 |
raise err(400, refusal_code or "bad_query_artifact", refusal or "that Query is invalid")
|
| 2891 |
-
|
| 2892 |
-
|
| 2893 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2894 |
row_ids = [str(row.get("pid") or row.get("id") or index)
|
| 2895 |
for index, row in enumerate(rows)]
|
| 2896 |
hidden = [key for key in requested if key not in set(view.get("visible") or ())]
|
| 2897 |
-
groups = _tool_groups(ordered, view)
|
| 2898 |
-
numeric = _numeric_result(view, ordered)
|
| 2899 |
artifacts = {"filters": _safe(view.get("filters") or []),
|
| 2900 |
"sorts": _safe(view.get("sorts") or []),
|
| 2901 |
"group": _safe(view.get("groupBy")),
|
|
@@ -2903,11 +3294,13 @@ def governed_query(body: dict = Body(default=None),
|
|
| 2903 |
"formulas": _safe(formulas),
|
| 2904 |
"source": {"database": database, "fields": requested,
|
| 2905 |
"permissionScopeApplied": True}}
|
| 2906 |
-
wording = _tool_wording(question, numeric,
|
|
|
|
| 2907 |
return {"status": "answered", "wording": wording, "speakable": wording,
|
| 2908 |
"citations": [{"database": database, "rowId": value} for value in row_ids],
|
| 2909 |
"rows": [{key: row.get(key) for key in view["visible"]} for row in rows],
|
| 2910 |
"groups": groups, "numeric": numeric,
|
|
|
|
| 2911 |
"artifacts": artifacts, "semanticRouter": semantic_rt.router_projection(records, database),
|
| 2912 |
"model": _model_identity(provider), "routedTo": routed}
|
| 2913 |
|
|
@@ -3364,7 +3757,11 @@ router.routes.extend(_session_only.routes)
|
|
| 3364 |
router.routes.extend(_analyst_routes.routes)
|
| 3365 |
|
| 3366 |
from assistant_routers import ROUTERS as _ASSISTANT_ROUTERS # noqa: E402
|
|
|
|
| 3367 |
for _assistant_router in _ASSISTANT_ROUTERS:
|
|
|
|
|
|
|
|
|
|
| 3368 |
_start = len(router.routes)
|
| 3369 |
router.include_router(_assistant_router)
|
| 3370 |
# FastAPI 0.139 adds lazy wrappers; existing route audits need the actual gated routes.
|
|
|
|
| 10 |
import datetime as _dt
|
| 11 |
import base64
|
| 12 |
import hashlib
|
| 13 |
+
import functools
|
| 14 |
import hmac
|
| 15 |
import io
|
| 16 |
import json
|
| 17 |
+
import logging
|
| 18 |
import os
|
| 19 |
import re
|
| 20 |
import dash_norm
|
|
|
|
| 30 |
import provider_limits
|
| 31 |
import provider_stream
|
| 32 |
|
| 33 |
+
from fastapi import APIRouter, Body, Depends, HTTPException, Response
|
| 34 |
+
from fastapi.exceptions import RequestValidationError
|
| 35 |
+
from fastapi.routing import APIRoute
|
| 36 |
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
| 37 |
+
from starlette.responses import StreamingResponse
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class _C2Route(APIRoute):
|
| 41 |
+
"""Cover dependency and request validation refusals before the endpoint runs."""
|
| 42 |
+
|
| 43 |
+
def get_route_handler(self):
|
| 44 |
+
handler = super().get_route_handler()
|
| 45 |
+
if self.path not in {"/api/v1/query/tool", "/api/v1/query/chat", "/api/v1/query/chat/stream"}:
|
| 46 |
+
return handler
|
| 47 |
+
|
| 48 |
+
async def door(request):
|
| 49 |
+
route = self.path.removeprefix("/api/v1")
|
| 50 |
+
try:
|
| 51 |
+
return await handler(request)
|
| 52 |
+
except StarletteHTTPException as exc:
|
| 53 |
+
raise _c2_http(exc, route, None) from None
|
| 54 |
+
except RequestValidationError:
|
| 55 |
+
raise _c2_http(err(422, "bad_request", "request validation failed"), route, None) from None
|
| 56 |
+
except Exception as exc:
|
| 57 |
+
from core import grid_events
|
| 58 |
+
cause = "store_unavailable" if isinstance(exc, grid_events.StoreUnavailable) else "stream_failed"
|
| 59 |
+
raise _c2_http(err(503 if cause == "store_unavailable" else 500, cause,
|
| 60 |
+
_RefusalDetail(type(exc).__name__)), route, None) from None
|
| 61 |
+
|
| 62 |
+
return door
|
| 63 |
|
| 64 |
from deps import (Session, assistant_read_scope, assistant_source_status, err,
|
| 65 |
module_gate, require_session)
|
|
|
|
| 93 |
#: `analyst` grant. One entry, and adding a second is a decision somebody has to write down here.
|
| 94 |
SESSION_ONLY_PATHS = ("/api/v1/query/formula-catalogue",)
|
| 95 |
|
| 96 |
+
_analyst = APIRouter(prefix="/api/v1", dependencies=[Depends(module_gate("analyst"))], route_class=_C2Route)
|
| 97 |
_session_only = APIRouter(prefix="/api/v1")
|
| 98 |
#: ⚠ REBOUND AT THE BOTTOM OF THIS FILE to the ungated parent that `main.py` mounts. Until then it
|
| 99 |
#: is the gated router, which is what keeps every `@router.` decorator below a gated door.
|
|
|
|
| 128 |
QUERY_DRAFT_MEMBER = "This database has no approved fields yet. Pick the ones you need and your administrators will be asked to approve them."
|
| 129 |
QUERY_DRAFT_SENT = "Sent to your administrators. Ask again once one of them approves."
|
| 130 |
|
| 131 |
+
_LOG = logging.getLogger(__name__)
|
| 132 |
+
#: C2: the refusal codes a client renders, each with its one sentence. Add a code only by a dated PRD amendment.
|
| 133 |
+
C2_MESSAGES = {
|
| 134 |
+
"assistant_forbidden": "You do not have access to that database.",
|
| 135 |
+
"query_source_unavailable": "That source is still syncing. Try again in a few minutes.",
|
| 136 |
+
"source_needs_filter": "That question needs every row at once. Add a filter or ask for a total.",
|
| 137 |
+
"provider_unreachable": "The model did not answer. Try again in a moment.",
|
| 138 |
+
"provider_limited": "The model is busy. Your answer resumes shortly.",
|
| 139 |
+
"store_unavailable": "Loopable could not reach its store. Try again in a moment.",
|
| 140 |
+
"question_too_long": "That question is too long. Shorten it and send it again.",
|
| 141 |
+
"semantic_field_unapproved": "That field is not approved for answers yet. Ask an Administrator.",
|
| 142 |
+
"session_expired": "Your session ended. Sign in again.",
|
| 143 |
+
}
|
| 144 |
+
C2_GENERIC = "This database could not answer right now. Please try again."
|
| 145 |
+
#: Internal refusal codes that answer as a C2 code. Any other code keeps its own name.
|
| 146 |
+
_C2_ALIASES = {
|
| 147 |
+
"assistant_snapshot_unavailable": "query_source_unavailable",
|
| 148 |
+
"assistant_store_not_ready": "query_source_unavailable",
|
| 149 |
+
"assistant_unknown_database": "assistant_forbidden",
|
| 150 |
+
"forbidden": "assistant_forbidden",
|
| 151 |
+
"shared_channel_unavailable": "assistant_forbidden",
|
| 152 |
+
"invalid_session": "session_expired",
|
| 153 |
+
"no_session": "session_expired",
|
| 154 |
+
"shared_channel_semantics": "semantic_field_unapproved",
|
| 155 |
+
"not_configured": "provider_unreachable",
|
| 156 |
+
"no_credit": "provider_unreachable",
|
| 157 |
+
"no_provider": "provider_unreachable",
|
| 158 |
+
"model_unavailable": "provider_unreachable",
|
| 159 |
+
"provider_stream_error": "provider_unreachable",
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class _RefusalDetail(str):
|
| 164 |
+
"""Diagnostics composed from provider status or exception type, never response text."""
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
_LOG_CAUSES = set(C2_MESSAGES) | set(_C2_ALIASES) | {
|
| 168 |
+
"model_refused", "no_spec", "unknown_columns",
|
| 169 |
+
"assistant_source_too_large", "query_no_source_matched", "bad_request", "unknown_model",
|
| 170 |
+
"turn_join_scope", "query_limit", "tool_arguments_invalid", "bad_formula", "bad_resume_token",
|
| 171 |
+
"unsupported_kind", "no_columns", "unknown_filter", "bad_filter", "bad_query_artifact",
|
| 172 |
+
"stream_failed", "stream_replaced", "turn_stopped",
|
| 173 |
+
"query_resume_refused", "filter_dropped", "rhs_dropped", "values_missing", "bad_aggregation",
|
| 174 |
+
"missing_ref", "wrong_ref_type", "display_dropped", "assistant_bad_filter", "assistant_bad_fields",
|
| 175 |
+
"assistant_unknown_field",
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def c2_code(cause, detail=""):
|
| 180 |
+
"""The C2 code a refusal answers with. An unmapped code stays itself."""
|
| 181 |
+
cause = str(cause or "")
|
| 182 |
+
if cause == "assistant_source_too_large":
|
| 183 |
+
# An evicted stored table is unavailable. The mirror row cap needs a narrower question.
|
| 184 |
+
return "query_source_unavailable" if "is not stored" in str(detail or "") else "source_needs_filter"
|
| 185 |
+
return _C2_ALIASES.get(cause, cause)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def c2_message(code):
|
| 189 |
+
"""The one sentence a C2 code carries. Any other code carries the generic sentence."""
|
| 190 |
+
return C2_MESSAGES.get(code, C2_GENERIC)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _log_refusal(route, code, cause, detail, session):
|
| 194 |
+
"""One line per refusal: the C2 code and the real cause, never a key, URL, token or record value."""
|
| 195 |
+
tenant = str(getattr(session, "tenant", "") or "")
|
| 196 |
+
user = hashlib.sha256(f"{tenant}:{getattr(session, 'uname', '')}".encode("utf-8")).hexdigest()[:12]
|
| 197 |
+
# Redaction cannot prove arbitrary exception/model text is free of secrets or record values.
|
| 198 |
+
# Only diagnostics constructed at the transport boundary enter this line.
|
| 199 |
+
detail = str(detail) if isinstance(detail, _RefusalDetail) else ""
|
| 200 |
+
cause = cause if cause in _LOG_CAUSES else "unclassified"
|
| 201 |
+
logged_code = code if code in _LOG_CAUSES else "unclassified"
|
| 202 |
+
tenant = hashlib.sha256(tenant.encode("utf-8")).hexdigest()[:12]
|
| 203 |
+
_LOG.warning("assistant refusal route=%s code=%s cause=%s detail=%s tenant=%s user=%s",
|
| 204 |
+
route, logged_code, cause, json.dumps(detail, ensure_ascii=False), tenant, user)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _refusal(route, cause, detail, session):
|
| 208 |
+
"""The C2 fields of a 200 refusal, logged once."""
|
| 209 |
+
code = c2_code(cause, detail)
|
| 210 |
+
_log_refusal(route, code, cause, detail, session)
|
| 211 |
+
return {"code": code, "message": c2_message(code), "cause": cause}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _c2_http(exc, route, session):
|
| 215 |
+
"""The same HTTP refusal under its C2 code and sentence, with the original code as `cause`."""
|
| 216 |
+
detail = getattr(exc, "detail", None)
|
| 217 |
+
error = detail.get("error") if isinstance(detail, dict) else None
|
| 218 |
+
if getattr(exc, "_c2_normalized", False):
|
| 219 |
+
return exc
|
| 220 |
+
error = error if isinstance(error, dict) else {}
|
| 221 |
+
cause = error.get("cause") or error.get("code") or {
|
| 222 |
+
401: "session_expired", 403: "assistant_forbidden"}.get(exc.status_code, "bad_request")
|
| 223 |
+
shaped = _refusal(route, str(cause), error.get("message", detail), session)
|
| 224 |
+
normalized = HTTPException(status_code=exc.status_code, detail={"error": shaped},
|
| 225 |
+
headers=getattr(exc, "headers", None))
|
| 226 |
+
normalized._c2_normalized = True
|
| 227 |
+
return normalized
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _c2_refusals(route):
|
| 231 |
+
"""Raise every refusal of the wrapped door under its C2 code and sentence."""
|
| 232 |
+
def wrap(fn):
|
| 233 |
+
@functools.wraps(fn)
|
| 234 |
+
def door(*args, **kwargs):
|
| 235 |
+
from core import grid_events
|
| 236 |
+
session = kwargs.get("session", args[1] if len(args) > 1 else None)
|
| 237 |
+
try:
|
| 238 |
+
return fn(*args, **kwargs)
|
| 239 |
+
except StarletteHTTPException as exc:
|
| 240 |
+
raise _c2_http(exc, route, session)
|
| 241 |
+
except grid_events.StoreUnavailable:
|
| 242 |
+
raise _c2_http(err(503, "store_unavailable", _RefusalDetail("StoreUnavailable")), route, session) from None
|
| 243 |
+
return door
|
| 244 |
+
return wrap
|
| 245 |
+
|
| 246 |
|
| 247 |
def _draft_approved_line(name, date):
|
| 248 |
return f"Approved by {_no_dashes(name)} on {str(date)[:10]}."
|
|
|
|
| 403 |
|
| 404 |
def model_choices():
|
| 405 |
"""Choices are stable even when one is not configured, so explicit means explicit."""
|
| 406 |
+
return [MODEL_AUTO, *prov.LLM_DEFAULT_ORDER]
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _resolve_model(model):
|
| 410 |
+
"""A retired provider name resolves to `auto` (R112), and any other string stays as sent."""
|
| 411 |
+
requested = str(model or MODEL_AUTO).strip().lower()
|
| 412 |
+
if requested in prov.LLM_PROVIDERS and requested not in model_choices():
|
| 413 |
+
return MODEL_AUTO
|
| 414 |
+
return requested
|
| 415 |
|
| 416 |
|
| 417 |
def _ladder_drift():
|
|
|
|
| 492 |
|
| 493 |
|
| 494 |
def _providers(model=MODEL_AUTO):
|
| 495 |
+
"""The callable ladder for this turn, narrowed to one provider when one was chosen."""
|
| 496 |
+
requested = _resolve_model(model)
|
| 497 |
chain = prov.llm_chain("llm_tool_calling")
|
| 498 |
if requested != MODEL_AUTO:
|
| 499 |
chain = [p for p in chain if p.name == requested]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
return [{"name": p.name, "label": p.label, "env": p.env, "url": p.url,
|
| 501 |
+
"model": p.current_model(), "wire": p.wire} for p in chain]
|
| 502 |
|
| 503 |
|
| 504 |
def _model_identity(provider):
|
|
|
|
| 598 |
"filters": {"type": "array", "items": {"type": "object", "properties": {
|
| 599 |
"colId": col, "op": {"type": "string", "enum": sorted(_grid().FILTER_OPS)},
|
| 600 |
"value": {"type": "string"},
|
| 601 |
+
"value2": {"type": "string"},
|
| 602 |
"values": {"type": "array", "items": {"type": "string"}},
|
| 603 |
"rhs": {"type": "object", "properties": {
|
| 604 |
"kind": {"type": "string", "enum": ["field"]}, "colId": col,
|
|
|
|
| 613 |
}, "required": ["colId", "dir"]}},
|
| 614 |
"groupBy": col,
|
| 615 |
"aggregation": {"type": "object", "properties": {
|
| 616 |
+
"op": {"type": "string", "enum": ["count", "count_distinct", "sum", "avg", "min", "max"]},
|
| 617 |
"field": col,
|
| 618 |
}, "required": ["op"]},
|
| 619 |
"stackField": col,
|
|
|
|
| 721 |
|
| 722 |
def _system_prompt(snapshot):
|
| 723 |
fields = snapshot["fields"]
|
| 724 |
+
today = _dt.datetime.fromisoformat(_now_iso()).date()
|
| 725 |
+
last_monday = today - _dt.timedelta(days=today.weekday() + 7)
|
| 726 |
+
scope = ""
|
| 727 |
+
try:
|
| 728 |
+
from harness import semantic as sem
|
| 729 |
+
topic = next((row for row in sem.topics().values()
|
| 730 |
+
if row.get("grid") == snapshot["database"]), {})
|
| 731 |
+
except Exception:
|
| 732 |
+
topic = {}
|
| 733 |
+
for text in (topic.get("scope"), (topic.get("semantic") or {}).get("scope")):
|
| 734 |
+
if isinstance(text, str) and text.strip():
|
| 735 |
+
scope += "\nCURATED TOPIC SCOPE: " + _no_dashes(text.strip())
|
| 736 |
+
schema_only = snapshot.get("query_schema_only") is True
|
| 737 |
+
population = "Unknown. No rows were read for planning." if schema_only else len(snapshot["records"])
|
| 738 |
+
planning = ("This is a schema-only Query plan. Call build_view for totals and groups too. "
|
| 739 |
+
"The server executes its validated aggregation over all permitted matching rows. "
|
| 740 |
+
"Do not infer values or a zero count from the empty planning records.") if schema_only else ""
|
| 741 |
cols = json.dumps([{"key": field["key"], "label": field.get("label", field["key"]),
|
| 742 |
"type": field.get("type", "text")} for field in fields], separators=(",", ":"))
|
| 743 |
return f"""You are the assistant inside this product, talking with one person about exactly one
|
|
|
|
| 745 |
|
| 746 |
DATABASE: {snapshot['database']}
|
| 747 |
SNAPSHOT VERSION: {json.dumps(snapshot['source_version'], default=str)}
|
| 748 |
+
PERMISSION-FILTERED RECORD COUNT: {population}
|
| 749 |
FIELDS: {cols}
|
| 750 |
VIEW KINDS: {", ".join(QUERY_KINDS)}
|
| 751 |
+
CURRENT DATE (UTC): {today.isoformat()}
|
| 752 |
+
Last week means {last_monday.isoformat()} through {(last_monday + _dt.timedelta(days=6)).isoformat()}, inclusive, Monday to Sunday.
|
| 753 |
+
Preserve the source's date and timezone semantics. Use explicit ISO dates for relative periods.{scope}
|
| 754 |
|
| 755 |
You may answer in words alone, and you may ask ONE short question back when the request is
|
| 756 |
ambiguous: which field is meant, which period, whether they want every record or a narrower set.
|
|
|
|
| 762 |
it you may also write one sentence saying what you built.
|
| 763 |
|
| 764 |
Inside build_view: choose visible fields, supported filters and an optional aggregation. Use count
|
| 765 |
+
for record counts and count_distinct for distinct values. Sum, avg, min and max require one numeric field. The server computes and cites
|
| 766 |
every number from this exact snapshot. Never write SQL, invent fields, or name another database.
|
| 767 |
Return kind=refused with one plain sentence if the database cannot answer.
|
| 768 |
+
For between, set value to the first bound and value2 to the second bound. Both are required.
|
| 769 |
+
{planning}
|
| 770 |
|
| 771 |
To compare one column against ANOTHER column rather than a typed value, give the filter an rhs of
|
| 772 |
{{"kind":"field","colId":"<other field>"}} and omit value. That is how you express questions like
|
|
|
|
| 969 |
signature change. An omitted session is COUNTED in ``usage_ledger.UNATTRIBUTED`` and reported
|
| 970 |
to an admin, never dropped.
|
| 971 |
"""
|
| 972 |
+
requested = _resolve_model(model)
|
| 973 |
if requested not in model_choices():
|
| 974 |
return None, f"the selected model ({requested or model}) is unavailable", None, "model_unavailable"
|
| 975 |
import agent_runtime
|
|
|
|
| 984 |
tools.extend(agent_runtime.tool_specs(session, snapshot=snapshot))
|
| 985 |
if turn.get("openWork"):
|
| 986 |
tools = [tool for tool in tools if tool["function"]["name"] == "open_items"]
|
| 987 |
+
if turn.get("admittedTools"):
|
| 988 |
+
tools = [tool for tool in tools if tool["function"]["name"] in set(turn["admittedTools"])]
|
| 989 |
if turn.get("memoryOnly"):
|
| 990 |
tools = [tool for tool in tools if tool["function"]["name"] in {"remember", "recall_memory"}]
|
| 991 |
+
if turn.get("toolShareRequests"):
|
| 992 |
+
tools = [tool for tool in tools if tool["function"]["name"] == "tool_share_decide"]
|
| 993 |
prompt = (_system_prompt(snapshot) if snapshot is not None else
|
| 994 |
"You are the Loopable Assistant. Use tools for facts. Writes run at once. Deletes need the user's yes.")
|
| 995 |
if turn.get("context"):
|
| 996 |
prompt += "\n\n" + turn["context"]
|
| 997 |
+
if turn.get("toolShareRequests"):
|
| 998 |
+
prompt += ("\nThis turn concerns a pending tool-share approval only. Use the prior conversation to identify "
|
| 999 |
+
"the request. Ask which request when the user's approval is ambiguous. "
|
| 1000 |
+
"No other write is authorized. The user already said yes to these requests: "
|
| 1001 |
+
+ json.dumps(turn["toolShareApproved"]) + ".")
|
| 1002 |
if turn.get("channel") and not turn.get("memoryOnly"):
|
| 1003 |
prompt += "\nThis is a shared channel. Only build_view over this snapshot is available."
|
| 1004 |
if session is not None:
|
|
|
|
| 1012 |
prompt += "\n\n" + memory
|
| 1013 |
messages = [{"role": "system", "content": _no_dashes(prompt)},
|
| 1014 |
*(history or []),
|
| 1015 |
+
{"role": "user", "content": agent_runtime.user_content(question)}]
|
| 1016 |
turn["intentTexts"] = [question]
|
| 1017 |
chosen = None
|
| 1018 |
offered = {tool["function"]["name"] for tool in tools}
|
|
|
|
| 1105 |
result = {"ok": False, "error": "New instructions arrived. Reconsider this tool before executing it."}
|
| 1106 |
elif name not in offered or session is None:
|
| 1107 |
result = {"ok": False, "error": "That tool is not available for this conversation."}
|
| 1108 |
+
elif turn.get("toolShareRequests") and (
|
| 1109 |
+
name != "tool_share_decide" or not isinstance(args, dict) or args.get("decision") != "yes"
|
| 1110 |
+
or args.get("request") not in turn["toolShareApproved"]
|
| 1111 |
+
or len(turn.get("intentTexts") or []) != 1):
|
| 1112 |
+
result = {"ok": False, "error": "Ask which pending tool-share request the user approves."}
|
| 1113 |
+
elif name == "open_items" and _AGENT_DOOR.get() != "whatsapp":
|
| 1114 |
import assistant_open_items
|
| 1115 |
if turn.get("handle") is not None:
|
| 1116 |
with turn["handle"].execution() as allowed:
|
|
|
|
| 1127 |
reconsider = True
|
| 1128 |
else:
|
| 1129 |
result = agent_runtime.execute(session, name, args, door=_AGENT_DOOR.get(), turn=turn)
|
| 1130 |
+
if (name == "remember" and isinstance(result, dict) and result.get("scope") == "company"
|
| 1131 |
+
and result.get("ok") is not False and result.get("id")):
|
| 1132 |
+
# The committed scope, rather than the model's requested scope, owns the acknowledgement.
|
| 1133 |
+
turn["companyRemembered"] = True
|
| 1134 |
+
for recorded in turn["toolCalls"]:
|
| 1135 |
+
if recorded.get("name") == "remember" and recorded.get("ref") == result["id"]:
|
| 1136 |
+
recorded.pop("linkNote", None)
|
| 1137 |
if isinstance(result, dict) and result.get("stopped"):
|
| 1138 |
return None, None, provider, "stopped"
|
| 1139 |
content = json.dumps(result, default=str, ensure_ascii=False)
|
|
|
|
| 1153 |
after_attempt=None, input_token_bound=None, output_token_bound=None):
|
| 1154 |
"""The provider ladder runs before the first response; subsequent steps pin that provider."""
|
| 1155 |
|
| 1156 |
+
requested = _resolve_model(requested)
|
| 1157 |
priced = before_attempt is not None or after_attempt is not None
|
| 1158 |
if priced:
|
| 1159 |
from core import login_run
|
|
|
|
| 1172 |
if chosen:
|
| 1173 |
providers = [provider for provider in providers if provider["name"] == chosen]
|
| 1174 |
if not providers:
|
| 1175 |
+
# No key or an out-of-credit cooldown is the C2 code `provider_unreachable` (R116).
|
| 1176 |
+
broke = [row["label"] for row in prov.llm_status() if row["outOfCredit"]]
|
| 1177 |
+
return None, _RefusalDetail("OpenRouter out of credit" if broke else "OpenRouter key unavailable"), None, "provider_unreachable"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1178 |
|
| 1179 |
import requests
|
| 1180 |
|
|
|
|
| 1210 |
def pause():
|
| 1211 |
if not turn.get("providerPaused"):
|
| 1212 |
turn["providerPaused"] = True
|
| 1213 |
+
provider_stream.emit("paused", {"code": "provider_limited", "message": provider_limits.PAUSED_MESSAGE})
|
| 1214 |
if turn.get("handle") is not None and session is not None:
|
| 1215 |
turn_audit.write(turn["handle"], session.runtime, result={"status": "paused"})
|
| 1216 |
|
|
|
|
| 1292 |
continue
|
| 1293 |
except provider_limits.RetryExhausted:
|
| 1294 |
turn["providerLimitExhausted"] = True
|
| 1295 |
+
return None, _RefusalDetail("HTTP 429 retry budget exhausted"), provider["name"], "provider_limited"
|
| 1296 |
except Exception as exc: # noqa: BLE001
|
| 1297 |
if priced:
|
| 1298 |
raise
|
| 1299 |
+
trouble.append(f"provider transport {type(exc).__name__}")
|
| 1300 |
continue
|
| 1301 |
|
| 1302 |
if response.status_code == 400 and provider["wire"] == "openai":
|
|
|
|
| 1314 |
# it instead of paying the round trip again.
|
| 1315 |
if prov.is_credit_failure(response.status_code, response.text):
|
| 1316 |
prov.mark_no_credit(provider["name"])
|
| 1317 |
+
trouble.append(f"provider HTTP {int(response.status_code)}")
|
|
|
|
| 1318 |
continue
|
| 1319 |
|
| 1320 |
try:
|
|
|
|
| 1326 |
_book(provider, body)
|
| 1327 |
spec, said, refused = read(body)
|
| 1328 |
if refused:
|
| 1329 |
+
trouble.append("provider refused its response")
|
| 1330 |
continue
|
| 1331 |
if spec is not None:
|
| 1332 |
# The prose rides ALONG with the view when the model wrote both, so the reader gets
|
|
|
|
| 1334 |
return spec, said, provider["name"], None
|
| 1335 |
if said:
|
| 1336 |
return None, said, provider["name"], None
|
| 1337 |
+
if turn.get("memoryReply"):
|
| 1338 |
+
# A committed tool's server reply completes an otherwise empty model response.
|
| 1339 |
+
return None, None, provider["name"], None
|
| 1340 |
# ⚠ Neither a call nor a word is a FAILED turn, not a silent one: falling through to
|
| 1341 |
# the next provider is right, and swallowing it as an empty answer would show the
|
| 1342 |
# reader a blank reply [[empty-answer-vs-unfinished-answer]].
|
| 1343 |
+
trouble.append("provider answered with nothing")
|
| 1344 |
except provider_stream.StreamFailure as exc:
|
| 1345 |
_book(provider, exc.body)
|
| 1346 |
+
return None, _RefusalDetail("provider stream interrupted"), provider["name"], "provider_stream_error"
|
| 1347 |
except Exception as exc: # noqa: BLE001
|
| 1348 |
+
trouble.append(f"provider response unreadable {type(exc).__name__}")
|
|
|
|
| 1349 |
if requested != MODEL_AUTO:
|
| 1350 |
+
return (None, _RefusalDetail("; ".join(trouble) or "provider did not respond"), None, "model_unavailable")
|
| 1351 |
+
return (None, _RefusalDetail("; ".join(trouble) or "provider did not respond"),
|
|
|
|
|
|
|
| 1352 |
None, "provider_unreachable")
|
| 1353 |
|
| 1354 |
|
|
|
|
| 1365 |
if kind in QUERY_EXCLUDED or kind not in QUERY_KINDS:
|
| 1366 |
return None, "that kind of view cannot be built from this question", "unsupported_kind"
|
| 1367 |
|
| 1368 |
+
named = dict.fromkeys(str(key) for key in (spec.get("visible") or ()))
|
| 1369 |
for item in spec.get("filters") or ():
|
| 1370 |
if isinstance(item, dict) and item.get("colId"):
|
| 1371 |
+
named[str(item["colId"])] = None
|
| 1372 |
# ⛔ THE RIGHT-HAND COLUMN IS A COLUMN AND MUST FACE THE SAME `missing` CHECK. Collecting
|
| 1373 |
# only the left side is what makes D-229 possible one layer down: `clean_filter_tree` does
|
| 1374 |
# NOT drop a leaf whose field-rhs names a column that does not exist — it keeps the leaf,
|
|
|
|
| 1378 |
# Naming it here turns that into the ordinary "this database does not have: X" refusal.
|
| 1379 |
rhs = item.get("rhs") if isinstance(item, dict) else None
|
| 1380 |
if isinstance(rhs, dict) and rhs.get("colId"):
|
| 1381 |
+
named[str(rhs["colId"])] = None
|
| 1382 |
for item in spec.get("sorts") or ():
|
| 1383 |
if isinstance(item, dict) and item.get("colId"):
|
| 1384 |
+
named[str(item["colId"])] = None
|
| 1385 |
for key in ("groupBy", "stackField", "dateField", "colorField", "sizeField"):
|
| 1386 |
if spec.get(key):
|
| 1387 |
+
named[str(spec[key])] = None
|
| 1388 |
raw_aggregation = spec.get("aggregation") or {"op": "count"}
|
| 1389 |
if isinstance(raw_aggregation, dict) and raw_aggregation.get("field"):
|
| 1390 |
+
named[str(raw_aggregation["field"])] = None
|
| 1391 |
+
missing = sorted(set(named) - keys)
|
| 1392 |
if missing:
|
| 1393 |
return None, "this database does not have: " + ", ".join(missing), "unknown_columns"
|
| 1394 |
|
| 1395 |
visible = [str(key) for key in (spec.get("visible") or ()) if str(key) in keys][:MAX_VISIBLE]
|
| 1396 |
+
# An empty `visible` shows the fields the spec names, else the snapshot's first fields.
|
| 1397 |
+
if not visible:
|
| 1398 |
+
visible = ([key for key in named if key in keys][:MAX_VISIBLE]
|
| 1399 |
+
or [str(field.get("key")) for field in fields if field.get("key")][:MAX_VISIBLE])
|
| 1400 |
if not visible:
|
| 1401 |
return None, "that question did not name any fields to show", "no_columns"
|
| 1402 |
raw_filters = [item for item in (spec.get("filters") or ()) if isinstance(item, dict)]
|
|
|
|
| 1413 |
# `_clean_rhs` rule). Both doors, because the two catch different causes and the cost of
|
| 1414 |
# missing this one is a wrong answer that looks right.
|
| 1415 |
for sent, kept in zip(raw_filters, filters):
|
| 1416 |
+
if sent.get("op") == "between":
|
| 1417 |
+
from harness import filter_eval, filter_sql
|
| 1418 |
+
if (by_key.get(kept.get("colId")) not in filter_eval.NUMERIC_TYPES | filter_eval.DATE_TYPES
|
| 1419 |
+
or sent.get("rhs") is not None
|
| 1420 |
+
or not filter_sql.is_rule_active(kept, keys)):
|
| 1421 |
+
return None, "that range filter needs two bounds on a numeric or date field", "range_invalid"
|
| 1422 |
if sent.get("rhs") and not kept.get("rhs"):
|
| 1423 |
return None, "that column cannot be compared against another column", "rhs_dropped"
|
| 1424 |
# D-658: an empty multi-value leaf survives cleaning but narrows no records.
|
|
|
|
| 1429 |
aggregation = raw_aggregation if isinstance(raw_aggregation, dict) else {}
|
| 1430 |
op = str(aggregation.get("op") or "").lower()
|
| 1431 |
field = aggregation.get("field")
|
| 1432 |
+
if op not in {"count", "count_distinct", "sum", "avg", "min", "max"}:
|
| 1433 |
return None, "the assistant gave an unsupported aggregation", "bad_aggregation"
|
| 1434 |
if op == "count":
|
| 1435 |
field = None
|
| 1436 |
+
elif field not in keys or (op != "count_distinct" and
|
| 1437 |
+
by_key.get(field) not in {"int", "currency", "pct", "formula"}):
|
| 1438 |
return None, "that aggregation needs one visible numeric field", "bad_aggregation"
|
| 1439 |
|
| 1440 |
display = {"mode": kind}
|
|
|
|
| 1511 |
aggregation = view["aggregation"]
|
| 1512 |
if aggregation["op"] == "count":
|
| 1513 |
return {"label": "Matching records", "value": len(records), "contributing_record_count": len(records)}
|
| 1514 |
+
if aggregation["op"] == "count_distinct":
|
| 1515 |
+
values = [row.get(aggregation["field"]) for row in records
|
| 1516 |
+
if row.get(aggregation["field"]) is not None]
|
| 1517 |
+
return {"label": f"Count distinct of {aggregation['field']}",
|
| 1518 |
+
"value": len({json.dumps(value, sort_keys=True, default=str) for value in values}),
|
| 1519 |
+
"contributing_record_count": len(values)}
|
| 1520 |
values = []
|
| 1521 |
for record in records:
|
| 1522 |
try:
|
|
|
|
| 1884 |
sources = list(dict.fromkeys(item for item in sources if item))
|
| 1885 |
if target not in sources:
|
| 1886 |
sources.insert(0, target)
|
| 1887 |
+
# Source chips validate metadata only. The model receives only the target's permitted data.
|
|
|
|
|
|
|
| 1888 |
for source in sources:
|
| 1889 |
+
assistant_read_scope(session, source, fields=[], filters=None, mode="schema")
|
| 1890 |
return sources
|
| 1891 |
|
| 1892 |
|
| 1893 |
+
@_c2_refusals("/query/chat")
|
| 1894 |
def _submit(body, session, chat=None, *, also_as=(), door="app", audit_handle=None):
|
| 1895 |
# C10 currently sets the door context; the explicit keyword is also the C12 consumer seam.
|
| 1896 |
door = _AGENT_DOOR.get() if door == "app" else door
|
|
|
|
| 1913 |
"toolCalls": [], "pendingDelete": None, "artifacts": [], "view": None, "citations": []}
|
| 1914 |
context_hint = assistant_dock.context_of(body, session)
|
| 1915 |
dock = assistant_dock.payload_context(body["dock"]) if context_hint is not None else None
|
| 1916 |
+
selected_model = _resolve_model(body.get("model"))
|
| 1917 |
if not question:
|
| 1918 |
raise err(400, "bad_request", "no question was asked")
|
| 1919 |
if len(question) > MAX_QUESTION:
|
|
|
|
| 1945 |
target = (dock.get("database", "") if dock is not None else
|
| 1946 |
str((replay or {}).get("database") or body.get("database") or body.get("scope") or "").strip())
|
| 1947 |
|
| 1948 |
+
share_requests, share_approved = [], []
|
| 1949 |
+
if (dock is None and not target and replay is None and not also_as and door != "slack"
|
| 1950 |
+
and re.fullmatch(r"yes(?:[,.]?\s+(?:please|share(?:\s+it)?))?[.!]*", question.casefold())):
|
| 1951 |
+
import loopy_tool_store
|
| 1952 |
+
share_requests = loopy_tool_store.pending_shares(session)
|
| 1953 |
+
if share_requests:
|
| 1954 |
+
history = _history(session)
|
| 1955 |
+
previous = history[-1]["content"] if history and history[-1]["role"] == "assistant" else ""
|
| 1956 |
+
if "share" in question.casefold() or re.search(r"\bshar(?:e|ing)\b", previous, re.I):
|
| 1957 |
+
named = [row["request"] for row in share_requests if
|
| 1958 |
+
row["request"] in previous or (row["tool"] and row["tool"] in previous)]
|
| 1959 |
+
share_approved = named if len(named) == 1 else (
|
| 1960 |
+
[share_requests[0]["request"]] if len(share_requests) == 1 else [])
|
| 1961 |
+
|
| 1962 |
import assistant_open_items
|
| 1963 |
+
import agent_tools
|
| 1964 |
+
import agent_runtime
|
| 1965 |
+
admitted = (agent_tools.admitted_tools(question)
|
| 1966 |
+
if dock is None and not target and replay is None and not also_as and door != "slack"
|
| 1967 |
+
else frozenset())
|
| 1968 |
open_work = (dock is None and not target and replay is None and not also_as and door != "slack"
|
| 1969 |
and assistant_open_items.admits(question))
|
| 1970 |
memory_only = dock is None and not target and replay is None and assistant_memory.admits(question)
|
| 1971 |
+
routed = _route(session, question) if dock is None and not open_work and not admitted and not memory_only and not share_requests and not agent_runtime.has_attachments() and not target and replay is None else {
|
| 1972 |
"database": target, "auto": False, "alternatives": []}
|
| 1973 |
target = routed["database"]
|
| 1974 |
+
route_refusal = (None if dock is not None or open_work or admitted or memory_only or share_requests or agent_runtime.has_attachments() else
|
| 1975 |
QUERY_NO_SOURCE_MATCHED if not target and replay is None else routed.get("refusal"))
|
| 1976 |
|
| 1977 |
+
# Snapshot turns plan mirrors from schema. Dock turns read through permissioned tools.
|
| 1978 |
scope_reader = assistant_read_scope
|
| 1979 |
scope_extra = {}
|
| 1980 |
if also_as:
|
|
|
|
| 1985 |
scope_reader = deps.assistant_read_scope
|
| 1986 |
scope_extra["also_as"] = also_as
|
| 1987 |
snapshot = (scope_reader(session, target, fields=None,
|
| 1988 |
+
filters=(replay or {}).get("filters", body.get("filters")),
|
| 1989 |
+
mode="query_plan", **scope_extra)
|
| 1990 |
if dock is None and target and not route_refusal else None)
|
| 1991 |
+
if snapshot is not None and snapshot.get("source_kind") == "mirror_user_table":
|
| 1992 |
+
snapshot["query_schema_only"] = True
|
| 1993 |
sources = (list(dict.fromkeys(key for key in
|
| 1994 |
[target, *(dock.get("databases") or []), *(body.get("sources") or [])] if key))
|
| 1995 |
if dock is not None else
|
|
|
|
| 2012 |
"also_as": list(also_as), "door": door, "turnKind": model_router.classify_turn(question, dock),
|
| 2013 |
"handle": handle, "dock": dock}
|
| 2014 |
handle.audit_turn = turn
|
| 2015 |
+
if share_requests:
|
| 2016 |
+
turn["toolShareRequests"] = [row["request"] for row in share_requests]
|
| 2017 |
+
turn["toolShareApproved"] = share_approved
|
| 2018 |
if open_work:
|
| 2019 |
turn["openWork"] = True
|
| 2020 |
+
if admitted:
|
| 2021 |
+
turn["admittedTools"] = sorted(admitted)
|
| 2022 |
if memory_only:
|
| 2023 |
turn["memoryOnly"] = True
|
| 2024 |
turn["memoryCompanyRequested"] = assistant_memory.company_requested(question)
|
|
|
|
| 2055 |
_AGENT_TURN.reset(token)
|
| 2056 |
if reason == "stopped":
|
| 2057 |
return turn_control.envelope(handle, "stopped")
|
| 2058 |
+
if spec is None and not said and not reason and not turn.get("memoryReply"):
|
| 2059 |
+
said, reason = _RefusalDetail("provider answered with nothing"), "provider_unreachable"
|
| 2060 |
view, refusal, refusal_code = (_validate(spec, snapshot["fields"])
|
| 2061 |
if spec is not None and snapshot is not None else (None, said, reason))
|
| 2062 |
|
| 2063 |
+
server_numeric = None
|
| 2064 |
+
if view is not None and snapshot.get("query_schema_only"):
|
| 2065 |
+
requested = [field["key"] for field in snapshot["fields"]]
|
| 2066 |
+
protected = {row["field"] for row in records.values()
|
| 2067 |
+
if row.get("sensitivity") in {"sensitive", "restricted"}}
|
| 2068 |
+
sensitive = (view["aggregation"]["field"] in protected or view.get("groupBy") in protected
|
| 2069 |
+
or bool(protected and view.get("filters")))
|
| 2070 |
+
if view.get("sorts") or sensitive:
|
| 2071 |
+
snapshot = scope_reader(session, target, fields=requested,
|
| 2072 |
+
filters=(replay or {}).get("filters", body.get("filters")), **scope_extra)
|
| 2073 |
+
snapshot = _semantic_answer_snapshot(snapshot, records)
|
| 2074 |
+
else:
|
| 2075 |
+
rows, server_numeric, groups, matching_count, group_page, summary = _tool_server_result(
|
| 2076 |
+
session, target, requested, view, body, records, scope_reader=scope_reader,
|
| 2077 |
+
also_as=also_as, base_filters=snapshot.get("filters"))
|
| 2078 |
+
snapshot = {**snapshot, "records": rows, "source_version": summary["source_version"],
|
| 2079 |
+
"retrieved_at": summary["retrieved_at"]}
|
| 2080 |
+
said = _tool_wording(question, server_numeric, matching_count, group_page["total"])
|
| 2081 |
+
|
| 2082 |
+
# C2: the turn answers with its C2 code. A provider failure says the C2 sentence, never the vendor list.
|
| 2083 |
+
cause, cause_detail = refusal_code, refusal
|
| 2084 |
+
refusal_code = c2_code(cause, refusal) if cause else cause
|
| 2085 |
+
if cause and not draft_card:
|
| 2086 |
+
said, refusal = None, c2_message(refusal_code)
|
| 2087 |
+
|
| 2088 |
# Injected callers and non-model refusals also seal their completion against joins.
|
| 2089 |
if handle.stopped or handle.cancel_requested.is_set():
|
| 2090 |
return turn_control.envelope(handle, "stopped")
|
|
|
|
| 2092 |
if handle.close() == "stopped":
|
| 2093 |
return turn_control.envelope(handle, "stopped")
|
| 2094 |
|
| 2095 |
+
if turn.get("memoryReply") and not cause:
|
| 2096 |
+
# A committed tool's server reply is also the saved reply.
|
| 2097 |
said, refusal = turn["memoryReply"], turn["memoryReply"]
|
| 2098 |
+
if turn.get("companyRemembered") and not cause:
|
| 2099 |
+
said, refusal = "I shared this fact with everyone.", "I shared this fact with everyone."
|
| 2100 |
|
| 2101 |
artifact = None
|
| 2102 |
citation = None
|
|
|
|
| 2105 |
raise err(400, "query_limit", f"you already have {len(state['views'])} Query artefacts")
|
| 2106 |
view_id = _new_id("query")
|
| 2107 |
citation_id = _new_id("citation")
|
| 2108 |
+
numeric = server_numeric if server_numeric is not None else _numeric_result(view, _view_records(snapshot, view))
|
| 2109 |
citation = _citation(citation_id, snapshot, view, numeric, view_id)
|
| 2110 |
if not _citation_complete(citation):
|
| 2111 |
raise RuntimeError("Query refused to persist an incomplete numeric citation")
|
|
|
|
| 2146 |
"targetDatabase": target, "requestedModel": selected_model, "model": provider, "turnKind": turn["turnKind"],
|
| 2147 |
"routedTo": routed,
|
| 2148 |
**_model_identity(provider),
|
| 2149 |
+
"reason": refusal_code, **({"cause": cause} if cause else {}),
|
| 2150 |
+
"viewId": artifact["id"] if artifact else None,
|
| 2151 |
"provenance": _answer_provenance(artifact),
|
| 2152 |
"citationIds": artifact["citationIds"] if artifact else [], "numeric": artifact["numeric"] if artifact else None,
|
| 2153 |
"toolCalls": turn["toolCalls"], "pendingDelete": turn["pendingDelete"], "artifacts": turn["artifacts"],
|
|
|
|
| 2180 |
if door != "slack" and not session.runtime.available():
|
| 2181 |
raise err(503, "store_unavailable", "the tenant store is unavailable; no chat was saved")
|
| 2182 |
if door != "slack":
|
| 2183 |
+
import agent_runtime
|
| 2184 |
+
held_preview = door == "whatsapp" and not refusal_code and (agent_runtime._HELD.get() or turn["pendingDelete"])
|
| 2185 |
for message in (user_message, assistant_message):
|
| 2186 |
+
if held_preview and message["role"] == "assistant":
|
| 2187 |
+
continue
|
| 2188 |
assistant_log.append(session.runtime, session.uname, {
|
| 2189 |
"role": message["role"], "door": door, "kind": "text", "text": message["content"],
|
| 2190 |
"at": now, "payload": {key: value for key, value in message.items()
|
|
|
|
| 2192 |
if artifact:
|
| 2193 |
session.runtime.update(_namespace_key(session), update, flush="async")
|
| 2194 |
import agent_runtime
|
| 2195 |
+
if not held_preview:
|
| 2196 |
+
agent_runtime.maybe_compact(session.runtime, session.uname, chat=chat)
|
| 2197 |
thread = {"id": thread_id, "title": "Conversation", "createdAt": now, "updatedAt": now,
|
| 2198 |
"sources": sources, "model": selected_model, "activeViewId": artifact["id"] if artifact else None}
|
| 2199 |
+
result = {"thread": thread, "userMessage": _safe(user_message),
|
| 2200 |
+
"message": _safe(assistant_message),
|
| 2201 |
+
"toolCalls": _safe(turn["toolCalls"]), "pendingDelete": _safe(turn["pendingDelete"]),
|
| 2202 |
+
"artifacts": _safe(turn["artifacts"]),
|
| 2203 |
+
"view": _public_view(artifact) if artifact else None, "citations": [citation] if citation else []}
|
| 2204 |
+
if cause and not draft_card:
|
| 2205 |
+
# `message` is the assistant turn here, so the C2 sentence rides in `error` as on an HTTP refusal.
|
| 2206 |
+
refused = _refusal("/query/chat", cause, cause_detail, session)
|
| 2207 |
+
result.update({"status": "refused", "code": refused["code"], "cause": cause,
|
| 2208 |
+
"error": {"code": refused["code"], "message": refused["message"]}})
|
| 2209 |
+
return result
|
| 2210 |
|
| 2211 |
|
| 2212 |
@router.post("/query/chat")
|
|
|
|
| 2214 |
return _submit(body, session)
|
| 2215 |
|
| 2216 |
|
| 2217 |
+
async def _c2_stream_events(body, session, *, submit=None):
|
| 2218 |
+
"""Keep the streaming turn's recovery result while giving every error its C2 sentence."""
|
| 2219 |
+
import assistant_stream
|
| 2220 |
+
async for frame in assistant_stream.events(body, session, submit=submit):
|
| 2221 |
+
if frame.startswith("event: error\n"):
|
| 2222 |
+
data = json.loads(frame.split("\ndata: ", 1)[1])
|
| 2223 |
+
result = data.get("result") or {}
|
| 2224 |
+
already_refused = result.get("status") == "refused"
|
| 2225 |
+
cause = result.get("cause") if already_refused else data.get("code")
|
| 2226 |
+
code = result.get("code") if already_refused else c2_code(cause)
|
| 2227 |
+
message = c2_message(code)
|
| 2228 |
+
# _submit logs its final refusal or normalized exception in the worker thread.
|
| 2229 |
+
already_logged = already_refused or data.get("message") == message
|
| 2230 |
+
if not already_logged:
|
| 2231 |
+
_log_refusal("/query/chat/stream", code, cause, "", session)
|
| 2232 |
+
data.update(code=code, message=message)
|
| 2233 |
+
frame = assistant_stream._event("error", data)
|
| 2234 |
+
yield frame
|
| 2235 |
+
|
| 2236 |
+
|
| 2237 |
+
@router.post("/query/chat/stream")
|
| 2238 |
+
def stream_chat(body: dict = Body(default=None), session: Session = Depends(require_session)):
|
| 2239 |
+
return StreamingResponse(_c2_stream_events(body, session), media_type="text/event-stream",
|
| 2240 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 2241 |
+
|
| 2242 |
+
|
| 2243 |
@router.get("/assistant/log")
|
| 2244 |
+
@_c2_refusals("/assistant/log")
|
| 2245 |
def conversation_log(before: str = None, limit: int = 50,
|
| 2246 |
session: Session = Depends(require_session)):
|
| 2247 |
try:
|
|
|
|
| 2390 |
next_cursor = base64.urlsafe_b64encode(json.dumps([
|
| 2391 |
assistant_log._hash(session.runtime, session.uname), last["createdAt"], last["id"]]).encode()).decode()
|
| 2392 |
return {"items": [{key: row[key] for key in (
|
| 2393 |
+
"id", "kind", "title", "door", "createdAt", "ref", "status", "toolCall", "actions")} |
|
| 2394 |
+
assistant_artifacts.c7(row) for row in page],
|
| 2395 |
"nextCursor": next_cursor}
|
| 2396 |
|
| 2397 |
|
|
|
|
| 2409 |
return item
|
| 2410 |
|
| 2411 |
|
| 2412 |
+
@router.get("/artifacts/{id}/snapshot")
|
| 2413 |
+
def get_artifact_snapshot(id: str, session: Session = Depends(require_session)):
|
| 2414 |
+
import artifact_snapshot
|
| 2415 |
+
row = _artifact_item(session, id)
|
| 2416 |
+
if row.get("kind") != "snapshot" or row.get("status") != "active":
|
| 2417 |
+
raise err(404, "unknown_artifact", "That snapshot does not exist.")
|
| 2418 |
+
sources = assistant_artifacts.c7(row)["sources"]
|
| 2419 |
+
if sources is None:
|
| 2420 |
+
raise err(403, "assistant_forbidden", "Your current permissions do not allow this snapshot.")
|
| 2421 |
+
for database in sources:
|
| 2422 |
+
if not _source_still_permitted(session, {"database": database}):
|
| 2423 |
+
raise err(403, "assistant_forbidden", "Your current permissions do not allow this snapshot.")
|
| 2424 |
+
snapshot = assistant_artifacts.read_snapshot(session.runtime, row)
|
| 2425 |
+
if snapshot is None:
|
| 2426 |
+
raise err(404, "unknown_artifact", "That snapshot does not exist.")
|
| 2427 |
+
artifact_snapshot.require_permission(session, sources, snapshot)
|
| 2428 |
+
return {"artifact": assistant_artifacts.c7(row),
|
| 2429 |
+
"snapshot": {key: value for key, value in snapshot.items() if key != "_authorization"}}
|
| 2430 |
+
|
| 2431 |
+
|
| 2432 |
def _replay_artifact(session, item, *, name=None, args=None):
|
| 2433 |
import agent_runtime
|
| 2434 |
call = item["toolCall"]
|
|
|
|
| 3137 |
"""Use the existing governed planner only when a channel did not supply typed artifacts."""
|
| 3138 |
artifact_keys = {"view", "filters", "sorts", "group", "hiddenFields", "aggregation", "kind"}
|
| 3139 |
if any(key in body for key in artifact_keys):
|
| 3140 |
+
return _tool_spec(body, [field["key"] for field in snapshot.get("fields") or ()]), None, None, None
|
| 3141 |
+
selected_model = _resolve_model(body.get("model"))
|
| 3142 |
if selected_model not in model_choices():
|
| 3143 |
raise err(400, "unknown_model", "that model is not available in Query")
|
| 3144 |
spec, said, provider, reason = _call_model(
|
| 3145 |
question, snapshot, model=selected_model, chat=None, history=None, session=session)
|
| 3146 |
if spec is None:
|
| 3147 |
+
return None, (said or "Query could not build an answer"), provider, reason
|
| 3148 |
+
return spec, said, provider, reason
|
| 3149 |
+
|
| 3150 |
+
|
| 3151 |
+
def _tool_view_filter(view):
|
| 3152 |
+
"""Represent an absent validated view predicate as no user filter."""
|
| 3153 |
+
return ({"conj": view["filterConj"], "nodes": view["filters"]}
|
| 3154 |
+
if view["filters"] else None)
|
| 3155 |
+
|
| 3156 |
+
|
| 3157 |
+
def _tool_server_result(session, database, requested, view, body, records, *,
|
| 3158 |
+
scope_reader=None, also_as=(), base_filters=None):
|
| 3159 |
+
"""Compute connector totals and groups in SQL, then read one bounded record page."""
|
| 3160 |
+
aggregation = view["aggregation"]
|
| 3161 |
+
op, field = aggregation["op"], aggregation["field"]
|
| 3162 |
+
specs = [{"fn": op, **({"field": field} if field else {})},
|
| 3163 |
+
{"fn": "count", **({"field": field} if field else {})}]
|
| 3164 |
+
filters = _tool_view_filter(view)
|
| 3165 |
+
if base_filters:
|
| 3166 |
+
from harness import filter_eval
|
| 3167 |
+
nodes, conj = filter_eval.tree_parts(base_filters)
|
| 3168 |
+
if nodes:
|
| 3169 |
+
filters = ({"conj": "and", "nodes": [{"conj": conj, "children": nodes},
|
| 3170 |
+
{"conj": filters["conj"], "children": filters["nodes"]}]}
|
| 3171 |
+
if filters else {"conj": conj, "nodes": nodes})
|
| 3172 |
+
reader = scope_reader or assistant_read_scope
|
| 3173 |
+
scope_extra = {"also_as": also_as} if also_as else {}
|
| 3174 |
+
mode = ("aggregate", specs)
|
| 3175 |
+
group_offset, group_limit = body.get("groupOffset", 0), body.get("groupLimit", 50)
|
| 3176 |
+
if (type(group_offset) is not int or group_offset < 0 or type(group_limit) is not int
|
| 3177 |
+
or not 1 <= group_limit <= 500):
|
| 3178 |
+
raise err(400, "bad_request", "Use a nonnegative groupOffset and a groupLimit from 1 to 500.")
|
| 3179 |
+
if view.get("groupBy"):
|
| 3180 |
+
mode += ({"groupBy": [{"field": view["groupBy"]}],
|
| 3181 |
+
"offset": group_offset, "limit": group_limit},)
|
| 3182 |
+
summary = reader(session, database, fields=requested, filters=filters, mode=mode, **scope_extra)
|
| 3183 |
+
|
| 3184 |
+
def numeric(values):
|
| 3185 |
+
return {"label": "Matching records" if op == "count" else f"{op.replace('_', ' ').title()} of {field}",
|
| 3186 |
+
"value": values[0]["value"], "contributing_record_count": values[1]["value"]}
|
| 3187 |
+
|
| 3188 |
+
groups = [{"value": str(group["keys"][view["groupBy"]])
|
| 3189 |
+
if group["keys"][view["groupBy"]] is not None else "(blank)",
|
| 3190 |
+
"numeric": numeric(group["aggregates"])} for group in summary.get("groups") or ()]
|
| 3191 |
+
page = reader(session, database, fields=requested, filters=filters, mode=("page", 0, 50), **scope_extra)
|
| 3192 |
+
if page["total_rows"] != summary["total_rows"]:
|
| 3193 |
+
raise err(409, "query_source_unavailable", "The source changed between its summary and record page.")
|
| 3194 |
+
page = _semantic_answer_snapshot(page, records)
|
| 3195 |
+
return (page["records"], numeric(summary["server_aggregates"]), groups, summary["total_rows"],
|
| 3196 |
+
{"offset": group_offset, "limit": group_limit, "total": summary.get("total_groups", 0)}, summary)
|
| 3197 |
|
| 3198 |
|
| 3199 |
@router.post("/query/tool")
|
| 3200 |
+
@_c2_refusals("/query/tool")
|
| 3201 |
def governed_query(body: dict = Body(default=None),
|
| 3202 |
session: Session = Depends(require_session)):
|
| 3203 |
+
"""Plan a governed answer and compute its numbers through the scoped reader."""
|
| 3204 |
body = body if isinstance(body, dict) else {}
|
| 3205 |
database = str(body.get("database") or "").strip()
|
| 3206 |
question = " ".join(str(body.get("prompt") or body.get("question") or "").split())
|
|
|
|
| 3215 |
_semantic_authorize(session, database, require_answerable=not routed["auto"])
|
| 3216 |
route_refusal = QUERY_NO_SOURCE_MATCHED if not database else routed.get("refusal")
|
| 3217 |
if route_refusal:
|
| 3218 |
+
refused = _refusal("/query/tool", "query_source_unavailable" if database else "query_no_source_matched",
|
| 3219 |
+
route_refusal, session)
|
| 3220 |
+
return {"status": "refused", "wording": refused["message"], "speakable": refused["message"],
|
| 3221 |
+
"artifacts": None, "routedTo": routed, "model": _model_identity(None),
|
| 3222 |
+
**refused}
|
| 3223 |
records = _semantic_records(session, database)
|
| 3224 |
if not routed["auto"]:
|
| 3225 |
from harness import semantic as sem
|
|
|
|
| 3241 |
selected = [semantic_rt.require_approved(records, database, key) for key in requested]
|
| 3242 |
except semantic_rt.SemanticError as exc:
|
| 3243 |
raise err(403, "semantic_field_unapproved", str(exc))
|
| 3244 |
+
snapshot = assistant_read_scope(session, database, fields=requested, filters=None, mode="query_plan")
|
| 3245 |
+
mirror_plan = snapshot.get("source_kind") == "mirror_user_table"
|
| 3246 |
snapshot = _semantic_answer_snapshot(snapshot, records)
|
| 3247 |
+
if mirror_plan:
|
| 3248 |
+
snapshot["query_schema_only"] = True
|
| 3249 |
snapshot, formulas = _tool_formula_snapshot(body, snapshot, requested)
|
| 3250 |
+
spec, planned_wording, provider, reason = _tool_plan(question, body, snapshot, session)
|
| 3251 |
if spec is None:
|
| 3252 |
+
refused = _refusal("/query/tool", reason or "no_spec", planned_wording, session)
|
| 3253 |
+
# A provider failure says the C2 sentence, never the vendor list.
|
| 3254 |
+
wording = refused["message"]
|
| 3255 |
+
return {"status": "refused", "wording": wording,
|
| 3256 |
+
"speakable": wording, "artifacts": None,
|
| 3257 |
+
"model": _model_identity(provider), "routedTo": routed, **refused}
|
| 3258 |
view, refusal, refusal_code = _validate(spec, snapshot.get("fields") or selected)
|
| 3259 |
if view is None:
|
| 3260 |
raise err(400, refusal_code or "bad_query_artifact", refusal or "that Query is invalid")
|
| 3261 |
+
# Formula evaluation and Python sorting require a complete filtered row set.
|
| 3262 |
+
# Keep the eager reader's memory refusal for those plans, never fold a partial page.
|
| 3263 |
+
protected = {row["field"] for row in selected if row.get("sensitivity") in {"sensitive", "restricted"}}
|
| 3264 |
+
sensitive = (view["aggregation"]["field"] in protected or view.get("groupBy") in protected
|
| 3265 |
+
or bool(protected and view.get("filters")))
|
| 3266 |
+
server = mirror_plan and not formulas and not view.get("sorts") and not sensitive
|
| 3267 |
+
group_page = None
|
| 3268 |
+
if server:
|
| 3269 |
+
rows, numeric, groups, matching_count, group_page, _summary = _tool_server_result(
|
| 3270 |
+
session, database, requested, view, body, records)
|
| 3271 |
+
else:
|
| 3272 |
+
if mirror_plan:
|
| 3273 |
+
formula_filter = any(item.get("colId") in formulas or
|
| 3274 |
+
(item.get("rhs") or {}).get("colId") in formulas
|
| 3275 |
+
for item in view["filters"])
|
| 3276 |
+
snapshot = assistant_read_scope(session, database, fields=requested,
|
| 3277 |
+
filters=None if sensitive or formula_filter else
|
| 3278 |
+
_tool_view_filter(view))
|
| 3279 |
+
snapshot = _semantic_answer_snapshot(snapshot, records)
|
| 3280 |
+
snapshot, formulas = _tool_formula_snapshot(body, snapshot, requested)
|
| 3281 |
+
filtered = _view_records(snapshot, view)
|
| 3282 |
+
ordered = _tool_sort(filtered, view.get("sorts"))
|
| 3283 |
+
rows = ordered[:50]
|
| 3284 |
+
groups = _tool_groups(ordered, view)
|
| 3285 |
+
numeric = _numeric_result(view, ordered)
|
| 3286 |
+
matching_count = len(ordered)
|
| 3287 |
row_ids = [str(row.get("pid") or row.get("id") or index)
|
| 3288 |
for index, row in enumerate(rows)]
|
| 3289 |
hidden = [key for key in requested if key not in set(view.get("visible") or ())]
|
|
|
|
|
|
|
| 3290 |
artifacts = {"filters": _safe(view.get("filters") or []),
|
| 3291 |
"sorts": _safe(view.get("sorts") or []),
|
| 3292 |
"group": _safe(view.get("groupBy")),
|
|
|
|
| 3294 |
"formulas": _safe(formulas),
|
| 3295 |
"source": {"database": database, "fields": requested,
|
| 3296 |
"permissionScopeApplied": True}}
|
| 3297 |
+
wording = _tool_wording(question, numeric, matching_count,
|
| 3298 |
+
group_page["total"] if group_page else len(groups))
|
| 3299 |
return {"status": "answered", "wording": wording, "speakable": wording,
|
| 3300 |
"citations": [{"database": database, "rowId": value} for value in row_ids],
|
| 3301 |
"rows": [{key: row.get(key) for key in view["visible"]} for row in rows],
|
| 3302 |
"groups": groups, "numeric": numeric,
|
| 3303 |
+
**({"total_rows": matching_count, "groupPage": group_page} if server else {}),
|
| 3304 |
"artifacts": artifacts, "semanticRouter": semantic_rt.router_projection(records, database),
|
| 3305 |
"model": _model_identity(provider), "routedTo": routed}
|
| 3306 |
|
|
|
|
| 3757 |
router.routes.extend(_analyst_routes.routes)
|
| 3758 |
|
| 3759 |
from assistant_routers import ROUTERS as _ASSISTANT_ROUTERS # noqa: E402
|
| 3760 |
+
from assistant_stream import router as _stream_router # noqa: E402
|
| 3761 |
for _assistant_router in _ASSISTANT_ROUTERS:
|
| 3762 |
+
if _assistant_router is _stream_router:
|
| 3763 |
+
# The C2 route above retains this extension's event worker and dependency walls.
|
| 3764 |
+
continue
|
| 3765 |
_start = len(router.routes)
|
| 3766 |
router.include_router(_assistant_router)
|
| 3767 |
# FastAPI 0.139 adds lazy wrappers; existing route audits need the actual gated routes.
|
api/routes_shared_artifact.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serve one frozen artifact through a signed capability without creating a session."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import base64
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
from collections import OrderedDict
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
from functools import lru_cache
|
| 10 |
+
from hashlib import sha256
|
| 11 |
+
from html import escape
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from threading import Lock
|
| 14 |
+
from urllib.parse import quote
|
| 15 |
+
|
| 16 |
+
from fastapi import APIRouter, Request
|
| 17 |
+
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
| 18 |
+
from starlette.concurrency import run_in_threadpool
|
| 19 |
+
|
| 20 |
+
import artifact_share
|
| 21 |
+
import assistant_artifacts
|
| 22 |
+
import assistant_files
|
| 23 |
+
import loopy_links
|
| 24 |
+
|
| 25 |
+
router = APIRouter()
|
| 26 |
+
MAX_BODY_BYTES = 1024
|
| 27 |
+
RATE_WINDOW_S = 60
|
| 28 |
+
MAX_RATE_KEYS = 4096
|
| 29 |
+
GET_LIMIT = 60
|
| 30 |
+
POST_LIMIT = 5
|
| 31 |
+
FAILURE_LIMIT = 30
|
| 32 |
+
MAX_FILE_BYTES = 20 * 1024 * 1024
|
| 33 |
+
_HITS = OrderedDict()
|
| 34 |
+
_LOCK = Lock()
|
| 35 |
+
FILE_TYPES = {"application/pdf": ".pdf",
|
| 36 |
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
|
| 37 |
+
"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
|
| 38 |
+
HEADERS = {"Cache-Control": "no-store", "Referrer-Policy": "no-referrer",
|
| 39 |
+
"X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY",
|
| 40 |
+
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; "
|
| 41 |
+
"font-src data:; img-src data:; form-action 'self'; "
|
| 42 |
+
"base-uri 'none'; frame-ancestors 'none'"}
|
| 43 |
+
|
| 44 |
+
CSS = """
|
| 45 |
+
:root { --lp-font: Inter, sans-serif; --lp-root: 17px; --lp-fs-sm: .875rem;
|
| 46 |
+
--lp-fs-lg: 1.25rem; --lp-canvas: #f7f7f6; --lp-panel: #fff; --lp-surface: #fff;
|
| 47 |
+
--lp-ink: #252525; --lp-muted: #686868; --lp-line: #e6e6e4; --lp-primary: #5433cc;
|
| 48 |
+
--lp-primary-hover: #472bad; --lp-blue-deep: #2563a6; --lp-r-panel: 18px;
|
| 49 |
+
--lp-scroll-thumb: #bfbfbf; --lp-scroll-thumb-hover: #a8a8a8;
|
| 50 |
+
--lp-r-md: 8px; --lp-panel-shadow: 0 2px 12px #0000000a; }
|
| 51 |
+
* { box-sizing: border-box; }
|
| 52 |
+
html { font-size: var(--lp-root); font-family: var(--lp-font); color: var(--lp-ink);
|
| 53 |
+
background: var(--lp-canvas); }
|
| 54 |
+
body { margin: 0; padding: 24px 16px; }
|
| 55 |
+
main { width: 100%; max-width: 720px; margin: 0 auto; padding: 24px;
|
| 56 |
+
background: var(--lp-panel); border-radius: var(--lp-r-panel); box-shadow: var(--lp-panel-shadow); }
|
| 57 |
+
h1 { margin: 0 0 8px; font-size: var(--lp-fs-lg); font-weight: 600; overflow-wrap: anywhere; }
|
| 58 |
+
p, time { font-size: var(--lp-fs-sm); line-height: 1.5; }
|
| 59 |
+
time, .note { color: var(--lp-muted); }
|
| 60 |
+
.table-scroll { overflow-x: auto; margin: 24px 0 16px; scrollbar-width: thin;
|
| 61 |
+
scrollbar-color: var(--lp-scroll-thumb) transparent; }
|
| 62 |
+
.table-scroll::-webkit-scrollbar { width: 8px; height: 8px; }
|
| 63 |
+
.table-scroll::-webkit-scrollbar-track { background: transparent; }
|
| 64 |
+
.table-scroll::-webkit-scrollbar-thumb { background: var(--lp-scroll-thumb); border: 1px solid transparent;
|
| 65 |
+
background-clip: padding-box; border-radius: var(--lp-r-md); }
|
| 66 |
+
@media (hover: hover) and (pointer: fine) {
|
| 67 |
+
.table-scroll::-webkit-scrollbar-thumb:hover { background-color: var(--lp-scroll-thumb-hover); } }
|
| 68 |
+
table { border-collapse: collapse; width: 100%; font-size: var(--lp-fs-sm); }
|
| 69 |
+
th, td { padding: 12px 8px; border-bottom: 1px solid var(--lp-line); text-align: left;
|
| 70 |
+
vertical-align: top; overflow-wrap: anywhere; }
|
| 71 |
+
th { font-weight: 600; white-space: nowrap; overflow-wrap: normal; }
|
| 72 |
+
.number, .totals { text-align: right; font-variant-numeric: tabular-nums; }
|
| 73 |
+
.number { white-space: pre; overflow-wrap: normal; }
|
| 74 |
+
.totals { margin: 16px 0; font-size: var(--lp-fs-sm); }
|
| 75 |
+
img { display: block; max-width: 100%; height: auto; margin: 24px 0; }
|
| 76 |
+
a { color: var(--lp-blue-deep); font-size: var(--lp-fs-sm); }
|
| 77 |
+
.open { display: block; margin-top: 24px; }
|
| 78 |
+
button { border: 0; background: transparent; font: inherit; color: inherit; cursor: pointer; }
|
| 79 |
+
.primary { display: inline-block; padding: 12px 16px; border-radius: var(--lp-r-md);
|
| 80 |
+
background: var(--lp-primary); color: var(--lp-surface); font-size: var(--lp-fs-sm);
|
| 81 |
+
font-weight: 600; text-decoration: none; }
|
| 82 |
+
.primary:hover { background: var(--lp-primary-hover); }
|
| 83 |
+
a:focus-visible, button:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 4px; }
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@lru_cache(maxsize=1)
|
| 88 |
+
def _font_css():
|
| 89 |
+
"""Reuse the embedded Inter face from the shell's source or shipped CSS."""
|
| 90 |
+
web = Path(__file__).resolve().parents[1] / "web"
|
| 91 |
+
paths = [web / "src/index.css", *sorted((web / "dist/assets").glob("*.css"))]
|
| 92 |
+
for path in paths:
|
| 93 |
+
if not path.is_file():
|
| 94 |
+
continue
|
| 95 |
+
for face in re.findall(r"@font-face\s*\{[^}]*\}", path.read_text(encoding="utf-8")):
|
| 96 |
+
if re.search(r"font-family\s*:\s*['\"]?Inter\b", face) and "data:" in face:
|
| 97 |
+
return face
|
| 98 |
+
raise RuntimeError("The embedded Inter face is missing.")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _page(content, *, title="Shared artifact", status=200):
|
| 102 |
+
document = ("<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
| 103 |
+
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
|
| 104 |
+
f"<title>{escape(title)}</title><style>{_font_css()}{CSS}</style></head>"
|
| 105 |
+
f"<body><main>{content}</main></body></html>")
|
| 106 |
+
return HTMLResponse(document, status_code=status, headers=HEADERS)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _invalid(status=403):
|
| 110 |
+
return _page(f"<p>{artifact_share.NOT_VALID}</p>", status=status)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _admit(request, token, valid):
|
| 114 |
+
"""Limit valid capabilities separately from failed guesses at the socket peer."""
|
| 115 |
+
peer = request.client.host if request.client else "unknown"
|
| 116 |
+
locator = sha256(token.encode()).hexdigest() if valid else peer
|
| 117 |
+
key = (request.method, valid, locator)
|
| 118 |
+
limit = (POST_LIMIT if request.method == "POST" else GET_LIMIT) if valid else FAILURE_LIMIT
|
| 119 |
+
now = time.monotonic()
|
| 120 |
+
with _LOCK:
|
| 121 |
+
seen = [stamp for stamp in _HITS.pop(key, ()) if now - stamp < RATE_WINDOW_S]
|
| 122 |
+
admitted = len(seen) < limit
|
| 123 |
+
if admitted:
|
| 124 |
+
seen.append(now)
|
| 125 |
+
_HITS[key] = seen
|
| 126 |
+
while len(_HITS) > MAX_RATE_KEYS:
|
| 127 |
+
_HITS.popitem(last=False)
|
| 128 |
+
return admitted
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _renew_button(token):
|
| 132 |
+
return (f'<form method="post" action="/a/{escape(token, quote=True)}/request-again">'
|
| 133 |
+
'<button class="primary" type="submit">Request the link again</button></form>')
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
_NUMERIC_TYPES = frozenset({"currency", "int", "float", "number", "decimal", "percent", "percentage"})
|
| 137 |
+
_DISPLAY_AMOUNT = re.compile(
|
| 138 |
+
r"(?:[-+]?[$€£]\s*|[$€£]\s*[-+]?)(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?"
|
| 139 |
+
r"|\([$€£]\s*(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?\)"
|
| 140 |
+
r"|[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?\s*%"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _numeric(value, column, summed):
|
| 145 |
+
"""Use frozen column semantics, then explicit currency or percentage display text."""
|
| 146 |
+
kind = column.get("type")
|
| 147 |
+
if kind:
|
| 148 |
+
return kind in _NUMERIC_TYPES
|
| 149 |
+
if column.get("key") in summed:
|
| 150 |
+
return True
|
| 151 |
+
return ((isinstance(value, (int, float)) and not isinstance(value, bool))
|
| 152 |
+
or (isinstance(value, str) and _DISPLAY_AMOUNT.fullmatch(value.strip()) is not None))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _snapshot(rt, row):
|
| 156 |
+
content = assistant_artifacts.read_snapshot(rt, row)
|
| 157 |
+
if not isinstance(content, dict):
|
| 158 |
+
return None
|
| 159 |
+
columns, rows = content.get("columns"), content.get("rows")
|
| 160 |
+
if not isinstance(columns, list) or not isinstance(rows, list):
|
| 161 |
+
return None
|
| 162 |
+
totals = content.get("totals") or {}
|
| 163 |
+
summed = totals.get("sum") or {}
|
| 164 |
+
numeric_columns = [
|
| 165 |
+
_numeric(None, col, summed) or (
|
| 166 |
+
any(isinstance(values, list) and index < len(values) and values[index] not in (None, "")
|
| 167 |
+
for values in rows)
|
| 168 |
+
and all(_numeric(values[index], col, summed) for values in rows
|
| 169 |
+
if isinstance(values, list) and index < len(values) and values[index] not in (None, "")))
|
| 170 |
+
for index, col in enumerate(columns)
|
| 171 |
+
]
|
| 172 |
+
header = "".join('<th scope="col"' + (' class="number"' if numeric_columns[index] else "")
|
| 173 |
+
+ f'>{escape(str(col.get("label", col.get("key", ""))))}</th>'
|
| 174 |
+
for index, col in enumerate(columns))
|
| 175 |
+
rendered = []
|
| 176 |
+
for values in rows:
|
| 177 |
+
if not isinstance(values, list):
|
| 178 |
+
return None
|
| 179 |
+
cells = []
|
| 180 |
+
for index, value in enumerate(values):
|
| 181 |
+
col = columns[index] if index < len(columns) else {}
|
| 182 |
+
numeric = _numeric(value, col, summed)
|
| 183 |
+
cls = ' class="number"' if numeric else ""
|
| 184 |
+
text = "" if value is None else str(value)
|
| 185 |
+
cells.append(f"<td{cls}>{escape(text)}</td>")
|
| 186 |
+
rendered.append("<tr>" + "".join(cells) + "</tr>")
|
| 187 |
+
labels = {col.get("key"): col.get("label", col.get("key", "")) for col in columns}
|
| 188 |
+
footer = []
|
| 189 |
+
if "count" in totals:
|
| 190 |
+
footer.append(f'Rows: {escape(str(totals["count"]))}')
|
| 191 |
+
for key, value in (totals.get("sum") or {}).items():
|
| 192 |
+
footer.append(f'{escape(str(labels.get(key, key)))}: {escape(str(value))}')
|
| 193 |
+
return ('<div class="table-scroll"><table><thead><tr>' + header + '</tr></thead><tbody>'
|
| 194 |
+
+ "".join(rendered) + '</tbody></table></div><div class="totals">'
|
| 195 |
+
+ "<br>".join(footer) + '</div>'
|
| 196 |
+
+ (f'<p class="note">{escape(str(content["note"]))}</p>' if content.get("note") else ""))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _file(rt, share, artifact):
|
| 200 |
+
metadata = assistant_files.owned_metadata(rt, share["owner"], artifact.get("file_id"))
|
| 201 |
+
if (not isinstance(metadata, dict) or metadata.get("artifactId") != artifact["id"]
|
| 202 |
+
or metadata.get("mime") not in FILE_TYPES
|
| 203 |
+
or artifact.get("mime", metadata.get("mime")) != metadata.get("mime")
|
| 204 |
+
or not isinstance(metadata.get("size"), int) or isinstance(metadata.get("size"), bool)
|
| 205 |
+
or not 0 <= metadata["size"] <= MAX_FILE_BYTES):
|
| 206 |
+
return None
|
| 207 |
+
data = assistant_files.read_bytes(rt, metadata)
|
| 208 |
+
if not isinstance(data, bytes) or len(data) != metadata["size"]:
|
| 209 |
+
return None
|
| 210 |
+
return metadata, data
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _sign_in(found):
|
| 214 |
+
"""Accept T31's validated resolution without exposing content or arbitrary redirects."""
|
| 215 |
+
row, share, rt = found.get("row"), found.get("share"), found.get("rt")
|
| 216 |
+
if (not isinstance(row, dict) or not isinstance(share, dict)
|
| 217 |
+
or row.get("id") != share.get("artifact_id") or row.get("status") != "active"
|
| 218 |
+
or getattr(rt, "key", None) is None):
|
| 219 |
+
return _invalid()
|
| 220 |
+
link = loopy_links.artifact_link(row["id"])
|
| 221 |
+
return RedirectResponse(link, status_code=303, headers=HEADERS) if link else _invalid()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@router.get("/a/{token}", response_class=HTMLResponse)
|
| 225 |
+
def shared_artifact(token: str, request: Request):
|
| 226 |
+
key = artifact_share._secret()
|
| 227 |
+
signed = key is not None and artifact_share._claims(token, key) is not None
|
| 228 |
+
if not _admit(request, token, signed):
|
| 229 |
+
return _invalid(429)
|
| 230 |
+
found = artifact_share.resolve(token)
|
| 231 |
+
if found["state"] == "sign_in":
|
| 232 |
+
return _sign_in(found)
|
| 233 |
+
if found["state"] == "expired":
|
| 234 |
+
return _page(_renew_button(token))
|
| 235 |
+
if found["state"] != "ok":
|
| 236 |
+
return _invalid()
|
| 237 |
+
row, rt, share = found["row"], found["rt"], found["share"]
|
| 238 |
+
try:
|
| 239 |
+
artifact = assistant_artifacts.c7(row)
|
| 240 |
+
content = None
|
| 241 |
+
if artifact["kind"] == "snapshot":
|
| 242 |
+
content = _snapshot(rt, row)
|
| 243 |
+
elif artifact["kind"] in {"pdf", "xlsx", "image"}:
|
| 244 |
+
frozen = _file(rt, share, artifact)
|
| 245 |
+
if frozen is not None:
|
| 246 |
+
metadata, data = frozen
|
| 247 |
+
mime = metadata["mime"]
|
| 248 |
+
if request.query_params.get("download") == "1":
|
| 249 |
+
name = re.sub(r"[^A-Za-z0-9._ ]", "_", str(artifact["title"]))[:100].strip(". ") or "Artifact"
|
| 250 |
+
name += FILE_TYPES[mime]
|
| 251 |
+
return Response(data, media_type=mime, headers={**HEADERS,
|
| 252 |
+
"Content-Disposition": f"attachment; filename*=UTF-8''{quote(name)}"})
|
| 253 |
+
if artifact["kind"] == "image" and mime.startswith("image/"):
|
| 254 |
+
content = (f'<img src="data:{mime};base64,{base64.b64encode(data).decode()}" '
|
| 255 |
+
f'alt="{escape(str(artifact["title"]), quote=True)}">')
|
| 256 |
+
else:
|
| 257 |
+
content = f'<a class="primary" href="/a/{token}?download=1">Download file</a>'
|
| 258 |
+
if content is None:
|
| 259 |
+
return _invalid()
|
| 260 |
+
title = escape(str(artifact["title"]))
|
| 261 |
+
made = escape(str(artifact["created_at"]), quote=True)
|
| 262 |
+
stamp = datetime.fromisoformat(str(artifact["created_at"]).replace("Z", "+00:00"))
|
| 263 |
+
if stamp.tzinfo is None:
|
| 264 |
+
stamp = stamp.replace(tzinfo=timezone.utc)
|
| 265 |
+
label = escape(stamp.astimezone(timezone.utc).strftime("%d %b %Y, %H:%M UTC"))
|
| 266 |
+
link = loopy_links.artifact_link(artifact["id"])
|
| 267 |
+
opening = f'<a class="open" href="{escape(link, quote=True)}">Open in Loopable</a>' if link else ""
|
| 268 |
+
return _page(f'<h1>{title}</h1><time datetime="{made}">Made {label}</time>{content}{opening}',
|
| 269 |
+
title=str(artifact["title"]))
|
| 270 |
+
except Exception:
|
| 271 |
+
return _invalid()
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@router.post("/a/{token}/request-again", response_class=HTMLResponse)
|
| 275 |
+
async def request_again(token: str, request: Request):
|
| 276 |
+
key = artifact_share._secret()
|
| 277 |
+
signed = key is not None and artifact_share._claims(token, key) is not None
|
| 278 |
+
if not _admit(request, token, signed):
|
| 279 |
+
return _invalid(429)
|
| 280 |
+
size = 0
|
| 281 |
+
chunks = []
|
| 282 |
+
async for chunk in request.stream():
|
| 283 |
+
size += len(chunk)
|
| 284 |
+
if size > MAX_BODY_BYTES:
|
| 285 |
+
return _invalid(413)
|
| 286 |
+
chunks.append(chunk)
|
| 287 |
+
if b"".join(chunks).strip() not in {b"", b"{}"}:
|
| 288 |
+
return _invalid(400)
|
| 289 |
+
found = await run_in_threadpool(artifact_share.resolve, token)
|
| 290 |
+
if found["state"] == "sign_in":
|
| 291 |
+
return _sign_in(found)
|
| 292 |
+
try:
|
| 293 |
+
result = await run_in_threadpool(artifact_share.request_again, token)
|
| 294 |
+
except Exception:
|
| 295 |
+
result = {"outcome": "failed", "message": artifact_share.NOT_SENT}
|
| 296 |
+
if result["outcome"] in {"invalid", "refused"}:
|
| 297 |
+
return _invalid()
|
| 298 |
+
button = _renew_button(token) if result["outcome"] == "failed" else ""
|
| 299 |
+
return _page(f'<p role="status">{escape(result["message"])}</p>{button}')
|
api/routes_shares.py
CHANGED
|
@@ -4,6 +4,7 @@
|
|
| 4 |
PUT /api/v1/share/{kind}/{oid} <- {entries:[{user,role}]} (REPLACES the set)
|
| 5 |
PUT /api/v1/share/{kind}/{oid}/owner <- {owner: "<username>"} (R6d — `field` ONLY)
|
| 6 |
GET /api/v1/share/mine -> {view:[id], folder:[id], database:[id]}
|
|
|
|
| 7 |
|
| 8 |
`kind` ∈ view | folder | database | field. Roles are `view` | `edit` — the same two words the
|
| 9 |
view rail already speaks, now extended to folders, databases and COLUMNS so there is ONE
|
|
@@ -866,6 +867,27 @@ def _find_view_topic(session, oid):
|
|
| 866 |
return None, None
|
| 867 |
|
| 868 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 869 |
def _promote_field_for_grant(session, table_key, field_key, resolved=None):
|
| 870 |
"""Promote a private column exactly once, stamp it shared, and answer its GRANT OID.
|
| 871 |
|
|
@@ -1487,6 +1509,20 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
|
|
| 1487 |
return out
|
| 1488 |
|
| 1489 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1490 |
@router.post("/share/view/{oid}/assign")
|
| 1491 |
def assign_view(oid: str, body: dict = Body(default=None),
|
| 1492 |
session: Session = Depends(require_session)):
|
|
|
|
| 4 |
PUT /api/v1/share/{kind}/{oid} <- {entries:[{user,role}]} (REPLACES the set)
|
| 5 |
PUT /api/v1/share/{kind}/{oid}/owner <- {owner: "<username>"} (R6d — `field` ONLY)
|
| 6 |
GET /api/v1/share/mine -> {view:[id], folder:[id], database:[id]}
|
| 7 |
+
POST /api/v1/assistant/inbox/{request_id}/{action} -> {state} (C6, S72-T28: approve | not_now)
|
| 8 |
|
| 9 |
`kind` ∈ view | folder | database | field. Roles are `view` | `edit` — the same two words the
|
| 10 |
view rail already speaks, now extended to folders, databases and COLUMNS so there is ONE
|
|
|
|
| 867 |
return None, None
|
| 868 |
|
| 869 |
|
| 870 |
+
def _find_view_record(session, oid):
|
| 871 |
+
"""`(topic, creator, view)` for a saved view, else `(None, None, None)` (S72-T28).
|
| 872 |
+
|
| 873 |
+
Same loop as `_find_view_topic`. `find_view` answers `(owner_username, view, ...)`, and the
|
| 874 |
+
creator is the view's owner until a grant record names one.
|
| 875 |
+
"""
|
| 876 |
+
try:
|
| 877 |
+
import core.table_store as table_store
|
| 878 |
+
except Exception: # noqa: BLE001
|
| 879 |
+
return None, None, None
|
| 880 |
+
for topic in _topics(session):
|
| 881 |
+
try:
|
| 882 |
+
hit = table_store.make(f"{topic}_table_workspace", st=session.runtime).find_view(oid)
|
| 883 |
+
except Exception: # noqa: BLE001
|
| 884 |
+
continue
|
| 885 |
+
if hit:
|
| 886 |
+
return (str(topic), str(hit[0] or "") or None,
|
| 887 |
+
(hit[1] if len(hit) > 1 and isinstance(hit[1], dict) else {}))
|
| 888 |
+
return None, None, None
|
| 889 |
+
|
| 890 |
+
|
| 891 |
def _promote_field_for_grant(session, table_key, field_key, resolved=None):
|
| 892 |
"""Promote a private column exactly once, stamp it shared, and answer its GRANT OID.
|
| 893 |
|
|
|
|
| 1509 |
return out
|
| 1510 |
|
| 1511 |
|
| 1512 |
+
@router.post("/assistant/inbox/{request_id}/{action}")
|
| 1513 |
+
def inbox_action(request_id: str, action: str, session: Session = Depends(require_session)):
|
| 1514 |
+
"""C6 (S72-T28): the owner, or an Administrator for a database, answers an access request.
|
| 1515 |
+
|
| 1516 |
+
`action` is `approve` or `not_now` and the answer is `{"state"}`. This route is the only
|
| 1517 |
+
caller of `agent_inbox.decide_request`: a grant changes on a person's click, never an agent's.
|
| 1518 |
+
"""
|
| 1519 |
+
import agent_inbox
|
| 1520 |
+
try:
|
| 1521 |
+
return agent_inbox.decide_request(session, request_id, action)
|
| 1522 |
+
except agent_inbox.Denied as exc:
|
| 1523 |
+
raise err(exc.status, exc.code, exc.message)
|
| 1524 |
+
|
| 1525 |
+
|
| 1526 |
@router.post("/share/view/{oid}/assign")
|
| 1527 |
def assign_view(oid: str, body: dict = Body(default=None),
|
| 1528 |
session: Session = Depends(require_session)):
|
api/routes_sheet.py
CHANGED
|
@@ -2507,6 +2507,61 @@ def write_sheet(workbook_id: str, body: dict = Body(default=None),
|
|
| 2507 |
return {"workbook": _response_workbook(book)}
|
| 2508 |
|
| 2509 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2510 |
@router.delete("/sheets/{workbook_id}")
|
| 2511 |
def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
|
| 2512 |
"""Delete a workbook. THE OWNER's door, and an editor is refused by name (C5).
|
|
|
|
| 2507 |
return {"workbook": _response_workbook(book)}
|
| 2508 |
|
| 2509 |
|
| 2510 |
+
def _rename_rev(raw):
|
| 2511 |
+
"""Require an integer revision on every rename."""
|
| 2512 |
+
rev = raw.get("rev")
|
| 2513 |
+
if isinstance(rev, bool) or not isinstance(rev, int) or rev < 0:
|
| 2514 |
+
raise HTTPException(status_code=400, detail={"error": {
|
| 2515 |
+
"code": "workbook_revision_invalid", "message": "A rename needs the workbook revision."}})
|
| 2516 |
+
return rev
|
| 2517 |
+
|
| 2518 |
+
|
| 2519 |
+
def _require_rename_editor(session, book):
|
| 2520 |
+
"""Keep rename permission refusals short and ahead of revision checks."""
|
| 2521 |
+
if _role_on_workbook(session, book) not in ("owner", "edit"):
|
| 2522 |
+
from core import sheets
|
| 2523 |
+
raise _refuse(sheets.SheetRefusal("workbook_read_only", "This workbook is read only."))
|
| 2524 |
+
|
| 2525 |
+
|
| 2526 |
+
@router.patch("/sheets/{workbook_id}/name")
|
| 2527 |
+
def rename_sheet(workbook_id: str, body: dict = Body(default=None),
|
| 2528 |
+
session: Session = Depends(require_session)):
|
| 2529 |
+
"""S72-T64: rename a workbook. Body `{name, rev}`, answer `{workbook}` without cells.
|
| 2530 |
+
|
| 2531 |
+
The read-only check runs before the revision check, as on every write door.
|
| 2532 |
+
"""
|
| 2533 |
+
from core import sheets
|
| 2534 |
+
raw = dict(body or {})
|
| 2535 |
+
try:
|
| 2536 |
+
_require_rename_editor(session, sheets.rename_access(_store(session), workbook_id))
|
| 2537 |
+
expect = _rename_rev(raw)
|
| 2538 |
+
book = sheets.rename_workbook(_store(session), workbook_id, raw.get("name"),
|
| 2539 |
+
expect_rev=expect)
|
| 2540 |
+
except sheets.SheetRefusal as exc:
|
| 2541 |
+
raise _refuse(exc)
|
| 2542 |
+
return {"workbook": sheets.rename_meta(book)}
|
| 2543 |
+
|
| 2544 |
+
|
| 2545 |
+
@router.patch("/sheets/{workbook_id}/tabs/{tab}/name")
|
| 2546 |
+
def rename_sheet_tab(workbook_id: str, tab: str, body: dict = Body(default=None),
|
| 2547 |
+
session: Session = Depends(require_session)):
|
| 2548 |
+
"""S72-T64: rename one tab. Body `{name, rev}`, answer `{workbook}` without cells.
|
| 2549 |
+
|
| 2550 |
+
Formulas that name the old tab follow the new name on the server, so tabs the client never
|
| 2551 |
+
loaded are covered without sending them.
|
| 2552 |
+
"""
|
| 2553 |
+
from core import sheets
|
| 2554 |
+
raw = dict(body or {})
|
| 2555 |
+
try:
|
| 2556 |
+
_require_rename_editor(session, sheets.rename_access(_store(session), workbook_id))
|
| 2557 |
+
expect = _rename_rev(raw)
|
| 2558 |
+
book = sheets.rename_tab(_store(session), workbook_id, tab, raw.get("name"),
|
| 2559 |
+
expect_rev=expect)
|
| 2560 |
+
except sheets.SheetRefusal as exc:
|
| 2561 |
+
raise _refuse(exc)
|
| 2562 |
+
return {"workbook": sheets.rename_meta(book)}
|
| 2563 |
+
|
| 2564 |
+
|
| 2565 |
@router.delete("/sheets/{workbook_id}")
|
| 2566 |
def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
|
| 2567 |
"""Delete a workbook. THE OWNER's door, and an editor is refused by name (C5).
|