fsanyoto commited on
Commit
1295f71
·
verified ·
1 Parent(s): 2e77cd4

Prune files not in the deploy set (stale build context)

Browse files
api/routes_script_views.py DELETED
@@ -1,439 +0,0 @@
1
- """routes_script_views.py — CONTRACT C3: a database View that is a PYTHON SCRIPT (R3 / R5 / R10).
2
-
3
- Owner item 6, verbatim (2026-08-18): *"Add code script as an interface (database View) so a user
4
- can build whatever they want through the Agent chat interface. be able to create any dashboard
5
- they want. User should have the ability to see the code AND the dashboard output of course… Limit
6
- the code script View per database… Any agent can add into more AI script, so we can see different
7
- versions or different things the AI code for us."*
8
-
9
- GET /api/v1/script-views?database=K the views bound to ONE database
10
- POST /api/v1/script-views create one {database, name?, source}
11
- GET /api/v1/script-views/{id} one view, its source and its history
12
- PUT /api/v1/script-views/{id} a NEW VERSION of the source
13
- DELETE /api/v1/script-views/{id} drop it
14
- POST /api/v1/script-views/{id}/run run it -> {ok, spec | error, stdout, ms}
15
- POST /api/v1/script-views/{id}/revert go back to an earlier version {version}
16
-
17
- ⭐⭐ **R3 IS "SCOPED, NOT CAPPED", AND THE TWO HALVES POINT OPPOSITE WAYS.** *Scoped*: a view may
18
- read ONLY the database it lives in, and a script that names another database is REFUSED with a
19
- message naming both. *Not capped*: there is **no limit on how many script views a database may
20
- carry**, because that is how an agent offers three attempts and the owner picks one. So nothing
21
- below counts views. What IS bounded is what makes them big — one source is capped, and one view's
22
- edit history is capped and REPORTS what it dropped.
23
-
24
- ⛔ **THE RUN IS THE CALLER'S, NEVER THE AUTHOR'S (R5).** `script_sandbox.run_view` is handed
25
- `session.user`, so a script written by an administrator and opened by a scoped analyst reads the
26
- ANALYST's rows. The author decides what the code does; the reader decides what it can see.
27
- ⚠ And the reverse case is safe rather than lucky: a narrowly-scoped author cannot write a script
28
- that exfiltrates anything, because the only thing a script can return is a render spec drawn on
29
- the screen of the person who ran it. There is no network, no file and no second reader.
30
-
31
- ⛔ **`run` IS `def`, NOT `async def`.** It waits on a subprocess for up to ten seconds; as a
32
- coroutine that would block the event loop for every other request in the container. FastAPI runs a
33
- plain `def` in the threadpool, which is what makes one slow script one slow REQUEST.
34
- """
35
- import threading
36
- from datetime import datetime, timezone
37
-
38
- from fastapi import APIRouter, Body, Depends
39
-
40
- from deps import Session, err, require_session
41
-
42
- router = APIRouter(prefix="/api/v1")
43
-
44
- #: The tenant's script views: `{id: record}`. Per tenant, so it rides `runtime.store_key`.
45
- VIEWS_KEY = "script_views"
46
-
47
- MAX_NAME = 80
48
- MAX_SOURCE_BYTES = 128 * 1024
49
-
50
- #: Edit history per view. ⚠ NOT a cap on the NUMBER of views (R3 forbids that) — a cap on how far
51
- #: back ONE view's source is kept. Past this the oldest go and `trimmed` counts them, so a reader
52
- #: can see the history is partial instead of concluding the view was only ever saved twice.
53
- MAX_HISTORY = 40
54
-
55
- #: ⛔ HOW MANY SCRIPTS MAY BE RUNNING IN THIS CONTAINER AT ONCE, and it is a REPORTED refusal
56
- #: rather than a queue. Each run is a real subprocess with a ten-second wall clock; without this,
57
- #: holding down refresh forks until the box gives up, and the tenant's ONE FastAPI process is what
58
- #: gives up. A 429 that says so is honest; an unbounded fork is not.
59
- MAX_CONCURRENT_RUNS = 4
60
- _RUN_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_RUNS)
61
-
62
-
63
- def _now():
64
- return datetime.now(timezone.utc).isoformat(timespec="seconds")
65
-
66
-
67
- def _all(rt):
68
- """`{id: record}` for one tenant. `{}` on any failure — an unreadable bucket must degrade to
69
- "this database has no script views", never to a 500 on the view rail."""
70
- try:
71
- found = rt.get(VIEWS_KEY) or {}
72
- except Exception: # noqa: BLE001
73
- return {}
74
- return found if isinstance(found, dict) else {}
75
-
76
-
77
- def _database_ok(session, database):
78
- """Does this database EXIST, and may this caller read it? Answered by C1, never by a list.
79
-
80
- ⛔ `perm_scope.may_read` ALONE IS NOT ENOUGH and the reason is easy to miss: it answers True
81
- for an ADMIN on any key at all, including one no database answers to. So a create validated
82
- with `may_read` would let an administrator bind a view to a typo and leave an orphan nothing
83
- can ever run. `scoped_fields` is the cheap half of C1 (a `ut_*` definition, no rows) and it
84
- RAISES `UnknownTable`, which is exactly the question being asked.
85
- """
86
- import core.perm_scope as perm_scope
87
- try:
88
- perm_scope.scoped_fields(session.user, database, st=session.runtime)
89
- except perm_scope.UnknownTable:
90
- raise err(404, "no_database", f"there is no database '{database}' in this workspace")
91
- except perm_scope.Denied:
92
- raise err(403, "forbidden", f"your account may not read '{database}'")
93
- except perm_scope.Unresolvable as exc:
94
- # The database is real and cannot be served under this call's constraints. Standing rule
95
- # 1's second sentence: report the cause and the recommendation, never a bare refusal.
96
- raise err(409, "unresolvable", str(exc)) from None
97
-
98
-
99
- def _clean_source(raw, *, allow_empty=False):
100
- """The stored source, or a 400. `allow_empty` is CREATE's alone and the asymmetry is the point.
101
-
102
- ⭐⭐ W37-T41 — WHY CREATE MAY BE EMPTY AND SAVE MAY NOT.
103
- Picking "Custom View" in the mode picker mints the view immediately, before a line of code
104
- exists, so that `mode === 'script'` always implies a real id and no reader has to carry a
105
- "the id might be missing" branch (the create semantics handed to lane C in mailbox E-7).
106
- A view that has been created and not yet written is therefore a REAL, legible state: the editor
107
- shows its starter placeholder and the Run control is right there.
108
- A PUT is a different act. It appends a VERSION to a history capped at 40, and blanking a
109
- working script by saving nothing over it is not an edit anybody means to make. So the guard
110
- stays exactly where it was on that door, and a person who wants the view gone deletes it.
111
-
112
- ⛔ THIS WAS FOUND BY THE GATE, NOT BY READING. `core.script_sandbox.check_source("")` returns
113
- None, so "an empty script is storable" looked true and was written into a mailbox answer another
114
- lane was about to build on. The refusal was HERE, one layer above, in a function the sandbox
115
- knows nothing about. Two validators for one question, disagreeing
116
- [[one-question-two-normalizers]] — and the one that would have bitten a person is the one no
117
- unit of this feature was asserting.
118
- """
119
- source = str(raw or "")
120
- if not source.strip() and not allow_empty:
121
- raise err(400, "no_source", "a script view needs some code")
122
- if len(source.encode("utf-8", "replace")) > MAX_SOURCE_BYTES:
123
- raise err(413, "source_too_long",
124
- f"a script view is at most {MAX_SOURCE_BYTES // 1024} KB of code")
125
- return source
126
-
127
-
128
- def _row(rec, *, source=False):
129
- """One view as the list door reports it. ⚠ NO SOURCE unless asked: the rail lists names."""
130
- out = {"id": rec.get("id") or "", "database": rec.get("database") or "",
131
- "name": rec.get("name") or "", "author": rec.get("author") or "",
132
- "version": int(rec.get("version") or 1),
133
- "created": rec.get("created") or "", "updated": rec.get("updated") or "",
134
- "versions": len(rec.get("history") or []) + 1,
135
- "trimmed": int(rec.get("trimmed") or 0),
136
- # ⭐ W37-T46: which version this one was RESTORED from, when it was. Present on the
137
- # row (not only the history) because the editor's header is where a person reads "what
138
- # am I looking at", and "v5, restored from v2" is the sentence that makes a roll-back
139
- # legible as an event rather than as a coincidence of matching code.
140
- "restoredFrom": rec.get("restoredFrom")}
141
- if source:
142
- out["source"] = rec.get("source") or ""
143
- out["history"] = [{"version": int(h.get("version") or 0), "author": h.get("author") or "",
144
- "created": h.get("created") or "",
145
- "bytes": len(str(h.get("source") or "").encode("utf-8", "replace"))}
146
- for h in reversed(rec.get("history") or []) if isinstance(h, dict)]
147
- return out
148
-
149
-
150
- def _limits():
151
- return {"maxSourceBytes": MAX_SOURCE_BYTES, "maxName": MAX_NAME,
152
- "maxHistory": MAX_HISTORY, "maxConcurrentRuns": MAX_CONCURRENT_RUNS,
153
- # ⭐ SAID OUT LOUD, because R3's "not capped" half is the one a reader assumes wrong.
154
- "maxViewsPerDatabase": None}
155
-
156
-
157
- def _put(session, view_id, mutate):
158
- """Read-modify-write ONE view, synchronously — the client re-reads the rail immediately."""
159
- def _set(cur):
160
- cur = dict(cur or {})
161
- nxt = mutate(cur.get(view_id) if isinstance(cur.get(view_id), dict) else None)
162
- if nxt is None:
163
- cur.pop(view_id, None)
164
- else:
165
- cur[view_id] = nxt
166
- return cur
167
-
168
- session.runtime.update(VIEWS_KEY, _set, flush="sync")
169
-
170
-
171
- def _mine_or_admin(session, rec):
172
- """Who may EDIT or DELETE a view: its author, or an administrator.
173
-
174
- ⚠ RUNNING IS A DIFFERENT QUESTION and deliberately wider — anybody who may read the database
175
- may run any view on it, under their OWN scope. That is the whole of "so we can see different
176
- versions or different things the AI code for us": a colleague's attempt is worth nothing if
177
- only its author can open it.
178
- """
179
- if session.admin or str(rec.get("author") or "") == session.uname:
180
- return
181
- raise err(403, "forbidden", "only the author or an administrator can change this script view")
182
-
183
-
184
- # ── the routes ────────────────────────────────────────────────────────────────────────────────
185
- @router.get("/script-views")
186
- def list_script_views(database: str = "", session: Session = Depends(require_session)):
187
- """Every script view bound to ONE database, newest first. `database` is required."""
188
- key = str(database or "").strip()
189
- if not key:
190
- raise err(400, "no_database", "name the database whose script views you want")
191
- _database_ok(session, key)
192
- rows = [_row(rec) for rec in _all(session.runtime).values()
193
- if isinstance(rec, dict) and str(rec.get("database") or "") == key]
194
- rows.sort(key=lambda r: (r["created"], r["id"]), reverse=True)
195
- return {"database": key, "views": rows, "limits": _limits()}
196
-
197
-
198
- @router.post("/script-views")
199
- def create_script_view(body: dict = Body(default=None),
200
- session: Session = Depends(require_session)):
201
- """Create one. ⛔ THE SOURCE IS CHECKED BEFORE IT IS STORED, not first at run time.
202
-
203
- A script view that cannot be run is a broken feature the reader discovers by pressing a button,
204
- and the agent that wrote it is long gone by then. `check_source` is pure and costs no process,
205
- so the refusal arrives while the author still has the code in front of them.
206
- """
207
- import secrets # noqa: PLC0415
208
- import core.script_sandbox as sandbox # noqa: PLC0415
209
-
210
- body = body if isinstance(body, dict) else {}
211
- database = str(body.get("database") or "").strip()
212
- if not database:
213
- raise err(400, "no_database", "a script view is bound to one database")
214
- _database_ok(session, database)
215
- # ⭐ `allow_empty` is CREATE's alone - see `_clean_source`. The picker mints a view the
216
- # moment a person chooses the mode, so the empty source is the normal first state, not a slip.
217
- source = _clean_source(body.get("source"), allow_empty=True)
218
- refusal = sandbox.check_source(source)
219
- if refusal is not None:
220
- raise err(400, refusal.code, refusal.message)
221
-
222
- view_id = "sv_" + secrets.token_urlsafe(9)
223
- rec = {"id": view_id, "database": database,
224
- "name": " ".join(str(body.get("name") or "Script view").split())[:MAX_NAME],
225
- "source": source, "author": session.uname, "version": 1,
226
- "created": _now(), "updated": _now(), "history": [], "trimmed": 0}
227
- _put(session, view_id, lambda _prior: rec)
228
- fresh = _all(session.runtime).get(view_id)
229
- if not isinstance(fresh, dict):
230
- # The store took the write and did not record it. A 200 here would tell the author their
231
- # script was saved when it was not.
232
- raise err(503, "store_unavailable", "the script view was NOT created")
233
- return {"view": _row(fresh, source=True), "limits": _limits()}
234
-
235
-
236
- @router.get("/script-views/{view_id}")
237
- def get_script_view(view_id: str, session: Session = Depends(require_session)):
238
- """One view WITH its source and its edit history. Owner item 6's *"see the code"* half."""
239
- rec = _all(session.runtime).get(str(view_id))
240
- if not isinstance(rec, dict):
241
- raise err(404, "no_view", "there is no script view with that id")
242
- _database_ok(session, str(rec.get("database") or ""))
243
- return {"view": _row(rec, source=True), "limits": _limits()}
244
-
245
-
246
- @router.put("/script-views/{view_id}")
247
- def update_script_view(view_id: str, body: dict = Body(default=None),
248
- session: Session = Depends(require_session)):
249
- """A NEW VERSION of one view's source. The prior source is KEPT, never replaced in place."""
250
- import core.script_sandbox as sandbox # noqa: PLC0415
251
-
252
- view_id = str(view_id)
253
- rec = _all(session.runtime).get(view_id)
254
- if not isinstance(rec, dict):
255
- raise err(404, "no_view", "there is no script view with that id")
256
- _mine_or_admin(session, rec)
257
- body = body if isinstance(body, dict) else {}
258
- source = _clean_source(body.get("source"))
259
- refusal = sandbox.check_source(source)
260
- if refusal is not None:
261
- raise err(400, refusal.code, refusal.message)
262
-
263
- def _mutate(prior):
264
- prior = dict(prior or rec)
265
- history = list(prior.get("history") or [])
266
- history.append({"version": int(prior.get("version") or 1),
267
- "source": prior.get("source") or "",
268
- "author": prior.get("author") or "", "created": prior.get("updated") or ""})
269
- dropped = max(0, len(history) - MAX_HISTORY)
270
- prior["history"] = history[dropped:] if dropped else history
271
- prior["trimmed"] = int(prior.get("trimmed") or 0) + dropped
272
- prior["source"] = source
273
- prior["version"] = int(prior.get("version") or 1) + 1
274
- prior["updated"] = _now()
275
- if body.get("name"):
276
- prior["name"] = " ".join(str(body["name"]).split())[:MAX_NAME]
277
- return prior
278
-
279
- _put(session, view_id, _mutate)
280
- fresh = _all(session.runtime).get(view_id)
281
- if not isinstance(fresh, dict):
282
- raise err(503, "store_unavailable", "the new version was NOT saved")
283
- return {"view": _row(fresh, source=True), "limits": _limits()}
284
-
285
-
286
- @router.post("/script-views/{view_id}/revert")
287
- def revert_script_view(view_id: str, body: dict = Body(default=None),
288
- session: Session = Depends(require_session)):
289
- """Put one view back to an earlier version. D-338 / W37-T46.
290
-
291
- ⭐⭐ A ROLL-BACK IS A NEW VERSION, NEVER A DELETE OF THE ONES AFTER IT, and that is the whole
292
- point of the ticket rather than an implementation detail. The history is what lets a person
293
- trust an agent with their code: if reverting destroyed the versions it stepped over, one
294
- mistaken revert would cost exactly what the history existed to protect, and there would be no
295
- way back from the way back. So this appends, and `restoredFrom` records where the text came
296
- from — the same posture the agent-harness roll-back already takes, so a reader who has seen one
297
- is not surprised by the other.
298
-
299
- ⛔ IT LIVES ON THE SERVER BECAUSE THE HISTORY DOES. The list door deliberately serves history
300
- entries WITHOUT their source (`_row`: the rail lists names), so a client cannot assemble an old
301
- version's text to re-PUT it. Handing the source out just so the client could send it straight
302
- back would widen a payload for a round trip that does not need to exist, and would make the
303
- revert non-atomic: two calls, and a failure between them leaves the person looking at code that
304
- is not what is stored.
305
- ⚠ `_clean_source` is NOT re-run. The text being restored was already validated when it was
306
- first saved, and a source that a later, stricter rule would now reject is exactly the source a
307
- person is most likely to want back. `check_source` still runs, because the SANDBOX's refusal is
308
- about what the code would DO and that must never be bypassed by a route.
309
- """
310
- import core.script_sandbox as sandbox # noqa: PLC0415
311
-
312
- view_id = str(view_id)
313
- rec = _all(session.runtime).get(view_id)
314
- if not isinstance(rec, dict):
315
- raise err(404, "no_view", "there is no script view with that id")
316
- _mine_or_admin(session, rec)
317
- body = body if isinstance(body, dict) else {}
318
- try:
319
- want = int(body.get("version"))
320
- except (TypeError, ValueError):
321
- raise err(400, "no_version", "say which version to go back to") from None
322
-
323
- history = [h for h in (rec.get("history") or []) if isinstance(h, dict)]
324
- match = next((h for h in history if int(h.get("version") or 0) == want), None)
325
- if match is None:
326
- # ⛔ TWO REASONS A VERSION IS MISSING AND THEY ARE NOT THE SAME FACT. One was never
327
- # written; the other was TRIMMED off the 40-deep history and the record even counts how
328
- # many. Saying "that version is gone" for the first would be a lie a person could act on.
329
- trimmed = int(rec.get("trimmed") or 0)
330
- if trimmed and want <= trimmed:
331
- raise err(410, "version_trimmed",
332
- f"version {want} is older than this view's history keeps "
333
- f"({trimmed} earlier versions have been dropped)")
334
- raise err(404, "no_version", f"this view has no version {want}")
335
-
336
- source = str(match.get("source") or "")
337
- refusal = sandbox.check_source(source)
338
- if refusal is not None:
339
- # An older version that today's sandbox refuses. The person is told which version and why,
340
- # rather than being handed a 400 about code they did not just type.
341
- raise err(400, refusal.code, f"version {want} cannot be restored: {refusal.message}")
342
-
343
- def _mutate(prior):
344
- prior = dict(prior or rec)
345
- history_now = list(prior.get("history") or [])
346
- history_now.append({"version": int(prior.get("version") or 1),
347
- "source": prior.get("source") or "",
348
- "author": prior.get("author") or "",
349
- "created": prior.get("updated") or ""})
350
- dropped = max(0, len(history_now) - MAX_HISTORY)
351
- prior["history"] = history_now[dropped:] if dropped else history_now
352
- prior["trimmed"] = int(prior.get("trimmed") or 0) + dropped
353
- prior["source"] = source
354
- prior["version"] = int(prior.get("version") or 1) + 1
355
- prior["updated"] = _now()
356
- # ⚠ ON THE RECORD, so the history reads as WHAT HAPPENED rather than as a version that
357
- # mysteriously matches an older one. Without it a reader sees v5 and v2 with identical
358
- # code and no way to tell a revert from a coincidence.
359
- prior["restoredFrom"] = want
360
- return prior
361
-
362
- _put(session, view_id, _mutate)
363
- fresh = _all(session.runtime).get(view_id)
364
- if not isinstance(fresh, dict):
365
- raise err(503, "store_unavailable", "the roll-back was NOT saved")
366
- return {"view": _row(fresh, source=True), "restoredFrom": want, "limits": _limits()}
367
-
368
-
369
- @router.delete("/script-views/{view_id}")
370
- def delete_script_view(view_id: str, session: Session = Depends(require_session)):
371
- view_id = str(view_id)
372
- rec = _all(session.runtime).get(view_id)
373
- if not isinstance(rec, dict):
374
- raise err(404, "no_view", "there is no script view with that id")
375
- _mine_or_admin(session, rec)
376
- _put(session, view_id, lambda _prior: None)
377
- return {"deleted": view_id}
378
-
379
-
380
- @router.post("/script-views/{view_id}/run")
381
- def run_script_view(view_id: str, body: dict = Body(default=None),
382
- session: Session = Depends(require_session)):
383
- """CONTRACT C3's run door: `{ok, spec | error, stdout, ms}`.
384
-
385
- ⛔ `spec` IS A DESCRIPTION THE CLIENT DRAWS. It is never HTML and never text the browser
386
- executes — the sandbox refuses a spec carrying an `html`, `script`, `src`, `href` or `on*` key
387
- before this function ever sees it, so a renderer cannot be talked into running something by a
388
- script that was itself perfectly well behaved.
389
-
390
- ⛔ AND IT IS PLAIN `def`, NOT `async def` — see this module's header. A ten-second subprocess
391
- wait on the event loop is a ten-second outage for the whole container.
392
- """
393
- import core.script_sandbox as sandbox # noqa: PLC0415
394
-
395
- rec = _all(session.runtime).get(str(view_id))
396
- if not isinstance(rec, dict):
397
- raise err(404, "no_view", "there is no script view with that id")
398
- database = str(rec.get("database") or "")
399
- # A DRAFT run: the editor sends unsaved code so the author can try it before committing to it.
400
- # It is checked exactly as a stored one is, because "unsaved" is not a permission.
401
- draft = (body or {}).get("source") if isinstance(body, dict) else None
402
- source = _clean_source(draft) if draft else str(rec.get("source") or "")
403
- # ⚠ NO `_database_ok` CALL HERE. `run_view` asks C1 the identical question a line later, and
404
- # asking twice builds a registry topic's pool twice. The three refusals are translated below
405
- # instead, which is the same wall reached through the same door.
406
-
407
- if not _RUN_SLOTS.acquire(blocking=False):
408
- raise err(429, "busy",
409
- f"{MAX_CONCURRENT_RUNS} script views are already running on this server. "
410
- f"Try again in a moment")
411
- try:
412
- out = sandbox.run_view(session.user, database, source, st=session.runtime)
413
- finally:
414
- _RUN_SLOTS.release()
415
-
416
- # ⛔ C1'S THREE REFUSALS ARE HTTP STATUSES, NOT `ok:false`. "You may not read this database"
417
- # answered 200 would be a permission decision the client has to go looking for, and every
418
- # other door in this app answers 403 for it. Everything BELOW this line is a well-formed
419
- # request whose ANSWER is that the script did not produce a view — that is a 200 with
420
- # `ok:false`, the shape `routes_web_agent.test` already uses for the same reason.
421
- if out.get("code") == "unknown_table":
422
- raise err(404, "no_database", out.get("message") or f"there is no database '{database}'")
423
- if out.get("code") == "denied":
424
- raise err(403, "forbidden", out.get("message") or "your account may not read that database")
425
- if out.get("code") == "unresolvable":
426
- refusal = err(409, "unresolvable", out.get("message") or "these rows cannot be served")
427
- refusal.detail["error"]["limit"] = out.get("limit") or {}
428
- raise refusal
429
-
430
- answer = {"ok": bool(out.get("ok")), "spec": out.get("spec"),
431
- "stdout": out.get("stdout") or "", "truncated": bool(out.get("truncated")),
432
- "ms": int(out.get("ms") or 0), "code": out.get("code") or "",
433
- # ⭐ `caps` RIDES ON THE ANSWER (standing rule 1). On a POSIX host all three limits
434
- # were applied; on a Windows host the memory and CPU ones were not, and a screen
435
- # that claims an enforcement which did not happen is the failure the rule is about.
436
- "caps": out.get("caps") or {}}
437
- if not answer["ok"]:
438
- answer["error"] = out.get("message") or "the script view did not produce a view"
439
- return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/core/script_sandbox.py DELETED
@@ -1,519 +0,0 @@
1
- """core/script_sandbox.py — WAVE 36 (R5 / R10, contract C1): running a tenant's OWN Python.
2
-
3
- Owner item 6: *"Add code script as an interface (database View) so a user can build whatever they
4
- want through the Agent chat interface."* Item 8: *"We need to really guardrail the reach of this
5
- script. So let's really grill this down."* R10 ruled it SERVER-SIDE PYTHON after the trade was
6
- stated, so this file is the guardrail, and one engine serves both items.
7
-
8
- ════════════════════════════════════════════════════════════════════════════════════════════════
9
- ⛔⛔ THE ONE PARAGRAPH TO READ BEFORE CHANGING ANYTHING HERE.
10
-
11
- In-process CPython cannot deliver two of this ticket's clauses. An AST allow-list plus a curated
12
- namespace stops import, file, network and environment access — but it **cannot cap memory and
13
- cannot interrupt a runaway loop**, because a `while True:` in the same interpreter is not a slow
14
- request, it is the tenant's ONE FastAPI process gone. So the script runs in a **SUBPROCESS**:
15
- `resource.setrlimit` for address space and CPU, a hard wall-clock kill from the parent, and the
16
- allow-list inside. Neither half is sufficient; both are load-bearing.
17
-
18
- ⭐ AND THE SUBPROCESS RECEIVES **ROWS, NEVER A STORE**. The parent calls C1's `scoped_table` under
19
- the CALLING user's record and serialises the result; the child imports nothing from this repo and
20
- holds no credential, no runtime and no store handle. Wiring W1 ("the sandbox has no second store
21
- path") is then true by CONSTRUCTION rather than by discipline, and it is checkable: the child
22
- reports its own `sys.modules`, and no `core.*` name may appear in it.
23
-
24
- ⛔ NEVER A BLACKLIST. Every rule below is an ALLOW-LIST — a set of node types, a set of attribute
25
- names, a dict of builtins. A blacklist of dangerous spellings is bypassable by construction, and
26
- the bypass is usually one string method away (`"{0.__class__}".format(x)` performs its attribute
27
- lookup inside `format`, so there is no `ast.Attribute` node to refuse).
28
- ════════════════════════════════════════════════════════════════════════════════════════════════
29
-
30
- The two layers, and they refuse DIFFERENT things on purpose:
31
-
32
- 1. `check_source()` — a pure function over source text. Refuses a construct the language offers
33
- and this sandbox does not: `import`, `class`, `with`, `async`, `yield`, `global`, and every
34
- attribute name outside `ALLOWED_ATTRS`.
35
- 2. `SANDBOX_BUILTINS` — the names that resolve at all. `__import__`, `open`, `eval`, `exec`,
36
- `compile`, `getattr`, `globals`, `vars` and `type` are simply absent, so a source that gets
37
- past layer 1 still finds nothing to call.
38
-
39
- ⚠ THAT DUPLICATION IS DELIBERATE AND IT CHANGES HOW THE GATE MUST BE WRITTEN. `import os` is
40
- refused twice, so a negative control that drops ONE layer sees the other refuse and reports
41
- green — the shape that already cost this wave one missed control in `routes_agent_harness`. So
42
- each layer is tested AT ITS OWN BOUNDARY: `check_source()` is called directly on source strings,
43
- and `run()` is driven end to end. An NC drops one entry from one frozenset and the matching
44
- boundary goes red.
45
- """
46
- import ast
47
- import json
48
- import os
49
- import subprocess
50
- import sys
51
- import tempfile
52
- import time
53
- from pathlib import Path
54
-
55
- #: Wall clock, enforced by the PARENT with a kill. The one cap that works on every platform.
56
- DEFAULT_TIMEOUT_S = 10.0
57
-
58
- #: Address space for the child (`RLIMIT_AS`). POSIX only — see `run()`'s `caps` report.
59
- DEFAULT_MEMORY_BYTES = 512 * 1024 * 1024
60
-
61
- #: CPU seconds for the child (`RLIMIT_CPU`). POSIX only. Deliberately above the wall clock: the
62
- #: wall-clock kill is the primary control and this is the backstop for a child that stops being
63
- #: reachable. A CPU limit BELOW the timeout would make every slow script look like a CPU refusal.
64
- DEFAULT_CPU_SECONDS = 15
65
-
66
- #: What the script may print, in bytes. `print` is a curated builtin writing to a capped buffer,
67
- #: and the child's real stdout goes to DEVNULL — so a script cannot fill a pipe, and anything
68
- #: that escaped far enough to write to fd 1 has nowhere for it to land.
69
- MAX_STDOUT_BYTES = 64 * 1024
70
-
71
- #: The serialised ROW payload handed to the child. ⛔ A REFUSAL, NEVER A TRUNCATION (standing rule
72
- #: 1): a short answer from a data tool is a wrong answer that looks right. Over this, `run()`
73
- #: returns a named limit carrying its cause and a recommendation.
74
- MAX_PAYLOAD_BYTES = 32 * 1024 * 1024
75
-
76
- #: The emitted spec. A render spec is a description of a picture; one larger than this is data
77
- #: pretending to be a description.
78
- MAX_SPEC_BYTES = 2 * 1024 * 1024
79
-
80
- MAX_SOURCE_BYTES = 128 * 1024
81
-
82
-
83
- # ═══════���══════════════════════════════════════════════ LAYER 1 — the AST allow-list ═══════════
84
- #: Every `ast` node class a script may contain. ⛔ THE ABSENCES ARE THE POLICY: `Import` /
85
- #: `ImportFrom` (no module reaches the script), `ClassDef` (a class body is a namespace with its
86
- #: own scoping rules and buys a data script nothing), `With` (a context manager is `__enter__`
87
- #: by another spelling), `Global` / `Nonlocal` (rebinding the sandbox's own names), and every
88
- #: `Async*` / `Await` / `Yield` form (this engine is synchronous; a coroutine that is never
89
- #: awaited is a silent no-op that looks like a working script).
90
- ALLOWED_NODES = frozenset("""
91
- Module Expr Assign AugAssign AnnAssign NamedExpr Return Pass Break Continue Delete Assert Raise
92
- If For While Try TryStar ExceptHandler FunctionDef Lambda arguments arg keyword
93
- BoolOp BinOp UnaryOp IfExp Dict Set List Tuple Starred Subscript Slice Compare Call Attribute Name
94
- Constant JoinedStr FormattedValue ListComp SetComp DictComp GeneratorExp comprehension
95
- Load Store Del
96
- And Or Not Invert UAdd USub
97
- Add Sub Mult Div FloorDiv Mod Pow LShift RShift BitOr BitXor BitAnd MatMult
98
- Eq NotEq Lt LtE Gt GtE Is IsNot In NotIn
99
- """.split())
100
-
101
- #: Every attribute name a script may READ or CALL. ⛔⛔ THIS IS THE LOAD-BEARING SET, and it is
102
- #: an allow-list of NAMES rather than a refusal of dunders, because the interesting escapes are
103
- #: ordinary-looking: `f.__globals__` on any function reaches the runner's own module namespace,
104
- #: `e.__traceback__.tb_frame.f_globals` reaches it from an exception handler, and `().__class__`
105
- #: reaches `object.__subclasses__`. None of those names is here, and neither is any name this
106
- #: sandbox has not been asked for.
107
- #: ⚠ `format` IS ABSENT DELIBERATELY. `"{0.__class__}".format(x)` performs the attribute lookup
108
- #: INSIDE `str.format`, where no `ast.Attribute` node exists for layer 1 to see. f-strings are
109
- #: fine — `f"{x.__class__}"` compiles to a real `Attribute` node and is refused.
110
- ALLOWED_ATTRS = frozenset("""
111
- append extend insert pop remove clear sort reverse copy count index
112
- keys values items get setdefault update
113
- add discard union intersection difference issubset issuperset
114
- join split rsplit splitlines strip lstrip rstrip lower upper title capitalize casefold
115
- replace startswith endswith find rfind zfill ljust rjust center partition removeprefix removesuffix
116
- isdigit isalpha isalnum isspace isupper islower isnumeric
117
- real imag numerator denominator
118
- """.split())
119
-
120
-
121
- class Refused(Exception):
122
- """A named refusal: `code` for a caller to branch on, `message` for a person to read."""
123
-
124
- def __init__(self, code, message):
125
- self.code, self.message = code, message
126
- super().__init__(f"{code}: {message}")
127
-
128
-
129
- def _attr_ok(name):
130
- """An attribute name passes only if it is on the list AND is not private.
131
-
132
- ⚠ THE SECOND TEST IS NOT A BLACKLIST — it narrows an allow-list that already excludes every
133
- private name. It is here so that adding a name to `ALLOWED_ATTRS` cannot open a dunder by
134
- accident, which is the one edit a future reader is most likely to make in a hurry.
135
- """
136
- return name in ALLOWED_ATTRS and not name.startswith("_")
137
-
138
-
139
- def check_source(source):
140
- """LAYER 1. Return a `Refused` for source this sandbox will not run, or `None`.
141
-
142
- ⭐ PURE, AND THAT IS WHAT MAKES IT TESTABLE AT ITS OWN BOUNDARY. It reads no file, spawns no
143
- process and touches no store, so a gate can hand it a hundred hostile strings for free and an
144
- NC can drop one entry from one frozenset and watch exactly this function change its answer.
145
- """
146
- text = str(source or "")
147
- if len(text.encode("utf-8", "replace")) > MAX_SOURCE_BYTES:
148
- return Refused("source_too_long",
149
- f"a script view is at most {MAX_SOURCE_BYTES // 1024} KB of source")
150
- try:
151
- tree = ast.parse(text)
152
- except SyntaxError as exc:
153
- return Refused("syntax", f"line {exc.lineno or 0}: {exc.msg}")
154
-
155
- for node in ast.walk(tree):
156
- kind = type(node).__name__
157
- if kind not in ALLOWED_NODES:
158
- return Refused("refused_construct",
159
- f"line {getattr(node, 'lineno', 0)}: this sandbox does not run "
160
- f"{_english(kind)}")
161
- if isinstance(node, ast.Attribute) and not _attr_ok(node.attr):
162
- return Refused("refused_attribute",
163
- f"line {getattr(node, 'lineno', 0)}: the attribute "
164
- f"'{node.attr}' is not available inside a script view")
165
- # ⛔ A NAME may not be private either. `_` prefixed names are the runner's own, and a
166
- # script that could bind one could shadow the machinery it runs on top of.
167
- if isinstance(node, ast.Name) and node.id.startswith("_"):
168
- return Refused("reserved_name",
169
- f"line {getattr(node, 'lineno', 0)}: names starting with an "
170
- f"underscore are reserved by the sandbox")
171
- if isinstance(node, (ast.FunctionDef, ast.arg, ast.ExceptHandler)) and str(
172
- getattr(node, "name", None) or getattr(node, "arg", "") or "").startswith("_"):
173
- return Refused("reserved_name",
174
- f"line {getattr(node, 'lineno', 0)}: names starting with an "
175
- f"underscore are reserved by the sandbox")
176
- if isinstance(node, ast.keyword) and str(node.arg or "").startswith("_"):
177
- return Refused("reserved_name",
178
- f"line {getattr(node, 'lineno', 0)}: keyword arguments starting with "
179
- f"an underscore are reserved by the sandbox")
180
- return None
181
-
182
-
183
- _ENGLISH = {
184
- "Import": "an import", "ImportFrom": "an import", "ClassDef": "a class definition",
185
- "With": "a with block", "AsyncWith": "a with block", "AsyncFor": "an async loop",
186
- "AsyncFunctionDef": "an async function", "Await": "await", "Yield": "yield",
187
- "YieldFrom": "yield from", "Global": "a global statement", "Nonlocal": "a nonlocal statement",
188
- "Match": "a match statement",
189
- }
190
-
191
-
192
- def _english(kind):
193
- return _ENGLISH.get(kind, f"a {kind} expression")
194
-
195
-
196
- # ══════════════════════════════════════════ LAYER 2 — the namespace, and the child program ═════
197
- #: The builtins a script may reach, BY NAME. Everything else is a `NameError` in the child.
198
- #: ⛔ THE ABSENCES, again, are the policy: `__import__` `open` `eval` `exec` `compile` `input`
199
- #: `getattr` `setattr` `delattr` `globals` `locals` `vars` `dir` `type` `super` `object` `help`
200
- #: `exit` `breakpoint` `memoryview` `id`. Several are harmless on their own; each one is a step
201
- #: on a published escape, and none has ever been asked for by a script that shapes rows.
202
- #: ⚠ THE EXCEPTION CLASSES ARE HERE BECAUSE `try:` IS, and a `try` block whose `except` clause
203
- #: cannot name what it catches is a construct that reads as supported and is not. They are safe
204
- #: for the same reason everything else is: `Exception.__subclasses__` needs an attribute this
205
- #: sandbox does not allow, so a class object in the namespace is a leaf, not a doorway.
206
- SANDBOX_BUILTIN_NAMES = (
207
- "abs all any bool bytes callable chr dict divmod enumerate filter float frozenset hash hex "
208
- "int isinstance issubclass iter len list map max min next oct ord pow range repr reversed "
209
- "round set slice sorted str sum tuple zip True False None "
210
- "Exception ValueError TypeError KeyError IndexError ZeroDivisionError ArithmeticError "
211
- "AttributeError StopIteration OverflowError"
212
- ).split()
213
-
214
- #: The literal program the child runs. It is TEXT rather than a module because the child must
215
- #: import nothing from this repo: a module would be found on `sys.path` and would drag `core`
216
- #: with it, which is exactly the second store path W1 forbids.
217
- #: ⚠ Every name in here is underscore-prefixed and layer 1 refuses a script from binding one, so
218
- #: the runner's own machinery cannot be shadowed by the source it executes.
219
- _RUNNER = r'''
220
- import json as _json, os as _os, sys as _sys
221
-
222
- _pay = _json.loads(open(_sys.argv[1], "r", encoding="utf-8").read())
223
- _out = {"ok": False, "code": "not_run", "message": "the script did not run",
224
- "stdout": "", "spec": None, "caps": {"wallClock": True, "memory": False, "cpu": False}}
225
-
226
- # ── the caps this platform can actually apply, reported either way (standing rule 1) ──────────
227
- try:
228
- import resource as _res
229
- _mem = int(_pay["memoryBytes"])
230
- _res.setrlimit(_res.RLIMIT_AS, (_mem, _mem))
231
- _out["caps"]["memory"] = True
232
- _cpu = int(_pay["cpuSeconds"])
233
- _res.setrlimit(_res.RLIMIT_CPU, (_cpu, _cpu))
234
- _out["caps"]["cpu"] = True
235
- except Exception:
236
- # `resource` is POSIX only. The wall-clock kill in the parent still applies, and `caps` says
237
- # which of the three held, never a silent partial.
238
- pass
239
-
240
- _printed = []
241
- _spent = [0]
242
- _LIMIT = int(_pay["maxStdout"])
243
-
244
-
245
- def _print(*_a, **_k):
246
- _text = (_k.get("sep") or " ").join(str(_x) for _x in _a) + (_k.get("end") or "\n")
247
- _room = _LIMIT - _spent[0]
248
- if _room > 0:
249
- _printed.append(_text[:_room])
250
- _spent[0] += len(_text)
251
-
252
-
253
- class _Refusal(Exception):
254
- """The SANDBOX refusing, as distinct from the SCRIPT failing.
255
-
256
- Without its own class these arrive as `ValueError`, indistinguishable from a `ValueError` the
257
- script raised itself, and the answer then says "refused" about an ordinary bug in the tenant's
258
- own code. Two different facts, two different codes.
259
- """
260
-
261
-
262
- _emitted = []
263
-
264
-
265
- def _emit(_spec):
266
- if not isinstance(_spec, dict):
267
- raise _Refusal("emit() takes a view spec, which is a dictionary")
268
- if _emitted:
269
- raise _Refusal("emit() was already called; a script view emits exactly one view")
270
- _emitted.append(_spec)
271
-
272
-
273
- _rows = _pay["rows"]
274
- _fields = _pay["fields"]
275
- _bound = _pay["table"]
276
-
277
-
278
- def _scoped_table(_table=None):
279
- if _table is not None and str(_table) != _bound:
280
- raise _Refusal(
281
- "this script view is bound to the database '" + _bound + "' and asked for '"
282
- + str(_table) + "'. A script view reads its own database only")
283
- return [dict(_r) for _r in _rows]
284
-
285
-
286
- def _scoped_fields():
287
- return [dict(_f) for _f in _fields]
288
-
289
-
290
- _ns = {"__builtins__": {_n: __builtins__[_n] if isinstance(__builtins__, dict)
291
- else getattr(__builtins__, _n)
292
- for _n in _pay["builtins"]}}
293
- _ns["__builtins__"]["print"] = _print
294
- _ns["print"] = _print
295
- _ns["emit"] = _emit
296
- _ns["scoped_table"] = _scoped_table
297
- _ns["scoped_fields"] = _scoped_fields
298
- _ns["table"] = _bound
299
-
300
- try:
301
- exec(compile(_pay["source"], "<script view>", "exec"), _ns)
302
- if not _emitted:
303
- _out.update(ok=False, code="no_view",
304
- message="the script finished without calling emit(spec)")
305
- else:
306
- _out.update(ok=True, code="", message="", spec=_emitted[0])
307
- except _Refusal as _e:
308
- _out.update(ok=False, code="refused", message=str(_e)[:400])
309
- except MemoryError:
310
- _out.update(ok=False, code="memory",
311
- message="the script used more memory than a script view is allowed")
312
- except NameError as _e:
313
- _out.update(ok=False, code="refused_name",
314
- message=str(_e)[:200] + ". A script view may use only the names the sandbox "
315
- "provides")
316
- except BaseException as _e:
317
- _out.update(ok=False, code="error",
318
- message=type(_e).__name__ + ": " + str(_e)[:400])
319
-
320
- _out["stdout"] = "".join(_printed)
321
- _out["truncated"] = _spent[0] > _LIMIT
322
- # ⭐ THE PROBE: what this child actually had. The PARENT strips it unless it was asked for, so a
323
- # production run never carries it and a gate can still prove that no `core.*` module and no
324
- # secret-shaped environment key was ever inside this process.
325
- # ⚠ SNAPSHOTTED AFTER `exec`, and `os` is imported at the TOP so this list does not depend on
326
- # dict-literal evaluation order. The first draft called `__import__("os")` inside this very
327
- # expression, so whether `os` appeared depended on which value Python built first: a probe whose
328
- # contents move with an unrelated edit is a probe a gate cannot assert against.
329
- _out["probe"] = {"modules": sorted(_sys.modules), "env": sorted(_os.environ)}
330
- open(_sys.argv[2], "w", encoding="utf-8").write(_json.dumps(_out, default=str))
331
- '''
332
-
333
-
334
- def _child_env():
335
- """The child's WHOLE environment. An allow-list of two keys, and neither is a credential.
336
-
337
- ⛔ NOT `os.environ.copy()` MINUS SOMETHING. A subtractive environment ships every key nobody
338
- thought to name: `HF_TOKEN`, `ODOO_PASSWORD`, `ANTHROPIC_API_KEY` and whatever the next
339
- connector adds. The three names below are here because Python will not start on Windows
340
- without them; on Linux this returns `{}` and the child runs with no environment at all.
341
- """
342
- env = {}
343
- for name in ("SystemRoot", "SYSTEMROOT", "WINDIR"):
344
- if os.environ.get(name):
345
- env[name] = os.environ[name]
346
- return env
347
-
348
-
349
- def run(source, rows, fields, table_key, *, timeout_s=DEFAULT_TIMEOUT_S,
350
- memory_bytes=DEFAULT_MEMORY_BYTES, cpu_seconds=DEFAULT_CPU_SECONDS, probe=False):
351
- """Run ONE script over rows that are ALREADY scoped. Returns C3's envelope plus `caps`.
352
-
353
- {ok, code, message, spec, stdout, truncated, ms, caps: {wallClock, memory, cpu}}
354
-
355
- ⛔ THIS FUNCTION NEVER TOUCHES A STORE, AND THAT IS THE POINT: it takes rows. `run_view()`
356
- below is the door that fetches them through C1; keeping the two apart is what lets a gate
357
- drive the sandbox with no tenant, no runtime and no credential anywhere in the process.
358
-
359
- ⚠ `caps` IS PART OF THE ANSWER, NOT DEBUG OUTPUT. On Windows `resource` does not exist, so
360
- the memory and CPU limits are NOT applied and this says so. A caller that reports `ok:true`
361
- without reading `caps` is claiming an enforcement that did not happen (standing rule 1).
362
- """
363
- started = time.monotonic()
364
- refusal = check_source(source)
365
- if refusal is not None:
366
- return _refusal(refusal.code, refusal.message, started)
367
-
368
- payload = {"source": str(source or ""), "rows": rows, "fields": fields,
369
- "table": str(table_key or ""), "builtins": SANDBOX_BUILTIN_NAMES,
370
- "maxStdout": MAX_STDOUT_BYTES, "memoryBytes": int(memory_bytes),
371
- "cpuSeconds": int(cpu_seconds)}
372
- try:
373
- blob = json.dumps(payload, default=str)
374
- except (TypeError, ValueError) as exc:
375
- return _refusal("bad_rows", f"these rows cannot be handed to a script ({exc})", started)
376
- if len(blob.encode("utf-8", "replace")) > MAX_PAYLOAD_BYTES:
377
- # ⛔ REPORTED, NOT TRUNCATED (standing rule 1's second sentence): cause and recommendation,
378
- # in the words the owner asked for, rather than a quietly short answer.
379
- return _refusal(
380
- "payload_too_large",
381
- f"this database's rows are larger than the {MAX_PAYLOAD_BYTES // (1024 * 1024)} MB a "
382
- f"script view can be handed at once. Narrow the view with a filter, or raise the "
383
- f"sandbox payload limit for this deployment", started)
384
-
385
- with tempfile.TemporaryDirectory(prefix="aios-script-") as work:
386
- pay_path = Path(work) / "payload.json"
387
- res_path = Path(work) / "result.json"
388
- pay_path.write_text(blob, encoding="utf-8")
389
- # `-I` isolates the interpreter (no PYTHON* env, no user site), `-S` skips site-packages,
390
- # and the program arrives on STDIN so there is no file for anything to import it as.
391
- # ⛔ `-X utf8` AND AN EXPLICIT `encoding` ARE NOT TIDINESS. Without them this pipe is
392
- # encoded with the parent's locale codec, which on this Windows box is cp1252: the runner
393
- # text below cannot be represented in it and `subprocess.run` died with
394
- # `UnicodeEncodeError` before the child ever started. A sandbox whose behaviour depends on
395
- # the operator's locale is a sandbox with two behaviours. `-I` implies `-E`, so
396
- # `PYTHONUTF8` in the environment could not have carried this, it has to be a flag.
397
- argv = [sys.executable, "-I", "-S", "-X", "utf8", "-", str(pay_path), str(res_path)]
398
- try:
399
- done = subprocess.run(
400
- argv, input=_RUNNER, text=True, encoding="utf-8", errors="replace",
401
- cwd=work, env=_child_env(),
402
- stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=timeout_s)
403
- except subprocess.TimeoutExpired:
404
- return _refusal("timeout",
405
- f"the script ran longer than {timeout_s:g} seconds and was stopped",
406
- started)
407
- except OSError as exc:
408
- return _refusal("no_sandbox",
409
- f"a script view could not be started on this deployment ({exc})",
410
- started)
411
-
412
- if not res_path.is_file():
413
- # The child died without writing an answer: an rlimit signal, an OOM kill, or a crash.
414
- # ⚠ NAMED BY ITS RETURN CODE rather than reported as a generic failure — a memory kill
415
- # and a bug in this file must not read identically to an operator.
416
- return _refusal(*_died(done), started)
417
- try:
418
- out = json.loads(res_path.read_text(encoding="utf-8"))
419
- except (OSError, ValueError) as exc:
420
- return _refusal("unreadable", f"the script's answer could not be read ({exc})",
421
- started)
422
-
423
- out["ms"] = int((time.monotonic() - started) * 1000)
424
- if out.get("ok"):
425
- spec_error = _check_spec(out.get("spec"))
426
- if spec_error:
427
- out.update(ok=False, code="bad_spec", message=spec_error, spec=None)
428
- if not probe:
429
- out.pop("probe", None)
430
- return out
431
-
432
-
433
- def _died(done):
434
- """`(code, message)` for a child that produced no answer."""
435
- rc = done.returncode
436
- tail = " ".join((done.stderr or "").split())[-300:]
437
- if rc in (-9, 137):
438
- return "memory", "the script was stopped for using too much memory"
439
- if rc in (-24, 152):
440
- return "timeout", "the script used more processor time than a script view is allowed"
441
- return "crashed", f"the script view engine stopped without an answer{': ' + tail if tail else ''}"
442
-
443
-
444
- def _refusal(code, message, started):
445
- return {"ok": False, "code": code, "message": message, "spec": None, "stdout": "",
446
- "truncated": False, "ms": int((time.monotonic() - started) * 1000),
447
- "caps": {"wallClock": True, "memory": False, "cpu": False}}
448
-
449
-
450
- def _check_spec(spec):
451
- """C3: a spec is a DESCRIPTION the client draws. Never HTML, never a script, never a URL.
452
-
453
- ⛔ THE CHECK IS ON THE KEYS, NOT ON THE STRING CONTENTS. Scanning values for `<script>` is a
454
- blacklist and would pass `<SCR` + `IPT>`; refusing a spec that carries an `html`, `script`,
455
- `src` or `onclick` key refuses the SHAPE that would let a renderer be talked into executing
456
- something. The vocabulary of legal `kind`s is the ROUTE's business (W36-T37) — this is the
457
- floor every caller gets whether or not the route above it remembers.
458
- """
459
- if not isinstance(spec, dict):
460
- return "the script emitted something that is not a view spec"
461
- try:
462
- blob = json.dumps(spec)
463
- except (TypeError, ValueError):
464
- return "the emitted view spec is not something the client can be sent"
465
- if len(blob.encode("utf-8", "replace")) > MAX_SPEC_BYTES:
466
- return (f"the emitted view spec is over {MAX_SPEC_BYTES // (1024 * 1024)} MB. A view spec "
467
- f"describes a picture; it is not where the rows go")
468
- banned = {"html", "innerhtml", "script", "src", "srcdoc", "href", "style", "onclick", "onload"}
469
- found = sorted(k for k in _keys_of(spec) if str(k).lower() in banned)
470
- if found:
471
- return (f"a view spec may not carry {', '.join(found)}. The client DRAWS a spec, so a "
472
- f"markup or URL key would be a script by another name")
473
- return None
474
-
475
-
476
- def _keys_of(value, depth=0):
477
- """Every key anywhere in a nested spec. Bounded, so a deep structure cannot spin this."""
478
- if depth > 12:
479
- return
480
- if isinstance(value, dict):
481
- for key, sub in value.items():
482
- yield key
483
- yield from _keys_of(sub, depth + 1)
484
- elif isinstance(value, (list, tuple)):
485
- for sub in value:
486
- yield from _keys_of(sub, depth + 1)
487
-
488
-
489
- # ══════════════════════════════════════════════ THE DOOR — C1 is the ONLY way to a row ═════════
490
- def run_view(user, table_key, source, st=None, **kw):
491
- """Fetch through C1 under `user`'s scope, then run the script over what came back (R5).
492
-
493
- ⭐⭐ THE FETCH HAPPENS IN THE PARENT AND ONLY ROWS CROSS INTO THE CHILD. That is wiring W1
494
- made structural: the child has no runtime to ask, no store handle to open and no credential
495
- to use, so "a script cannot read what its caller cannot read" is not a rule anybody has to
496
- keep — there is no second path for it to be broken through.
497
-
498
- ⛔ C1'S THREE EXCEPTIONS ARE ANSWERED, NEVER SWALLOWED. `UnknownTable`, `Denied` and
499
- `Unresolvable` mean three different things to a person; collapsing them into "no rows" is the
500
- silent-empty answer C1 was written to make impossible. `Unresolvable.as_limit()` is handed
501
- through in the words it was raised with — standing rule 1's second sentence, verbatim.
502
- """
503
- import core.perm_scope as perm_scope
504
-
505
- key = str(table_key or "")
506
- try:
507
- rows = perm_scope.scoped_table(user, key, st=st)
508
- fields = perm_scope.scoped_fields(user, key, st=st)
509
- except perm_scope.UnknownTable as exc:
510
- return _refusal("unknown_table", str(exc) or f"there is no database '{key}'",
511
- time.monotonic())
512
- except perm_scope.Denied as exc:
513
- return _refusal("denied", str(exc) or "this account may not read that database",
514
- time.monotonic())
515
- except perm_scope.Unresolvable as exc:
516
- out = _refusal("unresolvable", str(exc), time.monotonic())
517
- out["limit"] = exc.as_limit()
518
- return out
519
- return run(source, rows, fields, key, **kw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/customer-grid/ScriptViewPanel.tsx DELETED
@@ -1,343 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / ScriptViewPanel.tsx — owner item 6's renderer (W36-T04, contract C3).
3
- //
4
- // ⛔ ITS OWN MODULE, AND THAT IS A HARNESS FACT AS WELL AS A TIDINESS ONE. It began inside
5
- // `viewModes.tsx`, where the other display modes live — and that module `require`s `./cells`,
6
- // which imports glide-data-grid, whose CJS build cannot load under this repo's node harness. So
7
- // putting it there made the whole component untestable: the ONE thing this surface must prove is
8
- // that a hostile spec is rendered as text, and that claim can only be made by RENDERING. Here the
9
- // import graph is `react` + `./scriptViews` and nothing else, so `gridUx.test.ts` renders it for
10
- // real and asserts on the HTML a person would receive.
11
- // ⚠ The stylesheet is imported by `CustomerGrid.tsx` (the mount) for the same reason: tsc
12
- // preserves a side-effect CSS import into the emitted CommonJS and node dies on it.
13
- // ---------------------------------------------------------------------------
14
-
15
- import { memo, useEffect, useRef, useState } from "react";
16
- import { foldNavOnWorkSurface } from "./navFold";
17
- import { barScale, renderableSpec, specKindName } from "./scriptViews";
18
- import type { DrawableSpec, ScriptRun, ScriptView as ScriptViewRecord } from "./scriptViews";
19
-
20
- // ═══════════════════════════════════════════════════════════════════════════════════════════
21
- // ⭐⭐ W36-T04 (owner item 6 · rulings R3/R10 · contract C3) — THE CODE-SCRIPT VIEW
22
- //
23
- // Owner, verbatim: *"Add code script as an interface (database View) so a user can build whatever
24
- // they want through the Agent chat interface. be able to create any dashboard they want. User
25
- // should have the ability to see the code AND the dashboard output of course."* Both halves are
26
- // on screen at once, which is the whole of that sentence.
27
- //
28
- // ⛔⛔ NO BRANCH OF THIS RENDERER EXECUTES A STRING, AND THAT IS THE TICKET'S OWN `done-when`.
29
- // R10 runs the Python in a SERVER sandbox exactly so the browser never has to trust the result;
30
- // a renderer that then evaluated one would hand back everything the sandbox contains. So there is
31
- // no `dangerouslySetInnerHTML`, no `new Function`, no `eval`, no `href`/`src` taken from a spec,
32
- // and no `style` built from spec data anywhere below. Every value reaching the DOM is a SCALAR
33
- // that `renderableSpec` admitted, rendered as TEXT — the one exception being a bar's width, which
34
- // is a number clamped to a percentage here and never a string from the wire.
35
- //
36
- // ⛔ AN UNKNOWN `kind` IS A SENTENCE, NOT A BLANK. `spec` is whatever the script emitted (E's C3
37
- // note 1: there is no fixed vocabulary, deliberately), so a view whose author invented
38
- // `kind: "sankey"` is a legitimate thing this build cannot draw. Saying so, by name, is the
39
- // difference between "this build does not know that shape yet" and "your script is broken".
40
- //
41
- // ⚠ `ok: false` IS A 200. A script that timed out or divided by zero asked a well-formed question
42
- // whose ANSWER is that no view was produced; it is rendered beside the code, never thrown, and
43
- // never a toast that disappears while the reader is looking at the line that caused it.
44
- // ═══════════════════════════════════════════════════════════════════════════════════════════
45
-
46
- function SpecTable({ spec }: { spec: DrawableSpec }) {
47
- return (
48
- <table className="cg-script-table">
49
- <thead>
50
- <tr>{(spec.columns ?? []).map((c, i) => <th key={`${c}:${i}`} scope="col">{c}</th>)}</tr>
51
- </thead>
52
- <tbody>
53
- {(spec.rows ?? []).map((row, r) => (
54
- <tr key={r}>{row.map((cell, c) => <td key={c}>{cell}</td>)}</tr>
55
- ))}
56
- </tbody>
57
- </table>
58
- );
59
- }
60
-
61
- function SpecMetrics({ spec }: { spec: DrawableSpec }) {
62
- return (
63
- <div className="cg-script-metrics">
64
- {(spec.items ?? []).map((item, i) => (
65
- <div className="cg-script-metric" key={`${item.label}:${i}`}>
66
- <div className="cg-script-metric-label">{item.label}</div>
67
- <div className="cg-script-metric-value">{item.value}</div>
68
- {item.note ? <div className="cg-script-metric-note">{item.note}</div> : null}
69
- </div>
70
- ))}
71
- </div>
72
- );
73
- }
74
-
75
- function SpecBars({ spec }: { spec: DrawableSpec }) {
76
- const series = spec.series ?? [];
77
- const scale = barScale(series);
78
- return (
79
- <div className="cg-script-bars">
80
- {series.map((s, i) => (
81
- <div className="cg-script-bar" key={`${s.label}:${i}`}>
82
- <span>{s.label}</span>
83
- <span className="cg-script-bar-track">
84
- {/* ⚠ The ONE computed style on this surface, and it is arithmetic on a NUMBER the
85
- spec reader already validated as finite, clamped here. Never a string from the
86
- wire, which is what would make this an injection point. */}
87
- <span
88
- className="cg-script-bar-fill"
89
- style={{ width: `${Math.min(100, Math.round((Math.abs(s.value) / scale) * 100))}%` }}
90
- />
91
- </span>
92
- <span className="cg-script-bar-value">{s.display}</span>
93
- </div>
94
- ))}
95
- </div>
96
- );
97
- }
98
-
99
- /** The refusal, and the four limit fields PRINTED rather than re-worded (C3 note 2). */
100
- function ScriptRefusal({ run }: { run: ScriptRun }) {
101
- return (
102
- <div className="cg-script-refusal" role="status">
103
- <h4>This script did not produce a view</h4>
104
- <p>{run.error ?? "The run ended without emitting anything."}</p>
105
- <dl>
106
- <dt>Reason</dt>
107
- <dd>{run.code}</dd>
108
- {run.limit ? <><dt>Subject</dt><dd>{run.limit.subject}</dd></> : null}
109
- {run.limit ? <><dt>Effect</dt><dd>{run.limit.effect}</dd></> : null}
110
- {run.limit ? <><dt>Cause</dt><dd>{run.limit.cause}</dd></> : null}
111
- {run.limit ? <><dt>What to do</dt><dd>{run.limit.recommendation}</dd></> : null}
112
- </dl>
113
- </div>
114
- );
115
- }
116
-
117
- /**
118
- * ⭐⭐ W37-T41 — THE SHAPE OF A SCRIPT, SHOWN AS A PLACEHOLDER RATHER THAN PREFILLED.
119
- *
120
- * Picking Custom View mints a view with an EMPTY source (verified: `script_sandbox.check_source("")`
121
- * accepts it, which is why "mint on pick" was safe to hand lane C in mailbox E-7). Without this, the
122
- * person who has just created one meets a blank box and a Run button, which is not an invitation.
123
- *
124
- * ⛔ A PLACEHOLDER, NEVER A PREFILLED `value`. Prefilling would make the view DIRTY the moment it
125
- * opened, arm Save on code nobody wrote, and put a version nobody asked for into a 40-deep history.
126
- * A placeholder vanishes on the first keystroke and is never stored.
127
- * ⚠ It is the two lines the sandbox's own fixture uses, so the example a person is shown is the
128
- * example the gate proves runs [[test-double-built-from-the-producer]].
129
- */
130
- const SCRIPT_STARTER =
131
- "rows = scoped_table()\nemit({'kind': 'kpi', 'label': 'Records', 'value': len(rows)})";
132
-
133
-
134
- export function ScriptOutput({ run }: { run: ScriptRun | null }) {
135
- if (run === null)
136
- return <p className="cg-script-empty">Run the script to see what it draws.</p>;
137
- const drawable = run.ok ? renderableSpec(run.spec) : null;
138
- const claimed = specKindName(run.spec);
139
- return (
140
- <>
141
- {!run.ok ? <ScriptRefusal run={run} /> : null}
142
- {run.ok && drawable === null ? (
143
- <div className="cg-script-refusal" role="status">
144
- <h4>This build cannot draw that shape yet</h4>
145
- <p>
146
- {claimed
147
- ? `The script emitted a view of kind "${claimed}", which this version does not
148
- render. It knows table, metrics, bars and text.`
149
- : `The script emitted a view with no recognisable kind. This version renders
150
- table, metrics, bars and text.`}
151
- </p>
152
- </div>
153
- ) : null}
154
- {drawable !== null ? (
155
- <>
156
- {drawable.title ? <h3 className="cg-script-title">{drawable.title}</h3> : null}
157
- {drawable.kind === "table" ? <SpecTable spec={drawable} /> : null}
158
- {drawable.kind === "metrics" ? <SpecMetrics spec={drawable} /> : null}
159
- {drawable.kind === "bars" ? <SpecBars spec={drawable} /> : null}
160
- {drawable.kind === "text" ? <p className="cg-script-text">{drawable.body}</p> : null}
161
- </>
162
- ) : null}
163
- {run.stdout ? (
164
- <pre className="cg-script-stdout">
165
- {run.stdout}
166
- {run.truncated ? "\n[output truncated]" : ""}
167
- </pre>
168
- ) : null}
169
- </>
170
- );
171
- }
172
-
173
- /**
174
- * The whole View: the source on the left, what it drew on the right.
175
- *
176
- * ⚠ A DRAFT RUN NEEDS NO SAVE (C3 note 3), which is what makes this usable: type, run, save when
177
- * it works. The Save button is separate and deliberately not automatic, because a PUT is a NEW
178
- * VERSION and an autosaving editor would fill the 40-deep history with keystrokes.
179
- */
180
- export const ScriptView = memo(function ScriptView({
181
- view,
182
- running,
183
- run,
184
- saving,
185
- readOnly = false,
186
- loading = false,
187
- reverting = false,
188
- onRun,
189
- onSave,
190
- onRevert,
191
- }: {
192
- view: ScriptViewRecord | null;
193
- running: boolean;
194
- run: ScriptRun | null;
195
- saving?: boolean;
196
- readOnly?: boolean;
197
- /** ⚠ The host knows whether a fetch is outstanding; the panel cannot tell that from a null view.
198
- * Defaulted so no existing caller breaks, which is safe HERE because the default is the older,
199
- * more pessimistic sentence rather than a silently disabled feature. */
200
- loading?: boolean;
201
- reverting?: boolean;
202
- onRun: (draft: string) => void;
203
- onSave?: (source: string) => void;
204
- /**
205
- * ⭐ W37-T46 / D-338. Optional for the SAME reason `onSave` is: a read-only reader gets the
206
- * editor without the controls, and a caller that cannot revert simply does not pass this. The
207
- * control is not rendered at all when it is absent, rather than rendered and refused
208
- * [[permitted-is-not-answerable]].
209
- */
210
- onRevert?: (version: number) => void;
211
- }) {
212
- const [draft, setDraft] = useState(view?.source ?? "");
213
- const loadedId = useRef<string | null>(null);
214
- useEffect(() => {
215
- // Re-seed only when a DIFFERENT view is opened. Re-seeding on every `view` identity would
216
- // discard what somebody is typing the moment the list refreshes underneath them.
217
- if (!view || loadedId.current === view.id) return;
218
- loadedId.current = view.id;
219
- setDraft(view.source);
220
- }, [view]);
221
- const dirty = view !== null && draft !== view.source;
222
- // ⛔ W37-T41: "STILL LOADING" AND "COULD NOT BE OPENED" ARE DIFFERENT FACTS AND USED TO SHARE A
223
- // SENTENCE. With mint-on-pick (E-7) the normal path now passes through `view === null` for as
224
- // long as the fetch takes, so the old copy told every person who created a Custom View that it
225
- // was broken, for a moment, every time. A state that renames itself is exactly what cost this
226
- // product a QA pass one wave ago [[a-store-outage-renames-itself-at-every-layer]].
227
- if (view === null)
228
- return (
229
- <div className="cg-script" onPointerDown={foldNavOnWorkSurface}>
230
- <p className="cg-script-empty cg-script-empty--pad">
231
- {loading === true ? "Opening this view." : "This script view could not be opened."}
232
- </p>
233
- </div>
234
- );
235
- return (
236
- <div className="cg-script" onPointerDown={foldNavOnWorkSurface}>
237
- <div className="cg-script-body">
238
- <section className="cg-script-pane" aria-label="Script source">
239
- <div className="cg-script-pane-head">
240
- <span>Code</span>
241
- <span className="cg-script-meta">
242
- {`v${view.version}`}
243
- {/* ⚠ "v5" alone cannot tell a roll-back from a coincidence of matching code. This is
244
- the sentence that makes the history read as what happened. */}
245
- {view.restoredFrom ? `, restored from v${view.restoredFrom}` : ""}
246
- {dirty ? ", unsaved changes" : ""}
247
- </span>
248
- <span className="cg-script-spacer" />
249
- <button
250
- type="button"
251
- className="cg-script-ghost"
252
- disabled={!dirty || saving === true || readOnly || onSave === undefined}
253
- onClick={() => onSave?.(draft)}
254
- >
255
- {saving === true ? "Saving" : "Save version"}
256
- </button>
257
- <button
258
- type="button"
259
- className="cg-script-run"
260
- disabled={running}
261
- onClick={() => onRun(draft)}
262
- >
263
- {running ? "Running" : "Run"}
264
- </button>
265
- </div>
266
- {/* ⭐⭐ W37-T41 — THE PLACEHOLDER IS THE CREATE FLOW'S WHOLE EMPTY STATE, and it is the
267
- half that made item 10 worth reopening. Picking Custom View mints a view with an
268
- EMPTY source (verified: `script_sandbox.check_source("")` accepts it, which is why
269
- "mint on pick" was safe to hand lane C in mailbox E-7). Without this the person who
270
- just created one meets a blank box and a Run button, which is not an invitation, it
271
- is a puzzle.
272
- ⛔ A PLACEHOLDER, NOT A PREFILLED `value`. Prefilling would make the view DIRTY the
273
- moment it opened, arm Save on code nobody wrote, and put a version nobody asked for
274
- into a 40-deep history. It vanishes on the first keystroke and is never saved. */}
275
- {/* ⭐⭐ W37-T46 / D-338 — THE CONTROL THAT WAS MISSING. The API already returned
276
- `history` newest-first and the header already showed `v<n>`; there was simply no way
277
- to go back, which is the whole of D-338. It matters more now that a chat writes the
278
- code (R2): generation without roll-back means one bad answer costs somebody their
279
- view, and the person cannot tell in advance which answer that will be.
280
- ⛔ THE STRIP IS ABSENT, NOT DISABLED, WHEN THERE IS NOTHING TO GO BACK TO. A first
281
- version has no history, and a row of dead controls reads as a broken feature rather
282
- than as an empty one.
283
- ⚠ `trimmed` is PRINTED when it is non-zero. A history capped at 40 that silently
284
- showed 40 would let a reader conclude the view was only ever saved 40 times; saying
285
- how many were dropped is the difference between a partial record and a wrong one. */}
286
- {/* ⛔ W37-T46 — THE STRIP IS ABSENT WHEN THE CALLER CANNOT REVERT, which is what the
287
- prop's own doc twelve lines up already prescribed ("The control is not rendered at
288
- all when it is absent, rather than rendered and refused"). Line 293 shipped
289
- `onRevert === undefined` folded into `disabled` instead, so the one mount in the
290
- product rendered a permanently dead "Earlier | v1" pill and the comment disowned the
291
- code beside it. Two facts, two shapes: NOTHING TO GO BACK TO is an absent strip, and
292
- BUSY is a disabled button. */}
293
- {onRevert !== undefined && (view.history?.length ?? 0) > 0 ? (
294
- <div className="cg-script-history" aria-label="Earlier versions">
295
- <span className="cg-script-history-lead">Earlier</span>
296
- {[...(view.history ?? [])].map((h) => (
297
- <button
298
- type="button"
299
- key={h.version}
300
- className="cg-script-history-item"
301
- disabled={readOnly || reverting}
302
- title={`Go back to version ${h.version}, saved by ${h.author || "somebody"}`}
303
- onClick={() => onRevert?.(h.version)}
304
- >
305
- {`v${h.version}`}
306
- </button>
307
- ))}
308
- {view.trimmed > 0 ? (
309
- <span className="cg-script-history-trimmed">
310
- {`${view.trimmed} older ${view.trimmed === 1 ? "version" : "versions"} dropped`}
311
- </span>
312
- ) : null}
313
- {reverting ? <span className="cg-script-history-trimmed">Going back</span> : null}
314
- </div>
315
- ) : null}
316
- <textarea
317
- className="cg-script-code"
318
- value={draft}
319
- spellCheck={false}
320
- readOnly={readOnly}
321
- placeholder={SCRIPT_STARTER}
322
- aria-label="Script source"
323
- onChange={(e) => setDraft(e.target.value)}
324
- />
325
- </section>
326
- <section className="cg-script-pane" aria-label="Script output">
327
- <div className="cg-script-pane-head">
328
- <span>Output</span>
329
- <span className="cg-script-spacer" />
330
- {run !== null ? (
331
- <span className="cg-script-meta">
332
- {run.ms > 0 ? `${run.ms} ms` : ""}
333
- </span>
334
- ) : null}
335
- </div>
336
- <div className="cg-script-out">
337
- <ScriptOutput run={run} />
338
- </div>
339
- </section>
340
- </div>
341
- </div>
342
- );
343
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/customer-grid/ViewAgentPanel.tsx DELETED
@@ -1,198 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / ViewAgentPanel.tsx — owner item 6's View agent (W36-T05, R3, contract C3).
3
- //
4
- // Owner: *"We should place this agent, just like how `Airtable AI 2.png` place it, to the left of
5
- // the View navigation. We should be able to open this Agent view, by clicking a button (robot
6
- // icon) beside the "III" of View navigation."*
7
- //
8
- // ⭐ THE LAYOUT IS COPIED, THE COLOURS ARE NOT (PRD, "reference/Airtable AI 2.png"). What makes
9
- // that panel look calm is whitespace and a single accent: one card border, one filled button,
10
- // everything else flat. Ours substitutes navy + gold from DESIGN.md.
11
- //
12
- // ⛔⛔ THE ROOT WEARS `cg-agent-panel`, AND THAT ONE CLASS IS THE WHOLE CROSS-FENCE CONTRACT
13
- // (wiring W8, F's `DONE B-3`). `index.css` folds the main rail to `--lp-rail-min` on
14
- // `.shell-root:has(.cg-agent-panel) .shell-side` across seventeen selectors; F measured it at
15
- // 344 -> 48px, which gives the grid back 187 -> 483px at a 1440 window. There is no prop, no
16
- // callback and no lifted state in either direction.
17
- // ⛔ AND THE PANEL MUST BE ABSENT FROM THE TREE WHEN CLOSED, never `display: none` — `:has()`
18
- // matches an element that EXISTS, so a hidden panel would hold the rail folded over nothing.
19
- // That is F's half of W8 handed back, and it is enforced at the call site in `ViewSidebar`.
20
- //
21
- // ⚠ WHAT THIS PANEL DOES NOT DO, STATED RATHER THAN IMPLIED: it does not generate code. C3
22
- // publishes storage, versioning and a sandboxed run; there is no "write me a script" endpoint in
23
- // this wave, so the copy below never claims one wrote anything. The panel STARTS a script view
24
- // from the request, records the request in the source, and opens it in the editor beside its
25
- // output. Booked as a PENDING line rather than faked.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { useState } from "react";
29
- import type { ScriptViewRow } from "./scriptViews";
30
-
31
- /** The starter a new script view is seeded with. Runnable as written, so the first Run answers
32
- * something instead of erroring, and the request is recorded where its author will read it. */
33
- export function seedScript(request: string): string {
34
- const asked = request.trim().replace(/\r?\n/g, " ").slice(0, 300);
35
- return [
36
- '"""' + (asked || "A new script view.") + '"""',
37
- "# This view runs on the server, scoped to the database it lives in and to what YOU can see.",
38
- "# `rows` is that scope. Call emit() once with the view you want drawn.",
39
- "",
40
- "emit({",
41
- ' "kind": "metrics",',
42
- ' "title": "Rows in scope",',
43
- ' "items": [{"label": "Records", "value": len(rows)}],',
44
- "})",
45
- "",
46
- ].join("\n");
47
- }
48
-
49
- /** A short, stable name from the request, so the rail reads as a list of questions. */
50
- export function seedName(request: string): string {
51
- const words = request.trim().replace(/\s+/g, " ").split(" ").filter(Boolean).slice(0, 6);
52
- const name = words.join(" ").slice(0, 60);
53
- return name || "New script";
54
- }
55
-
56
- function RobotMark() {
57
- return (
58
- <svg width="15" height="15" viewBox="0 0 16 16" fill="none" aria-hidden="true">
59
- <path d="M4.2 6.2h7.6v5.1H4.2z" stroke="currentColor" strokeWidth="1.3"
60
- strokeLinejoin="round" />
61
- <path d="M8 3.4v2.8M2.6 8.4v1.6M13.4 8.4v1.6" stroke="currentColor" strokeWidth="1.3"
62
- strokeLinecap="round" />
63
- <path d="M6.4 8.5v.8M9.6 8.5v.8" stroke="currentColor" strokeWidth="1.5"
64
- strokeLinecap="round" />
65
- </svg>
66
- );
67
- }
68
-
69
- /**
70
- * The panel. One column, full height, to the LEFT of the view navigation.
71
- *
72
- * ⚠ `busy` and `error` are the caller's, not this component's: the write goes through C3 from
73
- * `CustomerGrid`, which already owns the script list this panel adds to. A second fetch here
74
- * would be a second source of truth for the same rail.
75
- */
76
- export function ViewAgentPanel({
77
- database,
78
- views,
79
- busy = false,
80
- error = null,
81
- onCreate,
82
- onOpen,
83
- onClose,
84
- }: {
85
- database: string;
86
- views: ScriptViewRow[];
87
- busy?: boolean;
88
- error?: string | null;
89
- onCreate: (request: string) => void;
90
- onOpen: (id: string) => void;
91
- onClose: () => void;
92
- }) {
93
- const [request, setRequest] = useState("");
94
- const send = () => {
95
- const asked = request.trim();
96
- if (!asked || busy) return;
97
- onCreate(asked);
98
- setRequest("");
99
- };
100
- return (
101
- <aside className="cg-agent-panel" aria-label="View agent">
102
- <header className="cg-agent-head">
103
- <span className="cg-agent-title">New script</span>
104
- <span className="cg-agent-spacer" />
105
- <button
106
- type="button"
107
- className="cg-agent-icon"
108
- onClick={onClose}
109
- aria-label="Close the view agent"
110
- title="Close the view agent"
111
- >
112
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
113
- <path d="M9.8 3.6 5.4 8l4.4 4.4M12.6 3.2v9.6" stroke="currentColor" strokeWidth="1.35"
114
- strokeLinecap="round" strokeLinejoin="round" />
115
- </svg>
116
- </button>
117
- </header>
118
-
119
- <div className="cg-agent-body">
120
- {views.length === 0 ? (
121
- <div className="cg-agent-empty">
122
- <span className="cg-agent-mark" aria-hidden="true" />
123
- <p className="cg-agent-ask">What should this database show you?</p>
124
- </div>
125
- ) : (
126
- <>
127
- <p className="cg-agent-listhead">Scripts in this database</p>
128
- <ul className="cg-agent-list">
129
- {views.map((view) => (
130
- <li key={view.id}>
131
- <button type="button" className="cg-agent-row" onClick={() => onOpen(view.id)}>
132
- <span className="cg-agent-row-tile" aria-hidden="true"><RobotMark /></span>
133
- <span className="cg-agent-row-text">
134
- <span className="cg-agent-row-title">{view.name}</span>
135
- <span className="cg-agent-row-sub">
136
- {`Version ${view.version} by ${view.author}`}
137
- </span>
138
- </span>
139
- <span className="cg-agent-row-go" aria-hidden="true">
140
- <svg width="12" height="12" viewBox="0 0 16 16" fill="none">
141
- <path d="M4.6 11.4 11.4 4.6M6.2 4.6h5.2v5.2" stroke="currentColor"
142
- strokeWidth="1.35" strokeLinecap="round" strokeLinejoin="round" />
143
- </svg>
144
- </span>
145
- </button>
146
- </li>
147
- ))}
148
- </ul>
149
- </>
150
- )}
151
- {error ? <p className="cg-agent-error" role="status">{error}</p> : null}
152
- </div>
153
-
154
- {/* The composer as ONE bordered card: input on top, the affordances BELOW it inside the
155
- same border, the send button bottom right. That grouping is what the reference does and
156
- it is the reason the surface reads as calm rather than as a toolbar. */}
157
- <div className="cg-agent-composer">
158
- <textarea
159
- className="cg-agent-input"
160
- value={request}
161
- placeholder="Ask or build anything for this database"
162
- aria-label="Describe the script view you want"
163
- rows={2}
164
- onChange={(e) => setRequest(e.target.value)}
165
- onKeyDown={(e) => {
166
- if (e.key === "Enter" && !e.shiftKey) {
167
- e.preventDefault();
168
- send();
169
- }
170
- }}
171
- />
172
- <div className="cg-agent-composer-foot">
173
- {/* ⚠ NOT A FAKE AFFORDANCE. This says what the panel will do, because it is the one
174
- thing a reader cannot tell from an empty input: the script is STARTED here and
175
- written in the editor, and no model is called in this wave. */}
176
- <span className="cg-agent-pill">Starts a script you can edit and run</span>
177
- <span className="cg-agent-spacer" />
178
- <button
179
- type="button"
180
- className="cg-agent-send"
181
- onClick={send}
182
- disabled={busy || request.trim() === ""}
183
- aria-label="Start a script view from this request"
184
- title="Start a script view from this request"
185
- >
186
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
187
- <path d="M8 12.6V3.8M4.4 7.2 8 3.6l3.6 3.6" stroke="currentColor" strokeWidth="1.5"
188
- strokeLinecap="round" strokeLinejoin="round" />
189
- </svg>
190
- </button>
191
- </div>
192
- </div>
193
- <p className="cg-agent-foot">
194
- {`Scripts here read only ${database}, and only the rows and columns you can see.`}
195
- </p>
196
- </aside>
197
- );
198
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/customer-grid/scriptView.css DELETED
@@ -1,509 +0,0 @@
1
- /* customer-grid/scriptView.css — owner item 6, the code-script View.
2
- *
3
- * ⛔ MODULE-LOCAL BY RULING, not by preference. `index.css` is a 12k-line shared file and this
4
- * wave's PRD hands it to ONE session; a new surface that grew it would be three lanes editing the
5
- * monolith at once. It is also item 13's smallest real win: the monolith stops growing.
6
- * ⚠ Colours come from the design tokens (navy #1F4E78 + gold #C8A24B, DESIGN.md), never from
7
- * fresh hexes: a surface that invents its own palette is the thing the constitution exists to
8
- * prevent. Only the tokens this file actually uses are named. */
9
-
10
- .cg-script {
11
- display: flex;
12
- flex-direction: column;
13
- height: 100%;
14
- min-height: 0;
15
- background: var(--lp-surface, #ffffff);
16
- }
17
-
18
- /* The two halves the owner asked for by name: "the code AND the dashboard output of course."
19
- Side by side above 900px, stacked below it, and the SPLIT is the point either way. */
20
- .cg-script-body {
21
- display: grid;
22
- grid-template-columns: minmax(280px, 5fr) minmax(320px, 7fr);
23
- gap: 1px;
24
- flex: 1 1 auto;
25
- min-height: 0;
26
- background: var(--lp-border, #e4e7ec);
27
- }
28
- @media (max-width: 900px) {
29
- .cg-script-body { grid-template-columns: 1fr; grid-template-rows: minmax(180px, 2fr) 3fr; }
30
- }
31
-
32
- .cg-script-pane {
33
- display: flex;
34
- flex-direction: column;
35
- min-width: 0;
36
- min-height: 0;
37
- background: var(--lp-surface, #ffffff);
38
- }
39
-
40
- .cg-script-pane-head {
41
- display: flex;
42
- align-items: center;
43
- gap: 8px;
44
- padding: 8px 12px;
45
- border-bottom: 1px solid var(--lp-border, #e4e7ec);
46
- font: 500 var(--lp-fs-2xs)/1.4 Inter, system-ui, sans-serif;
47
- color: var(--lp-text-muted, #667085);
48
- }
49
- .cg-script-pane-head .cg-script-spacer { flex: 1 1 auto; }
50
-
51
- /* ⚠ A textarea, not a highlighted editor. A syntax highlighter is a second parser of the same
52
- source, and the two disagree the first time either learns a token; the owner asked to SEE the
53
- code, which a monospaced pane does. */
54
- .cg-script-code {
55
- flex: 1 1 auto;
56
- min-height: 0;
57
- width: 100%;
58
- resize: none;
59
- border: 0;
60
- outline: none;
61
- padding: 12px;
62
- font: 400 var(--lp-fs-xs)/1.6 "SFMono-Regular", Menlo, Consolas, monospace;
63
- color: var(--lp-text, #1d2939);
64
- background: var(--lp-surface-sunken, #fbfcfd);
65
- tab-size: 4;
66
- white-space: pre;
67
- overflow: auto;
68
- }
69
- .cg-script-code:focus-visible { box-shadow: inset 0 0 0 2px var(--lp-navy, #1f4e78); }
70
-
71
- .cg-script-out {
72
- flex: 1 1 auto;
73
- min-height: 0;
74
- overflow: auto;
75
- padding: 14px 16px;
76
- }
77
-
78
- .cg-script-run {
79
- display: inline-flex;
80
- align-items: center;
81
- gap: 6px;
82
- height: 26px;
83
- padding: 0 12px;
84
- border: 0;
85
- border-radius: 6px;
86
- background: var(--lp-navy, #1f4e78);
87
- color: #ffffff;
88
- font: 500 var(--lp-fs-2xs)/1 Inter, system-ui, sans-serif;
89
- cursor: pointer;
90
- }
91
- .cg-script-run:disabled { opacity: 0.55; cursor: default; }
92
- .cg-script-ghost {
93
- height: 26px;
94
- padding: 0 10px;
95
- border: 1px solid var(--lp-border, #e4e7ec);
96
- border-radius: 6px;
97
- background: transparent;
98
- color: var(--lp-text, #1d2939);
99
- font: 500 var(--lp-fs-2xs)/1 Inter, system-ui, sans-serif;
100
- cursor: pointer;
101
- }
102
- .cg-script-ghost:disabled { opacity: 0.5; cursor: default; }
103
-
104
- .cg-script-meta {
105
- font: 400 var(--lp-fs-3xs)/1.5 Inter, system-ui, sans-serif;
106
- color: var(--lp-text-muted, #667085);
107
- }
108
-
109
- /* A refusal is CONTENT, not a toast: the reader asked a question and this is the answer, so it
110
- stays on screen next to the code that caused it. */
111
- .cg-script-refusal {
112
- border: 1px solid var(--lp-border, #e4e7ec);
113
- border-left: 3px solid var(--lp-gold, #c8a24b);
114
- border-radius: 6px;
115
- padding: 12px 14px;
116
- background: var(--lp-surface-sunken, #fbfcfd);
117
- }
118
- .cg-script-refusal h4 {
119
- margin: 0 0 6px;
120
- font: 600 var(--lp-fs-xs)/1.4 Inter, system-ui, sans-serif;
121
- color: var(--lp-text, #1d2939);
122
- }
123
- .cg-script-refusal p { margin: 0 0 4px; font: 400 var(--lp-fs-xs)/1.6 Inter, system-ui, sans-serif; }
124
- .cg-script-refusal dl {
125
- margin: 8px 0 0;
126
- display: grid;
127
- grid-template-columns: auto 1fr;
128
- gap: 2px 10px;
129
- font: 400 var(--lp-fs-2xs)/1.5 Inter, system-ui, sans-serif;
130
- }
131
- .cg-script-refusal dt { color: var(--lp-text-muted, #667085); }
132
- .cg-script-refusal dd { margin: 0; }
133
-
134
- .cg-script-title {
135
- margin: 0 0 10px;
136
- font: 600 var(--lp-fs-sm)/1.4 Inter, system-ui, sans-serif;
137
- color: var(--lp-text, #1d2939);
138
- }
139
-
140
- .cg-script-table { width: 100%; border-collapse: collapse; }
141
- .cg-script-table th,
142
- .cg-script-table td {
143
- border-bottom: 1px solid var(--lp-border, #e4e7ec);
144
- padding: 6px 10px;
145
- text-align: left;
146
- font: 400 var(--lp-fs-xs)/1.5 Inter, system-ui, sans-serif;
147
- vertical-align: top;
148
- }
149
- .cg-script-table th {
150
- font-weight: 600;
151
- color: var(--lp-text-muted, #667085);
152
- position: sticky;
153
- top: 0;
154
- background: var(--lp-surface, #ffffff);
155
- }
156
-
157
- .cg-script-metrics {
158
- display: grid;
159
- grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
160
- gap: 10px;
161
- }
162
- .cg-script-metric {
163
- border: 1px solid var(--lp-border, #e4e7ec);
164
- border-radius: 8px;
165
- padding: 10px 12px;
166
- }
167
- .cg-script-metric-label {
168
- font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif;
169
- color: var(--lp-text-muted, #667085);
170
- }
171
- .cg-script-metric-value {
172
- margin-top: 4px;
173
- font: 600 var(--lp-fs-lg)/1.2 Inter, system-ui, sans-serif;
174
- color: var(--lp-text, #1d2939);
175
- }
176
- .cg-script-metric-note {
177
- margin-top: 2px;
178
- font: 400 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif;
179
- color: var(--lp-text-muted, #667085);
180
- }
181
-
182
- .cg-script-bars { display: flex; flex-direction: column; gap: 8px; }
183
- .cg-script-bar { display: grid; grid-template-columns: minmax(80px, 22%) 1fr auto; gap: 10px;
184
- align-items: center; font: 400 var(--lp-fs-xs)/1.4 Inter, system-ui, sans-serif; }
185
- .cg-script-bar-track {
186
- height: 10px;
187
- border-radius: 5px;
188
- background: var(--lp-surface-sunken, #f2f4f7);
189
- overflow: hidden;
190
- }
191
- .cg-script-bar-fill { height: 100%; border-radius: 5px; background: var(--lp-navy, #1f4e78); }
192
- .cg-script-bar-value { color: var(--lp-text-muted, #667085); font-variant-numeric: tabular-nums; }
193
-
194
- .cg-script-text {
195
- margin: 0;
196
- font: 400 var(--lp-fs-xs)/1.7 Inter, system-ui, sans-serif;
197
- color: var(--lp-text, #1d2939);
198
- white-space: pre-wrap;
199
- word-break: break-word;
200
- }
201
-
202
- .cg-script-stdout {
203
- margin: 14px 0 0;
204
- padding: 10px 12px;
205
- border-radius: 6px;
206
- background: var(--lp-surface-sunken, #fbfcfd);
207
- border: 1px solid var(--lp-border, #e4e7ec);
208
- font: 400 var(--lp-fs-3xs)/1.6 "SFMono-Regular", Menlo, Consolas, monospace;
209
- color: var(--lp-text-muted, #667085);
210
- white-space: pre-wrap;
211
- word-break: break-word;
212
- max-height: 220px;
213
- overflow: auto;
214
- }
215
-
216
- .cg-script-empty {
217
- font: 400 var(--lp-fs-xs)/1.6 Inter, system-ui, sans-serif;
218
- color: var(--lp-text-muted, #667085);
219
- }
220
- /* The whole-panel empty state needs its own padding: there is no `.cg-script-out` around it.
221
- Kept HERE rather than inline, so the renderer's one and only computed style stays the bar
222
- width, which is arithmetic on a validated number and is asserted as the only one. */
223
- .cg-script-empty--pad { padding: 16px; }
224
-
225
- /* ═══════════════════════════════════════════════════════════════════════════════════════════
226
- W36-T05 — THE VIEW AGENT PANEL, left of the View navigation.
227
-
228
- ⛔ `.cg-agent-panel` IS A CROSS-FENCE CLASS NAME (wiring W8, F's DONE B-3). `index.css` folds
229
- the main rail on `.shell-root:has(.cg-agent-panel) .shell-side`. Renaming it here silently
230
- un-folds the rail and leaves 187px of grid at 1440, with nothing going red. Its WIDTH lives
231
- here because the panel is B's; the FOLD lives in index.css because the rail is F's.
232
- ⚠ ~565px is the reference's own column at 1919px wide, and it is what R14's arithmetic is
233
- built on: 48 (folded nav) + 565 (this) + 344 (views rail) = 957, leaving 483px of grid.
234
- ═══════════════════════════════════════════════════════════════════════════════════════════ */
235
- .cg-agent-panel {
236
- display: flex;
237
- flex-direction: column;
238
- flex: 0 0 565px;
239
- width: 565px;
240
- max-width: 46vw;
241
- min-height: 0;
242
- border-right: 1px solid var(--lp-border, #e4e7ec);
243
- background: var(--lp-surface, #ffffff);
244
- }
245
-
246
- .cg-agent-head {
247
- display: flex;
248
- align-items: center;
249
- gap: 8px;
250
- padding: 10px 14px;
251
- border-bottom: 1px solid var(--lp-border, #e4e7ec);
252
- }
253
- .cg-agent-title { font: 600 var(--lp-fs-xs)/1.4 Inter, system-ui, sans-serif; color: var(--lp-text, #1d2939); }
254
- .cg-agent-spacer { flex: 1 1 auto; }
255
- .cg-agent-icon {
256
- display: inline-flex;
257
- align-items: center;
258
- justify-content: center;
259
- width: 26px;
260
- height: 26px;
261
- border: 0;
262
- border-radius: 6px;
263
- background: transparent;
264
- color: var(--lp-text-muted, #667085);
265
- cursor: pointer;
266
- }
267
- .cg-agent-icon:hover { background: var(--lp-surface-sunken, #f2f4f7); }
268
-
269
- .cg-agent-body { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 16px; }
270
-
271
- /* The empty state: centred, one soft mark, one question. Whitespace is the design. */
272
- .cg-agent-empty {
273
- height: 100%;
274
- display: flex;
275
- flex-direction: column;
276
- align-items: center;
277
- justify-content: center;
278
- gap: 14px;
279
- }
280
- .cg-agent-mark {
281
- width: 54px;
282
- height: 54px;
283
- border-radius: 50%;
284
- border: 2px dotted var(--lp-gold, #c8a24b);
285
- opacity: 0.55;
286
- }
287
- .cg-agent-ask {
288
- margin: 0;
289
- font: 500 var(--lp-fs-md)/1.4 Inter, system-ui, sans-serif;
290
- color: var(--lp-text-muted, #667085);
291
- }
292
-
293
- .cg-agent-listhead {
294
- margin: 0 0 8px;
295
- font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif;
296
- color: var(--lp-text-muted, #667085);
297
- }
298
- .cg-agent-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column;
299
- gap: 4px; }
300
- /* The suggestion row from the reference: icon tile, bold title, muted subtitle, an arrow right. */
301
- .cg-agent-row {
302
- display: flex;
303
- align-items: center;
304
- gap: 10px;
305
- width: 100%;
306
- padding: 8px 10px;
307
- border: 0;
308
- border-radius: 8px;
309
- background: transparent;
310
- text-align: left;
311
- cursor: pointer;
312
- }
313
- .cg-agent-row:hover { background: var(--lp-surface-sunken, #f2f4f7); }
314
- .cg-agent-row-tile {
315
- display: inline-flex;
316
- align-items: center;
317
- justify-content: center;
318
- width: 28px;
319
- height: 28px;
320
- flex: 0 0 28px;
321
- border-radius: 7px;
322
- background: var(--lp-surface-sunken, #f2f4f7);
323
- color: var(--lp-navy, #1f4e78);
324
- }
325
- .cg-agent-row-text { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
326
- .cg-agent-row-title {
327
- font: 600 var(--lp-fs-xs)/1.4 Inter, system-ui, sans-serif;
328
- color: var(--lp-text, #1d2939);
329
- overflow: hidden;
330
- text-overflow: ellipsis;
331
- white-space: nowrap;
332
- }
333
- .cg-agent-row-sub {
334
- font: 400 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif;
335
- color: var(--lp-text-muted, #667085);
336
- }
337
- .cg-agent-row-go { color: var(--lp-text-muted, #667085); }
338
-
339
- .cg-agent-error {
340
- margin: 12px 0 0;
341
- font: 400 var(--lp-fs-xs)/1.6 Inter, system-ui, sans-serif;
342
- color: var(--lp-text, #1d2939);
343
- border-left: 3px solid var(--lp-gold, #c8a24b);
344
- padding-left: 10px;
345
- }
346
-
347
- /* ONE card border around the input AND its affordances, which is what the reference does. */
348
- .cg-agent-composer {
349
- margin: 0 16px;
350
- border: 1px solid var(--lp-border, #e4e7ec);
351
- border-radius: 12px;
352
- background: var(--lp-surface, #ffffff);
353
- }
354
- .cg-agent-input {
355
- display: block;
356
- width: 100%;
357
- border: 0;
358
- outline: none;
359
- resize: none;
360
- padding: 12px 14px 6px;
361
- background: transparent;
362
- font: 400 var(--lp-fs-xs)/1.6 Inter, system-ui, sans-serif;
363
- color: var(--lp-text, #1d2939);
364
- }
365
- .cg-agent-composer:focus-within { border-color: var(--lp-navy, #1f4e78); }
366
- .cg-agent-composer-foot {
367
- display: flex;
368
- align-items: center;
369
- gap: 8px;
370
- padding: 6px 8px 8px 12px;
371
- }
372
- .cg-agent-pill {
373
- font: 400 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif;
374
- color: var(--lp-text-muted, #667085);
375
- border: 1px solid var(--lp-border, #e4e7ec);
376
- border-radius: 999px;
377
- padding: 3px 9px;
378
- }
379
- .cg-agent-send {
380
- display: inline-flex;
381
- align-items: center;
382
- justify-content: center;
383
- width: 30px;
384
- height: 30px;
385
- border: 0;
386
- border-radius: 50%;
387
- background: var(--lp-navy, #1f4e78);
388
- color: #ffffff;
389
- cursor: pointer;
390
- }
391
- .cg-agent-send:disabled { opacity: 0.4; cursor: default; }
392
-
393
- .cg-agent-foot {
394
- margin: 8px 16px 14px;
395
- font: 400 var(--lp-fs-3xs)/1.5 Inter, system-ui, sans-serif;
396
- color: var(--lp-text-muted, #667085);
397
- }
398
-
399
- /* The robot, beside the views rail's own minimize toggle (W35-T28 keeps that one FIRST). */
400
- .cg-agent-open {
401
- display: inline-flex;
402
- align-items: center;
403
- justify-content: center;
404
- width: 26px;
405
- height: 26px;
406
- border: 0;
407
- border-radius: 6px;
408
- background: transparent;
409
- color: var(--lp-text-muted, #667085);
410
- cursor: pointer;
411
- }
412
- .cg-agent-open:hover { background: var(--lp-surface-sunken, #f2f4f7); }
413
- .cg-agent-open.is-on { background: var(--lp-surface-sunken, #f2f4f7); color: var(--lp-navy, #1f4e78); }
414
-
415
- /* ═══════════════════════════════════════════════════════════════════════════════════════════
416
- W36-T07 — THE FIELD AGENT, inside the column menu's create pane.
417
- ⚠ It reuses the `cg-agent-*` composer above rather than growing a second chat look. What is
418
- added here is only what a conversation inside a 320px menu needs that a full-height panel
419
- does not: a bounded scroll, a proposal card, and the two-button accept row.
420
- ═══════════════════════════════════════════════════════════════════════════════════════════ */
421
- .cg-fagent { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
422
- .cg-fagent-body { max-height: 320px; overflow: auto; }
423
- .cg-fagent-turns { list-style: none; margin: 0 0 10px; padding: 0; display: flex;
424
- flex-direction: column; gap: 6px; }
425
- .cg-fagent-turn { display: flex; justify-content: flex-end; }
426
- .cg-fagent-said {
427
- max-width: 88%;
428
- padding: 6px 10px;
429
- border-radius: 10px 10px 2px 10px;
430
- background: var(--lp-surface-sunken, #f2f4f7);
431
- font: 400 var(--lp-fs-2xs)/1.5 Inter, system-ui, sans-serif;
432
- color: var(--lp-text, #1d2939);
433
- word-break: break-word;
434
- }
435
- .cg-fagent-card {
436
- border: 1px solid var(--lp-border, #e4e7ec);
437
- border-left: 3px solid var(--lp-gold, #c8a24b);
438
- border-radius: 8px;
439
- padding: 10px 12px;
440
- }
441
- .cg-fagent-card-head {
442
- margin: 0 0 6px;
443
- font: 600 var(--lp-fs-2xs)/1.4 Inter, system-ui, sans-serif;
444
- color: var(--lp-text, #1d2939);
445
- }
446
- .cg-fagent-def {
447
- margin: 0;
448
- display: grid;
449
- grid-template-columns: auto 1fr;
450
- gap: 2px 10px;
451
- font: 400 var(--lp-fs-2xs)/1.5 Inter, system-ui, sans-serif;
452
- }
453
- .cg-fagent-def dt { color: var(--lp-text-muted, #667085); }
454
- .cg-fagent-def dd { margin: 0; color: var(--lp-text, #1d2939); }
455
- .cg-fagent-why,
456
- .cg-fagent-missing {
457
- margin: 8px 0 0;
458
- padding-left: 16px;
459
- font: 400 var(--lp-fs-3xs)/1.55 Inter, system-ui, sans-serif;
460
- color: var(--lp-text-muted, #667085);
461
- }
462
- /* What is still OPEN reads differently from what was decided: the reader has to answer these. */
463
- .cg-fagent-missing { color: var(--lp-text, #1d2939); }
464
- .cg-fagent-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; }
465
- /* The agent's door in the create pane. A quiet row, not a second primary button. */
466
- .cg-fagent-open {
467
- display: inline-flex;
468
- align-items: center;
469
- gap: 6px;
470
- width: 100%;
471
- padding: 7px 10px;
472
- border: 1px dashed var(--lp-border, #e4e7ec);
473
- border-radius: 8px;
474
- background: transparent;
475
- color: var(--lp-text-muted, #667085);
476
- font: 500 var(--lp-fs-2xs)/1.4 Inter, system-ui, sans-serif;
477
- cursor: pointer;
478
- }
479
- .cg-fagent-open:hover { border-color: var(--lp-navy, #1f4e78); color: var(--lp-navy, #1f4e78); }
480
-
481
- /* ── W37-T46 / D-338: the roll-back strip ───────────────────────────────────
482
- ⚠ It sits between the head row and the code, where a person looking for "what came before" is
483
- already looking. A separate panel or a modal would put the history somewhere you have to go
484
- rather than somewhere you are. */
485
- .cg-script-history {
486
- display: flex;
487
- align-items: center;
488
- flex-wrap: wrap;
489
- gap: 6px;
490
- padding: 6px 12px;
491
- border-bottom: 1px solid var(--lp-border, #e4e7ec);
492
- background: var(--lp-surface-sunken, #fbfcfd);
493
- }
494
- .cg-script-history-lead,
495
- .cg-script-history-trimmed {
496
- font: 400 var(--lp-fs-3xs)/1.3 Inter, system-ui, sans-serif;
497
- color: var(--lp-text-muted, #667085);
498
- }
499
- .cg-script-history-item {
500
- border: 1px solid var(--lp-border, #e4e7ec);
501
- border-radius: 6px;
502
- background: var(--lp-surface, #ffffff);
503
- color: var(--lp-navy, #1f4e78);
504
- font: 500 var(--lp-fs-3xs)/1.2 Inter, system-ui, sans-serif;
505
- padding: 2px 7px;
506
- cursor: pointer;
507
- }
508
- .cg-script-history-item:hover:enabled { border-color: var(--lp-navy, #1f4e78); }
509
- .cg-script-history-item:disabled { opacity: 0.5; cursor: default; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/customer-grid/scriptViews.ts DELETED
@@ -1,387 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / scriptViews.ts — the CLIENT half of contract C3 (owner item 6).
3
- //
4
- // ⭐ THE ASK, verbatim: *"Add code script as an interface (database View) so a user can build
5
- // whatever they want through the Agent chat interface … User should have the ability to see the
6
- // code AND the dashboard output of course."* E owns the engine
7
- // (`aios-web/api/routes_script_views.py`, published as C3); this module is the typed door to it
8
- // and holds no policy of its own.
9
- //
10
- // ⛔⛔ THE ONE RULE THIS WHOLE FEATURE RESTS ON: **a run returns a DECLARATIVE SPEC, never HTML
11
- // and never a script.** R10 puts the Python in a server sandbox precisely so the browser never
12
- // has to trust the output; a renderer that then evaluated a string would hand back everything the
13
- // sandbox was built to contain. So nothing in this module or its renderer interprets a value as
14
- // code, as markup, as a URL or as CSS. `renderableSpec` below is where that is enforced, and the
15
- // enforcement is a WHITELIST of scalar leaves rather than a blacklist of dangerous keys — E's
16
- // server already refuses the dangerous keys at any depth, and two blacklists that must agree is
17
- // exactly the shape this repo keeps paying for.
18
- //
19
- // ⚠ R3 — SCOPED, NOT CAPPED. A script view may read only the database it lives in, and there is
20
- // no limit on how many a database holds (`limits.maxViewsPerDatabase` is `null` ON PURPOSE, so
21
- // an agent can leave three attempts side by side for the owner to compare). Do not build a
22
- // "you have reached the limit" state; there is none.
23
- //
24
- // ⚠ R5 — THE RUN IS THE READER'S SCOPE, NEVER THE AUTHOR'S. The same view opened by two accounts
25
- // returns two different numbers, correctly. Any cache keyed on the view id alone would show one
26
- // colleague another's totals, which is why nothing here caches a run at all.
27
- // ---------------------------------------------------------------------------
28
-
29
- import { API_V1, CREDENTIALS } from "../apiContract";
30
- import { refusalMessage } from "./apiBridge";
31
-
32
- /** One script view as the list endpoint returns it (C3 `row`). */
33
- export interface ScriptViewRow {
34
- id: string;
35
- database: string;
36
- name: string;
37
- author: string;
38
- version: number;
39
- created: string;
40
- updated: string;
41
- versions: number;
42
- trimmed: number;
43
- /**
44
- * ⭐ W37-T46 / D-338 — which version this one was RESTORED from, if it was.
45
- * ⚠ OPTIONAL BECAUSE MOST VERSIONS WERE NOT A ROLL-BACK, not because the server might forget to
46
- * send it. A view saved normally has no such fact, and `undefined` is that absence rather than a
47
- * missing field: rendering "restored from v0" for an ordinary save would be a lie about history.
48
- */
49
- restoredFrom?: number | null;
50
- }
51
-
52
- /** One version in a view's history. Newest first, per C3. */
53
- export interface ScriptViewVersion {
54
- version: number;
55
- author: string;
56
- created: string;
57
- bytes: number;
58
- }
59
-
60
- /** A single view read (C3 `view`): the row, plus the source and its history. */
61
- export interface ScriptView extends ScriptViewRow {
62
- source: string;
63
- history: ScriptViewVersion[];
64
- }
65
-
66
- /** C3's `limits` envelope. ⚠ `maxViewsPerDatabase` is `null` by ruling R3, not by omission. */
67
- export interface ScriptLimits {
68
- maxSourceBytes: number;
69
- maxName: number;
70
- maxHistory: number;
71
- maxConcurrentRuns: number;
72
- maxViewsPerDatabase: number | null;
73
- }
74
-
75
- /**
76
- * What a run answers.
77
- *
78
- * ⛔ `ok: false` IS A 200 (E's own note, and it is the half a caller gets wrong). A script that
79
- * timed out, refused an import or divided by zero is a well-formed request whose ANSWER is that
80
- * no view was produced. It is rendered, not thrown.
81
- */
82
- export interface ScriptRun {
83
- ok: boolean;
84
- spec?: unknown;
85
- stdout: string;
86
- truncated: boolean;
87
- ms: number;
88
- code: string;
89
- caps: { wallClock: boolean; memory: boolean; cpu: boolean };
90
- error?: string;
91
- /** Only on a 409: the four fields are PRINTED, never re-worded (standing rule 1's second half). */
92
- limit?: { subject: string; effect: string; cause: string; recommendation: string };
93
- }
94
-
95
- /** The three codes that are real HTTP statuses rather than script outcomes (C1's wall). */
96
- export type ScriptTransport = "not_found" | "forbidden" | "unavailable" | "unreachable";
97
-
98
- async function body(res: Response): Promise<unknown> {
99
- try {
100
- return await res.json();
101
- } catch {
102
- return null;
103
- }
104
- }
105
-
106
- /**
107
- * A transport failure, turned into the same envelope a refused RUN uses, so every caller has one
108
- * shape to render. ⚠ Not an exception: a 403 on a database somebody just lost access to is an
109
- * ordinary answer to an ordinary question, and a throw here would blank a working surface.
110
- */
111
- function transportRun(res: Response, payload: unknown): ScriptRun {
112
- const code: ScriptTransport =
113
- res.status === 404 ? "not_found" : res.status === 403 ? "forbidden" : "unavailable";
114
- const shaped = payload as { error?: { limit?: ScriptRun["limit"] } } | null;
115
- const out: ScriptRun = {
116
- ok: false,
117
- stdout: "",
118
- truncated: false,
119
- ms: 0,
120
- code,
121
- caps: { wallClock: false, memory: false, cpu: false },
122
- error: refusalMessage(payload, res.status, TRANSPORT_TEXT[code]),
123
- };
124
- const limit = shaped?.error?.limit;
125
- if (limit) out.limit = limit;
126
- return out;
127
- }
128
-
129
- /** ⚠ No dash of any kind: these strings reach a screen (standing rule 2). */
130
- const TRANSPORT_TEXT: Record<ScriptTransport, string> = {
131
- not_found: "This database no longer exists, so its scripts cannot run.",
132
- forbidden: "You do not have access to this database, so its scripts cannot run.",
133
- unavailable: "This database cannot be served right now, so its scripts cannot run.",
134
- unreachable: "The server could not be reached, so nothing was run.",
135
- };
136
-
137
- export const DEFAULT_SCRIPT_LIMITS: ScriptLimits = {
138
- maxSourceBytes: 131_072,
139
- maxName: 80,
140
- maxHistory: 40,
141
- maxConcurrentRuns: 4,
142
- maxViewsPerDatabase: null,
143
- };
144
-
145
- export async function listScriptViews(
146
- database: string
147
- ): Promise<{ views: ScriptViewRow[]; limits: ScriptLimits; error?: string }> {
148
- let res: Response;
149
- try {
150
- res = await fetch(`${API_V1}/script-views?database=${encodeURIComponent(database)}`,
151
- { credentials: CREDENTIALS });
152
- } catch {
153
- return { views: [], limits: DEFAULT_SCRIPT_LIMITS, error: TRANSPORT_TEXT.unreachable };
154
- }
155
- const payload = await body(res);
156
- if (!res.ok)
157
- return { views: [], limits: DEFAULT_SCRIPT_LIMITS,
158
- error: refusalMessage(payload, res.status, TRANSPORT_TEXT.unavailable) };
159
- const shaped = payload as { views?: ScriptViewRow[]; limits?: ScriptLimits } | null;
160
- return { views: Array.isArray(shaped?.views) ? shaped.views : [],
161
- limits: shaped?.limits ?? DEFAULT_SCRIPT_LIMITS };
162
- }
163
-
164
- export async function readScriptView(
165
- id: string
166
- ): Promise<{ view: ScriptView | null; error?: string }> {
167
- let res: Response;
168
- try {
169
- res = await fetch(`${API_V1}/script-views/${encodeURIComponent(id)}`,
170
- { credentials: CREDENTIALS });
171
- } catch {
172
- return { view: null, error: TRANSPORT_TEXT.unreachable };
173
- }
174
- const payload = await body(res);
175
- if (!res.ok)
176
- return { view: null, error: refusalMessage(payload, res.status, TRANSPORT_TEXT.unavailable) };
177
- const shaped = payload as { view?: ScriptView } | null;
178
- return { view: shaped?.view ?? null };
179
- }
180
-
181
- async function write(
182
- path: string, method: "POST" | "PUT", payload: Record<string, unknown>
183
- ): Promise<{ view: ScriptView | null; error?: string }> {
184
- let res: Response;
185
- try {
186
- res = await fetch(`${API_V1}${path}`, {
187
- method,
188
- credentials: CREDENTIALS,
189
- headers: { "Content-Type": "application/json" },
190
- body: JSON.stringify(payload),
191
- });
192
- } catch {
193
- return { view: null, error: TRANSPORT_TEXT.unreachable };
194
- }
195
- const answer = await body(res);
196
- if (!res.ok)
197
- return { view: null, error: refusalMessage(answer, res.status, TRANSPORT_TEXT.unavailable) };
198
- const shaped = answer as { view?: ScriptView } | null;
199
- return { view: shaped?.view ?? null };
200
- }
201
-
202
- export function createScriptView(database: string, source: string, name?: string) {
203
- return write("/script-views", "POST",
204
- name === undefined ? { database, source } : { database, source, name });
205
- }
206
-
207
- /** ⚠ A PUT is a NEW VERSION, never an overwrite (R8's shape, applied to scripts). */
208
- export function saveScriptView(id: string, source: string, name?: string) {
209
- return write(`/script-views/${encodeURIComponent(id)}`, "PUT",
210
- name === undefined ? { source } : { source, name });
211
- }
212
-
213
- /**
214
- * ⭐⭐ W37-T46 / D-338 — GO BACK TO AN EARLIER VERSION, AND IT IS A NEW VERSION.
215
- *
216
- * The API already RETURNED `history` newest-first and the editor already showed `v<n>`; there was
217
- * simply no control, which is D-338 in one sentence. This matters more now that a chat writes the
218
- * code (R2): generation without roll-back means one bad answer costs somebody their view.
219
- *
220
- * ⛔ THE SERVER DOES THE RESTORE, and the reason is in the payload rather than in taste: the list
221
- * door deliberately serves history entries WITHOUT their source, so a client cannot assemble an old
222
- * version's text to re-save it. One call is also atomic, where read-then-write leaves a window in
223
- * which a failure shows the person code that is not what is stored.
224
- */
225
- export function revertScriptView(id: string, version: number) {
226
- return write(`/script-views/${encodeURIComponent(id)}/revert`, "POST", { version });
227
- }
228
-
229
- export async function deleteScriptView(id: string): Promise<{ deleted: boolean; error?: string }> {
230
- let res: Response;
231
- try {
232
- res = await fetch(`${API_V1}/script-views/${encodeURIComponent(id)}`,
233
- { method: "DELETE", credentials: CREDENTIALS });
234
- } catch {
235
- return { deleted: false, error: TRANSPORT_TEXT.unreachable };
236
- }
237
- if (!res.ok)
238
- return { deleted: false,
239
- error: refusalMessage(await body(res), res.status, TRANSPORT_TEXT.unavailable) };
240
- return { deleted: true };
241
- }
242
-
243
- /**
244
- * Run a script view. `draft` runs UNSAVED source, checked exactly as stored source is, which is
245
- * what makes the editor usable: type, run, save when it works (E's note 3).
246
- */
247
- export async function runScriptView(id: string, draft?: string): Promise<ScriptRun> {
248
- let res: Response;
249
- try {
250
- res = await fetch(`${API_V1}/script-views/${encodeURIComponent(id)}/run`, {
251
- method: "POST",
252
- credentials: CREDENTIALS,
253
- headers: { "Content-Type": "application/json" },
254
- body: JSON.stringify(draft === undefined ? {} : { source: draft }),
255
- });
256
- } catch {
257
- return { ok: false, stdout: "", truncated: false, ms: 0, code: "unreachable",
258
- caps: { wallClock: false, memory: false, cpu: false },
259
- error: TRANSPORT_TEXT.unreachable };
260
- }
261
- const payload = await body(res);
262
- if (!res.ok) return transportRun(res, payload);
263
- const shaped = payload as Partial<ScriptRun> | null;
264
- return {
265
- ok: shaped?.ok === true,
266
- ...(shaped?.spec !== undefined ? { spec: shaped.spec } : {}),
267
- stdout: typeof shaped?.stdout === "string" ? shaped.stdout : "",
268
- truncated: shaped?.truncated === true,
269
- ms: typeof shaped?.ms === "number" ? shaped.ms : 0,
270
- code: typeof shaped?.code === "string" ? shaped.code : "error",
271
- caps: shaped?.caps ?? { wallClock: false, memory: false, cpu: false },
272
- ...(typeof shaped?.error === "string" ? { error: shaped.error } : {}),
273
- };
274
- }
275
-
276
- // ── the spec, reduced to what a renderer may DRAW ────────────────────────────────────────────
277
- //
278
- // ⛔ A WHITELIST OF SHAPES, NOT A BLACKLIST OF KEYS. E's server already refuses `html`,
279
- // `innerHTML`, `script`, `src`, `srcdoc`, `href`, `style`, `onclick` and `onload` at any depth.
280
- // Repeating that list here would be a SECOND blacklist that has to stay in step with the first,
281
- // and the two would drift the first time either side learns a new attribute. Instead this admits
282
- // only the four shapes the renderer knows how to draw, from scalar leaves — so a key nobody
283
- // anticipated cannot reach the DOM whatever it is called.
284
-
285
- export interface SpecCell { text: string }
286
- export type ScriptSpecKind = "table" | "metrics" | "bars" | "text";
287
- export interface DrawableSpec {
288
- kind: ScriptSpecKind;
289
- title?: string;
290
- /** `table` */
291
- columns?: string[];
292
- rows?: string[][];
293
- /** `metrics` */
294
- items?: { label: string; value: string; note?: string }[];
295
- /** `bars` */
296
- series?: { label: string; value: number; display: string }[];
297
- /** `text` */
298
- body?: string;
299
- }
300
-
301
- const MAX_ROWS = 500;
302
- const MAX_COLS = 40;
303
- const MAX_ITEMS = 60;
304
- const MAX_TEXT = 20_000;
305
-
306
- /** A scalar leaf, as text. Anything else (object, array, function) is NOT drawable and is
307
- * dropped rather than stringified: `[object Object]` in a cell is a bug wearing a value. */
308
- function scalar(v: unknown): string | null {
309
- if (typeof v === "string") return v.slice(0, 2_000);
310
- if (typeof v === "number") return Number.isFinite(v) ? String(v) : null;
311
- if (typeof v === "boolean") return v ? "Yes" : "No";
312
- if (v === null || v === undefined) return "";
313
- return null;
314
- }
315
-
316
- function text(v: unknown, cap = 200): string | undefined {
317
- const s = scalar(v);
318
- return typeof s === "string" && s !== "" ? s.slice(0, cap) : undefined;
319
- }
320
-
321
- /**
322
- * The one door a spec passes through before anything is drawn. Returns `null` for a kind this
323
- * build does not know, which is a legitimate answer and NOT an error: a script whose author
324
- * invented `kind: "sankey"` deserves a sentence naming the kind, not a blank panel.
325
- */
326
- export function renderableSpec(spec: unknown): DrawableSpec | null {
327
- if (!spec || typeof spec !== "object" || Array.isArray(spec)) return null;
328
- const raw = spec as Record<string, unknown>;
329
- const kind = typeof raw.kind === "string" ? raw.kind : "";
330
- const title = text(raw.title, 160);
331
- if (kind === "table") {
332
- const columns = (Array.isArray(raw.columns) ? raw.columns : [])
333
- .slice(0, MAX_COLS).map((c) => scalar(c) ?? "").map((c) => c.slice(0, 120));
334
- if (columns.length === 0) return null;
335
- const rows = (Array.isArray(raw.rows) ? raw.rows : []).slice(0, MAX_ROWS).map((r) => {
336
- const cells = Array.isArray(r) ? r : [r];
337
- return columns.map((_c, i) => scalar(cells[i]) ?? "");
338
- });
339
- return { kind: "table", columns, rows, ...(title ? { title } : {}) };
340
- }
341
- if (kind === "metrics" || kind === "metric") {
342
- const source = Array.isArray(raw.items) ? raw.items
343
- : raw.label !== undefined || raw.value !== undefined ? [raw] : [];
344
- const items = source.slice(0, MAX_ITEMS).flatMap((it) => {
345
- if (!it || typeof it !== "object") return [];
346
- const e = it as Record<string, unknown>;
347
- const label = text(e.label, 120) ?? "";
348
- const value = scalar(e.value);
349
- if (value === null) return [];
350
- const note = text(e.note, 160);
351
- return [{ label, value, ...(note ? { note } : {}) }];
352
- });
353
- if (items.length === 0) return null;
354
- return { kind: "metrics", items, ...(title ? { title } : {}) };
355
- }
356
- if (kind === "bars" || kind === "bar") {
357
- const series = (Array.isArray(raw.series) ? raw.series : []).slice(0, MAX_ITEMS)
358
- .flatMap((it) => {
359
- if (!it || typeof it !== "object") return [];
360
- const e = it as Record<string, unknown>;
361
- const value = typeof e.value === "number" && Number.isFinite(e.value) ? e.value : null;
362
- if (value === null) return [];
363
- return [{ label: text(e.label, 120) ?? "", value,
364
- display: text(e.display, 40) ?? String(value) }];
365
- });
366
- if (series.length === 0) return null;
367
- return { kind: "bars", series, ...(title ? { title } : {}) };
368
- }
369
- if (kind === "text") {
370
- const bodyText = text(raw.body ?? raw.text, MAX_TEXT);
371
- if (bodyText === undefined) return null;
372
- return { kind: "text", body: bodyText, ...(title ? { title } : {}) };
373
- }
374
- return null;
375
- }
376
-
377
- /** The kind a spec CLAIMED, for the sentence shown when this build cannot draw it. */
378
- export function specKindName(spec: unknown): string {
379
- if (!spec || typeof spec !== "object" || Array.isArray(spec)) return "";
380
- const kind = (spec as Record<string, unknown>).kind;
381
- return typeof kind === "string" ? kind.slice(0, 60) : "";
382
- }
383
-
384
- /** The widest bar's value, so every bar is drawn as a share of it. Never zero. */
385
- export function barScale(series: { value: number }[]): number {
386
- return series.reduce((m, s) => Math.max(m, Math.abs(s.value)), 0) || 1;
387
- }