File size: 10,151 Bytes
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ce703c
 
8145bee
 
7ce703c
8145bee
 
 
 
7ce703c
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"""Store owner-bound worklist snapshots as tenant-scoped JSON blobs."""
import copy
import datetime
import importlib
import json
import math
import re
import secrets
import time
from urllib.parse import urlsplit

import assistant_artifacts
import assistant_log

COLUMN_TYPES = {"text", "number", "money", "date", "link"}
_WORKLIST_ID = re.compile(r"[0-9a-f]{32}")


def _https(value):
    if not isinstance(value, str) or not value or any(c.isspace() or ord(c) < 32 for c in value):
        raise ValueError("A worklist link must be an absolute HTTPS URL.")
    try:
        parsed = urlsplit(value)
        port = parsed.port
        if (parsed.scheme != "https" or not parsed.hostname or not parsed.netloc
                or parsed.username is not None or parsed.password is not None or "\\" in value
                or port == 0):
            raise ValueError
    except ValueError as exc:
        raise ValueError("A worklist link must be an absolute HTTPS URL.") from exc
    return value


def _links():
    try:
        return importlib.import_module("loopy_links")
    except ModuleNotFoundError as exc:
        if exc.name != "loopy_links":
            raise
        raise ValueError("A secure public link is not configured.") from exc


def _principal(session):
    rt = getattr(session, "runtime", None)
    username = getattr(session, "uname", None)
    if rt is None or not isinstance(username, str) or not username.strip():
        raise ValueError("A worklist needs an authenticated owner session.")
    if getattr(session, "tenant", None) != assistant_log._tenant_of(rt):
        raise ValueError("A worklist needs its owner's tenant runtime.")
    return rt, username, assistant_log._hash(rt, username)


def _contains_rows(value):
    if isinstance(value, dict):
        return "rows" in value or any(_contains_rows(v) for v in value.values())
    if isinstance(value, (list, tuple)):
        return any(_contains_rows(v) for v in value)
    return False


def _provenance(session, tool_call):
    if tool_call is None:
        tool_call = getattr(session, "tool_call", None)
        if tool_call is None:
            tool_call = getattr(session, "_tool_call", None)
    if (not isinstance(tool_call, dict) or not isinstance(tool_call.get("name"), str)
            or not tool_call["name"].strip() or not isinstance(tool_call.get("args"), dict)):
        raise ValueError("A worklist needs its producing tool and source arguments.")
    if _contains_rows(tool_call["args"]):
        raise ValueError("Worklist replay arguments must not contain stored rows.")
    call = {"name": tool_call["name"], "args": copy.deepcopy(tool_call["args"])}
    json.dumps(call, allow_nan=False)
    return call


def _cell(kind, value):
    if value is None:
        return
    if kind == "link":
        if value != "":
            _https(value)
    elif kind in ("number", "money"):
        if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
            raise ValueError("A numeric worklist cell needs a finite number.")
    elif not isinstance(value, str):
        raise ValueError("A text or date worklist cell needs text.")
    elif kind == "date" and value:
        try:
            datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
        except ValueError as exc:
            raise ValueError("A worklist date needs an ISO date or timestamp.") from exc


def _table(columns, rows):
    if not isinstance(columns, list) or not columns or not isinstance(rows, list):
        raise ValueError("A worklist needs columns and a list of rows.")
    keys = []
    for column in columns:
        if (not isinstance(column, dict) or not isinstance(column.get("key"), str)
                or not column["key"].strip() or column["key"] in keys
                or not isinstance(column.get("label"), str) or not column["label"].strip()
                or not isinstance(column.get("type"), str) or column["type"] not in COLUMN_TYPES):
            raise ValueError("A worklist column needs a unique key, label, and supported type.")
        keys.append(column["key"])
    for row in rows:
        if isinstance(row, dict) and set(row) == set(keys):
            cells = [row[key] for key in keys]
        elif isinstance(row, (list, tuple)) and len(row) == len(keys):
            cells = row
        else:
            raise ValueError("A worklist row must match its columns.")
        for column, value in zip(columns, cells):
            _cell(column["type"], value)


def _checks(validation, resolve):
    if not isinstance(validation, list):
        raise ValueError("A worklist needs a list of validation checks.")
    for check in validation:
        if (not isinstance(check, dict) or set(check) != {"check", "a", "b", "ok"}
                or not isinstance(check["check"], str) or not check["check"].strip()
                or not isinstance(check["ok"], bool)):
            raise ValueError("A validation check needs check, a, b, and a boolean ok.")
    if (not isinstance(resolve, dict) or set(resolve) != {"label", "href"}
            or not isinstance(resolve["label"], str) or not resolve["label"].strip()):
        raise ValueError("A worklist needs a resolution label and link.")
    _https(resolve["href"])


def _key(worklist_id):
    return f"assistant_worklist_{worklist_id}"


def _path(item):
    return f"assistant_worklists/{item['ownerHash']}/{item['id']}.json"


def save(session, title, columns, rows, validation, resolve, *, tool_call=None, door=None):
    """Save all rows and one report artifact with the original producing tool's provenance."""
    rt, username, h = _principal(session)
    if not all(callable(getattr(rt, name, None)) for name in ("get", "update", "upload_bytes", "download_bytes")):
        raise RuntimeError("Worklist storage is not available in this workspace.")
    if not isinstance(title, str) or not title.strip():
        raise ValueError("A worklist needs a title.")
    call = _provenance(session, tool_call)
    door = door if door is not None else (getattr(session, "door", None) or getattr(session, "_door", None) or "app")
    if not isinstance(door, str) or door not in assistant_artifacts.DOORS:
        raise ValueError("That worklist door is not available.")
    _table(columns, rows)
    _checks(validation, resolve)
    links = _links()
    _https(links.app_link("#/artifacts"))
    from routes_query import _no_dashes
    title = _no_dashes(title).strip()[:200]
    worklist_id = secrets.token_hex(16)
    built_at = assistant_artifacts.timestamp(time.time())
    payload = {"title": title, "columns": columns, "rows": rows, "total": len(rows),
               "validation": validation, "resolve": resolve, "builtAt": built_at}
    data = json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")
    item = {"version": 1, "id": worklist_id, "owner": username, "ownerHash": h,
            "tenant": session.tenant, "total": len(rows), "size": len(data), "builtAt": built_at}
    rt.upload_bytes(_path(item), data, message="Save assistant worklist")
    import agent_runtime
    sources = agent_runtime.producing_turn_sources(session)
    item["artifactId"] = assistant_artifacts.record(rt, username, {
        "kind": "report", "ref": worklist_id, "title": title, "door": door,
        "toolCall": call, "createdAt": built_at, "frozen_at": built_at, "sources": sources})
    rt.update(_key(worklist_id), lambda _raw: copy.deepcopy(item), flush="sync")
    return {"id": worklist_id, "link": _https(links.artifact_link(item["artifactId"]))}


def owned_artifact(rt, username, row):
    """Validate an active report against its immutable owner-bound worklist metadata."""
    if (not isinstance(row, dict) or row.get("kind") != "report" or row.get("status") != "active"
            or (row.get("toolCall") or {}).get("name") not in {"build_chase_list", "build_contact_worklist"}):
        return None
    item = metadata(rt, row.get("ref"))
    if (item is None or item["owner"] != username
            or item["ownerHash"] != assistant_log._hash(rt, username)
            or item["artifactId"] != row.get("id") or item["builtAt"] != row.get("createdAt")
            or row.get("frozen_at", item["builtAt"]) != item["builtAt"]):
        return None
    return item


def metadata(rt, worklist_id):
    """Read tenant metadata without granting the caller ownership."""
    if not isinstance(worklist_id, str) or not _WORKLIST_ID.fullmatch(worklist_id):
        return None
    item = rt.get(_key(worklist_id))
    if (not isinstance(item, dict) or item.get("id") != worklist_id
            or item.get("tenant") != assistant_log._tenant_of(rt)
            or not isinstance(item.get("owner"), str) or not item["owner"]
            or item.get("ownerHash") != assistant_log._hash(rt, item["owner"])
            or any(type(item.get(k)) is not int or item[k] < 0 for k in ("total", "size"))
            or not isinstance(item.get("builtAt"), str) or not isinstance(item.get("artifactId"), str)):
        return None
    return copy.deepcopy(item)


def read_page(rt, item, *, offset=0, limit=200):
    """Read a page only after the route has authorized the owner metadata."""
    if type(offset) is not int or type(limit) is not int or offset < 0 or limit < 1:
        raise ValueError("A worklist page needs a nonnegative offset and positive limit.")
    data = rt.download_bytes(_path(item))
    if data is None:
        return None
    if not isinstance(data, (bytes, bytearray, memoryview)) or len(data) != item["size"]:
        raise RuntimeError("This worklist could not be read.")
    payload = json.loads(bytes(data))
    if (not isinstance(payload, dict)
            or set(payload) != {"title", "columns", "rows", "total", "validation", "resolve", "builtAt"}
            or not isinstance(payload["rows"], list) or len(payload["rows"]) != item["total"]
            or payload["total"] != item["total"] or payload["builtAt"] != item["builtAt"]):
        raise RuntimeError("This worklist could not be read.")
    payload["rows"] = payload["rows"][offset:offset + limit]
    return payload