File size: 5,894 Bytes
8145bee
 
 
 
 
 
98c8696
8145bee
affe37f
8145bee
 
98c8696
 
 
 
 
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
98c8696
8145bee
 
 
98c8696
 
8145bee
98c8696
8145bee
 
 
 
 
98c8696
 
8145bee
 
043da5c
 
8145bee
043da5c
 
98c8696
 
 
 
 
 
 
 
affe37f
8145bee
 
 
 
98c8696
 
affe37f
8145bee
98c8696
8145bee
98c8696
1ad1eea
8145bee
1ad1eea
8145bee
 
 
 
 
 
 
 
 
98c8696
 
8145bee
98c8696
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98c8696
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
"""Caller-assigned open work and its personal Tickets View."""
import copy
import re
from urllib.parse import urlencode

import agent_tools
import ticket_tools
import tickets
from core import perm_scope


def _line(item):
    sender = item["from"]
    parts = [str(sender["person"])]
    if sender.get("agent"):
        parts.append(str(sender["agent"]))
    if item.get("createdAt"):
        parts.append(str(item["createdAt"]))
    parts.append(str(item["task"]))
    return "- " + ": ".join(parts)


def admits(question):
    """Admit the open-work tool turn without requiring a semantic database match."""
    text = " ".join(re.findall(r"\w+", str(question).casefold()))
    return text in {"what is open for me", "what s open for me", "what is open for me now"}


def open_items(session, args):
    """Read attributed requests and assigned work, then save a View of visible assignments."""
    if not isinstance(args, dict) or args:
        raise ValueError("open_items takes no arguments and uses your signed-in account.")
    username = str(session.uname).strip().lower()
    source_check = ticket_tools._source_check(session)
    rows = tickets._recipient_request_rows(session.runtime, username)
    database, table = tickets._table(session.runtime)
    mine, assigned, assigned_ids = [], [], set()
    if table is not None:
        session.require(database)
        fields = perm_scope.scoped_fields(session.user, database, st=session.runtime)
        visible = {field["key"] for field in fields}
        if "assigned_to" not in visible:
            raise PermissionError("Your permissions do not expose request assignments.")
        candidates = [row for row in rows if not row.get("request_id") and ticket_tools._status(row) == "Open"]
        # Tickets stores comma-joined audience names; the common wall expects a detached list.
        normalized = [{**row, "audience": sorted(tickets._stored_audience(row))} for row in candidates]
        # The request reader keeps attribution and masks source text (_read_item), so it asks for
        # the audience and row walls without the generic door's source recheck (S73-T49).
        allowed = perm_scope.apply_row_scope(
            normalized, session.user, database, table["fields"], st=session.runtime,
            recheck_sources=False)
        assigned = [row for row in allowed if username in tickets._names(row.get("assigned_to"))]
        assigned_ids = {row["id"] for row in assigned}
        for row in allowed:
            if row["id"] in assigned_ids or row.get("kind") in tickets.REQUEST_KINDS:
                mine.append(ticket_tools._read_item(session, row, fields=visible, source_check=source_check))
    for row in rows:
        if row.get("request_id") and ticket_tools._status(row) == "Open":
            mine.append(ticket_tools._read_item(session, row, source_check=source_check))
    tasks = []
    if not mine and not tasks:
        return {"tickets": [], "tasks": [], "view": None, "message": "Nothing is open for you."}

    view, view_args = None, None
    hidden_assignment = any(not row["sourceVisible"] and row["id"] in assigned_ids
                            for row in mine)
    if database and assigned and not hidden_assignment:
        # Complete assignment strings preserve multi-user tickets without substring matches.
        assignments = sorted({username, *(str(row["assigned_to"]) for row in assigned)})
        if any(len(assignment) > 500 for assignment in assignments):
            raise ValueError("A request assignment exceeds the saved View filter limit.")
        from core import write_execution
        view_args = {"database": database, "view": {
            "id": "open_items_" + write_execution.new_id(), "name": "Open for me", "config": {
                "filters": [{"colId": "status", "op": "eq", "value": "Open"},
                            {"conj": "or", "children": [
                                {"colId": "assigned_to", "op": "eq", "value": assignment}
                                for assignment in assignments]}],
                "filterConj": "and"}}}
        import routes_external
        view = routes_external._view_event(session, "view_upsert", view_args)

    lines = ["Open for you:"]
    lines.extend(_line(row) for row in mine)
    lines.extend(_line(row) for row in tasks)
    if view:
        lines.append("[Open requests](#/data?" + urlencode({"database": database, "view": view["view_id"]}) + ")")
    return {"tickets": mine, "tasks": tasks, "view": view,
            "viewArgs": view_args, "message": "\n".join(lines)}


def execute(session, args, *, door, turn):
    """Dispatch the registered tool and record only the View it creates."""
    import agent_runtime
    call = {"name": "open_items", "args": copy.deepcopy(args), "effect": "write", "ok": False, "ref": None}
    turn["toolCalls"].append(call)
    try:
        result = agent_runtime._dispatch(session, "open_items", args)
        if result.get("view"):
            artifact_id = agent_runtime._record_artifact(
                session, door, "view_upsert", result["viewArgs"], result["view"])
            if artifact_id:
                turn["artifacts"].append(artifact_id)
            call["ref"] = result["view"]["view_id"]
        call["ok"] = True
        return result
    except Exception as exc:
        return {"ok": False, "error": agent_runtime._sentence(exc)}


TOOLS = [{"name": "open_items", "schema": {
    "type": "object", "description": "List requests addressed to me, my assigned open work and review tasks. Save a personal Requests view of visible assigned work. Show person, agent when present, createdAt and task first. Show stateLabel as the state.",
    "properties": {}, "additionalProperties": False}, "fn": open_items, "effect": "write"}]

for entry in TOOLS:
    agent_tools.register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])