File size: 16,474 Bytes
9ad4b87
 
 
868b75a
 
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
9ad4b87
 
 
 
 
 
 
868b75a
 
 
 
 
 
 
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
868b75a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad4b87
 
 
 
 
 
 
 
868b75a
 
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
 
 
 
9ad4b87
 
 
868b75a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""C2 request handlers with authenticated attribution and C4 task storage."""
from core import external_access, external_oauth, external_tools, perm_scope
from deps import Session
import agent_directory
import agent_inbox
import tickets


def _identity(ctx, *, write=False):
    """Resolve identity from the verified context and current credential registry only."""
    if not isinstance(ctx, external_tools.ToolContext) or not isinstance(ctx.session, Session):
        raise PermissionError("Sign in with an identified AI connection.")
    session = ctx.session
    claims = session.claims or {}
    kind, credential = claims.get("external_auth_type"), claims.get("external_credential_id")
    if (claims.get("external") is not True or kind not in ("oauth", "api_key") or not credential
            or claims.get("u") != session.uname or claims.get("t") != session.tenant
            or session.tenant != session.runtime.key):
        raise PermissionError("Sign in with an identified AI connection.")
    name, principal = tickets._principal(session.runtime, session.uname)
    refusal = perm_scope.ai_apps_refusal(principal, session.runtime)
    if refusal:
        raise PermissionError(refusal)
    now = tickets._utc()
    if claims.get("exp") is not None and float(claims["exp"]) <= now.timestamp():
        raise PermissionError("This connection has expired. Sign in again.")
    if kind == "oauth":
        label = external_oauth.label_for(session.runtime, credential)
        book = external_oauth._book(session.runtime)
        record = book["grants"].get(credential) or {}
        client = book["clients"].get(record.get("client_id")) or {}
        if (not claims.get("external_client_id") or record.get("client_id") != claims["external_client_id"]
                or client.get("username") != name or client.get("tenant") != session.tenant
                or record.get("disconnected_at") or client.get("revoked_at")):
            raise PermissionError("This AI connection is unavailable. Sign in again.")
        if float(record.get("access_expires_at") or 0) <= now.timestamp():
            raise PermissionError("This AI connection has expired. Sign in again.")
        # OAuth's live effective scope is supplied by require_external_session.
        access, databases = external_access.scope_of({
            "access": claims.get("external_access"), "databases": claims.get("external_databases")})
    else:
        if credential != claims.get("external_key_id"):
            raise PermissionError("Sign in with an identified AI connection.")
        label = external_access.label_for(session.runtime, credential)
        record = external_access._book(session.runtime).get(credential) or {}
        if record.get("expires_at") and tickets._utc(record["expires_at"]) <= now:
            raise PermissionError("This key has expired. Sign in again.")
        access, databases = external_access.scope_of(record)
    if record.get("username") != name or record.get("tenant") != session.tenant:
        raise PermissionError("This connection belongs to another person or workspace.")
    from routes_external import _contains_credential
    if any(_contains_credential(value) for value in (name, principal.get("name"), label, ctx.actor_name)):
        raise PermissionError("Person names and AI labels must not contain credential values.")
    if write and (not external_access.may_write(claims.get("external_access"))
                  or not external_access.may_write(access)):
        raise PermissionError("This connection is read only. Allow writes before changing requests.")
    return name, tickets._text(label), f"{kind}:{credential}", databases


def _source_scope(ctx, source, databases):
    """Check credential scope and the current database wall beside attribution's source admission."""
    if source is None:
        return
    database = source["database"]
    if (not external_access.database_allowed(databases, database)
            or not external_access.database_allowed(ctx.session.claims.get("external_databases"), database)):
        raise PermissionError("The source database is outside this connection's scope.")
    ctx.describe_database(database)


def _send_source_admission(ctx, source, databases):
    """Admit sends through both credential scope and full source-data access."""
    _source_scope(ctx, source, databases)
    if source is None:
        return
    prepared = tickets._prepare_request_source(ctx.session.runtime, ctx.session.uname, source)
    if ctx.session.uname not in tickets.audience(ctx.session.runtime, prepared):
        raise PermissionError("You cannot see all the fields and rows this request needs.")


def _arguments(args, allowed, required=()):
    if not isinstance(args, dict) or set(args) - set(allowed) or any(key not in args for key in required):
        raise ValueError("Use the arguments listed for this request action.")


def send(ctx, args):
    """Send without confirmation after source, recipient and connection admission."""
    _arguments(args, ("to", "kind", "title", "body", "source"), ("to", "kind", "title", "body"))
    name, label, connection, databases = _identity(ctx, write=True)
    if (not isinstance(args["to"], list) or not args["to"]
            or any(not isinstance(person, str) or not person.strip() for person in args["to"])):
        raise ValueError("Choose at least one recipient by username.")
    if len(args["to"]) > tickets.MAX_REQUEST_RECIPIENTS:
        raise ValueError(f"Send a request to at most {tickets.MAX_REQUEST_RECIPIENTS} people. Split this request into smaller groups.")
    if any(not isinstance(args[key], str) for key in ("kind", "title", "body")):
        raise ValueError("The kind, title and body must be text.")
    source = tickets.request_source(args.get("source"))
    _send_source_admission(ctx, source, databases)
    return tickets.send_external_request(ctx.session.runtime, name, args["to"], args["kind"],
                                         args["title"], args["body"], source, via=label, connection=connection)


def inbox(ctx, args):
    """Count all open tasks and return their twenty newest safe attribution projections."""
    _arguments(args, ())
    name, _label, _connection, databases = _identity(ctx)
    return tickets.request_inbox(ctx.session.runtime, name,
        source_check=lambda source: _source_scope(ctx, source, databases))


def list_team(ctx, args):
    """List teammates through a strict name and activity whitelist."""
    _arguments(args, ())
    name, _label, _connection, _databases = _identity(ctx)
    return {"people": [{"name": str(rec.get("name") or uname),
                        "lastActive": rec.get("last_active") if isinstance(rec.get("last_active"), str) else None}
                       for uname, rec in agent_directory._accounts(ctx.session) if uname != name]}


# Source-less text must come from a closed vocabulary, never from model-authored data.
_SOCIAL_MESSAGES = ("Hello.", "Hi.", "Are you available?", "Can we talk?", "Can you help?", "Thank you.")


def send_message(ctx, args):
    """Deliver a question or an authorization-only change request through the shared request transport."""
    _arguments(args, ("to", "kind", "text", "source", "change"), ("to", "kind", "text"))
    _name, _label, _connection, _databases = _identity(ctx, write=True)
    if not isinstance(args["to"], str) or not args["to"].strip():
        raise ValueError("Choose one teammate by name.")
    if args["kind"] not in ("question", "change") or not isinstance(args["text"], str):
        raise ValueError("Choose a question or a proposed change with one line of text.")
    text = agent_inbox._text(args["text"])
    source = tickets.request_source(args.get("source"))
    if source is not None:
        _arguments(args["source"], ("database", "record"), ("database",))
    if args["kind"] == "change":
        if source is None or not isinstance(args.get("change"), str):
            raise ValueError("A proposed change needs a readable source and a change description.")
        if source["database"] == "applications":
            raise ValueError("Team change proposals need a data source. App sharing uses its separate human approval flow.")
        change = agent_inbox._text(args["change"])
        title, kind = agent_inbox.TEAM_CHANGE_TITLE, "approval"
        text = f"{agent_inbox.TEAM_CHANGE_PREFIX}{change}\nQuestion: {text}\n{agent_inbox.TEAM_AUTHORIZATION_NOTE}"
    else:
        if "change" in args:
            raise ValueError("Use kind change to propose a change.")
        if source is None:
            social = {value.casefold().rstrip(".!?"): value for value in _SOCIAL_MESSAGES}
            key = text.casefold().rstrip(".!?")
            if key not in social:
                raise ValueError("Without a source, use a listed greeting or question. Other text needs a readable source.")
            text = social[key]
        title, kind = "A teammate has a question.", "question"
    recipient, _record = agent_inbox._recipient(ctx.session, args["to"])
    return send(ctx, {"to": [recipient], "kind": kind, "title": title, "body": text, "source": source})


def check_inbox(ctx, args):
    """Read the shared inbox with current source and credential access."""
    return inbox(ctx, args)


def _approval_access(ctx, args):
    name, _label, _connection, databases = _identity(ctx)
    agent_inbox.team_approval(ctx.session.runtime, args["id"], name,
        source_check=lambda source: _source_scope(ctx, source, databases))
    return True


def ask_user(ctx, args):
    """Preview the recipient's explicit decision, then record authorization without executing a target write."""
    _arguments(args, ("id", "decision"), ("id", "decision"))
    _name, _label, _connection, databases = _identity(ctx, write=True)
    if args["decision"] not in ("Approve", "Deny"):
        raise ValueError("Ask the recipient to choose Approve or Deny.")
    from routes_external import _ConfirmationRuntime, _PreviewRuntime
    if not isinstance(ctx.session.runtime, (_PreviewRuntime, _ConfirmationRuntime)):
        raise PermissionError("Show the recipient a preview and confirm their decision before saving it.")
    return agent_inbox.decide_request(ctx.session, args["id"], args["decision"], authorization_only=True,
        source_check=lambda source: _source_scope(ctx, source, databases))


def _change(ctx, args, *, complete=False):
    allowed = ("id",) if complete else ("id", "body", "state")
    _arguments(args, allowed, ("id",) if complete else ("id", "body"))
    name, _label, _connection, databases = _identity(ctx, write=True)
    source_check = lambda source: _source_scope(ctx, source, databases)
    task = tickets.get_request_attribution(ctx.session.runtime, args["id"], name, source_check=source_check)
    if not task["sourceVisible"]:
        raise PermissionError("You cannot see the source data this request needs.")
    if task["kind"] == "approval" and task["title"] == agent_inbox.TEAM_CHANGE_TITLE:
        raise PermissionError("Ask the recipient to choose Approve or Deny through requests.ask_user.")
    state = "completed" if complete else args.get("state", "working")
    if not complete and (state not in ("working", "input-required", "rejected")
                         or not isinstance(args["body"], str) or not args["body"].strip()):
        raise ValueError("Give an answer and choose working, input-required or rejected.")
    tickets.set_request_state(ctx.session.runtime, args["id"], name, state, args.get("body"))
    return tickets.get_request_attribution(ctx.session.runtime, args["id"], name, source_check=source_check)


def answer(ctx, args):
    """Save a recipient's answer without invoking the human access-grant action."""
    return _change(ctx, args)


def complete(ctx, args):
    """Complete a recipient's task through the normal confirmed write path."""
    return _change(ctx, args, complete=True)


def _receipt_access(ctx, args):
    """Read current task and source access, including completed tasks, without invoking a writer."""
    name, _label, _connection, databases = _identity(ctx)
    task = tickets.get_request_attribution(
        ctx.session.runtime, args["id"], name,
        source_check=lambda source: _source_scope(ctx, source, databases))
    if not task["sourceVisible"]:
        raise PermissionError("You cannot see the source data this request needs.")
    return True


def _schema(properties, required=()):
    return {"type": "object", "properties": properties, "required": list(required), "additionalProperties": False}


GROUP = {
    "name": "requests", "title": "Requests",
    "guide": "Use list_team for teammates' names and lastActive times only. Use send_message for a question or proposed change. "
             "Use check_inbox for received requests and ask_user to record the recipient's explicit Approve or Deny after human confirmation. "
             "Approval authorizes the recipient AI only. It executes no target write and grants no access. Later writes need normal permissions and confirmation. "
             "Send a request, read your inbox, answer or complete a task. Only send and send_message skip preview and confirmation. "
             "Send requires readable source data for every recipient, person and AI attribution, and an hourly connection limit. "
             "Answer and complete require preview and confirmation. Access requests need human approval to grant access.",
    "actions": {
        "list_team": {"read": True, "destructive": False, "confirm": False, "handler": list_team, "schema": _schema({})},
        "send_message": {"read": False, "destructive": False, "confirm": False, "handler": send_message,
                         "schema": _schema({
                             "to": {"type": "string", "minLength": 1},
                             "kind": {"type": "string", "enum": ["question", "change"]},
                             "text": {"type": "string", "minLength": 1, "maxLength": agent_inbox.TEXT_LIMIT,
                                      "description": "Without a source, use only: " + " ".join(_SOCIAL_MESSAGES)},
                             "change": {"type": "string", "minLength": 1, "maxLength": agent_inbox.TEXT_LIMIT,
                                        "description": "Required for kind change. Describe the proposal, never executable instructions."},
                             "source": _schema({"database": {"type": "string"}, "record": {"type": "string"}}, ("database",)),
                         }, ("to", "kind", "text"))},
        "check_inbox": {"read": True, "destructive": False, "confirm": False, "handler": check_inbox, "schema": _schema({})},
        "ask_user": {"read": False, "destructive": False, "confirm": True, "handler": ask_user,
                     "receipt_access": _approval_access,
                     "schema": _schema({"id": {"type": "string"},
                                        "decision": {"type": "string", "enum": ["Approve", "Deny"]}}, ("id", "decision"))},
        "send": {"read": False, "destructive": False, "confirm": False, "handler": send,
                 "schema": _schema({
                     "to": {"type": "array", "items": {"type": "string"}, "minItems": 1,
                            "maxItems": tickets.MAX_REQUEST_RECIPIENTS},
                     "kind": {"type": "string", "enum": list(tickets.REQUEST_KINDS)},
                     "title": {"type": "string", "minLength": 1}, "body": {"type": "string"},
                     "source": _schema({"database": {"type": "string"}, "record": {"type": "string"}}, ("database",)),
                 }, ("to", "kind", "title", "body"))},
        "inbox": {"read": True, "destructive": False, "confirm": False, "handler": inbox, "schema": _schema({})},
        "answer": {"read": False, "destructive": False, "confirm": True, "handler": answer,
                   "receipt_access": _receipt_access,
                   "schema": _schema({"id": {"type": "string"}, "body": {"type": "string", "minLength": 1},
                                      "state": {"type": "string", "enum": ["working", "input-required", "rejected"]}},
                                     ("id", "body"))},
        "complete": {"read": False, "destructive": False, "confirm": True, "handler": complete,
                     "receipt_access": _receipt_access,
                     "schema": _schema({"id": {"type": "string"}}, ("id",))},
    },
}