|
3 | 3 | import html |
4 | 4 | import json |
5 | 5 |
|
| 6 | +from datasette.resources import QueryResource |
6 | 7 | from datasette_agent_edit import EditError, EditToolset, Editable, NotFound |
7 | 8 |
|
8 | 9 | from .csp import configured_csp_allowlist, resolve_csp_origins |
|
66 | 67 | "Each edit is a str_replace or insert operation, and the batch " |
67 | 68 | "is saved as one app revision." + APP_RUNTIME_API_GUIDANCE |
68 | 69 | ), |
| 70 | + "add_stored_queries": ( |
| 71 | + "Give an existing stored Datasette app access to one or more stored " |
| 72 | + "queries, so its HTML can call them with " |
| 73 | + "await datasette.storedQuery(database, query, params?). Pass each " |
| 74 | + "query as a database/query string. The queries must already exist " |
| 75 | + "(use save_query first to create a new one). Read-only queries are " |
| 76 | + "granted immediately. Write queries (INSERT/UPDATE/DELETE) let the " |
| 77 | + "app modify data as whoever views it, so the user is shown the SQL " |
| 78 | + "and asked to approve first; if they decline, do not retry unless " |
| 79 | + "they ask you to. Requires edit permission for that app." |
| 80 | + ), |
| 81 | + "remove_stored_queries": ( |
| 82 | + "Remove stored query access from an existing stored Datasette app. " |
| 83 | + "Pass each query as a database/query string. Requires edit " |
| 84 | + "permission for that app." |
| 85 | + ), |
69 | 86 | "render": "Render links to the current stored Datasette app after editing.", |
70 | 87 | "debug": ( |
71 | 88 | "Run a JavaScript debug script inside a live sandboxed render of a " |
@@ -209,6 +226,142 @@ def _render_created_app(app, view_path, edit_path): |
209 | 226 | ) |
210 | 227 |
|
211 | 228 |
|
| 229 | +class StoredQueryAccessError(ValueError): |
| 230 | + pass |
| 231 | + |
| 232 | + |
| 233 | +async def _resolve_stored_queries(datasette, actor, keys): |
| 234 | + """Validate database/query strings the actor may grant to an app. |
| 235 | +
|
| 236 | + Mirrors the web form: the query must exist and the actor must have |
| 237 | + view-query on it. Returns one dict per unique key, in input order. |
| 238 | + """ |
| 239 | + if keys is None: |
| 240 | + return [] |
| 241 | + if isinstance(keys, str) or not isinstance(keys, list): |
| 242 | + raise StoredQueryAccessError( |
| 243 | + "stored_queries must be a list of database/query strings" |
| 244 | + ) |
| 245 | + resolved = [] |
| 246 | + seen = set() |
| 247 | + for key in keys: |
| 248 | + if not isinstance(key, str): |
| 249 | + raise StoredQueryAccessError( |
| 250 | + "stored_queries must be a list of database/query strings" |
| 251 | + ) |
| 252 | + key = key.strip() |
| 253 | + database_name, _, query_name = key.partition("/") |
| 254 | + if not database_name or not query_name: |
| 255 | + raise StoredQueryAccessError( |
| 256 | + 'Invalid stored query "{}" - use database/query'.format(key) |
| 257 | + ) |
| 258 | + if key in seen: |
| 259 | + continue |
| 260 | + seen.add(key) |
| 261 | + stored_query = None |
| 262 | + if database_name in datasette.databases: |
| 263 | + stored_query = await datasette.get_query(database_name, query_name) |
| 264 | + if stored_query is None or not await datasette.allowed( |
| 265 | + action="view-query", |
| 266 | + resource=QueryResource(database=database_name, query=query_name), |
| 267 | + actor=actor, |
| 268 | + ): |
| 269 | + raise StoredQueryAccessError("Stored query not found: {}".format(key)) |
| 270 | + resolved.append( |
| 271 | + { |
| 272 | + "key": key, |
| 273 | + "database": database_name, |
| 274 | + "name": query_name, |
| 275 | + "title": getattr(stored_query, "title", None) or "", |
| 276 | + "sql": stored_query.sql, |
| 277 | + "is_write": bool(stored_query.is_write), |
| 278 | + } |
| 279 | + ) |
| 280 | + return resolved |
| 281 | + |
| 282 | + |
| 283 | +def _write_query_approval(app_name, write_queries): |
| 284 | + sections = [] |
| 285 | + text_sections = [] |
| 286 | + for query in write_queries: |
| 287 | + sections.append( |
| 288 | + "<p><strong>{}</strong>{}</p><pre>{}</pre>".format( |
| 289 | + html.escape(query["key"]), |
| 290 | + ( |
| 291 | + " – {}".format(html.escape(query["title"])) |
| 292 | + if query["title"] |
| 293 | + else "" |
| 294 | + ), |
| 295 | + html.escape(query["sql"]), |
| 296 | + ) |
| 297 | + ) |
| 298 | + text_sections.append("{}\n{}".format(query["key"], query["sql"])) |
| 299 | + warning = ( |
| 300 | + "Write queries can insert, update or delete data. The app runs them " |
| 301 | + "with the permissions of whoever is viewing it." |
| 302 | + ) |
| 303 | + html_body = ( |
| 304 | + '<div class="datasette-app-query-approval">' |
| 305 | + "<p>App: <strong>{}</strong></p><p>{}</p>{}</div>".format( |
| 306 | + html.escape(app_name), html.escape(warning), "".join(sections) |
| 307 | + ) |
| 308 | + ) |
| 309 | + text_body = "App: {}\n{}\n\n{}".format( |
| 310 | + app_name, warning, "\n\n".join(text_sections) |
| 311 | + ) |
| 312 | + if len(write_queries) == 1: |
| 313 | + prompt = 'Allow app "{}" to run write query "{}"?'.format( |
| 314 | + app_name, write_queries[0]["key"] |
| 315 | + ) |
| 316 | + else: |
| 317 | + prompt = 'Allow app "{}" to run {} write queries?'.format( |
| 318 | + app_name, len(write_queries) |
| 319 | + ) |
| 320 | + return prompt, html_body, text_body |
| 321 | + |
| 322 | + |
| 323 | +async def _approve_write_queries(context, app_name, queries): |
| 324 | + """Ask the user before granting write queries to an app. |
| 325 | +
|
| 326 | + Returns None if approved (or nothing needs approval), otherwise an |
| 327 | + error/cancellation payload string. Read-only queries never prompt. |
| 328 | + Must run before any side effects: the tool call re-executes from the |
| 329 | + start once the user answers. |
| 330 | + """ |
| 331 | + write_queries = [query for query in queries if query["is_write"]] |
| 332 | + if not write_queries: |
| 333 | + return None |
| 334 | + not_supported = ( |
| 335 | + "Granting write queries requires user approval, which is not " |
| 336 | + "available in this conversation. Ask the user to grant them from " |
| 337 | + "the app's edit page instead." |
| 338 | + ) |
| 339 | + if context is None or not hasattr(context, "ask_user"): |
| 340 | + return _error(not_supported) |
| 341 | + prompt, html_body, text_body = _write_query_approval(app_name, write_queries) |
| 342 | + try: |
| 343 | + approved = await context.ask_user(prompt, html=html_body, text=text_body) |
| 344 | + except Exception as e: |
| 345 | + # Matched by name so datasette-agent stays an optional dependency; |
| 346 | + # QuestionPending (an llm.PauseChain) must keep propagating. |
| 347 | + if e.__class__.__name__ == "QuestionsNotSupported": |
| 348 | + return _error(not_supported) |
| 349 | + raise |
| 350 | + if not approved: |
| 351 | + return json.dumps( |
| 352 | + { |
| 353 | + "cancelled": True, |
| 354 | + "message": ( |
| 355 | + "The user declined to grant the write queries " |
| 356 | + "{}. Do not retry unless they ask you to.".format( |
| 357 | + ", ".join(query["key"] for query in write_queries) |
| 358 | + ) |
| 359 | + ), |
| 360 | + } |
| 361 | + ) |
| 362 | + return None |
| 363 | + |
| 364 | + |
212 | 365 | def _toolset(datasette, actor): |
213 | 366 | return EditToolset( |
214 | 367 | StoredAppHtmlStore(datasette, actor), |
@@ -236,11 +389,20 @@ async def _app_create( |
236 | 389 | sql_databases=None, |
237 | 390 | stored_queries=None, |
238 | 391 | csp_origins=None, |
| 392 | + context=None, |
239 | 393 | ): |
240 | 394 | if not await _can_create_app(datasette, actor): |
241 | 395 | return _error("Permission denied: create-app") |
242 | 396 | try: |
243 | 397 | csp_origins = await resolve_csp_origins(datasette, actor, csp_origins or []) |
| 398 | + queries = await _resolve_stored_queries(datasette, actor, stored_queries) |
| 399 | + except ValueError as e: |
| 400 | + return _error(str(e)) |
| 401 | + stored_queries = [query["key"] for query in queries] |
| 402 | + refusal = await _approve_write_queries(context, name or "Untitled app", queries) |
| 403 | + if refusal is not None: |
| 404 | + return refusal |
| 405 | + try: |
244 | 406 | app = await Registry(datasette).create_stored_app( |
245 | 407 | actor_id=_actor_id(actor), |
246 | 408 | name=name or "Untitled app", |
@@ -399,6 +561,49 @@ async def _with_app_edit_permission(datasette, actor, app_id, callback): |
399 | 561 | return await callback() |
400 | 562 |
|
401 | 563 |
|
| 564 | +async def _app_update_stored_queries(datasette, actor, context, app_id, queries, add): |
| 565 | + if not await _can_edit_app(datasette, actor, app_id): |
| 566 | + return _error("Permission denied: edit-app", app_id=app_id) |
| 567 | + registry = Registry(datasette) |
| 568 | + app = await registry.get_app(app_id) |
| 569 | + if app is None or app["external"] or app.get("deleted_at"): |
| 570 | + return _error("App not found", app_id=app_id) |
| 571 | + current = await registry.get_stored_queries(app_id) |
| 572 | + if add: |
| 573 | + try: |
| 574 | + resolved = await _resolve_stored_queries(datasette, actor, queries) |
| 575 | + except ValueError as e: |
| 576 | + return _error(str(e), app_id=app_id) |
| 577 | + new_queries = [query for query in resolved if query["key"] not in current] |
| 578 | + refusal = await _approve_write_queries( |
| 579 | + context, app["name"] or app_id, new_queries |
| 580 | + ) |
| 581 | + if refusal is not None: |
| 582 | + return refusal |
| 583 | + updated = current + [query["key"] for query in new_queries] |
| 584 | + changed = [query["key"] for query in new_queries] |
| 585 | + else: |
| 586 | + if isinstance(queries, str) or not isinstance(queries, list): |
| 587 | + return _error( |
| 588 | + "stored_queries must be a list of database/query strings", |
| 589 | + app_id=app_id, |
| 590 | + ) |
| 591 | + remove = {key.strip() for key in queries if isinstance(key, str)} |
| 592 | + updated = [key for key in current if key not in remove] |
| 593 | + changed = [key for key in current if key in remove] |
| 594 | + try: |
| 595 | + await registry.set_stored_queries(app_id, updated, actor_id=_actor_id(actor)) |
| 596 | + except KeyError: |
| 597 | + return _error("App not found", app_id=app_id) |
| 598 | + return json.dumps( |
| 599 | + { |
| 600 | + "app_id": app_id, |
| 601 | + "added" if add else "removed": changed, |
| 602 | + "stored_queries": sorted(dict.fromkeys(updated)), |
| 603 | + } |
| 604 | + ) |
| 605 | + |
| 606 | + |
402 | 607 | def _csp_origins_schema_description(datasette=None): |
403 | 608 | description = ( |
404 | 609 | "Optional exact https:// origins this app may contact " |
@@ -521,6 +726,22 @@ async def app_edit(datasette, actor, app_id, edits): |
521 | 726 | lambda: _toolset(datasette, actor).edit(app_id, edits), |
522 | 727 | ) |
523 | 728 |
|
| 729 | + async def app_add_stored_queries(datasette, actor, context, app_id, stored_queries): |
| 730 | + return await _app_update_stored_queries( |
| 731 | + datasette, actor, context, app_id, stored_queries, add=True |
| 732 | + ) |
| 733 | + |
| 734 | + async def app_remove_stored_queries(datasette, actor, app_id, stored_queries): |
| 735 | + return await _app_update_stored_queries( |
| 736 | + datasette, actor, None, app_id, stored_queries, add=False |
| 737 | + ) |
| 738 | + |
| 739 | + stored_queries_property = { |
| 740 | + "type": "array", |
| 741 | + "description": "Stored queries as database/query strings", |
| 742 | + "items": {"type": "string"}, |
| 743 | + } |
| 744 | + |
524 | 745 | async def app_render(datasette, actor, app_id): |
525 | 746 | return await _with_app_edit_permission( |
526 | 747 | datasette, |
@@ -586,8 +807,9 @@ async def app_render(datasette, actor, app_id): |
586 | 807 | "stored_queries": { |
587 | 808 | "type": "array", |
588 | 809 | "description": ( |
589 | | - "Optional stored queries this app may call, as " |
590 | | - "database/query strings" |
| 810 | + "Optional existing stored queries this app may " |
| 811 | + "call, as database/query strings. Write queries " |
| 812 | + "require user approval" |
591 | 813 | ), |
592 | 814 | "items": {"type": "string"}, |
593 | 815 | }, |
@@ -702,6 +924,38 @@ async def app_render(datasette, actor, app_id): |
702 | 924 | }, |
703 | 925 | fn=app_edit, |
704 | 926 | ), |
| 927 | + AgentTool( |
| 928 | + name="app_add_stored_queries", |
| 929 | + description=APP_TOOL_DESCRIPTIONS["add_stored_queries"], |
| 930 | + input_schema={ |
| 931 | + "type": "object", |
| 932 | + "properties": { |
| 933 | + "app_id": { |
| 934 | + "type": "string", |
| 935 | + "description": "The stored Datasette app ID", |
| 936 | + }, |
| 937 | + "stored_queries": stored_queries_property, |
| 938 | + }, |
| 939 | + "required": ["app_id", "stored_queries"], |
| 940 | + }, |
| 941 | + fn=app_add_stored_queries, |
| 942 | + ), |
| 943 | + AgentTool( |
| 944 | + name="app_remove_stored_queries", |
| 945 | + description=APP_TOOL_DESCRIPTIONS["remove_stored_queries"], |
| 946 | + input_schema={ |
| 947 | + "type": "object", |
| 948 | + "properties": { |
| 949 | + "app_id": { |
| 950 | + "type": "string", |
| 951 | + "description": "The stored Datasette app ID", |
| 952 | + }, |
| 953 | + "stored_queries": stored_queries_property, |
| 954 | + }, |
| 955 | + "required": ["app_id", "stored_queries"], |
| 956 | + }, |
| 957 | + fn=app_remove_stored_queries, |
| 958 | + ), |
705 | 959 | AgentTool( |
706 | 960 | name="app_render", |
707 | 961 | description=APP_TOOL_DESCRIPTIONS["render"], |
|
0 commit comments