@zenera/cli 1.3.19 → 1.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,278 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Items</title>
7
+ <!-- Calls the functions of api/*.api.py: api('api/items').add_item({...}). Keep it. -->
8
+ <script src="api.js"></script>
9
+ <style>
10
+ :root {
11
+ color-scheme: light dark;
12
+ --bg: #f7f7f8;
13
+ --card: #ffffff;
14
+ --fg: #1d1d1f;
15
+ --muted: #6e6e73;
16
+ --line: #e3e3e6;
17
+ --accent: #2563eb;
18
+ --danger: #b91c1c;
19
+ --gap: 16px;
20
+ --radius: 10px;
21
+ font:
22
+ 14px/1.45 system-ui,
23
+ -apple-system,
24
+ 'Segoe UI',
25
+ Roboto,
26
+ sans-serif;
27
+ }
28
+ @media (prefers-color-scheme: dark) {
29
+ :root {
30
+ --bg: #141416;
31
+ --card: #1e1e21;
32
+ --fg: #ececf0;
33
+ --muted: #9a9aa2;
34
+ --line: #2e2e33;
35
+ --accent: #60a5fa;
36
+ --danger: #f87171;
37
+ }
38
+ }
39
+ * {
40
+ box-sizing: border-box;
41
+ }
42
+ body {
43
+ margin: 0;
44
+ background: var(--bg);
45
+ color: var(--fg);
46
+ }
47
+ main {
48
+ max-width: 900px;
49
+ margin: 0 auto;
50
+ padding: var(--gap);
51
+ display: grid;
52
+ gap: var(--gap);
53
+ }
54
+ header h1 {
55
+ margin: 0;
56
+ font-size: 1.4rem;
57
+ }
58
+ header p {
59
+ margin: 4px 0 0;
60
+ color: var(--muted);
61
+ }
62
+ .card {
63
+ background: var(--card);
64
+ border: 1px solid var(--line);
65
+ border-radius: var(--radius);
66
+ padding: var(--gap);
67
+ min-width: 0;
68
+ }
69
+ .row {
70
+ display: flex;
71
+ flex-wrap: wrap;
72
+ gap: 8px;
73
+ align-items: center;
74
+ }
75
+ .row > * {
76
+ min-width: 0;
77
+ }
78
+ input[type='text'],
79
+ select,
80
+ button {
81
+ font: inherit;
82
+ color: var(--fg);
83
+ background: var(--card);
84
+ border: 1px solid var(--line);
85
+ border-radius: 6px;
86
+ padding: 6px 10px;
87
+ }
88
+ input[type='text'] {
89
+ flex: 1 1 14rem;
90
+ }
91
+ button {
92
+ cursor: pointer;
93
+ }
94
+ button.primary {
95
+ background: var(--accent);
96
+ border-color: var(--accent);
97
+ color: #fff;
98
+ }
99
+ button.danger {
100
+ color: var(--danger);
101
+ }
102
+ button:disabled {
103
+ opacity: 0.6;
104
+ cursor: default;
105
+ }
106
+ ul.list {
107
+ list-style: none;
108
+ margin: 0;
109
+ padding: 0;
110
+ }
111
+ ul.list li {
112
+ display: flex;
113
+ gap: 10px;
114
+ align-items: center;
115
+ padding: 8px 0;
116
+ border-bottom: 1px solid var(--line);
117
+ }
118
+ ul.list li:last-child {
119
+ border-bottom: 0;
120
+ }
121
+ ul.list .title {
122
+ flex: 1;
123
+ min-width: 0;
124
+ overflow-wrap: anywhere;
125
+ }
126
+ ul.list .done .title {
127
+ color: var(--muted);
128
+ text-decoration: line-through;
129
+ }
130
+ .muted {
131
+ color: var(--muted);
132
+ }
133
+ .error {
134
+ color: var(--danger);
135
+ border-color: var(--danger);
136
+ }
137
+ [hidden] {
138
+ display: none !important;
139
+ }
140
+ </style>
141
+ </head>
142
+ <body>
143
+ <main>
144
+ <header>
145
+ <h1 id="title">Items</h1>
146
+ <p id="subtitle">Add, check off and remove items. Changes are saved.</p>
147
+ <p id="user" class="muted" hidden></p>
148
+ </header>
149
+
150
+ <!-- The page: replace from here -->
151
+ <div id="error" class="card error" role="alert" hidden></div>
152
+
153
+ <section class="card">
154
+ <div class="row">
155
+ <input id="new-title" type="text" placeholder="New item" maxlength="200" />
156
+ <button id="add" class="primary">Add</button>
157
+ <select id="show" aria-label="Show">
158
+ <option value="all">All</option>
159
+ <option value="open">Open</option>
160
+ <option value="done">Done</option>
161
+ </select>
162
+ </div>
163
+ </section>
164
+
165
+ <section class="card">
166
+ <p id="status" class="muted">Loading…</p>
167
+ <ul id="items" class="list"></ul>
168
+ </section>
169
+ </main>
170
+
171
+ <script>
172
+ const items = api('api/items');
173
+ const state = { show: 'all', list: [], loading: true };
174
+ const $ = (id) => document.getElementById(id);
175
+
176
+ function showError(err) {
177
+ const box = $('error');
178
+ box.textContent = err ? err.message || String(err) : '';
179
+ box.hidden = !err;
180
+ }
181
+
182
+ // Every change goes through here: call, then reload and draw, or show what failed.
183
+ async function run(work) {
184
+ showError(null);
185
+ try {
186
+ await work();
187
+ await reload();
188
+ } catch (err) {
189
+ showError(err);
190
+ }
191
+ }
192
+
193
+ async function reload() {
194
+ state.loading = true;
195
+ render();
196
+ try {
197
+ state.list = await items.list_items({ show: state.show });
198
+ } finally {
199
+ state.loading = false;
200
+ render();
201
+ }
202
+ }
203
+
204
+ function render() {
205
+ $('status').textContent = state.loading
206
+ ? 'Loading…'
207
+ : state.list.length
208
+ ? `${state.list.length} item${state.list.length === 1 ? '' : 's'}`
209
+ : 'Nothing here yet.';
210
+ const ul = $('items');
211
+ ul.replaceChildren(
212
+ ...state.list.map((item) => {
213
+ const li = document.createElement('li');
214
+ li.className = item.done ? 'done' : '';
215
+ const box = document.createElement('input');
216
+ box.type = 'checkbox';
217
+ box.checked = item.done;
218
+ box.ariaLabel = 'Done';
219
+ box.addEventListener('change', () =>
220
+ run(() => items.set_done({ id: item.id, done: box.checked })),
221
+ );
222
+ const title = document.createElement('span');
223
+ title.className = 'title';
224
+ title.textContent = item.title;
225
+ // No dialogs: the sandbox blocks them. A second click confirms.
226
+ const del = document.createElement('button');
227
+ del.className = 'danger';
228
+ del.textContent = 'Delete';
229
+ del.addEventListener('click', () => {
230
+ if (del.dataset.armed)
231
+ return run(() => items.remove_item({ id: item.id }));
232
+ del.dataset.armed = '1';
233
+ del.textContent = 'Sure?';
234
+ setTimeout(() => {
235
+ delete del.dataset.armed;
236
+ del.textContent = 'Delete';
237
+ }, 3000);
238
+ });
239
+ li.append(box, title, del);
240
+ return li;
241
+ }),
242
+ );
243
+ }
244
+
245
+ async function add() {
246
+ const input = $('new-title');
247
+ const title = input.value.trim();
248
+ if (!title) return;
249
+ $('add').disabled = true;
250
+ await run(async () => {
251
+ await items.add_item({ title });
252
+ input.value = '';
253
+ });
254
+ $('add').disabled = false;
255
+ input.focus();
256
+ }
257
+
258
+ $('add').addEventListener('click', add);
259
+ $('new-title').addEventListener('keydown', (e) => e.key === 'Enter' && add());
260
+ $('show').addEventListener('change', (e) => {
261
+ state.show = e.target.value;
262
+ run(async () => {});
263
+ });
264
+
265
+ // Who is signed in comes from the server (me() in api/items.api.py), never the page.
266
+ items
267
+ .me()
268
+ .then((me) => {
269
+ if (!me) return;
270
+ $('user').textContent = `Signed in as ${me.name}`;
271
+ $('user').hidden = false;
272
+ })
273
+ .catch(showError);
274
+
275
+ run(async () => {});
276
+ </script>
277
+ </body>
278
+ </html>
@@ -216,6 +216,8 @@
216
216
  const charts = [];
217
217
 
218
218
  // Data inlined in <script type="application/json" id="data"> wins; otherwise data.json beside the page.
219
+ // Live data instead: copy api.js beside the page, load it with <script src="api.js"> above
220
+ // this script, and return api('api/report').get_data() here (references/python-functions.md).
219
221
  async function loadData(file = 'data.json') {
220
222
  const inline = document.getElementById('data');
221
223
  if (inline) return JSON.parse(inline.textContent);
@@ -0,0 +1,71 @@
1
+ # Charts, tables and headline numbers
2
+
3
+ For a page built from `/skills/html-page/assets/dashboard.html`. The core
4
+ rules (where it goes, the sandbox, adaptive layout, checks) are in `SKILL.md`.
5
+
6
+ ## Its data
7
+
8
+ - Default: `data.json` beside the page, loaded with `fetch` (the template's
9
+ `loadData()`).
10
+ - Very small data (a few KB) may be inlined instead, in a JSON `<script>`
11
+ block with `id="data"` - `loadData()` uses it when present.
12
+ - Live data instead: copy `api.js` beside the page, add
13
+ `<script src="api.js"></script>` before the page's script, and make
14
+ `loadData()` return `api('api/report').get_data()` - a function of
15
+ `api/report.api.py` that returns the same shape (`python-functions.md`).
16
+ - Ship the data the page needs, not the raw source: aggregate in Python, SQL
17
+ or DuckDB first. Keep it under ~5 MB; past ~20 000 rows send aggregates plus
18
+ the top rows, and say so on the page.
19
+ - Plain JSON shapes the page can use directly: `{ "title", "subtitle",
20
+ "source", "updated", "kpis": [...], "rows": [{...}] }`, or one array per
21
+ chart. Numbers as numbers, dates as ISO strings (`2026-03-31`), no `NaN`
22
+ (write `null`).
23
+ - Several pages can share one data file by a relative path that starts with
24
+ `..`.
25
+
26
+ ## Sizing
27
+
28
+ - Chart cards: `grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr))`;
29
+ KPI cards `minmax(150px, 1fr)`. `.wide` spans the full row.
30
+ - Charts: width 100% of their card, a fixed height (`320px`, `260px` under
31
+ 520 px). Never size charts in `vh` or by the window. The template's
32
+ `chart()` resizes them with a `ResizeObserver`, so they follow the panel
33
+ being dragged, not only the window, and re-theme on light/dark.
34
+ - Tables: the template's `table()` collapses columns that do not fit and
35
+ paginates. Put the most important columns first.
36
+
37
+ ## Components
38
+
39
+ Use these, from the CDN URLs in the template, pinned to the version shown
40
+ there:
41
+
42
+ | Need | Use |
43
+ | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
44
+ | Charts of any kind - bar, line, area, pie, scatter, heatmap, treemap, sankey, funnel, gauge | ECharts (`chart()` helper). Same library as the chat's charts, so `a2ui-charts` advice on choosing a chart type applies. |
45
+ | Tables - sort, filter per column, pagination, many rows | Tabulator (`table()` helper) |
46
+ | Headline numbers with change vs. a previous period | KPI cards (`kpis()` helper) |
47
+ | Filters across the whole page | `<select>` per field (`filters()` helper); `<input type="date">` or `type="range"` for ranges |
48
+ | Number, money, percent and date formatting | `Intl.NumberFormat` and `Intl.DateTimeFormat` (`fmt` helper) - never format by hand |
49
+ | Long time series | ECharts `dataZoom` (`inside`, plus `slider` on wide pages) |
50
+ | Text sections, notes, method | Plain HTML in a `.card`; `<details>` for anything secondary |
51
+ | Tabs between views | Buttons that show and hide sections; keep the active tab in `location.hash` |
52
+
53
+ Avoid: CSS frameworks and Tailwind's browser build (heavy, and the template
54
+ styles are enough), React or Vue (no build step here), Leaflet or any map
55
+ with tiles (blocked - use an ECharts `map` with GeoJSON you write to the
56
+ folder), Plotly unless a chart type ECharts lacks is needed (it is ~3 MB).
57
+
58
+ Every chart and table has a short heading saying what it shows, with units.
59
+ The page footer names the source and the date of the data.
60
+
61
+ ## Interactivity
62
+
63
+ - One `render(state)` draws everything from the filtered rows; every control
64
+ just updates `state` and calls it. KPIs, charts and table then always agree.
65
+ - Tooltips on every chart (on by default in `chart()`), `confine: true` so
66
+ they stay inside a narrow panel.
67
+ - Clicking a bar or slice may set a filter: `bar.on('click', (p) => ...)`
68
+ with `p.name` the category clicked; the handler survives a theme switch.
69
+ - Show "No data for these filters" rather than an empty chart.
70
+ - Filters over live data with many rows: pass them to the function
71
+ (`get_data({ region })`) and filter in SQL, instead of loading every row.
@@ -0,0 +1,200 @@
1
+ # Python functions a page calls (`*.api.py`)
2
+
3
+ For a page that shows live data or saves changes. The core rules (where it
4
+ goes, the sandbox, adaptive layout, checks) are in `SKILL.md`.
5
+
6
+ Every **public function** in an `*.api.py` beside the page can be called from
7
+ the page's JavaScript by name, with its arguments as an object, and returns
8
+ JSON. No server code, routes or framework: write plain Python functions.
9
+
10
+ ```js
11
+ const items = api('api/items'); // api/items.api.py
12
+ const list = await items.list_items({ show: 'open' }); // list_items(show="open")
13
+ await items.add_item({ title: 'Milk' }); // add_item(title="Milk")
14
+ ```
15
+
16
+ The app template (`/skills/html-page/assets/app`) is a working example: a
17
+ list in SQLite with add, check off, filter and delete. Rename
18
+ `api/items.api.py` to what it holds; one `*.api.py` per area of the app
19
+ (`orders.api.py`, `customers.api.py`), shared helpers in plain `.py` files
20
+ beside them.
21
+
22
+ ## Writing the functions
23
+
24
+ ```python
25
+ from zenera.api import HttpError, connect
26
+
27
+ def _db(): # `_`: not callable from the page
28
+ db = connect("app.sqlite") # api/.data/app.sqlite, made on first use
29
+ db.execute("CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL, status TEXT)")
30
+ return db
31
+
32
+ def list_orders(status: str = "open"):
33
+ """Orders with this status, newest first."""
34
+ return _db().execute(
35
+ "SELECT * FROM orders WHERE status = ? ORDER BY id DESC", (status,)
36
+ ).fetchall() # rows are dicts: returned as JSON as they are
37
+
38
+ def set_status(id: int, status: str):
39
+ if status not in ("open", "paid", "cancelled"):
40
+ raise HttpError(400, f"unknown status {status!r}")
41
+ db = _db()
42
+ with db: # commits, or rolls back on an exception
43
+ cur = db.execute("UPDATE orders SET status = ? WHERE id = ?", (status, id))
44
+ if cur.rowcount == 0:
45
+ raise HttpError(404, f"no order {id}")
46
+ return {"id": id, "status": status}
47
+ ```
48
+
49
+ The rules:
50
+
51
+ - **Callable** = defined in the file, name not starting with `_`. Imported
52
+ functions and `_helpers` are not reachable from the page.
53
+ - **Arguments** are keyword arguments from the JS object. Give each a type
54
+ annotation (`int`, `float`, `bool`, `str`) and a default when optional: a
55
+ value of the wrong type, a missing or an unknown argument is a 400 the page
56
+ sees, with the reason. Lists and dicts arrive as they were sent.
57
+ - **Return** what the page needs, JSON-ready: dicts, lists, numbers, strings,
58
+ `None`. Dates become ISO strings, `Decimal` a number, `NaN` `null`. Never
59
+ return bytes: write a file (below) and return its name.
60
+ - **Errors**: `raise HttpError(status, "message the user can act on")` -
61
+ 400 for bad input, 404 for a missing record, 403 for not allowed. Any other
62
+ exception is a 500 with its message; the traceback goes to the log.
63
+ - **Each call is a new process.** Nothing kept in a global variable is there
64
+ the next time. Keep state in the database or in files.
65
+ - **Fast and small**: a call has 30 seconds and a few MB of arguments and
66
+ result. Page through large tables (`limit`, `offset` arguments) and
67
+ aggregate in SQL instead of returning every row.
68
+ - `print()` goes to the log, not to the page: use it freely to debug.
69
+ - **Validate everything** that comes from the page, and always use `?`
70
+ placeholders in SQL - never build SQL from arguments with `f"..."`.
71
+
72
+ ## Data
73
+
74
+ - `connect("app.sqlite")`: the page's SQLite database in the `.data` folder
75
+ beside the `.api.py` (WAL, foreign keys on, rows as dicts). Create tables
76
+ with `CREATE TABLE IF NOT EXISTS` in one `_db()` helper, as above, so a
77
+ fresh copy starts by itself.
78
+ - `data_path("exports/report.csv")`: a path in the same folder, for other
79
+ files it keeps.
80
+ - A file the page should download or show (a CSV export, a chart image):
81
+ write it next to the page instead, e.g. `../exports/orders.csv` from
82
+ `api/`, and return the relative name; the page links to it.
83
+ - An external database or service: connect from the function, with its
84
+ address and credentials from environment variables
85
+ (`os.environ["DATABASE_URL"]`). Only the project's `.env` names reach
86
+ them. Never write a secret into a file of the page, and never return it.
87
+ - Packages: prefer the standard library (`sqlite3`, `json`, `csv`,
88
+ `urllib.request`). Anything else must be installed in the sandbox
89
+ (`pip install --user <pkg>`); say which in your reply.
90
+
91
+ ## Who is calling
92
+
93
+ Every call runs as the signed-in user who opened the page, as the chat's own
94
+ commands do. `zenera.identity()` says who that is:
95
+
96
+ | Field | What it is |
97
+ | --------- | ---------------------------------------------------------------------------------------- |
98
+ | `.id` | the user's id: stable, the one to store |
99
+ | `.email` | their email, or `None` |
100
+ | `.name` | their display name, or `None` |
101
+ | `.role` | `owner`, `editor`, `viewer` or `admin` in this project, or `None` |
102
+ | `.source` | `"host"` when the app signed them in; `"local"` on a test server (anyone could claim it) |
103
+
104
+ `zenera.identity()` is `None` when nobody is signed in.
105
+
106
+ The page itself cannot know who is signed in: give it a function that says so.
107
+
108
+ ```python
109
+ import zenera
110
+ from zenera.api import HttpError
111
+
112
+ def me():
113
+ """Who is using the page, for its header."""
114
+ u = zenera.identity()
115
+ if u is None:
116
+ return None
117
+ return {"id": u.id, "name": u.name or u.email or u.id, "role": u.role}
118
+
119
+ def _user():
120
+ u = zenera.identity()
121
+ if u is None:
122
+ raise HttpError(401, "sign in to use this page")
123
+ return u
124
+
125
+ def my_notes():
126
+ """The caller's own notes."""
127
+ return _db().execute("SELECT * FROM notes WHERE owner = ?", (_user().id,)).fetchall()
128
+
129
+ def delete_note(id: int):
130
+ """Only the note's owner, or an owner of the project, may delete it."""
131
+ u = _user()
132
+ db = _db()
133
+ with db:
134
+ cur = db.execute(
135
+ "DELETE FROM notes WHERE id = ? AND (owner = ? OR ? = 'owner')", (id, u.id, u.role)
136
+ )
137
+ if cur.rowcount == 0:
138
+ raise HttpError(404, f"no note {id} of yours")
139
+ return {"removed": id}
140
+ ```
141
+
142
+ - **Who calls comes only from `zenera.identity()`**, never from the page: no
143
+ `user_id` or `role` argument. Anything the page sends, a user can change.
144
+ - Store `.id` (an `owner` column), never the email or name: those can change.
145
+ - Check permissions in the function (`HttpError(403, ...)`); hiding a button
146
+ in the page is not a check.
147
+ - In the page: `const me = await api('api/users').me();`, then show
148
+ `me.name` in the header, and hide what `me.role` may not do.
149
+ - When it matters: a page in a chat's workspace already belongs to one user
150
+ (each has their own copy and `.data`). Identity matters for data shared
151
+ between users: an external database, or a page published in the project's
152
+ assets.
153
+ - Testing from the shell: your commands already run as the chat's user. To
154
+ try another one, set the variables for one command:
155
+ `ZEN_USER_ID=u2 ZEN_USER_ROLE=viewer python3 -m zenera.api api/notes.api.py my_notes`.
156
+
157
+ ## Calling them from the page
158
+
159
+ - Copy `/skills/html-page/assets/api.js` beside the page and load it once,
160
+ **by a relative path**: `<script src="api.js"></script>` (from a page in a
161
+ subfolder: `../api.js`). Never edit it.
162
+ - `api('<path to the file, relative to the page, without .api.py>')` gives an
163
+ object whose methods are the file's functions:
164
+ `api('api/orders').set_status({ id: 7, status: 'paid' })`.
165
+ - Always pass **one object** of named arguments (or nothing). Each call
166
+ returns a promise of what the function returned.
167
+ - A failure rejects with an `ApiError`: `.message` is the `HttpError`
168
+ message, `.status` the HTTP status (0: not reachable). Show the message on
169
+ the page.
170
+ - After a change, load the data again from the function that lists it, so
171
+ the page shows what is really saved. Disable a button while its call runs.
172
+ The app template's `run(work)` does all three.
173
+
174
+ | JavaScript | Request | Python |
175
+ | --------------------------------------------- | ----------------------------- | ---------------------------- |
176
+ | `api('api/orders').list_orders()` | `POST api/orders/list_orders` | `list_orders()` |
177
+ | `api('api/orders').set_status({id: 7, ...})` | `POST api/orders/set_status` | `set_status(id=7, ...)` |
178
+ | `api('../api/users').me()` (page in a folder) | `POST ../api/users/me` | `me()` in `api/users.api.py` |
179
+
180
+ A plain link works for reads too: `api/orders/list_orders?status=open`
181
+ (arguments as text, converted by their annotations).
182
+
183
+ ## Test before you link it
184
+
185
+ Run every function from the shell, against a scratch copy of the data:
186
+
187
+ ```sh
188
+ cd /workspace/pages/todo
189
+ export ZEN_APP_DATA=/tmp/todo-test # leaves the page's own data alone
190
+ python3 -m zenera.api api/items.api.py # the callable functions and their arguments
191
+ python3 -m zenera.api api/items.api.py add_item '{"title": "Milk"}'
192
+ python3 -m zenera.api api/items.api.py list_items
193
+ python3 -m zenera.api api/items.api.py set_done '{"id": 1, "done": true}'
194
+ python3 -m zenera.api api/items.api.py remove_item '{"id": 99}' # expect: 404: no item 99
195
+ rm -rf /tmp/todo-test; unset ZEN_APP_DATA
196
+ grep -noE "api\('[^']+'\)" *.html # each path, + .api.py, must exist relative to the page
197
+ ```
198
+
199
+ Every name the page calls must be a function the listing showed, with the
200
+ argument names it shows.
@@ -72,5 +72,6 @@ agents:
72
72
  #
73
73
  # The skills in agents/skills, listed in the prompt for it to load when a
74
74
  # case needs one — among them a2ui and a2ui-charts, for forms and charts,
75
- # data-analysis, and html-dashboard for interactive pages.
75
+ # data-analysis, and html-page for dashboards and for pages that call
76
+ # Python to read and change data.
76
77
  skills: {}