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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
"""Agent messages: one person's agent sends an access request, a share or a question (C6).

R94: three kinds, one line of text each. A repeat within a day folds into the first message.
R108(l): the recipient gets one notice turn in their conversation at the next visit, and on
WhatsApp when connected and inside the 24-hour window (`assistant_feed.post` decides that).
R81: the inbox has no screen of its own. It lives in the chat.
R84: a recipient is resolved only among the caller's own workspace accounts.
`send` is the one door: the `agent_message` tool and the T28 route both use it.
R93 (S72-T28): an access request goes to the item's owner, and to the Administrators for a
database. Access grants require a person's click on the C6 route. Team decisions grant no access.
"""
import copy
import datetime as _dt
import logging
import re
import secrets

import ai_enrich
import agent_directory
import assistant_log
from core import alerts, perms, users

_LOG = logging.getLogger(__name__)

STORE_KEY = "agent_inbox"
KINDS = ("access_request", "share", "question")
TARGET_KINDS = ("database", "sheet", "view", "app")
ROLES = ("view", "edit")
ACTIONS = ["approve", "not_now"]
C6_KEYS = ("type", "request_id", "sender", "target", "text", "actions", "state")
TEXT_LIMIT = 280
FOLD_SECONDS = 24 * 3600
TEAM_CHANGE_TITLE = "Review a proposed change."
TEAM_CHANGE_PREFIX = "Proposed change: "
TEAM_AUTHORIZATION_NOTE = "Approval authorizes the recipient AI only. No target change is executed."

NOT_IN_WORKSPACE = "That person is not in your workspace."
TWO_NAMES = "Two people share that name. Use their username."
NOT_YOURSELF = "You cannot send a message to yourself."
NAME_ASK = "Name the person to ask."
NAME_TO = "Name the person to send this to."
NO_KIND = "Choose an access request, a share or a question."
NO_TEXT = "Write one line to send."
TOO_LONG = f"Keep the message to one line of {TEXT_LIMIT} characters or fewer."
NO_TARGET = "Name the database, sheet, view or app this message is about."
BAD_TARGET = "That target is not a database, sheet, view or app."
BAD_ROLE = "Ask for view or edit access."
APP_VIEW_ONLY = "Apps can only be shared for viewing."
UNAVAILABLE = "The message could not be sent. Try again in a moment."
NOT_FOUND = "I could not find that item."
OWN_ITEM = "That item is already yours."
ALREADY_HELD = "You already have that access."
NO_ANSWERER = "No one in your workspace can answer this request."
NO_REQUEST = "I could not find that request."
BAD_ACTION = "Choose approve or not now."
ONLY_ADMIN = "Only an Administrator can answer a database request."
ONLY_APP_ADMIN = "Only an Administrator can approve a workspace App share."
ONLY_OWNER = "Only the owner of this item can answer this request."
USE_MANAGE_USERS = "Give access to this database in Manage users."
TURN_ON = "Turn this database on for them in Manage users."
CHANGED = "Someone changed who has access while you were answering. Try again."
NOT_GRANTED = "The access could not be granted. Try again in a moment."
NOT_ANSWERED = "The request could not be answered. Try again in a moment."
RANK = {None: 0, "view": 1, "edit": 2, "owner": 3}

SCHEMA = {
    "type": "object",
    "description": ("Send one short message to a person in your workspace: an access request, "
                    "a share or a question."),
    "properties": {
        "type": {"type": "string", "enum": list(KINDS)},
        "to": {"type": "string"},
        "target": {"type": "object", "properties": {
            "kind": {"type": "string", "enum": list(TARGET_KINDS)},
            "key": {"type": "string"},
            "label": {"type": "string"}}, "additionalProperties": False},
        "text": {"type": "string"},
        "role": {"type": "string", "enum": list(ROLES)},
    },
    "required": ["type", "text"],
    "additionalProperties": False,
}


class Refused(ValueError):
    """A message that cannot be sent. The text is one plain sentence for the sender."""


class Denied(Exception):
    """A click on the C6 route that changes nothing: an HTTP status, a code and one sentence."""

    def __init__(self, status, code, message):
        super().__init__(message)
        self.status, self.code, self.message = status, code, message


def _now(now=None):
    if isinstance(now, _dt.datetime):
        return now.astimezone(_dt.timezone.utc)
    from core import write_execution
    return write_execution.utcnow()


def _age(created_at, now):
    try:
        return (now - _dt.datetime.fromisoformat(str(created_at))).total_seconds()
    except (TypeError, ValueError):
        return None


def _recipient(session, who):
    """`(registry_key, record)` of one active account in the caller's tenant. Raises Refused."""
    want = str(who or "").strip().casefold()
    if not want:
        raise Refused(NOT_IN_WORKSPACE)
    try:
        accounts = agent_directory._accounts(session)
    except agent_directory.DirectoryUnavailable as exc:
        raise Refused(UNAVAILABLE) from exc
    match = [(n, rec) for n, rec in accounts
             if want in {str(n).strip().casefold(),
                         str(rec.get("username_original") or "").strip().casefold()}]
    if not match:
        match = [(n, rec) for n, rec in accounts
                 if str(rec.get("name") or "").strip().casefold() == want]
        if len(match) > 1:
            raise Refused(TWO_NAMES)
    if not match:
        # One sentence for another tenant, an inactive account and nobody alike.
        raise Refused(NOT_IN_WORKSPACE)
    uname, rec = match[0]
    uname = str(uname).strip().lower()
    if uname == str(session.uname or "").strip().lower():
        raise Refused(NOT_YOURSELF)
    return uname, rec


def _text(value):
    text = ai_enrich.no_dashes(" ".join(str(value or "").split())).strip()
    if not text:
        raise Refused(NO_TEXT)
    if len(text) > TEXT_LIMIT:
        raise Refused(TOO_LONG)
    return text


def _target(kind, value):
    if value is None or value == {}:
        if kind == "question":
            return None
        raise Refused(NO_TARGET)
    if not isinstance(value, dict):
        raise Refused(BAD_TARGET)
    tkind, key = str(value.get("kind") or ""), str(value.get("key") or "").strip()
    if tkind not in TARGET_KINDS or not key or len(key) > 200:
        raise Refused(BAD_TARGET)
    label = ai_enrich.no_dashes(" ".join(str(value.get("label") or key).split()))[:160]
    return {"kind": tkind, "key": key, "label": label or key}


# ── S72-T28: the real item behind a target, and who answers for it (R93) ──────────────────────
def _ids(key):
    """`key`, then its last part: a link key reads `<database>/<id>`."""
    key = str(key or "").strip()
    tail = re.split(r"[/:]", key)[-1].strip()
    return [key] + ([tail] if tail and tail != key else [])


def _lower(value):
    return str(value or "").strip().lower() or None


def _database_ref(session, key):
    from core import user_tables
    want = str(key).strip().casefold()
    for db in agent_directory._databases(session, agent_directory._lend(session)) or ():
        if not isinstance(db, dict) or not db.get("key"):
            continue
        if want not in {str(db["key"]).casefold(), str(db.get("label") or "").strip().casefold()}:
            continue
        oid = str(db["key"])
        ref = {"kind": "database", "key": oid, "oid": oid, "label": db.get("label") or oid,
               "owner": None, "creator": None}
        if oid.startswith(user_tables.KEY_PREFIX):
            table = user_tables.get_one(oid, session.runtime)
            if not table:
                return None
            ref["creator"] = _lower(table.get("createdBy"))
        return ref
    return None


def _sheet_ref(session, key):
    from core import shares, sheets
    for oid in _ids(key):
        try:
            book = sheets.get_workbook(session.runtime, oid)
        except sheets.SheetRefusal:
            continue
        bid = str(book.get("id") or oid)
        owner = (shares.grants("workbook", bid, st=session.runtime)["owner"]
                 or _lower(book.get("created_by")))
        return {"kind": "sheet", "key": bid, "oid": bid, "label": book.get("name") or "A sheet",
                "owner": owner, "book": book}
    return None


def _view_ref(session, key):
    import routes_shares
    from core import shares
    for oid in _ids(key):
        topic, creator, view = routes_shares._find_view_record(session, oid)
        if not topic:
            continue
        database = {"customer": "customer_data", "product": "product_data"}.get(topic, topic)
        owner = shares.grants("view", oid, st=session.runtime)["owner"] or _lower(creator)
        return {"kind": "view", "key": f"{database}/{oid}", "oid": oid,
                "label": (view or {}).get("name") or "A view", "owner": owner}
    return None


def _app_ref(session, key):
    import application_registry as apps
    found = apps.load(session.runtime).get("applications") or {}
    for oid in _ids(key):
        app = found.get(oid)
        if not isinstance(app, dict) or app.get("templateKind") == apps.FINANCE_TEMPLATE_KIND:
            continue
        dbs = [str(d) for d in app.get("compatibleDatabases") or () if d]
        return {"kind": "app", "key": f"{dbs[0]}/{oid}" if dbs else oid, "oid": oid,
                "label": app.get("name") or "An app", "owner": _lower(app.get("createdBy")),
                "app": app}
    return None


_RESOLVERS = {"database": _database_ref, "sheet": _sheet_ref, "view": _view_ref, "app": _app_ref}


def _resolve(session, target):
    """The real item behind a C6 target, with its real label and owner. Raises Refused."""
    try:
        ref = _RESOLVERS[target["kind"]](session, target["key"])
    except Exception as exc:                                             # noqa: BLE001
        _LOG.warning("Inbox target was not resolved (%s)", type(exc).__name__)
        ref = None
    if not ref:
        # One sentence for missing, unreadable and failed alike: a refusal never confirms an id.
        raise Refused(NOT_FOUND)
    ref["label"] = ai_enrich.no_dashes(" ".join(str(ref["label"]).split()))[:160] or ref["key"]
    return ref


def _public_target(ref):
    return {"kind": ref["kind"], "key": ref["key"], "label": ref["label"]}


def _held(session, ref, principal):
    """`principal`'s current role on the item: `owner`, `edit`, `view` or None."""
    from core import perm_scope, shares, sheets, user_tables
    import application_registry as apps
    rt, uname = session.runtime, _lower((principal or {}).get("username"))
    if not uname:
        return None
    if perms.is_admin(principal) or (ref["kind"] != "database" and ref.get("owner") == uname):
        return "owner"
    kind, oid = ref["kind"], ref["oid"]
    if kind == "database":
        if not perm_scope.may_read(principal, oid, st=rt):
            return None
        if oid.startswith(user_tables.KEY_PREFIX) and \
                user_tables.may_edit_database(oid, uname, False, st=rt):
            return "edit"
        return "view"
    if kind == "sheet":
        return sheets.workbook_role(rt, ref["book"], uname)
    if kind == "view":
        return shares.role_for("view", oid, uname, st=rt)
    if apps.may_edit(ref["app"], uname):
        return "edit"
    return "view" if apps.may_read(ref["app"], uname) else None


def _answerers(session, ref):
    """`(usernames, owner)`: who answers a request about `ref` in the caller's tenant (R93).

    A sheet, view or app goes to its active owner. A database, or an item whose owner is not
    an active account here, goes to every active Administrator.
    """
    active = {str(n).strip().lower(): rec for n, rec in agent_directory._accounts(session)}
    owner = ref.get("owner")
    if ref["kind"] != "database" and owner in active:
        return [owner], owner
    return sorted(n for n, rec in active.items() if perms.is_admin(rec)), None


def _route_request(session, ref, role):
    """Recipients of an access request. Raises Refused for an item the sender already holds."""
    me = _lower(session.uname)
    if ref["kind"] != "database" and ref.get("owner") == me:
        raise Refused(OWN_ITEM)
    if RANK[_held(session, ref, session.user)] >= RANK[role]:
        raise Refused(ALREADY_HELD)
    try:
        answerers, _owner = _answerers(session, ref)
    except agent_directory.DirectoryUnavailable as exc:
        raise Refused(UNAVAILABLE) from exc
    recipients = [u for u in answerers if u != me]
    if not recipients:
        raise Refused(NO_ANSWERER)
    return recipients


def _same(record, sender, recipients, kind, target, text, role, now):
    """True when `record` is an earlier copy of this message within a day."""
    if record.get("type") != kind or (record.get("sender") or {}).get("username") != sender:
        return False
    if record.get("state") in ("completed", "rejected", "canceled", "failed"):
        return False
    if not set(recipients) & set(record.get("recipients") or ()):
        return False
    age = _age(record.get("created_at"), now)
    if age is None or not 0 <= age < FOLD_SECONDS:
        return False
    theirs = record.get("target") or {}
    mine = target or {}
    if (theirs.get("kind"), theirs.get("key")) != (mine.get("kind"), mine.get("key")):
        return False
    if kind == "access_request":
        return record.get("state") in ("pending", "input-required") and record.get("role") == role
    return record.get("text") == text


def _title(record):
    name = record["sender"]["name"]
    label = (record.get("target") or {}).get("label") or ""
    if record["type"] == "access_request":
        level = "edit access" if record.get("role") == "edit" else "access"
        return ai_enrich.no_dashes(f"{name} asks for {level} to {label}")
    if record["type"] == "share":
        return ai_enrich.no_dashes(f"{name} shared {label} with you")
    return ai_enrich.no_dashes(f"{name} has a question" + (f" about {label}" if label else ""))


def notice_payload(record, recipient=None):
    """The C6 payload of one record. `recipient` is reserved for per-recipient state."""
    import tickets
    kind = record.get("type")
    state = record.get("state") if kind in ("access_request", "approval") else "pending"
    if record.get("state") in tickets.REQUEST_STATES:
        state = record["state"]
    if state not in ("pending", "approved", "declined") + tickets.REQUEST_STATES:
        state = "pending"
    if kind in ("access_request", "approval") and state == "input-required":
        state = "pending"
    actions = list(ACTIONS) if kind in ("access_request", "approval") and state == "pending" else []
    sender = record.get("sender") or {}
    return {"type": kind, "request_id": record.get("request_id"),
            "sender": {"username": str(sender.get("username") or ""),
                       "name": str(sender.get("name") or "")},
            "target": copy.deepcopy(record.get("target")), "text": record.get("text") or "",
            "actions": actions, "state": state}


def get(rt, request_id):
    """One stored record, or None."""
    return copy.deepcopy(((rt.get(STORE_KEY) or {}).get("requests") or {}).get(str(request_id)))


def _task_record(record):
    """Adapt the inbox columns for the shared C4 projection."""
    target = record.get("target") or {}
    source = record.get("source")
    if source is None and target.get("kind") == "database":
        source = {"database": target["key"], "record": ""}
    return {**record, "title": record.get("title") or _title(record), "source": source}


def get_request(rt, request_id, by):
    """Read one C4 inbox request after tenant, participant and source checks."""
    import tickets
    from types import SimpleNamespace
    record = get(rt, request_id)
    if not isinstance(record, dict):
        raise PermissionError(NO_REQUEST)
    name, principal = tickets._principal(rt, by)
    row = _task_record(record)
    task = tickets.project_request(row)
    sender = name == task["from"]["person"]
    if name not in task["to"] and not sender:
        raise PermissionError(NO_REQUEST)
    # The author may still read their own access request while waiting for its grant.
    if not (sender and task["kind"] == "access_request"):
        session = SimpleNamespace(runtime=rt, uname=name, user=principal, tenant=rt.key)
        if record.get("target"):
            try:
                ref = _resolve(session, record["target"])
                if _held(session, ref, principal) is None:
                    raise PermissionError(NO_REQUEST)
            except Refused as exc:
                raise PermissionError(NO_REQUEST) from exc
        if task["source"]:
            try:
                prepared = tickets._prepare_request_source(rt, name, task["source"])
                if name not in tickets.audience(rt, prepared):
                    raise PermissionError(NO_REQUEST)
            except ValueError as exc:
                raise PermissionError(NO_REQUEST) from exc
    return task


def list_for(rt, by):
    """Read the recipient's inbox as C4 tasks without exposing stored source values."""
    import tickets
    try:
        name, _user = tickets._principal(rt, by)
    except PermissionError:
        return []
    found = []
    for rid, record in ((rt.get(STORE_KEY) or {}).get("requests") or {}).items():
        if name not in (record.get("recipients") or ()):
            continue
        try:
            found.append(get_request(rt, rid, name))
        except PermissionError:
            continue
    return sorted(found, key=lambda row: (row["createdAt"], row["id"]), reverse=True)


def recipient_records(rt, by):
    """Return participant-owned rows for internal projection, never for direct serialization."""
    import tickets
    name, _user = tickets._principal(rt, by)
    return [_task_record(record) for record in ((rt.get(STORE_KEY) or {}).get("requests") or {}).values()
            if name in (record.get("recipients") or ())]


def list_attributions(rt, by, *, source_check=None):
    """Keep a recipient's safe task attribution even when the source grant was revoked."""
    import tickets
    return [tickets.request_attribution(rt, row, by, source_check=source_check)
            for row in recipient_records(rt, by)]


def set_request_state(rt, request_id, by, state, reason=None):
    """Change inbox task state without making a database or object grant."""
    import tickets

    def change(record):
        changes = tickets._transition(rt, _task_record(record), by, state, reason)
        return {**record, **changes}

    record = update(rt, request_id, change)
    if record is None:
        raise PermissionError(NO_REQUEST)
    _close_cards(rt, record)
    if by is tickets.SYSTEM_ACTOR:
        return tickets.project_request(_task_record(record))
    try:
        return get_request(rt, request_id, by)
    except PermissionError:
        return {"id": str(request_id), "state": state}


def update(rt, request_id, fn):
    """Apply `fn(record) -> record` under the store lock. Returns the new record or None."""
    if get(rt, request_id) is None:
        import tickets
        return tickets.update_app_share_request(rt, request_id, fn)
    out = []

    def apply(raw):
        data = copy.deepcopy(raw) if isinstance(raw, dict) else {}
        requests = data.setdefault("requests", {})
        current = requests.get(str(request_id))
        if not isinstance(current, dict):
            return data
        new = fn(copy.deepcopy(current))
        if not isinstance(new, dict):
            raise ValueError("Updating an inbox request needs an object.")
        new.update(request_id=current["request_id"], updated_at=_now().isoformat())
        requests[str(request_id)] = new
        out[:] = [copy.deepcopy(new)]
        return data

    rt.update(STORE_KEY, apply, flush="sync")
    return out[0] if out else None


def _notice_id(rt, uname, request_id):
    try:
        turns = assistant_log.read(rt, uname, limit=20).get("turns") or []
    except Exception:                                                    # noqa: BLE001
        return None
    return next((t.get("id") for t in reversed(turns)
                 if (t.get("payload") or {}).get("request_id") == request_id), None)


def _public(record, folded):
    return {"ok": True, "folded": folded, "request_id": record["request_id"],
            "type": record["type"], "state": record["state"],
            "to": [str(u) for u in record.get("recipients") or ()],
            "target": copy.deepcopy(record.get("target")), "text": record["text"]}


def _send(session, kind, to, target, text, role, now):
    if kind not in KINDS:
        raise Refused(NO_KIND)
    # R93: an access request is routed to whoever may answer it, so `to` is not needed there.
    if kind != "access_request" and not str(to or "").strip():
        raise Refused(NAME_TO)
    if role not in ROLES:
        raise Refused(BAD_ROLE)
    text = _text(text)
    target = _target(kind, target)
    if kind == "access_request":
        if target["kind"] == "app" and role != "view":
            raise Refused(APP_VIEW_ONLY)
        ref = _resolve(session, target)
        recipients = _route_request(session, ref, role)
        target = _public_target(ref)
    else:
        recipients = [_recipient(session, to)[0]]
        if target is not None:
            ref = _resolve(session, target)
            if _held(session, ref, session.user) is None:
                raise Refused(NOT_FOUND)
            target = _public_target(ref)
    me = str(session.uname or "").strip().lower()
    sender = {"username": me, "name": str((session.user or {}).get("name") or me)}
    stamp = _now(now)
    found = {}

    def apply(raw):
        data = copy.deepcopy(raw) if isinstance(raw, dict) else {}
        requests = data.setdefault("requests", {})
        for rec in requests.values():
            if isinstance(rec, dict) and _same(rec, me, recipients, kind, target, text, role, stamp):
                found["record"], found["folded"] = copy.deepcopy(rec), True
                return data
        from core import write_execution
        rid = write_execution.new_id()[:24]
        rec = {"request_id": rid, "type": kind, "sender": sender, "recipients": list(recipients),
               "target": target, "text": text,
               "role": role if kind == "access_request" else None,
               "state": "pending" if kind == "access_request" else "sent",
               "created_at": stamp.isoformat(), "updated_at": stamp.isoformat(),
               "notices": {}, "decided_by": None, "decided_at": None}
        requests[rid] = rec
        found["record"], found["folded"] = copy.deepcopy(rec), False
        return data

    session.runtime.update(STORE_KEY, apply, flush="sync")
    record = found["record"]
    if found["folded"]:
        return _public(record, True)
    rt, rid = session.runtime, record["request_id"]
    notices = {}
    for uname in record["recipients"]:
        alerts.notify(uname, _title(record), topic="inbox", key=rid, detail=record["text"],
                      actor=sender["name"], st=rt, target=copy.deepcopy(record["target"]),
                      inbox=notice_payload(record, uname))
        turn_id = _notice_id(rt, uname, rid)
        if turn_id:
            notices[uname] = turn_id
    if notices:
        record = update(rt, rid, lambda rec: {**rec, "notices": {**rec.get("notices", {}),
                                                                   **notices}}) or record
    return _public(record, False)


def send(session, *, type, to, target, text, role="view", now=None):     # noqa: A002
    """Send one message. Returns the request, `folded: true` for a repeat, or a refusal."""
    try:
        return _send(session, type, to, target, text, role, now)
    except Refused as exc:
        return {"ok": False, "refused": str(exc)}
    except Exception as exc:                                             # noqa: BLE001
        _LOG.warning("Agent message was not sent (%s)", exc.__class__.__name__)
        return {"ok": False, "refused": UNAVAILABLE}


def agent_message(session, args):
    """The `agent_message` tool."""
    args = args if isinstance(args, dict) else {}
    return send(session, type=str(args.get("type") or ""), to=args.get("to"),
                target=args.get("target"), text=args.get("text"),
                role=str(args.get("role") or "view"))


# ── S72-T28: a person answers an access request (C6 route only) ───────────────────────────────
# Access grants need a person's click. Confirmed team decisions never enter a grant writer.
def _may_answer(session, ref):
    """R93: the owner answers a sheet, view or app. An Administrator answers a database."""
    if ref["kind"] == "database":
        return bool(session.admin)  # only an Administrator grants a database
    _who, owner = _answerers(session, ref)
    if owner:
        return owner == _lower(session.uname)
    return bool(session.admin)


def _asker(session, record):
    want = _lower((record.get("sender") or {}).get("username"))
    for n, rec in agent_directory._accounts(session):
        if str(n).strip().lower() == want:
            return want, users._public(n, rec)
    raise Denied(409, "asker_gone", NOT_IN_WORKSPACE)


def _with_grant(prior, user, role):
    """`prior` with `user` at `role`. Every other entry is copied unchanged."""
    rows = [dict(e) for e in prior or ()]
    for row in rows:
        if row.get("user") == user:
            row["role"] = role
            return rows
    return rows + [{"user": user, "role": role}]


def _add_grant(kind, oid, user, role, *, owner, granter, st):
    """Add one grant through `shares.set_grants`, guarded by `expect`, the PUT door's own CAS."""
    from core import shares
    held = shares.grants(kind, oid, st=st)
    return shares.set_grants(kind, oid, _with_grant(held["entries"], user, role),
                             owner=None if held["owner"] else owner, st=st,
                             granter=granter, expect=held["entries"])


def _approve_grant(session, ref, asker, principal, role):
    """Grant exactly `role` to exactly `asker` on exactly the item. Raises Denied."""
    rt, kind, oid = session.runtime, ref["kind"], ref["oid"]
    if kind == "app" and role != "view":
        raise Denied(409, "unsupported_role", APP_VIEW_ONLY)
    if kind == "database":
        import routes_admin
        routes_admin.grant_database_access(session, asker, oid, role)
        return
    if RANK[_held(session, ref, principal)] >= RANK[role]:
        return  # The asker holds this already: nothing to write.
    if kind == "sheet":
        from core import sheets
        _add_grant("workbook", oid, asker, role, owner=ref.get("owner"),
                   granter=session.uname, st=rt)
        if "access" not in ref["book"]:
            sheets.narrow_workbook(rt, oid)  # the marker `routes_sheet.share_sheet` writes too
    elif kind == "view":
        # The PUT door's View path: the audience and its field boundary in one transaction.
        import routes_shares
        from core import field_permissions, shares
        held = shares.grants("view", oid, st=rt)
        _topic, view, grant_topic, _keys, _owned = routes_shares._prepare_view_share(session, oid)
        field_permissions.set_view_grants_with_boundary(
            view, grant_topic, _with_grant(held["entries"], asker, role),
            owner=None if held["owner"] else ref.get("owner"), granter=session.uname,
            expect=held["entries"], st=rt)
    else:
        import application_registry as apps
        app = (apps.load(rt).get("applications") or {}).get(oid) or {}
        share = app.get("share") if isinstance(app.get("share"), dict) else {}
        names = list(share.get("users") or ()) if share.get("mode") == "users" else []
        apps.mutate(rt, oid, session.uname, session.admin,
                    {"share": {"mode": "users", "users": names + [asker]}}, expect=share)


def _claim(rt, request_id, state, who):
    """Move a pending request to `state` once. Returns `(record, claimed)`."""
    claimed = []

    def fn(rec):
        # A store replay must report whether this invocation won the claim.
        claimed.clear()
        if rec.get("state") not in ("pending", "input-required"):
            return rec
        claimed.append(True)
        return {**rec, "state": state, "decided_by": who, "decided_at": _now().isoformat()}

    return update(rt, request_id, fn), bool(claimed)


def _close_cards(rt, record):
    """Refresh each recipient's notice using the compatible human approval controls."""
    def fn(turn):
        notice = notice_payload(record)
        payload = dict(turn.get("payload") or {}, state=notice["state"], actions=notice["actions"])
        return {**turn, "payload": payload}

    for uname in record.get("recipients") or ():
        turn_id = ((record.get("notices") or {}).get(uname)
                   or _notice_id(rt, uname, record["request_id"]))
        try:
            if turn_id:
                assistant_log.update_turn(rt, uname, turn_id, fn)
        except Exception as exc:                                         # noqa: BLE001
            _LOG.warning("Inbox card was not closed (%s)", type(exc).__name__)


def _tell_asker(session, record):
    """One outcome notice to the asker. It never raises: the decision already stands."""
    me = _lower(session.uname)
    name = str((session.user or {}).get("name") or me)
    text = ai_enrich.no_dashes(f"{name} approved your request." if record["state"] == "approved"
                               else f"{name} said not now.")
    payload = dict(notice_payload(record), sender={"username": me, "name": name}, text=text)
    try:
        alerts.notify(record["sender"]["username"], text, topic="inbox",
                      key=record["request_id"], detail=text, actor=name, st=session.runtime,
                      target=copy.deepcopy(record.get("target")), inbox=payload)
    except Exception as exc:                                             # noqa: BLE001
        _LOG.warning("Inbox outcome was not sent (%s)", type(exc).__name__)


def _unclaim(rt, request_id, state, who):
    """Put a claimed request back to pending, only while it still reads `state` by `who`."""
    def fn(rec):
        if rec.get("state") != state or rec.get("decided_by") != who:
            return rec
        return {**rec, "state": "pending", "decided_by": None, "decided_at": None}

    return update(rt, request_id, fn)


def _denied(exc):
    """The Denied a failed answer maps to. Every refusal stays one plain sentence."""
    from core import shares
    from fastapi import HTTPException
    if isinstance(exc, Denied):
        return exc
    if isinstance(exc, HTTPException) and isinstance(exc.detail, dict):
        error = exc.detail.get('error') or {}
        return Denied(exc.status_code, error.get('code') or 'not_granted',
                      error.get('message') or NOT_GRANTED)
    if isinstance(exc, agent_directory.DirectoryUnavailable):
        return Denied(503, "unavailable", NOT_ANSWERED)
    if isinstance(exc, PermissionError):
        return Denied(403, "not_allowed", ONLY_OWNER)
    if isinstance(exc, shares.GrantsChanged):
        return Denied(409, "grants_changed", CHANGED)
    _LOG.warning("Inbox request was not answered (%s)", type(exc).__name__)
    return Denied(409, "not_granted", NOT_GRANTED)


def _decide_app_share(session, record, action):
    """Claim an Administrator's choice before applying the App's guarded share mutation."""
    import application_registry as apps
    import tickets
    import deps
    import routes_assets
    rt = session.runtime
    try:
        me, principal = tickets._principal(rt, session.uname)
        if str(session.tenant) != str(rt.key) or me not in record["recipients"]:
            raise Denied(404, "no_request", NO_REQUEST)
        if not perms.is_admin(principal):
            raise Denied(403, "not_allowed", ONLY_APP_ADMIN)
        if record["state"] in ("approved", "declined"):
            return {"state": record["state"]}
        if record["state"] != "pending":
            raise Denied(409, "request_ended", "This request has already ended.")
        tickets.get_request(rt, record["request_id"], me)
        asker, _asker_principal = tickets._principal(rt, record["sender"]["username"])
        app = tickets._application_source(rt, record["source"]["record"])
        if app.get("createdBy") != asker or not apps.workspace_share_needs_approval(app):
            raise Denied(409, "app_changed", "This App no longer matches the share request.")
    except Exception as exc:
        raise _denied(exc) from exc
    state = "approved" if action == "approve" else "declined"
    final, claimed = _claim(rt, record["request_id"], state, me)
    if not claimed or not final:
        return {"state": (final or record).get("state")}
    if action == "approve":
        try:
            current_session = deps.Session(rt.key, principal, {}, rt)
            allowed, records = routes_assets.application_access_context(
                current_session, app.get("compatibleDatabases") or (), strict=True)
            apps.mutate(rt, app["id"], me, True, {"share": {"mode": "tenant"}},
                        allowed_databases=allowed, semantic_records=records,
                        field_contracts=routes_assets._application_chart_fields(
                            current_session, allowed, application_id=app["id"]),
                        expect=record["expectedShare"])
        except Exception as exc:
            _unclaim(rt, record["request_id"], state, me)
            raise _denied(exc) from exc
    _close_cards(rt, final)
    _tell_asker(session, final)
    return {"state": final["state"]}


def team_approval(rt, request_id, by, *, source_check=None):
    """Admit only a recipient's sourced team proposal, excluding access grants and App shares."""
    import tickets
    _key, row = tickets._ticket(rt, request_id)
    task = tickets.get_request_attribution(rt, request_id, by, source_check=source_check)
    if (task["kind"] != "approval" or task["title"] != TEAM_CHANGE_TITLE
            or not task["body"].startswith(TEAM_CHANGE_PREFIX)
            or not task["body"].endswith(TEAM_AUTHORIZATION_NOTE)
            or row.get("approvalAction") or row.get("target")
            or by not in task["to"] or by == task["from"]["person"]):
        raise PermissionError("Only the recipient can answer a team change proposal.")
    if not task["sourceVisible"] or task["source"] is None:
        raise PermissionError("You cannot see the source data this request needs.")
    return task


def _decide_team_approval(session, request_id, decision, source_check):
    """Record one explicit authorization decision without invoking any target writer or grant."""
    import tickets
    from core import user_tables
    rt, me = session.runtime, _lower(session.uname)
    if decision not in ("Approve", "Deny"):
        raise ValueError("Choose Approve or Deny.")
    proposal = team_approval(rt, request_id, me, source_check=source_check)
    key, _row = tickets._ticket(rt, request_id)
    state = "completed" if decision == "Approve" else "rejected"
    result = {}

    def write(data):
        result.clear()
        row = data[key]["rows"].get(str(request_id))
        # Recheck the locked candidate as well as the public source projection.
        if (not isinstance(row, dict) or row.get("kind") != "approval"
                or row.get("title") != TEAM_CHANGE_TITLE or row.get("approvalAction") or row.get("target")
                or me not in tickets._request_recipients(row) or row.get("from_person") == me):
            raise PermissionError("Only the recipient can answer a team change proposal.")
        current = tickets.project_request({**row, "id": str(request_id)})
        if any(current[field] != proposal[field] for field in ("from", "to", "title", "body", "source")):
            raise ValueError("This proposal changed. Read it and preview your decision again.")
        tickets._request_reader(rt, row, me, sender=False)
        if source_check:
            source_check(tickets.project_request(row)["source"])
        if row.get("state") not in ("submitted", "input-required"):
            if row.get("state") != state or row.get("decided_by") != me:
                raise ValueError("This proposal has already been answered.")
        else:
            row.update(tickets._transition(rt, row, me, state, decision + ". " + TEAM_AUTHORIZATION_NOTE))
            row.update(status="Resolved", decided_by=me, decided_at=tickets._utc().isoformat(),
                       updated_at=tickets._utc().isoformat(), closed_at=tickets._utc().isoformat())
        result.update(id=str(request_id), decision=decision, authorized=decision == "Approve", executed=False,
                      state=state, notice=TEAM_AUTHORIZATION_NOTE)
        return data

    rt.update(user_tables.STORE_KEY, write, flush="sync")
    return result


def decide_request(session, request_id, action, *, authorization_only=False, source_check=None):
    """Answer one access request on a person's click (C6, R93). Returns `{"state"}`.

    The decision is claimed before the grant, so a parallel click can never leave a grant under
    a declined record. A failed grant puts the claim back.
    """
    if authorization_only:
        return _decide_team_approval(session, request_id, action, source_check)
    if action not in ACTIONS:
        raise Denied(400, "bad_action", BAD_ACTION)
    rt, me = session.runtime, _lower(session.uname)
    record = get(rt, request_id)
    if record is None:
        import tickets
        approval = tickets.app_share_record(rt, request_id)
        if approval is not None:
            return _decide_app_share(session, approval, action)
    # The store is the tenant's own, so another tenant's id is simply not here.
    if not isinstance(record, dict) or record.get("type") != "access_request" \
            or not isinstance(record.get("target"), dict):
        raise Denied(404, "no_request", NO_REQUEST)
    decided = record.get("state") in ("approved", "declined")
    try:
        try:
            ref = _resolve(session, record["target"])
        except Refused:
            if decided and (session.admin or me == record.get("decided_by")
                            or me in (record.get("recipients") or ())):
                return {"state": record["state"]}
            raise Denied(404, "no_item", NOT_FOUND)
        if not _may_answer(session, ref):
            raise Denied(403, "not_allowed",
                         ONLY_ADMIN if ref["kind"] == "database" else ONLY_OWNER)
        if decided:
            return {"state": record["state"]}  # A second click changes nothing.
        asker, principal = _asker(session, record)
        state = "approved" if action == "approve" else "declined"
        role = record.get("role")
        if action == 'approve' and role not in ROLES:
            raise Denied(409, "unsupported_role", BAD_ROLE)
    except Exception as exc:                                             # noqa: BLE001
        raise _denied(exc) from exc
    final, claimed = _claim(rt, record["request_id"], state, me)
    if not claimed or not final:
        return {"state": (final or record).get("state")}  # Another click decided first.
    if action == "approve":
        try:
            _approve_grant(session, ref, asker, principal, role)
        except Exception as exc:                                         # noqa: BLE001
            _unclaim(rt, record["request_id"], state, me)
            raise _denied(exc) from exc
    _close_cards(rt, final)
    _tell_asker(session, final)
    return {"state": final["state"]}


TOOLS = ({"name": "agent_message", "schema": SCHEMA, "fn": agent_message, "effect": "write"},)