File size: 33,968 Bytes
dec006b
 
 
 
07a68d0
 
 
dec006b
07a68d0
 
dec006b
 
 
 
 
103a492
e198d0b
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
07a68d0
dec006b
 
 
 
 
8cbc29f
 
 
 
dec006b
 
103a492
dec006b
8cbc29f
dec006b
103a492
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
103a492
 
 
 
 
 
07a68d0
 
 
 
 
 
dec006b
 
 
07a68d0
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
dec006b
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
8133df9
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
8cbc29f
dec006b
07a68d0
 
dec006b
 
 
 
 
 
 
f462120
 
 
 
 
 
dec006b
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
dec006b
 
 
8cbc29f
 
 
07a68d0
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
07a68d0
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
07a68d0
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
dec006b
 
103a492
 
 
 
 
 
dec006b
e198d0b
 
dec006b
e198d0b
 
 
dec006b
 
 
 
103a492
 
dec006b
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
dec006b
e198d0b
 
dec006b
07a68d0
 
 
 
dec006b
 
 
 
103a492
dec006b
 
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
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
"""App actions through the registry and the shared confirmation path."""
import base64
import copy
import hashlib
import importlib
import importlib.util
import inspect
import json
import re
import sys

from core import external_tools, perm_scope, sheets
import application_registry as applications
from app_guide import BRIEF
from loopy_catalog_tools import _schema as catalog_pdf_schema
from loopy_catalog_tools import build_schema as catalog_build_schema
from . import legacy_action


def _admit(ctx, *, write=False):
    session = ctx.session
    reason = perm_scope.ai_apps_refusal(session.user, session.runtime)
    if reason:
        raise sheets.SheetRefusal("ai_apps_off", reason)
    if write:
        from routes_external import _assert_write_scope
        _assert_write_scope(session, "apps")
    return session


def _access(ctx, databases, *, strict=False):
    from routes_assets import application_access_context
    from routes_external import _assert_database_scope
    for database in databases:
        _assert_database_scope(ctx.session, database)
    return application_access_context(ctx.session, databases, strict=strict)


def _fields(ctx, databases):
    return {database: ctx.describe_database(database)["fields"] for database in databases}


def _attribution(session):
    from routes_external import _trusted_activity_via
    external = (session.claims or {}).get("external") is True
    return {"via": _trusted_activity_via(session), "on_behalf_of": session.uname,
            "origin_door": "mcp" if external else "loopy"}


def _refuse(exc):
    from routes_assets import _application_error
    _application_error(exc)


def templates(ctx, args):
    _admit(ctx)
    return {"templates": applications.template_contracts()}


def _catalog_link(app):
    if app.get("templateKind") == "catalog":
        from loopy_links import application_link
        databases = app.get("compatibleDatabases") or []
        app["deepLink"] = application_link(app["id"], databases[0] if databases else None)
    return app


#: R35: a template App answers over tools with these keys only. Its definition stays sealed.
TEMPLATE_APP_KEYS = ("id", "name", "templateKind", "purpose", "status", "tools")
#: Tools a template App can use today when the C1 template catalogue is absent.
_FALLBACK_TOOLS = {"catalog": ("catalog_build", "catalog_pdf")}
TEMPLATE_SEALED_CODE = "template_app_sealed"


def is_template_app(app):
    """A Loopable template App: its templateKind is set and it is not a code App."""
    return isinstance(app, dict) and bool(app.get("templateKind")) and app.get("type") != "code"


def _template_entry(kind):
    """The C1 `app_templates.TEMPLATES` entry for a kind, or None while C1 is absent."""
    try:
        import app_templates
    except ImportError:
        return None
    rows = getattr(app_templates, "TEMPLATES", None)
    if isinstance(rows, dict):
        entry = rows.get(kind)
        if isinstance(entry, dict):
            return entry
        rows = rows.values()
    for entry in rows or ():
        if isinstance(entry, dict) and entry.get("kind") == kind:
            return entry
    return None


def _template_purpose(kind, entry):
    purpose = entry.get("purpose") if entry else None
    if not isinstance(purpose, str) or not purpose.strip():
        contract = applications._template_contract(kind) or {}
        purpose = str(contract.get("label") or kind or "").replace("_", " ")
        purpose = purpose[:1].upper() + purpose[1:].lower()
    return " ".join(purpose.split())


def template_tools(kind):
    """The tool names a template App answers to, from C1 or the actions it can use today."""
    entry = _template_entry(kind)
    tools = entry.get("tools") if entry else None
    if isinstance(tools, (list, tuple)):
        return [str(tool) for tool in tools]
    return list(_FALLBACK_TOOLS.get(kind, ()))


def template_public(app):
    """R35: name, one line purpose, status and tool list. No definition, source binding or code."""
    kind = app.get("templateKind")
    entry = _template_entry(kind)
    return {"id": app.get("id"), "name": app.get("name"), "templateKind": kind,
            "purpose": _template_purpose(kind, entry), "status": "active", "tools": template_tools(kind)}


def template_sealed_message(app):
    """The fix sentence for a definition write on a template App."""
    tools = ", ".join("apps." + tool if "." not in tool else tool
                      for tool in template_tools(app.get("templateKind")))
    use = ("Use its own tools: " + tools + ". ") if tools else ""
    return ("This App is a Loopable template. Its definition cannot be read or changed over tools. " + use
            + "An Administrator can rename or share it in Loopable.")


def template_sealed(app):
    """The named refusal for a definition write on a template App."""
    from deps import err
    return err(403, TEMPLATE_SEALED_CODE, template_sealed_message(app))


def _list_row(app):
    if not is_template_app(app):
        return _catalog_link(app)
    row = template_public(app)
    if app.get("updatedAt"):
        # files.list reads the change time of each build.
        row["updatedAt"] = app["updatedAt"]
    return row


def list_apps(ctx, args):
    session = _admit(ctx)
    from core import external_access
    from routes_external import _key_scope

    scope = _key_scope(session)[1]
    databases = {database for app in applications.load(session.runtime)["applications"].values()
                 if applications._listed(app, session.uname)
                 for database in app.get("compatibleDatabases") or []
                 if external_access.database_allowed(scope, database)}
    try:
        allowed, _ = _access(ctx, sorted(databases))
        return {"applications": [_list_row(app) for app in applications.list_apps(
            session.runtime, session.uname, session.admin, allowed_databases=allowed)]}
    except (applications.ApplicationError, PermissionError) as exc:
        _refuse(exc)


CATALOG_ID_FIX = ("No stored catalog has this catalog_id. Use the catalog_id that apps.catalog_build returned, "
                  "after confirm_change committed that build. A preview saves no catalog until it is confirmed.")


def catalog_pdf(ctx, args):
    session = _admit(ctx)
    import catalog_store
    import loopy_catalog_tools
    from fastapi import HTTPException

    # The stored record admits its actual App source and credential scope.
    try:
        catalog_store._record(session, args["catalog_id"])
    except HTTPException as exc:
        code = ((exc.detail or {}).get("error") or {}).get("code") if isinstance(exc.detail, dict) else None
        if code == "catalog_not_found":
            from deps import err
            raise err(404, "catalog_not_found", CATALOG_ID_FIX) from exc
        raise
    if (session.claims or {}).get("external") is True:
        # An MCP call has a time budget. A longer render answers with an operation_id.
        return loopy_catalog_tools.catalog_pdf_within_budget(
            session, args, render=lambda caller, values: loopy_catalog_tools.catalog_pdf(caller, values))
    return loopy_catalog_tools.catalog_pdf(session, args)


def catalog_build(ctx, args):
    _admit(ctx, write=True)
    from loopy_catalog_tools import catalog_build as build
    return build(ctx, args)


def _held(app):
    """R11: an App whose kind is held out of the product reads as absent."""
    import app_templates
    return app_templates.held(app)


def _read(ctx, app_id):
    session = _admit(ctx)
    app = applications.load(session.runtime)["applications"].get(app_id)
    if (not app or app.get("retired") is True or _held(app)
            or not applications.may_read(app, session.uname, session.admin)):
        raise applications.ApplicationError("application does not exist")
    databases = app.get("compatibleDatabases") or []
    allowed, _ = _access(ctx, databases)
    if applications._is_finance(app):
        if not applications._account_wall(session.runtime, session.user)(applications._finance_permission(app)):
            raise applications.ApplicationError("application does not exist")
    elif databases and not allowed:
        raise applications.ApplicationError("application does not exist")
    return app, allowed


def get(ctx, args):
    try:
        app, allowed = _read(ctx, args["app_id"])
        if is_template_app(app):
            return {"application": template_public(app)}
        result = applications._public(app, ctx.session.uname, ctx.session.admin, allowed_databases=allowed)
        if app["type"] == "code":
            result["config"]["display"]["html"] = app["config"]["display"]["html"]
        return {"application": _catalog_link(result)}
    except (applications.ApplicationError, PermissionError) as exc:
        _refuse(exc)


#: C8 refusal codes. A caller is refused by name, never shown an empty list.
APP_UNAVAILABLE = "app_unavailable"
APP_ITEMS_UNAVAILABLE = "app_items_unavailable"
APP_ITEMS_FORBIDDEN = "app_items_forbidden"
APP_ITEM_STATUS_INVALID = "app_item_status_invalid"
APP_ITEM_UNKNOWN = "app_item_unknown"
#: An Operator approval runs only in the Operator inbox, where each removal is reviewed first.
APP_OPERATOR_APPROVE_IN_APP = "operator_approve_in_app"
_KIND = re.compile(r"[a-z][a-z0-9_]{0,63}")


def _refusal(status, code, message, details=None):
    from deps import err
    return err(status, code, message, details)


def _item_app(ctx, app_id, *, edit):
    """C8: the App the caller may read (items) or edit (set_status). One refusal for absent and unshared."""
    try:
        app, _ = _read(ctx, app_id)
    except (applications.ApplicationError, PermissionError):
        raise _refusal(404, APP_UNAVAILABLE, "No App with this id is shared with this account. "
                       "Call apps.list for the Apps this account can open.") from None
    session = ctx.session
    if edit and not applications.may_edit(app, session.uname, session.admin):
        raise _refusal(403, APP_ITEMS_FORBIDDEN, "This account can read this App but cannot change its items. "
                       "Ask its owner or an Administrator to change them.")
    return app


def _item_module(app):
    """C8 dispatch: templateKind to the C1 `module`, else `modules.<templateKind>`."""
    kind = app.get("templateKind") if is_template_app(app) else None
    entry = _template_entry(kind) if kind else None
    name = entry.get("module") if entry else None
    if not isinstance(name, str) or not name.strip():
        name = "modules." + str(kind or "")
    module = None
    if kind and _KIND.fullmatch(str(kind)) and re.fullmatch(r"modules\.[a-z][a-z0-9_]{0,63}", name):
        try:
            module = importlib.import_module(name)
        except Exception:
            module = None
    if module is None or not callable(getattr(module, "items", None)) or not callable(
            getattr(module, "set_status", None)):
        raise _refusal(409, APP_ITEMS_UNAVAILABLE, "This App has no items to list or change over tools. "
                       "Open it in Loopable, or ask an Administrator to update it.")
    return module


def _kind_modules():
    """Each template kind with the module name C8 dispatches it to: the C1 row, else `modules.<kind>`."""
    try:
        import app_templates
        rows = getattr(app_templates, "TEMPLATES", None) or {}
    except ImportError:
        rows = {}
    entries = rows.values() if isinstance(rows, dict) else rows
    named = {entry["kind"]: entry.get("module") for entry in entries
             if isinstance(entry, dict) and isinstance(entry.get("kind"), str)}
    for row in applications.template_contracts():
        named.setdefault(row["kind"], None)
    return {kind: name if isinstance(name, str) and name.strip() else "modules." + kind
            for kind, name in named.items() if _KIND.fullmatch(kind)}


def items_supported():
    """Capability report: some template kind resolves to a module with items and set_status."""
    for name in _kind_modules().values():
        if not re.fullmatch(r"modules\.[a-z][a-z0-9_]{0,63}", name):
            continue
        try:
            # An absent module is skipped without an import attempt. A module already loaded is read as is.
            if name not in sys.modules and importlib.util.find_spec(name) is None:
                continue
            module = importlib.import_module(name)
        except Exception:
            continue
        if callable(getattr(module, "items", None)) and callable(getattr(module, "set_status", None)):
            return True
    return False


def _accepts_store(fn):
    """True when a C4 function takes the `st=` store override, so a preview writes privately."""
    try:
        params = inspect.signature(fn).parameters
    except (TypeError, ValueError):
        return False
    # Only a named `st`: a **kwargs catch-all may ignore it and write the real store during a preview.
    return "st" in params


def _tenant_key(session):
    return str(getattr(session.runtime, "key", "") or session.tenant)


def _statuses(module):
    values = getattr(module, "STATUSES", None)
    return [str(value) for value in values] if isinstance(values, (list, tuple, set, frozenset)) else None


def _status_refusal(module, status):
    allowed = _statuses(module)
    tail = (" Use one of: " + ", ".join(allowed) + ".") if allowed else " Use a status this App lists on its items."
    return _refusal(400, APP_ITEM_STATUS_INVALID, "This App does not allow the status " + json.dumps(str(status))
                    + "." + tail, {"allowed": allowed} if allowed else None)


def _item_refusal(module, exc, status=None):
    if isinstance(exc, PermissionError):
        return _refusal(403, APP_ITEMS_FORBIDDEN, "This account cannot work this App's items. "
                        "Ask its owner or an Administrator for access.")
    if isinstance(exc, KeyError):
        return _refusal(404, APP_ITEM_UNKNOWN, "Choose item ids that apps.items returned for this App.")
    return _status_refusal(module, status)


def items(ctx, args):
    """C8 apps.items: the App's own items with status, owner and reason, paged by the module's cursor."""
    _admit(ctx)
    app = _item_app(ctx, args["application"], edit=False)
    module = _item_module(app)
    session = ctx.session
    kwargs = {key: args[key] for key in ("status", "cursor") if args.get(key) is not None}
    if _accepts_store(module.items):
        kwargs["st"] = session.runtime
    try:
        page = module.items(_tenant_key(session), session.uname, **kwargs)
    except (PermissionError, ValueError) as exc:
        raise _item_refusal(module, exc, args.get("status")) from None
    page = page if isinstance(page, dict) else {}
    # Rule 1: the module pages by cursor. Nothing here caps or trims its page.
    return {"app_id": app["id"], "items": list(page.get("items") or []), "cursor": page.get("cursor")}


def _current_items(module, session, ids):
    """Each requested id with its current status, read from the module's pages."""
    found, cursor, seen = {}, None, set()
    while True:
        kwargs = {"cursor": cursor} if cursor is not None else {}
        if _accepts_store(module.items):
            kwargs["st"] = session.runtime
        page = module.items(_tenant_key(session), session.uname, **kwargs) or {}
        for item in page.get("items") or ():
            if isinstance(item, dict) and str(item.get("id")) in ids:
                found[str(item["id"])] = item
        cursor = page.get("cursor")
        if not cursor or cursor in seen or len(found) == len(ids):
            return found
        seen.add(cursor)


def set_status(ctx, args):
    """C8 apps.set_status: one preview for every id, applied only through confirm_change (R14 batch approve)."""
    from routes_external import _ConfirmationRuntime, _PreviewRuntime
    session = _admit(ctx, write=True)
    app = _item_app(ctx, args["application"], edit=True)
    module = _item_module(app)
    ids = list(dict.fromkeys(str(value) for value in args["item_ids"]))
    status, note = args["status"], args.get("note")
    if app.get("templateKind") == "amazon_operator" and str(status).strip().lower() == "approved":
        raise _refusal(403, APP_OPERATOR_APPROVE_IN_APP,
                       "Approve these in the Operator inbox, where each proposal is reviewed first.")
    allowed = _statuses(module)
    if allowed is not None and status not in allowed:
        raise _status_refusal(module, status)
    runtime = session.runtime
    previewing = isinstance(runtime, _PreviewRuntime)
    if not previewing and not isinstance(runtime, _ConfirmationRuntime):
        raise sheets.SheetRefusal("confirmation_not_write", "Preview this change, then apply it with confirm_change.")
    tenant = _tenant_key(session)
    if _accepts_store(module.set_status):
        # The module writes into the preview store, so the diff and the stale check see its own document.
        changed = []
        for item_id in ids:
            try:
                changed.append(module.set_status(tenant, session.uname, item_id, status, note=note, st=runtime))
            except (PermissionError, KeyError, ValueError) as exc:
                raise _item_refusal(module, exc, status) from None
        return {"app_id": app["id"], "item_ids": ids, "status": status, "items": changed}
    # The module writes its own store: a preview names the change and never calls set_status.
    try:
        current = _current_items(module, session, set(ids))
    except (PermissionError, ValueError) as exc:
        raise _item_refusal(module, exc, status) from None
    if len(current) != len(ids):
        raise _refusal(404, APP_ITEM_UNKNOWN, "Choose item ids that apps.items returned for this App.",
                       {"unknown": [item_id for item_id in ids if item_id not in current][:100]})
    plan = {item_id: {"status": status, "from": current[item_id].get("status")} for item_id in ids}
    if previewing:
        runtime.update(_PLAN_KEY_PREFIX + str(app["id"]), lambda doc: {**(doc or {}), **plan})
        return {"app_id": app["id"], "item_ids": ids, "status": status}
    if getattr(runtime, "preview_only", False) or getattr(runtime, "activity_preview", False):
        # A staged confirm (the Assistant's YES hold) must not reach a store it cannot stage.
        raise _refusal(409, APP_ITEMS_UNAVAILABLE, "This App applies item changes only through confirm_change. "
                       "Confirm the preview from the AI that made it.")
    changed = []
    for item_id in ids:
        try:
            changed.append(module.set_status(tenant, session.uname, item_id, status, note=note))
        except (PermissionError, KeyError, ValueError) as exc:
            raise _item_refusal(module, exc, status) from None
    return {"app_id": app["id"], "item_ids": ids, "status": status, "items": changed}


#: A preview-only document naming a planned change for a module that writes its own store.
_PLAN_KEY_PREFIX = "app_item_changes/"


def apply_template(ctx, args):
    session = _admit(ctx, write=True)
    try:
        payload = copy.deepcopy(args)
        if payload["templateKind"] not in {row["kind"] for row in applications.template_contracts()}:
            raise applications.ApplicationError("Choose a template from apps.templates.")
        _template_inputs(payload)
        share = payload.pop("share", None)
        import app_templates
        source = payload.get("sourceDatabase") or app_templates.source(payload["templateKind"])
        databases = [source] if source else []
        allowed, records = _access(ctx, databases, strict=True)
        payload.setdefault("navPlacement", {"section": "app", "order": 0})
        attribution = _attribution(session)
        result = applications.create(
            session.runtime, session.tenant, session.uname, payload,
            allowed_databases=allowed, semantic_records=records,
            field_contracts=_fields(ctx, allowed), is_admin=session.admin, **attribution)
        if result.get("existing") is True:
            # One live copy per template App per tenant: answer that copy and leave its sharing alone.
            answer = _result(result)
            answer.update(existing=True, message="This App is already in this workspace. Nothing new was added.")
            return answer
        if share is not None:
            result = applications.mutate(
                session.runtime, result["id"], session.uname, session.admin, {"share": share},
                allowed_databases=allowed, semantic_records=records,
                field_contracts=_fields(ctx, allowed), **attribution)
        return _result(result)
    except applications.ApplicationError as exc:
        # Keep typed refusals and inaccessible-App responses on their original path.
        if type(exc) is applications.ApplicationError and "does not exist" not in str(exc):
            kind = json.dumps(args["templateKind"], ensure_ascii=True)
            exc = applications.ApplicationError(
                f"Cannot apply templateKind {kind}. {str(exc).rstrip('.')}. "
                "Check this template's inputs with apps.templates and retry.")
        _refuse(exc)
    except PermissionError as exc:
        _refuse(exc)


def _template_inputs(payload):
    """Name the missing template input and where it goes before the registry answers generically."""
    contract = next(row for row in applications.template_contracts() if row["kind"] == payload["templateKind"])
    import app_templates
    if payload["templateKind"] in app_templates.BY_KIND:
        return
    required = [role["key"] for role in contract["fieldRoles"] if role["required"]]
    example = json.dumps({role: "<field key>" for role in required})
    if not isinstance(payload.get("sourceDatabase"), str) or not payload["sourceDatabase"].strip():
        raise applications.ApplicationError(
            "apply_template is missing sourceDatabase. Put sourceDatabase inside arguments: the database key "
            "this App reads, as table.list_databases returns it.")
    field_map = payload.get("fieldMap")
    if not isinstance(field_map, dict):
        raise applications.ApplicationError(
            "apply_template is missing fieldMap. Put fieldMap inside arguments: an object that maps the required "
            "roles " + ", ".join(required) + " to field keys of sourceDatabase, for example " + example
            + ". apps.templates lists the optional roles.")
    missing = [role for role in required if not str(field_map.get(role) or "").strip()]
    if missing:
        raise applications.ApplicationError(
            "fieldMap is missing the required role " + ", ".join(missing) + ". Map each to a field key of "
            "sourceDatabase inside arguments.fieldMap, for example " + example + ".")


def _result(app):
    result = {"application": _catalog_link(app)}
    if app.get("shareApproval"):
        result["warnings"] = [app["shareApproval"]["message"]]
    return result


def save_code(ctx, args):
    session = _admit(ctx, write=True)
    try:
        payload = {key: copy.deepcopy(args[key]) for key in ("name", "compatibleDatabases", "share") if key in args}
        payload["config"] = {"schemaVersion": 1, "display": {"mode": "code", "html": args["html"]}}
        attribution = _attribution(session)
        app_id = args.get("app_id")
        if app_id:
            current, allowed = _read(ctx, app_id)
            if is_template_app(current):
                raise template_sealed(current)
            if current["type"] != "code":
                raise applications.ApplicationError("Choose a code App to update.")
            proposed = payload.get("compatibleDatabases", current.get("compatibleDatabases") or [])
            proposed_allowed, records = _access(ctx, proposed, strict=True)
            result = applications.mutate(
                session.runtime, app_id, session.uname, session.admin, payload,
                allowed_databases=allowed | proposed_allowed, semantic_records=records, **attribution)
        else:
            share = payload.pop("share", None)
            payload.update(type="code")
            payload.setdefault("compatibleDatabases", [])
            allowed, records = _access(ctx, payload["compatibleDatabases"], strict=True)
            result = applications.create(
                session.runtime, session.tenant, session.uname, payload,
                allowed_databases=allowed, semantic_records=records, is_admin=session.admin, **attribution)
            if share is not None:
                result = applications.mutate(
                    session.runtime, result["id"], session.uname, session.admin, {"share": share},
                    allowed_databases=allowed, **attribution)
        return _result(result)
    except (applications.ApplicationError, PermissionError) as exc:
        _refuse(exc)


def guide(ctx, args):
    _admit(ctx)
    import app_guide
    return app_guide.read(args.get("section"))


def preview_documents(documents):
    """Project code bodies to a bounded excerpt before the host computes its diff."""
    projected = copy.deepcopy(documents)
    for key, pair in projected.items():
        if key != applications._KEY and not key.startswith(applications._RECORD_PREFIX):
            continue
        for side in ("before", "after"):
            if not isinstance(pair[side], dict):
                continue
            pair[side] = applications._clean_doc(pair[side])
            for app in pair[side]["applications"].values():
                if app.get("type") == "code":
                    html = app["config"]["display"].pop("html")
                    app["config"]["display"].update(
                        htmlBytes=len(html.encode("utf-8")),
                        htmlSha256=hashlib.sha256(html.encode("utf-8")).hexdigest(),
                        firstLines="\n".join(html.split("\n")[:5])[:500])
    import catalog_store
    pair = projected.get(catalog_store.STORE_KEY)
    for side in ("before", "after") if pair else ():
        doc = pair[side] if isinstance(pair[side], dict) else {}
        # R35: a catalog preview names its template App, never its field map or source binding.
        # Each digest keeps the confirmation bound to the definition the preview saw.
        snapshots = doc.get("appSnapshots") if isinstance(doc.get("appSnapshots"), dict) else {}
        for app_id, snapshot in snapshots.items():
            if is_template_app(snapshot):
                snapshots[app_id] = {**{key: snapshot[key] for key in ("id", "templateKind") if key in snapshot},
                                     "definitionSha256": _digest(snapshot)}
        catalogs = doc.get("catalogs") if isinstance(doc.get("catalogs"), dict) else {}
        for record in catalogs.values():
            if isinstance(record, dict) and "fields" in record:
                record["fieldsSha256"] = _digest(record.pop("fields"))
    return projected


def _digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode("utf-8")).hexdigest()


def pending_arguments(arguments, *, encode):
    """Encode the pending code body for JSONB and restore it before confirmation."""
    result = copy.deepcopy(arguments)
    if result.get("action") == "save_code":
        args = result["arguments"]
        if encode and isinstance(args.get("html"), str):
            args["html"] = {"encoding": "utf8-base64-v1",
                            "data": base64.b64encode(args["html"].encode("utf-8")).decode("ascii")}
        elif not encode and isinstance(args.get("html"), dict):
            encoded = args["html"]
            if set(encoded) != {"encoding", "data"} or encoded["encoding"] != "utf8-base64-v1":
                raise ValueError("The pending App body cannot be read.")
            args["html"] = base64.b64decode(encoded["data"], validate=True).decode("utf-8")
    return result


def code_transport_fits(value, limit):
    """Allow JSON escaping overhead while bounding the HTML and all other arguments."""
    if not isinstance(value, dict):
        return False
    document = copy.deepcopy(value)
    args = document.get("arguments") if document.get("tool") == "apps" else document
    if not isinstance(args, dict) or args.get("action") != "save_code":
        return False
    body = args.get("arguments")
    if not isinstance(body, dict):
        return False
    html = body.get("html")
    if isinstance(html, dict):
        html = pending_arguments(args, encode=False)["arguments"]["html"]
    if not isinstance(html, str) or len(html.encode("utf-8")) > applications._MAX_DISPLAY_BYTES:
        return False
    body["html"] = ""
    return len(json.dumps(document, ensure_ascii=True, allow_nan=False).encode("utf-8")) <= limit


def loopy(session, args):
    """Serve the Assistant's App group through the same preview and read dispatcher."""
    from routes_external import _dispatch_mcp
    reply = _dispatch_mcp({"jsonrpc": "2.0", "id": "loopy-apps", "method": "tools/call",
                           "params": {"name": "apps", "arguments": args}}, session)
    return json.loads(reply["result"]["content"][0]["text"])


def loopy_confirm(session, args):
    """Apply an agreed Assistant App preview through confirm_change."""
    from routes_external import _dispatch_mcp, _read_confirmation_token
    payload = _read_confirmation_token(args.get("confirmation_token"), session=session)
    if payload.get("tool") != "apps" or payload["arguments"].get("action") not in ("apply_template", "save_code", "catalog_build", "set_status"):
        raise sheets.SheetRefusal("confirmation_not_write", "Choose an App preview to confirm.")
    reply = _dispatch_mcp({"jsonrpc": "2.0", "id": "loopy-apps-confirm", "method": "tools/call",
                           "params": {"name": "confirm_change", "arguments": args}}, session)
    return json.loads(reply["result"]["content"][0]["text"])


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


def _action(handler, properties, required=(), *, read=True, description=None):
    schema = _schema(properties, required)
    if description is not None:
        schema["description"] = description
    return {"read": read, "destructive": False, "confirm": not read,
            "schema": schema, "handler": handler}


_TEXT = {"type": "string", "minLength": 1}
_INTENT = {"type": "string", "minLength": 1, "maxLength": 500}
_SHARE = _schema({"mode": {"enum": ["private", "users", "tenant"]},
                  "users": {"type": "array", "items": _TEXT}}, ("mode",))
LOOPY_SCHEMA = _schema({"action": {"type": "string"}, "arguments": {"type": "object"},
                        "intent": copy.deepcopy(_INTENT)}, ("action",))
if hasattr(external_tools, "ABOUT_SCHEMA"):
    LOOPY_SCHEMA["properties"]["about"] = copy.deepcopy(external_tools.ABOUT_SCHEMA)
_CONFIRM_SCHEMA = copy.deepcopy(external_tools.TOOLS["confirm_change"]["inputSchema"])
_CONFIRM_SCHEMA["properties"]["intent"] = copy.deepcopy(_INTENT)

GROUP = {
    "name": "apps", "title": "Apps",
    "guide": BRIEF,
    "actions": {
        "upsert": legacy_action("app_upsert"),
        "delete": legacy_action("app_delete", destructive=True),
        "templates": _action(templates, {}),
        "list": _action(list_apps, {}),
        "catalog_pdf": {"read": True, "destructive": False, "confirm": False,
                        "schema": catalog_pdf_schema(), "handler": catalog_pdf},
        "catalog_build": {"read": False, "destructive": False, "confirm": True,
                          "buildKind": "app", "schema": catalog_build_schema(), "handler": catalog_build},
        "apply_template": _action(apply_template, {
            "name": _TEXT, "templateKind": _TEXT, "sourceDatabase": _TEXT,
            "fieldMap": {"type": "object"}, "config": {"type": "object"},
            "navPlacement": _schema({"section": {"enum": ["app"]}, "order": {"type": "integer"}}, ("section", "order")),
            "share": _SHARE,
        }, ("name", "templateKind"), read=False),
        "save_code": _action(save_code, {
            "app_id": _TEXT, "name": _TEXT, "html": {"type": "string"},
            "compatibleDatabases": {"type": "array", "items": _TEXT}, "share": _SHARE,
        }, ("name", "html"), read=False, description=BRIEF),
        "get": _action(get, {"app_id": _TEXT}, ("app_id",)),
        "items": _action(items, {"application": _TEXT, "status": _TEXT,
                                  "cursor": {"type": ["string", "integer"]}}, ("application",),
                         description="List an App's items with status, owner and reason. Pass cursor for the next page."),
        "set_status": _action(set_status, {
            "application": _TEXT, "item_ids": {"type": "array", "items": _TEXT, "minItems": 1},
            "status": _TEXT, "note": {"type": "string", "maxLength": 1000},
        }, ("application", "item_ids", "status"), read=False,
            description="Change the status of one or more App items. Status approved on several ids approves them "
                        "in one confirm_change."),
        "guide": _action(guide, {"section": _TEXT}),
    },
}

# C8 reports items and set_status as supported once some template kind has a C4 module.
for _name in ("items", "set_status"):
    GROUP["actions"][_name]["available"] = items_supported

# The Assistant callback returns a preview. Only confirm_change applies its product write.
TOOLS = [{"name": "apps", "schema": {**LOOPY_SCHEMA, "description": GROUP["guide"]},
          "fn": loopy, "effect": "read"},
         {"name": "apps_confirm", "schema": {
             **_CONFIRM_SCHEMA,
             "description": "Call confirm_change only for an App preview the person agreed to. Use its confirmation_token."},
          "fn": loopy_confirm, "effect": "write"}]