@sigrix-io/gatehouse 0.1.0 → 0.2.0

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.
package/README.md CHANGED
@@ -1,14 +1,24 @@
1
1
  # Gatehouse
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/@sigrix-io/gatehouse)](https://www.npmjs.com/package/@sigrix-io/gatehouse)
4
+ [![CI](https://github.com/sigrix-io/gatehouse/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/sigrix-io/gatehouse/actions/workflows/ci.yml)
5
+ [![Licence](https://img.shields.io/github/license/sigrix-io/gatehouse)](https://github.com/sigrix-io/gatehouse/blob/main/LICENSE)
6
+
3
7
  A browser client for [Postern](https://github.com/sigrix-io/postern). Given a runner's `describe` and `status` documents, Gatehouse draws a run page (a form, a run button, the steps as they happen, the result and its usage) and connects it to Postern's four verbs over `fetch`. It holds nothing else.
4
8
 
5
- Four scripts and a stylesheet. No build step, no runtime dependency, no second origin.
9
+ Beside the run page, four blocks a host draws from its own data, for a page that shows several apps at once: a card per app, a list of them, a run history and a usage summary. They are handed documents rather than clients, so drawing a page of apps wakes none of their runners.
10
+
11
+ Five scripts and a stylesheet. No build step, no runtime dependency, no second origin.
6
12
 
7
13
  > **0.x.** Nothing is stable before 1.0; pin the minor. See `VERSIONING.md`.
8
14
 
9
15
  ## Use it
10
16
 
11
- Serve the five files from `src/` (or install `@sigrix-io/gatehouse` and serve them from `node_modules`), and load the scripts in this order:
17
+ ```sh
18
+ npm install @sigrix-io/gatehouse
19
+ ```
20
+
21
+ Serve the six files it installs in `node_modules/@sigrix-io/gatehouse/src/` (or copy them from this repository's `src/`; there is nothing to build). A run page loads four of the scripts, in this order:
12
22
 
13
23
  ```html
14
24
  <link rel="stylesheet" href="gatehouse.css">
@@ -38,6 +48,8 @@ Each script is an IIFE that adds to one global, `window.Gatehouse`. `window.Sigr
38
48
 
39
49
  `renderer.load()` reads `describe` and `status` and draws the page. Running, stopping and retrying are the page's own buttons.
40
50
 
51
+ A page of apps loads `host_blocks.js`, alone or after the four; see [Host blocks](#host-blocks).
52
+
41
53
  ## The rules that are easy to erode
42
54
 
43
55
  Each is held by a test rather than by memory (`tests/contract.test.js` and the suites beside it).
@@ -46,7 +58,8 @@ Each is held by a test rather than by memory (`tests/contract.test.js` and the s
46
58
  - **No markup from the agent.** `innerHTML` appears nowhere. Agent output and every streamed `delta.text` reach the page through `textContent`.
47
59
  - **No `EventSource`, and no retry loop around the stream.** It cannot POST and it reconnects on its own, and a reopened stream is a new run: the way a client spends someone's money twice. A disconnect is a cancel, so Stop is an `AbortController`.
48
60
  - **Zero imports, and no distributor.** Nothing here names a marketplace or a listing.
49
- - **Documents are handed in.** The composition and the choice arrive as data from whoever mounted the page. Fetching them here would be reaching for a fifth verb, and Postern has four.
61
+ - **Documents are handed in.** The composition and the choice arrive as data from whoever mounted the page, and so does everything the host blocks draw. Fetching them here would be reaching for a fifth verb, and Postern has four.
62
+ - **A link goes only to a web address.** An address a runner's author wrote becomes a link only when it is an absolute `http` or `https` one, so a `javascript:` address in `describe` is never something a click runs.
50
63
 
51
64
  ## The composition
52
65
 
@@ -78,9 +91,117 @@ The form shows only the chosen option's inputs; a chosen option's `required` add
78
91
 
79
92
  `options.hosted: true` says the page's operator runs the runner, not the person reading it. It changes only what a failure may quote back: an `agent_error` is the one refusal whose message carries what a model provider said about the *operator's* credentials, so on a hosted page it is withheld and the reader sees the next move alone.
80
93
 
94
+ ## Several apps on one page
95
+
96
+ A `RunRenderer` writes its ids under a scope of its own (`run-1-field-prompt` for the first renderer a page makes, `run-2-field-prompt` for the second), so two on one page never share one and each `<label>` stays bound to its own field. To find a field, look for its `name`, which is its input's key, inside the container you handed in: `container.querySelector('[name="prompt"]')`. The id is the renderer's own business.
97
+
98
+ ## Host blocks
99
+
100
+ A page listing several apps should not ask each runner how it is: a runner that is asleep would be woken to draw one card. These blocks are drawn from documents the host builds from what it already holds, and they fetch nothing.
101
+
102
+ ```html
103
+ <link rel="stylesheet" href="gatehouse.css">
104
+ <div id="apps"></div>
105
+ <div id="usage"></div>
106
+ <div id="runs"></div>
107
+
108
+ <script src="host_blocks.js"></script>
109
+ <script>
110
+ new Gatehouse.AppList(document.getElementById('apps'), data.apps).render();
111
+ new Gatehouse.UsageSummary(document.getElementById('usage'), data.usage).render();
112
+ new Gatehouse.RunHistory(document.getElementById('runs'), data.runs).render();
113
+ </script>
114
+ ```
115
+
116
+ | Constructor | Draws | Options |
117
+ | --- | --- | --- |
118
+ | `AppCard(container, summary, options)` | one app summary | `headingLevel` (2 to 6, default 3), `openLabel` (default `Open`), `locale`, `timeZone` |
119
+ | `AppList(container, summaries, options)` | a card per summary, in the order given | `emptyText`, and `AppCard`'s |
120
+ | `RunHistory(container, rows, options)` | a table of run rows, in the order given | `showApp` (default `true`), `emptyText`, `locale`, `timeZone` |
121
+ | `UsageSummary(container, usage, options)` | a period's figures, its caps, its runs per day and a table by app | `headingLevel`, `locale`, `timeZone` |
122
+
123
+ Each has `render()`, and `update(data)`, which replaces its document and draws again. `locale` and `timeZone` default to the reader's own. `Gatehouse.hostData` carries the readers the blocks use (`readAppSummary`, `readRunRow`, `readUsageSummary`, each answering `{ value }` or `{ refusal }`), so a host can test what it builds against them.
124
+
125
+ ### The documents
126
+
127
+ Each carries `"v": 1`. A block refuses a document in a version it does not read, or one missing what its shape requires, whole, in a sentence saying why; a list draws the rest and says how many it left out. A member a shape does not name is ignored.
128
+
129
+ **App summary.** `app_id`, `name` and `state` are required. `state` is `ready`, `needs_key`, `starting`, `unavailable` or `ended`; one this client does not know is shown as spelled, in no tone. `access_ends_at` and `last_run_at` may be null, and `run_url` may be a path on the host's own page.
130
+
131
+ ```json
132
+ {
133
+ "v": 1,
134
+ "app_id": "the host's id, opaque here",
135
+ "name": "Property copy",
136
+ "summary": "Writes a property's description from the agent's notes.",
137
+ "by": "fernhill",
138
+ "state": "needs_key",
139
+ "missing_keys": [{"env": "CRM_API_KEY", "purpose": "Reads your contacts", "signup_url": "https://crm.example.com/keys"}],
140
+ "access_ends_at": "2027-10-01T00:00:00Z",
141
+ "last_run_at": "2026-09-30T15:47:12Z",
142
+ "run_url": "/apps/a-property-copy/run"
143
+ }
144
+ ```
145
+
146
+ **Run row.** `app_id`, `app_name`, `started_at`, `input_tokens`, `output_tokens` and `outcome` are required. `outcome` is `done`, `timed_out`, `failed` or `cancelled`; `duration_seconds`, `model`, `cost_estimate` and `detail` may be null; `currency`, an ISO 4217 code, goes beside a cost. `detail` is the host's own sentence about how the run ended, drawn as given, so it is written for the person reading. A runner's error message is not one: on a hosted run it can carry what a provider said about the operator's key (see [Hosted runs](#hosted-runs)).
147
+
148
+ ```json
149
+ {
150
+ "v": 1,
151
+ "run_id": "r-77ae",
152
+ "app_id": "a-lead-digest",
153
+ "app_name": "Lead digest",
154
+ "started_at": "2026-09-30T11:02:40Z",
155
+ "duration_seconds": 240,
156
+ "model": "claude-sonnet-4-6",
157
+ "input_tokens": 52210,
158
+ "output_tokens": 0,
159
+ "cost_estimate": 0.15663,
160
+ "currency": "USD",
161
+ "outcome": "timed_out",
162
+ "detail": "Stopped at the 240-second limit."
163
+ }
164
+ ```
165
+
166
+ **Usage summary.** A `caps` member that is null or absent draws no meter. `runs_used` is what the host's own limit counts, over the last 24 hours, and the sentence above its meter says so. A bare date (`period.start`, `by_day[].date`) names a day and is written as that day in any time zone.
167
+
168
+ ```json
169
+ {
170
+ "v": 1,
171
+ "period": {"label": "September 2026", "start": "2026-09-01", "end": "2026-09-30"},
172
+ "runs": 128,
173
+ "runs_done": 124,
174
+ "input_tokens": 1391600,
175
+ "output_tokens": 396700,
176
+ "cost_estimate": 8.46,
177
+ "currency": "USD",
178
+ "caps": {"runs_per_day": 10, "runs_used": 3, "spend_per_period": 25.0},
179
+ "by_app": [{"app_id": "a-property-copy", "app_name": "Property copy", "runs": 71, "input_tokens": 852000, "output_tokens": 248500, "cost_estimate": 4.62}],
180
+ "by_day": [{"date": "2026-09-01", "runs": 5}]
181
+ }
182
+ ```
183
+
184
+ ### What every block keeps
185
+
186
+ - **Text only.** Every string reaches the page through `textContent`: an app's name and summary are its author's prose, and a model's name is whatever a runner reported.
187
+ - **A cost is an estimate, and says so.** It is the host's sum from token counts and a price list, not a bill, and the specification calls a runner's own `cost_usd` advisory too.
188
+ - **A link is a web address.** `signup_url` must be an absolute `http` or `https` address, and `run_url` may also be a path on the host's page; anything else draws no link.
189
+ - **Nothing is fetched.** A test spies on `fetch` while every block draws.
190
+
81
191
  ## Styling
82
192
 
83
- `gatehouse.css` styles every class the renderer draws, and `tests/stylesheet.test.js` fails when one has no rule. Colours are custom properties on `.run-shell`: each `--run-*` reads a host's `--sx-*` token when the page defines one and falls back to its own value, so the file works alone and a host can theme it. Dark values apply under `[data-theme="dark"]` on any ancestor.
193
+ `gatehouse.css` styles every class the scripts draw, the run page's `run-*` and the host blocks' `gh-*`, and `tests/stylesheet.test.js` fails when one has no rule. Colours are custom properties on `.run-shell` and on `.gh-block`, the root of every host block: each `--run-*` reads a host's `--sx-*` token when the page defines one and falls back to its own value, so the file works alone and a host can theme it. A status colour comes as a fill (`--run-ok`, `--run-warn`, `--run-danger`) for borders and bars, and as an ink (`--run-ok-text` and the rest, from a host's `--sx-*-text`) for words. Dark values apply under `[data-theme="dark"]` on any ancestor.
194
+
195
+ ## Where it fits
196
+
197
+ Gatehouse is one of the open-source projects [Sigrix](https://sigrix.io) publishes, and the page between a person and a runner. On Sigrix it draws the buyer's run page and the seller's preview; elsewhere it meets:
198
+
199
+ - **[Postern](https://github.com/sigrix-io/postern)**, the protocol whose four verbs it calls. Its [§2.3](https://github.com/sigrix-io/postern/blob/main/SPEC.md#23-browser-clients) says what a runner owes a browser client, and why the default is to refuse.
200
+ - **[sigrix-runtime](https://github.com/sigrix-io/sigrix-runtime)** (`pip install sigrix-runtime`), a runner to point it at: the one inside every bundle Sigrix delivers, which can also serve an MCP server's tools as one agent. Start it with `--allow-origin` set to the page's origin.
201
+ - **[postern-conformance](https://pypi.org/project/postern-conformance/)** (`pip install postern-conformance`), which reports the level a runner really meets before you draw a page for it.
202
+ - **[Bailey](https://github.com/sigrix-io/bailey)**, the open-source assistant: the app planned for its 0.1 draws a solution's apps with Gatehouse.
203
+
204
+ Every project Sigrix publishes, and a map of how they connect: [sigrix.io/open-source](https://sigrix.io/open-source).
84
205
 
85
206
  ## Tests
86
207
 
@@ -89,7 +210,7 @@ npm ci
89
210
  npm test
90
211
  ```
91
212
 
92
- The scripts are loaded the way a browser loads them, read and evaluated in order, rather than imported. The fixtures in `tests/fixtures/postern_describe/` are real documents: the Postern conformance fake's, a pipeline crew's, and an MCP server's as a runner builds it from a real `tools/list` answer.
213
+ The scripts are loaded the way a browser loads them, read and evaluated in order, rather than imported. The fixtures in `tests/fixtures/postern_describe/` are real documents: the Postern conformance fake's, a pipeline crew's, and an MCP server's as a runner builds it from a real `tools/list` answer. Those in `tests/fixtures/host_blocks/` are the three documents a host hands the blocks, one of each state and outcome among them.
93
214
 
94
215
  ## Licence
95
216
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sigrix-io/gatehouse",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A browser client for Postern: draws a run page from a describe document and connects it to the four verbs. No build step and no dependencies.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Sigrix",
@@ -28,6 +28,7 @@
28
28
  "./run_view_model.js": "./src/run_view_model.js",
29
29
  "./refusal_copy.js": "./src/refusal_copy.js",
30
30
  "./run_renderer.js": "./src/run_renderer.js",
31
+ "./host_blocks.js": "./src/host_blocks.js",
31
32
  "./gatehouse.css": "./src/gatehouse.css",
32
33
  "./package.json": "./package.json"
33
34
  },
@@ -38,7 +39,7 @@
38
39
  "test": "vitest run"
39
40
  },
40
41
  "devDependencies": {
41
- "jsdom": "30.1.0",
42
- "vitest": "5.0.1"
42
+ "jsdom": "30.1.1",
43
+ "vitest": "5.0.3"
43
44
  }
44
45
  }
package/src/gatehouse.css CHANGED
@@ -1,16 +1,18 @@
1
- /* Styles for Gatehouse, the Postern run renderer.
1
+ /* Styles for Gatehouse: the Postern run renderer and the host blocks.
2
2
  *
3
- * The scripts draw `run-*` classes and carry no CSS of their own, so a page
4
- * that mounts the renderer links this file. Every class the renderer emits has
5
- * a rule here, which `tests/stylesheet.test.js` checks.
3
+ * The scripts draw `run-*` classes (the run page) and `gh-*` classes (the
4
+ * blocks a host draws from its own data) and carry no CSS of their own, so a
5
+ * page that mounts either links this file. Every class they emit has a rule
6
+ * here, which `tests/stylesheet.test.js` checks.
6
7
  *
7
- * Colours are custom properties on `.run-shell`: each `--run-*` reads a host's
8
- * `--sx-*` token when the page defines one and falls back to the value beside
9
- * it, so the stylesheet works alone and a host can theme it. Light values are
10
- * unprefixed; dark ones sit under `[data-theme="dark"]` on any ancestor.
8
+ * Colours are custom properties on `.run-shell` and `.gh-block`, the root of
9
+ * every block: each `--run-*` reads a host's `--sx-*` token when the page
10
+ * defines one and falls back to the value beside it, so the stylesheet works
11
+ * alone and a host can theme it. Light values are unprefixed; dark ones sit
12
+ * under `[data-theme="dark"]` on any ancestor.
11
13
  */
12
14
 
13
- .run-shell {
15
+ .run-shell, .gh-block {
14
16
  --run-line: var(--sx-line, #E6E8EE);
15
17
  --run-surface: var(--sx-surface, #FFFFFF);
16
18
  --run-surface-2: var(--sx-surface-2, #F7F8FB);
@@ -19,23 +21,36 @@
19
21
  --run-text-3: var(--sx-text-3, #616879);
20
22
  --run-brand: var(--sx-brand, #2A33C4);
21
23
  --run-brand-text: var(--sx-brand-text, #1A1F6B);
22
- /* A literal, not var(--sx-ok): --sx-ok is a fill and #1F9D55 measured
23
- 3.49:1 as this tick's ink on white. #146B3A is 6.57:1. The dark value
24
- below is left on --sx-ok, which is a light green there and fine. */
25
- --run-ok: #146B3A;
24
+ /* Fills, for borders and bars. A status fill is too light to be read as
25
+ words on a light surface: --sx-ok's #1F9D55 measured 3.49:1 as a tick's
26
+ ink on white, and --sx-danger's #DC2C50 4.38:1 on --sx-surface-2. */
27
+ --run-ok: var(--sx-ok, #1F9D55);
26
28
  --run-warn: var(--sx-warn, #C77800);
27
29
  --run-danger: var(--sx-danger, #DC2C50);
30
+ /* Inks, for words: a host's -text token where it has one, and fallbacks
31
+ that read 6.57:1, 6.09:1 and 6.48:1 on white. */
32
+ --run-ok-text: var(--sx-ok-text, #146B3A);
33
+ --run-warn-text: var(--sx-warn-text, #8C5600);
34
+ --run-danger-text: var(--sx-danger-text, #B3243F);
28
35
  --run-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
36
+ color: var(--run-text);
37
+ }
38
+ .run-shell {
29
39
  display: grid;
30
40
  grid-template-columns: minmax(0, 1fr) 300px;
31
41
  grid-template-areas: "head rail" "form rail" "controls rail" "output rail";
32
42
  gap: 0 24px;
33
43
  align-items: start;
34
- color: var(--run-text);
35
44
  }
36
45
  @media (max-width: 960px) {
37
46
  .run-shell { grid-template-columns: minmax(0, 1fr); grid-template-areas: "head" "rail" "form" "controls" "output"; }
38
47
  }
48
+ /* Stated here rather than left to a host's reset, which a page linking only
49
+ * this file does not have. A browser draws `select` border-box and `input` and
50
+ * `textarea` content-box, so without it a full-width field spills past its card
51
+ * by its own padding and border while the select beside it fits. */
52
+ .run-shell, .run-shell *, .run-shell *::before, .run-shell *::after,
53
+ .gh-block, .gh-block *, .gh-block *::before, .gh-block *::after { box-sizing: border-box; }
39
54
 
40
55
  /* ---------- header ---------- */
41
56
  .run-header { grid-area: head; margin-bottom: 18px; }
@@ -87,11 +102,13 @@
87
102
  * because the default happens to be green converges with a missing one the
88
103
  * moment the default moves, and the two are the whole point of the list. */
89
104
  .run-credential-tick { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--run-text-3); }
90
- .run-credential.is-satisfied .run-credential-tick { color: var(--run-ok); }
91
- .run-credential.is-missing .run-credential-tick { color: var(--run-danger); }
105
+ .run-credential.is-satisfied .run-credential-tick { color: var(--run-ok-text); }
106
+ .run-credential.is-missing .run-credential-tick { color: var(--run-danger-text); }
92
107
  .run-credential-purpose { font-size: 11.5px; color: var(--run-text-3); }
93
108
  .run-credential-where { font-size: 11.5px; color: var(--run-text-2); margin: 0 0 10px; }
94
- .run-credential-link { font-size: 11.5px; margin-left: 6px; }
109
+ /* The words around it, underlined. Left to the browser, a link is its own
110
+ * blue, which reads 1.9:1 on the dark surface. */
111
+ .run-credential-link { font-size: 11.5px; margin-left: 6px; color: inherit; }
95
112
 
96
113
  .run-tools { margin: 0 0 8px; }
97
114
  .run-tool-list { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 5px; }
@@ -198,7 +215,141 @@
198
215
  .run-usage:empty { display: none; }
199
216
  .run-refuse { border-left: 3px solid var(--run-danger); padding: 14px 16px; background: var(--run-surface-2); border-radius: 0 10px 10px 0; margin: 0; font-size: 13.5px; }
200
217
 
201
- [data-theme="dark"] .run-shell {
218
+ /* ---------- host blocks ----------
219
+ *
220
+ * Drawn from a host's own data rather than from a runner, and themed through
221
+ * the same tokens. Each block's root carries `.gh-block`, which declares them,
222
+ * so a block works alone on a page that has no `.run-shell`. */
223
+
224
+ .gh-refuse { border-left: 3px solid var(--run-danger); padding: 12px 14px; background: var(--run-surface-2); border-radius: 0 10px 10px 0; margin: 0; font-size: 13px; color: var(--run-text); }
225
+ .gh-note, .gh-empty { font-size: 12.5px; color: var(--run-text-3); margin: 10px 0 0; max-width: 72ch; }
226
+ .gh-empty { margin: 0; }
227
+
228
+ /* A state or an outcome: the words carry it, in the status ink, and a dot of
229
+ * the status fill sits before them. Neither the colour nor the dot is the
230
+ * only way to tell one from another. */
231
+ .gh-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; color: var(--run-text-3); white-space: nowrap; }
232
+ .gh-status::before { content: ""; flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--run-text-3); }
233
+ .gh-status--ok { color: var(--run-ok-text); }
234
+ .gh-status--ok::before { background: var(--run-ok); }
235
+ .gh-status--caution { color: var(--run-warn-text); }
236
+ .gh-status--caution::before { background: var(--run-warn); }
237
+ .gh-status--blocked { color: var(--run-danger-text); }
238
+ .gh-status--blocked::before { background: var(--run-danger); }
239
+ .gh-status--quiet { color: var(--run-text-3); }
240
+
241
+ /* ---------- an app ---------- */
242
+ .gh-app {
243
+ display: flex; flex-direction: column; gap: 8px; min-width: 0;
244
+ background: var(--run-surface); border: 1px solid var(--run-line);
245
+ border-radius: 14px; padding: 16px;
246
+ }
247
+ .gh-app-head { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 6px 12px; }
248
+ /* An app's name is its author's, and may be one long word. */
249
+ .gh-app-name { font-size: 16px; font-weight: 650; letter-spacing: -0.01em; margin: 0; min-width: 0; overflow-wrap: anywhere; }
250
+ .gh-app-summary { font-size: 13px; line-height: 1.5; color: var(--run-text-2); margin: 0; overflow-wrap: anywhere; }
251
+ .gh-app-by { font-size: 12px; color: var(--run-text-3); margin: 0; }
252
+ /* The run page's credential row, in the card: an inline flow, for the same
253
+ * reason as `.run-credential`. */
254
+ .gh-app-keys { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
255
+ .gh-app-key { font-size: 12.5px; line-height: 1.5; overflow-wrap: anywhere; }
256
+ .gh-app-key-env { font-family: var(--run-mono); font-size: 11.5px; color: var(--run-text); }
257
+ .gh-app-key-tick { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--run-danger-text); }
258
+ .gh-app-key-purpose { font-size: 11.5px; color: var(--run-text-3); }
259
+ .gh-app-key-link { font-size: 11.5px; margin-left: 6px; color: inherit; }
260
+ .gh-app-meta { font-size: 12px; color: var(--run-text-3); margin: 0; }
261
+ .gh-app-open {
262
+ align-self: flex-start; margin-top: 4px;
263
+ display: inline-flex; align-items: center; height: 34px; padding: 0 14px;
264
+ font-size: 13px; font-weight: 600; text-decoration: none;
265
+ color: var(--run-text); background: var(--run-surface);
266
+ border: 1px solid var(--run-line); border-radius: 10px;
267
+ }
268
+ .gh-app-open:hover { border-color: var(--run-brand); }
269
+ .gh-app-open:focus-visible { outline: 2px solid var(--run-brand); outline-offset: 2px; }
270
+
271
+ .gh-app-list { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr)); gap: 14px; }
272
+ .gh-app-item { display: flex; min-width: 0; }
273
+ .gh-app-item > .gh-app { flex: 1 1 auto; }
274
+ .gh-apps { min-width: 0; }
275
+
276
+ /* ---------- tables ---------- */
277
+ /* A table is as wide as its columns, so it scrolls inside its own box rather
278
+ * than pushing a phone's page sideways. `contain: inline-size` is what makes
279
+ * that hold inside a host's grid or flex row too: without it the box still
280
+ * reports the table's width as its own smallest, and a host column sized to
281
+ * its content grows to fit the table, page and all. */
282
+ .gh-table-scroll { overflow-x: auto; max-width: 100%; contain: inline-size; border: 1px solid var(--run-line); border-radius: 12px; background: var(--run-surface); }
283
+ .gh-table-scroll:focus-visible { outline: 2px solid var(--run-brand); outline-offset: 2px; }
284
+ .gh-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
285
+ /* Inside its scroll box a table keeps a readable width and scrolls, rather
286
+ * than squeezing an app's name and a run's sentence a word to a line. */
287
+ .gh-table-scroll > .gh-table { min-width: 34rem; }
288
+ .gh-table-scroll > .gh-table--wide { min-width: 46rem; }
289
+ .gh-table-head { text-align: left; font-size: 11.5px; font-weight: 600; color: var(--run-text-2); padding: 9px 12px; border-bottom: 1px solid var(--run-line); white-space: nowrap; background: var(--run-surface-2); }
290
+ .gh-table-cell { padding: 9px 12px; color: var(--run-text); vertical-align: top; border-top: 1px solid var(--run-line); }
291
+ tbody tr:first-child > .gh-table-cell { border-top: 0; }
292
+ .gh-num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
293
+ .gh-table-total > .gh-table-cell { font-weight: 600; border-top: 1px solid var(--run-line); }
294
+ .gh-runs { min-width: 0; }
295
+ /* One line a cell, so a phone scrolls the table rather than stacking an app's
296
+ * name a word to a line; only the host's sentence about a run wraps. */
297
+ .gh-run > .gh-table-cell { white-space: nowrap; }
298
+ .gh-run > .gh-table-cell:first-child { color: var(--run-text-2); }
299
+ .gh-run-detail { display: block; margin-top: 3px; font-size: 11.5px; color: var(--run-text-3); white-space: normal; min-width: 24ch; max-width: 40ch; }
300
+
301
+ /* ---------- usage ---------- */
302
+ .gh-usage { display: grid; gap: 16px; min-width: 0; }
303
+ .gh-usage-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 12px; }
304
+ .gh-usage-title { font-size: 16px; font-weight: 650; margin: 0; }
305
+ .gh-usage-dates { font-size: 12px; color: var(--run-text-3); margin: 0; }
306
+ /* Four figures in a row, and two by two on a phone. A tile's figure keeps the
307
+ * font's own proportional digits: it stands alone, and even-width digits make
308
+ * a large number look loose. */
309
+ .gh-usage-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 140px), 1fr)); gap: 10px; margin: 0; }
310
+ .gh-usage-stat { background: var(--run-surface); border: 1px solid var(--run-line); border-radius: 12px; padding: 12px 14px; margin: 0; min-width: 0; }
311
+ .gh-usage-label { font-size: 12px; color: var(--run-text-2); margin: 0; }
312
+ .gh-usage-value { font-size: 22px; font-weight: 640; letter-spacing: -0.02em; color: var(--run-text); margin: 4px 0 0; }
313
+ .gh-usage-note { font-size: 11.5px; color: var(--run-text-3); margin: 2px 0 0; }
314
+
315
+ .gh-caps { display: grid; gap: 12px; }
316
+ .gh-cap { display: grid; gap: 6px; }
317
+ .gh-cap-label { font-size: 12.5px; color: var(--run-text-2); margin: 0; }
318
+ /* The track is a lighter step of the fill's own colour, so the share reads
319
+ * across the whole bar; the fill turns to the warning and then the danger
320
+ * colour as the cap nears, and the sentence above says so in words. */
321
+ .gh-meter { --gh-meter-fill: var(--run-brand); height: 8px; border-radius: 999px; overflow: hidden; background: color-mix(in srgb, var(--gh-meter-fill) 18%, var(--run-surface)); }
322
+ .gh-meter--clear { --gh-meter-fill: var(--run-brand); }
323
+ .gh-meter--near { --gh-meter-fill: var(--run-warn); }
324
+ .gh-meter--full { --gh-meter-fill: var(--run-danger); }
325
+ .gh-meter-fill { display: block; height: 100%; border-radius: 999px; background: var(--gh-meter-fill); }
326
+
327
+ /* Runs per day: one series, so one colour and no legend; columns no wider than
328
+ * 24px with 2px of surface between them, rounded at the data end and square
329
+ * on the baseline. */
330
+ .gh-days { margin: 0; min-width: 0; }
331
+ .gh-days-title { font-size: 12.5px; font-weight: 600; color: var(--run-text-2); margin: 0 0 8px; }
332
+ .gh-days-plot { position: relative; padding-top: 20px; }
333
+ .gh-days-max { position: absolute; top: 0; left: 0; font-size: 11px; color: var(--run-text-3); }
334
+ /* Spread across the plot, so the first and last days sit over the axis's
335
+ * first and last labels whatever the number of days. */
336
+ .gh-days-bars { list-style: none; margin: 0; padding: 0; height: 96px; display: flex; align-items: flex-end; justify-content: space-between; gap: 2px; border-bottom: 1px solid var(--run-line); }
337
+ .gh-day { position: relative; flex: 0 1 24px; min-width: 0; height: 100%; display: flex; align-items: flex-end; }
338
+ .gh-day-bar { display: block; width: 100%; background: var(--run-brand); border-radius: 4px 4px 0 0; }
339
+ .gh-day:hover .gh-day-bar { opacity: 0.72; }
340
+ .gh-day-tip {
341
+ display: none; position: absolute; bottom: calc(100% + 6px); left: 50%; transform: translateX(-50%); z-index: 1;
342
+ white-space: nowrap; font-size: 11.5px; color: var(--run-text);
343
+ background: var(--run-surface); border: 1px solid var(--run-line); border-radius: 8px; padding: 4px 8px;
344
+ }
345
+ .gh-day:hover .gh-day-tip { display: block; }
346
+ .gh-days-axis { display: flex; justify-content: space-between; gap: 12px; margin-top: 4px; }
347
+ .gh-days-axis-label { font-size: 11px; color: var(--run-text-3); }
348
+ .gh-days-table { margin-top: 8px; font-size: 12px; }
349
+ .gh-days-table > .gh-table { margin-top: 8px; border: 1px solid var(--run-line); }
350
+ .gh-days-table-toggle { cursor: pointer; color: var(--run-text-2); }
351
+
352
+ [data-theme="dark"] .run-shell, [data-theme="dark"] .gh-block {
202
353
  --run-line: var(--sx-line, #232936);
203
354
  --run-surface: var(--sx-surface, #14181F);
204
355
  --run-surface-2: var(--sx-surface-2, #1A1F28);
@@ -210,4 +361,7 @@
210
361
  --run-ok: var(--sx-ok, #6EE7A1);
211
362
  --run-warn: var(--sx-warn, #F5B454);
212
363
  --run-danger: var(--sx-danger, #F47B7B);
364
+ --run-ok-text: var(--sx-ok-text, #6EE7A1);
365
+ --run-warn-text: var(--sx-warn-text, #F5B454);
366
+ --run-danger-text: var(--sx-danger-text, #F47B7B);
213
367
  }
@@ -0,0 +1,770 @@
1
+ /* Blocks a host draws from its own data: an app card, a list of them, a run
2
+ * history and a usage summary.
3
+ *
4
+ * The run page speaks Postern; these do not. They are handed documents the
5
+ * host built from what it already holds, so a page listing four apps wakes no
6
+ * runner to draw itself, and they fetch nothing at all. Every document carries
7
+ * `"v": 1`, and a block refuses a version it does not read, whole, rather than
8
+ * drawing whichever members it happens to recognise.
9
+ *
10
+ * **Nothing here uses `innerHTML`**, for the run page's reason: an app's name
11
+ * and summary are its author's prose, a model's name is whatever a runner
12
+ * reported, and all of it reaches the page through `textContent`. The only
13
+ * attributes written from the data are a link's address, which must be a web
14
+ * address, and the host's own ids, kept as data for the host's scripts.
15
+ */
16
+ (function (global) {
17
+ const root = global || (typeof window !== 'undefined' ? window : {});
18
+
19
+ /* The one version of the three shapes this file reads. */
20
+ const VERSION = 1;
21
+
22
+ /* What an app's state is called here, and the tone it is drawn in. A state
23
+ * this client has not heard of is shown as the host spelled it, untoned,
24
+ * rather than guessed into one of these. */
25
+ const APP_STATES = {
26
+ ready: { label: 'Ready', tone: 'ok' },
27
+ needs_key: { label: 'Needs a key', tone: 'caution' },
28
+ starting: { label: 'Starting', tone: 'quiet' },
29
+ unavailable: { label: 'Unavailable', tone: 'blocked' },
30
+ ended: { label: 'Access ended', tone: 'quiet' },
31
+ };
32
+
33
+ /* How a run ended. Same rule for an outcome this client does not know. */
34
+ const OUTCOMES = {
35
+ done: { label: 'Done', tone: 'ok' },
36
+ timed_out: { label: 'Timed out', tone: 'caution' },
37
+ failed: { label: 'Failed', tone: 'blocked' },
38
+ cancelled: { label: 'Cancelled', tone: 'quiet' },
39
+ };
40
+
41
+ /* The share of a cap at or past which its meter turns to a warning. */
42
+ const NEAR_CAP = 0.8;
43
+
44
+ function el(tag, className, textContent) {
45
+ const node = document.createElement(tag);
46
+ if (className) node.className = className;
47
+ if (textContent !== undefined && textContent !== null) node.textContent = String(textContent);
48
+ return node;
49
+ }
50
+
51
+ function clear(node) {
52
+ while (node.firstChild) node.removeChild(node.firstChild);
53
+ }
54
+
55
+ function isObject(value) {
56
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
57
+ }
58
+
59
+ /* ---------- reading the documents ----------
60
+ *
61
+ * Each reader answers `{ value }` or `{ refusal }`, never both. A refusal is
62
+ * one sentence naming what was wrong, because the person who reads it is
63
+ * whoever built the host's data, and "could not be shown" alone would send
64
+ * them to the source. A member the shape does not name is ignored. */
65
+
66
+ class Fault extends Error {}
67
+
68
+ function versionOf(doc, what) {
69
+ if (!isObject(doc)) throw new Fault(what + ' is not an object.');
70
+ if (doc.v !== VERSION) {
71
+ const given = doc.v === undefined ? 'no version' : 'version ' + String(doc.v);
72
+ throw new Fault(what + ' carries ' + given + ', and this client reads version ' + VERSION + '.');
73
+ }
74
+ }
75
+
76
+ function textMember(doc, key, required) {
77
+ const value = doc[key];
78
+ if (value === undefined || value === null) {
79
+ if (required) throw new Fault('"' + key + '" is missing.');
80
+ return '';
81
+ }
82
+ if (typeof value !== 'string') throw new Fault('"' + key + '" is not text.');
83
+ if (required && !value.trim()) throw new Fault('"' + key + '" is empty.');
84
+ return value;
85
+ }
86
+
87
+ function countMember(doc, key) {
88
+ const value = doc[key];
89
+ if (!Number.isInteger(value) || value < 0) throw new Fault('"' + key + '" is not a count.');
90
+ return value;
91
+ }
92
+
93
+ function amountMember(doc, key, nullable) {
94
+ const value = doc[key];
95
+ if ((value === undefined || value === null) && nullable) return null;
96
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
97
+ throw new Fault('"' + key + '" is not an amount.');
98
+ }
99
+ return value;
100
+ }
101
+
102
+ function timeMember(doc, key, nullable) {
103
+ const value = doc[key];
104
+ if ((value === undefined || value === null) && nullable) return null;
105
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
106
+ throw new Fault('"' + key + '" is not a date.');
107
+ }
108
+ return value;
109
+ }
110
+
111
+ function listMember(doc, key) {
112
+ const value = doc[key];
113
+ if (value === undefined || value === null) return [];
114
+ if (!Array.isArray(value)) throw new Fault('"' + key + '" is not a list.');
115
+ return value;
116
+ }
117
+
118
+ /* An ISO 4217 code, which is what `Intl` formats a sum in. */
119
+ function currencyMember(doc, key) {
120
+ const value = textMember(doc, key, true);
121
+ if (!/^[A-Z]{3}$/.test(value)) throw new Fault('"' + key + '" is not a currency code.');
122
+ return value;
123
+ }
124
+
125
+ function read(what, doc, build) {
126
+ try {
127
+ versionOf(doc, what);
128
+ return { value: build(doc) };
129
+ } catch (err) {
130
+ if (err instanceof Fault) return { refusal: err.message };
131
+ throw err;
132
+ }
133
+ }
134
+
135
+ function readAppSummary(doc) {
136
+ return read('An app summary', doc, function (summary) {
137
+ return {
138
+ appId: textMember(summary, 'app_id', true),
139
+ name: textMember(summary, 'name', true),
140
+ summary: textMember(summary, 'summary', false),
141
+ by: textMember(summary, 'by', false),
142
+ state: textMember(summary, 'state', true),
143
+ missingKeys: listMember(summary, 'missing_keys').map(function (entry) {
144
+ if (!isObject(entry)) throw new Fault('"missing_keys" holds something other than a key.');
145
+ return {
146
+ env: textMember(entry, 'env', true),
147
+ purpose: textMember(entry, 'purpose', false),
148
+ signupUrl: textMember(entry, 'signup_url', false),
149
+ };
150
+ }),
151
+ accessEndsAt: timeMember(summary, 'access_ends_at', true),
152
+ lastRunAt: timeMember(summary, 'last_run_at', true),
153
+ runUrl: textMember(summary, 'run_url', false),
154
+ };
155
+ });
156
+ }
157
+
158
+ function readRunRow(doc) {
159
+ return read('A run row', doc, function (row) {
160
+ const costEstimate = amountMember(row, 'cost_estimate', true);
161
+ return {
162
+ runId: textMember(row, 'run_id', false),
163
+ appId: textMember(row, 'app_id', true),
164
+ appName: textMember(row, 'app_name', true),
165
+ startedAt: timeMember(row, 'started_at', false),
166
+ durationSeconds: amountMember(row, 'duration_seconds', true),
167
+ model: textMember(row, 'model', false),
168
+ inputTokens: countMember(row, 'input_tokens'),
169
+ outputTokens: countMember(row, 'output_tokens'),
170
+ costEstimate,
171
+ currency: costEstimate === null ? '' : currencyMember(row, 'currency'),
172
+ outcome: textMember(row, 'outcome', true),
173
+ detail: textMember(row, 'detail', false),
174
+ };
175
+ });
176
+ }
177
+
178
+ function readUsageSummary(doc) {
179
+ return read('A usage summary', doc, function (usage) {
180
+ if (!isObject(usage.period)) throw new Fault('"period" is missing.');
181
+ const caps = isObject(usage.caps) ? usage.caps : {};
182
+ return {
183
+ period: {
184
+ label: textMember(usage.period, 'label', true),
185
+ start: timeMember(usage.period, 'start', false),
186
+ end: timeMember(usage.period, 'end', false),
187
+ },
188
+ runs: countMember(usage, 'runs'),
189
+ runsDone: countMember(usage, 'runs_done'),
190
+ inputTokens: countMember(usage, 'input_tokens'),
191
+ outputTokens: countMember(usage, 'output_tokens'),
192
+ costEstimate: amountMember(usage, 'cost_estimate', false),
193
+ currency: currencyMember(usage, 'currency'),
194
+ caps: {
195
+ runsPerDay: caps.runs_per_day === undefined || caps.runs_per_day === null ? null : countMember(caps, 'runs_per_day'),
196
+ runsUsed: caps.runs_used === undefined || caps.runs_used === null ? null : countMember(caps, 'runs_used'),
197
+ spendPerPeriod: amountMember(caps, 'spend_per_period', true),
198
+ },
199
+ byApp: listMember(usage, 'by_app').map(function (entry) {
200
+ if (!isObject(entry)) throw new Fault('"by_app" holds something other than an app.');
201
+ return {
202
+ appId: textMember(entry, 'app_id', true),
203
+ appName: textMember(entry, 'app_name', true),
204
+ runs: countMember(entry, 'runs'),
205
+ inputTokens: countMember(entry, 'input_tokens'),
206
+ outputTokens: countMember(entry, 'output_tokens'),
207
+ costEstimate: amountMember(entry, 'cost_estimate', false),
208
+ };
209
+ }),
210
+ byDay: listMember(usage, 'by_day').map(function (entry) {
211
+ if (!isObject(entry)) throw new Fault('"by_day" holds something other than a day.');
212
+ return { date: timeMember(entry, 'date', false), runs: countMember(entry, 'runs') };
213
+ }),
214
+ };
215
+ });
216
+ }
217
+
218
+ /* ---------- writing them down ---------- */
219
+
220
+ /* A link this file may draw: a web address and nothing else. `signup_url`
221
+ * comes from a runner's author, and an anchor is the one element through
222
+ * which a string becomes something a click runs, so a `javascript:` address
223
+ * is dropped rather than drawn. `relative` admits a path on the host's own
224
+ * page, which is what a host's `run_url` usually is. */
225
+ function webLink(value, relative) {
226
+ const candidate = String(value || '').trim();
227
+ if (!candidate) return '';
228
+ let parsed;
229
+ try {
230
+ parsed = relative ? new URL(candidate, root.document && root.document.baseURI) : new URL(candidate);
231
+ } catch (err) {
232
+ return '';
233
+ }
234
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : '';
235
+ }
236
+
237
+ /* Numbers, sums and dates in the reader's own conventions, or in the ones a
238
+ * host names (`options.locale`, `options.timeZone`). A locale or a time zone
239
+ * `Intl` refuses falls back to the reader's own rather than failing the
240
+ * block. */
241
+ function formats(options) {
242
+ const settings = options || {};
243
+ let locale = settings.locale;
244
+ try {
245
+ new Intl.NumberFormat(locale);
246
+ } catch (err) {
247
+ locale = undefined;
248
+ }
249
+ let timeZone = settings.timeZone;
250
+ try {
251
+ new Intl.DateTimeFormat(locale, { timeZone });
252
+ } catch (err) {
253
+ timeZone = undefined;
254
+ }
255
+
256
+ function count(value) {
257
+ return new Intl.NumberFormat(locale).format(value);
258
+ }
259
+
260
+ /* A tile's figure, compact from 100,000 up. The exact figure stays in the
261
+ * per-app table's totals row. */
262
+ function figure(value) {
263
+ if (value < 100000) return count(value);
264
+ return new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: 1 }).format(value);
265
+ }
266
+
267
+ /* A cost, to the cent. A run that cost less than one is said to, rather
268
+ * than rounded to nothing: "$0.00" reads as free. */
269
+ function money(value, currency) {
270
+ let format;
271
+ try {
272
+ format = new Intl.NumberFormat(locale, {
273
+ style: 'currency', currency, minimumFractionDigits: 2, maximumFractionDigits: 2,
274
+ });
275
+ } catch (err) {
276
+ format = { format: amount => amount.toFixed(2) + ' ' + currency };
277
+ }
278
+ if (value > 0 && value < 0.01) return '< ' + format.format(0.01);
279
+ return format.format(value);
280
+ }
281
+
282
+ /* A moment, in the reader's time zone. */
283
+ function moment(value) {
284
+ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short', timeZone }).format(new Date(value));
285
+ }
286
+
287
+ /* A calendar day. A bare date names a day rather than an instant, so it is
288
+ * read and written in UTC: in a time zone west of Greenwich, midnight UTC
289
+ * on the 1st is still the 31st. */
290
+ function day(value) {
291
+ const instant = /^\d{4}-\d{2}-\d{2}$/.test(value) ? new Date(value + 'T00:00:00Z') : new Date(value);
292
+ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' }).format(instant);
293
+ }
294
+
295
+ function duration(seconds) {
296
+ if (seconds < 1) return 'under 1 s';
297
+ const whole = Math.round(seconds);
298
+ if (whole < 60) return whole + ' s';
299
+ const hours = Math.floor(whole / 3600);
300
+ const minutes = Math.floor((whole % 3600) / 60);
301
+ const rest = whole % 60;
302
+ if (hours) return hours + ' h' + (minutes ? ' ' + minutes + ' min' : '');
303
+ return minutes + ' min' + (rest ? ' ' + rest + ' s' : '');
304
+ }
305
+
306
+ return { count, figure, money, moment, day, duration };
307
+ }
308
+
309
+ function plural(count, one, many) {
310
+ return count + ' ' + (count === 1 ? one : many);
311
+ }
312
+
313
+ /* A share as a CSS length, to a tenth of a percent. */
314
+ function percent(share) {
315
+ return Math.round(share * 1000) / 10 + '%';
316
+ }
317
+
318
+ function headingLevel(options) {
319
+ const level = Number(options && options.headingLevel);
320
+ return Number.isInteger(level) && level >= 2 && level <= 6 ? level : 3;
321
+ }
322
+
323
+ /* A state or an outcome, said in words beside a dot of its tone: the words
324
+ * carry it, so a reader who cannot tell the colours apart loses nothing. */
325
+ function statusLabel(table, value) {
326
+ const known = Object.prototype.hasOwnProperty.call(table, value) ? table[value] : null;
327
+ const node = el('span', 'gh-status', known ? known.label : value);
328
+ node.classList.add('gh-status--' + (known ? known.tone : 'quiet'));
329
+ return node;
330
+ }
331
+
332
+ function refusalNote(sentence) {
333
+ return el('p', 'gh-refuse', sentence);
334
+ }
335
+
336
+ /* What a list could not show, said once below what it could, with the
337
+ * first reason: the rest are usually the same one. */
338
+ function skippedNote(refusals, one, many) {
339
+ if (!refusals.length) return null;
340
+ const count = plural(refusals.length, one, many);
341
+ return el('p', 'gh-note', refusals.length === 1
342
+ ? count + ' could not be shown. ' + refusals[0]
343
+ : count + ' could not be shown. The first: ' + refusals[0]);
344
+ }
345
+
346
+ /* ---------- an app ---------- */
347
+
348
+ function drawApp(app, options) {
349
+ const formatted = formats(options);
350
+ const card = el('article', 'gh-block gh-app');
351
+ card.dataset.appId = app.appId;
352
+
353
+ const head = el('header', 'gh-app-head');
354
+ head.appendChild(el('h' + headingLevel(options), 'gh-app-name', app.name));
355
+ head.appendChild(statusLabel(APP_STATES, app.state));
356
+ card.appendChild(head);
357
+
358
+ if (app.summary) card.appendChild(el('p', 'gh-app-summary', app.summary));
359
+ if (app.by) card.appendChild(el('p', 'gh-app-by', 'by ' + app.by));
360
+
361
+ if (app.missingKeys.length) {
362
+ const keys = el('ul', 'gh-app-keys');
363
+ app.missingKeys.forEach(function (key) {
364
+ const item = el('li', 'gh-app-key');
365
+ item.appendChild(el('code', 'gh-app-key-env', key.env));
366
+ item.appendChild(el('span', 'gh-app-key-tick', ' not set'));
367
+ if (key.purpose) item.appendChild(el('span', 'gh-app-key-purpose', ' — ' + key.purpose));
368
+ const href = webLink(key.signupUrl, false);
369
+ if (href) {
370
+ const link = el('a', 'gh-app-key-link', 'Get a key');
371
+ link.href = href;
372
+ link.rel = 'noopener noreferrer';
373
+ link.target = '_blank';
374
+ item.appendChild(link);
375
+ }
376
+ keys.appendChild(item);
377
+ });
378
+ card.appendChild(keys);
379
+ }
380
+
381
+ const facts = [];
382
+ if (app.lastRunAt) facts.push('Last run ' + formatted.moment(app.lastRunAt));
383
+ else if (app.state !== 'ended') facts.push('No runs yet');
384
+ if (app.accessEndsAt) {
385
+ facts.push((app.state === 'ended' ? 'Access ended ' : 'Access ends ') + formatted.day(app.accessEndsAt));
386
+ }
387
+ if (facts.length) card.appendChild(el('p', 'gh-app-meta', facts.join(' · ')));
388
+
389
+ const href = webLink(app.runUrl, true);
390
+ if (href) {
391
+ const open = el('a', 'gh-app-open', (options && options.openLabel) || 'Open');
392
+ open.href = href;
393
+ card.appendChild(open);
394
+ }
395
+ return card;
396
+ }
397
+
398
+ class AppCard {
399
+ /* `summary` is one app summary; `options.headingLevel` (2 to 6, default
400
+ * 3) is the level of the app's name, `options.openLabel` the words of the
401
+ * link to its `run_url`. */
402
+ constructor(container, summary, options) {
403
+ this.container = container;
404
+ this.summary = summary;
405
+ this.options = options || {};
406
+ }
407
+
408
+ render() {
409
+ clear(this.container);
410
+ const read = readAppSummary(this.summary);
411
+ if (read.refusal) {
412
+ const block = el('div', 'gh-block');
413
+ block.appendChild(refusalNote('This app could not be shown. ' + read.refusal));
414
+ this.container.appendChild(block);
415
+ return;
416
+ }
417
+ this.container.appendChild(drawApp(read.value, this.options));
418
+ }
419
+
420
+ update(summary) {
421
+ this.summary = summary;
422
+ this.render();
423
+ }
424
+ }
425
+
426
+ class AppList {
427
+ /* `summaries` is a list of app summaries, drawn as cards in the order
428
+ * given. `options.emptyText` is said when there are none; the rest are
429
+ * `AppCard`'s. */
430
+ constructor(container, summaries, options) {
431
+ this.container = container;
432
+ this.summaries = summaries;
433
+ this.options = options || {};
434
+ }
435
+
436
+ render() {
437
+ clear(this.container);
438
+ const block = el('section', 'gh-block gh-apps');
439
+ this.container.appendChild(block);
440
+ if (!Array.isArray(this.summaries)) {
441
+ block.appendChild(refusalNote('These apps could not be shown: the host handed in something other than a list.'));
442
+ return;
443
+ }
444
+ const list = el('ul', 'gh-app-list');
445
+ const refusals = [];
446
+ const options = this.options;
447
+ this.summaries.forEach(function (doc) {
448
+ const read = readAppSummary(doc);
449
+ if (read.refusal) {
450
+ refusals.push(read.refusal);
451
+ return;
452
+ }
453
+ const item = el('li', 'gh-app-item');
454
+ item.appendChild(drawApp(read.value, options));
455
+ list.appendChild(item);
456
+ });
457
+ if (list.childNodes.length) block.appendChild(list);
458
+ else if (!refusals.length) block.appendChild(el('p', 'gh-empty', options.emptyText || 'No apps yet.'));
459
+ const note = skippedNote(refusals, 'app', 'apps');
460
+ if (note) block.appendChild(note);
461
+ }
462
+
463
+ update(summaries) {
464
+ this.summaries = summaries;
465
+ this.render();
466
+ }
467
+ }
468
+
469
+ /* ---------- runs ---------- */
470
+
471
+ /* A figure's column is right-aligned on even-width digits, so a column of
472
+ * them reads by place value. */
473
+ function headCell(label, numeric) {
474
+ const node = el('th', 'gh-table-head', label);
475
+ if (numeric) node.classList.add('gh-num');
476
+ node.scope = 'col';
477
+ return node;
478
+ }
479
+
480
+ function cell(value, numeric) {
481
+ const node = el('td', 'gh-table-cell', value);
482
+ if (numeric) node.classList.add('gh-num');
483
+ return node;
484
+ }
485
+
486
+ class RunHistory {
487
+ /* `rows` is a list of run rows, drawn in the order given (a host sorts
488
+ * them). `options.showApp: false` drops the app column, for a page about
489
+ * one app; `options.emptyText` is said when there are none. */
490
+ constructor(container, rows, options) {
491
+ this.container = container;
492
+ this.rows = rows;
493
+ this.options = options || {};
494
+ }
495
+
496
+ render() {
497
+ clear(this.container);
498
+ const block = el('section', 'gh-block gh-runs');
499
+ this.container.appendChild(block);
500
+ if (!Array.isArray(this.rows)) {
501
+ block.appendChild(refusalNote('These runs could not be shown: the host handed in something other than a list.'));
502
+ return;
503
+ }
504
+ const options = this.options;
505
+ const showApp = options.showApp !== false;
506
+ const formatted = formats(options);
507
+ const refusals = [];
508
+ const runs = [];
509
+ this.rows.forEach(function (doc) {
510
+ const read = readRunRow(doc);
511
+ if (read.refusal) refusals.push(read.refusal);
512
+ else runs.push(read.value);
513
+ });
514
+
515
+ if (!runs.length) {
516
+ if (!refusals.length) block.appendChild(el('p', 'gh-empty', options.emptyText || 'No runs yet.'));
517
+ } else {
518
+ /* Wide by nature, so it scrolls inside its own box rather than pushing
519
+ * the page sideways on a phone. The box takes focus so a keyboard can
520
+ * scroll it too. */
521
+ const scroller = el('div', 'gh-table-scroll');
522
+ scroller.tabIndex = 0;
523
+ scroller.setAttribute('role', 'region');
524
+ scroller.setAttribute('aria-label', 'Runs');
525
+ const table = el('table', 'gh-table gh-table--wide');
526
+ const head = el('thead');
527
+ const headRow = el('tr');
528
+ headRow.appendChild(headCell('Started', false));
529
+ if (showApp) headRow.appendChild(headCell('App', false));
530
+ headRow.appendChild(headCell('Outcome', false));
531
+ headRow.appendChild(headCell('Duration', true));
532
+ headRow.appendChild(headCell('Tokens in', true));
533
+ headRow.appendChild(headCell('Tokens out', true));
534
+ /* The column says what the figure is. A run's cost is the host's
535
+ * estimate from token counts and a price list, never a bill. */
536
+ headRow.appendChild(headCell('Cost (estimate)', true));
537
+ headRow.appendChild(headCell('Model', false));
538
+ head.appendChild(headRow);
539
+ table.appendChild(head);
540
+
541
+ const body = el('tbody');
542
+ runs.forEach(function (run) {
543
+ const row = el('tr', 'gh-run');
544
+ if (run.runId) row.dataset.runId = run.runId;
545
+ row.appendChild(cell(formatted.moment(run.startedAt), false));
546
+ if (showApp) row.appendChild(cell(run.appName, false));
547
+ const outcome = el('td', 'gh-table-cell');
548
+ outcome.appendChild(statusLabel(OUTCOMES, run.outcome));
549
+ if (run.detail) outcome.appendChild(el('span', 'gh-run-detail', run.detail));
550
+ row.appendChild(outcome);
551
+ row.appendChild(cell(run.durationSeconds === null ? '—' : formatted.duration(run.durationSeconds), true));
552
+ row.appendChild(cell(formatted.count(run.inputTokens), true));
553
+ row.appendChild(cell(formatted.count(run.outputTokens), true));
554
+ row.appendChild(cell(run.costEstimate === null ? '—' : formatted.money(run.costEstimate, run.currency), true));
555
+ row.appendChild(cell(run.model || '—', false));
556
+ body.appendChild(row);
557
+ });
558
+ table.appendChild(body);
559
+ scroller.appendChild(table);
560
+ block.appendChild(scroller);
561
+ }
562
+ const note = skippedNote(refusals, 'run', 'runs');
563
+ if (note) block.appendChild(note);
564
+ }
565
+
566
+ update(rows) {
567
+ this.rows = rows;
568
+ this.render();
569
+ }
570
+ }
571
+
572
+ /* ---------- usage ---------- */
573
+
574
+ function stat(label, value, note) {
575
+ const tile = el('div', 'gh-usage-stat');
576
+ tile.appendChild(el('dt', 'gh-usage-label', label));
577
+ tile.appendChild(el('dd', 'gh-usage-value', value));
578
+ if (note) tile.appendChild(el('dd', 'gh-usage-note', note));
579
+ return tile;
580
+ }
581
+
582
+ /* One cap: the sentence first, since it carries the numbers, then a bar
583
+ * that shows the same share at a glance and is hidden from a screen reader,
584
+ * which has the sentence. */
585
+ function capRow(sentence, used, limit) {
586
+ const row = el('div', 'gh-cap');
587
+ row.appendChild(el('p', 'gh-cap-label', sentence));
588
+ const share = limit > 0 ? Math.min(1, used / limit) : 1;
589
+ const meter = el('div', 'gh-meter');
590
+ meter.classList.add(share >= 1 ? 'gh-meter--full' : share >= NEAR_CAP ? 'gh-meter--near' : 'gh-meter--clear');
591
+ meter.setAttribute('aria-hidden', 'true');
592
+ const fill = el('span', 'gh-meter-fill');
593
+ /* Through the object model rather than a `style` attribute, which a
594
+ * strict content security policy refuses and this property is not. */
595
+ fill.style.width = percent(share);
596
+ meter.appendChild(fill);
597
+ row.appendChild(meter);
598
+ return row;
599
+ }
600
+
601
+ /* Runs per day as columns. The tallest is labelled; the rest show on hover,
602
+ * and every day's figure is in the table beneath, so no value is reachable
603
+ * only by pointing at it. */
604
+ function dayChart(days, formatted) {
605
+ const figure = el('figure', 'gh-days');
606
+ figure.appendChild(el('figcaption', 'gh-days-title', 'Runs per day'));
607
+ const most = days.reduce((top, entry) => Math.max(top, entry.runs), 0);
608
+ const plot = el('div', 'gh-days-plot');
609
+ plot.setAttribute('aria-hidden', 'true');
610
+ plot.appendChild(el('span', 'gh-days-max', plural(most, 'run', 'runs')));
611
+ const bars = el('ol', 'gh-days-bars');
612
+ days.forEach(function (entry) {
613
+ const item = el('li', 'gh-day');
614
+ const bar = el('span', 'gh-day-bar');
615
+ bar.style.height = percent(most ? entry.runs / most : 0);
616
+ item.appendChild(bar);
617
+ item.appendChild(el('span', 'gh-day-tip', formatted.day(entry.date) + ' · ' + plural(entry.runs, 'run', 'runs')));
618
+ bars.appendChild(item);
619
+ });
620
+ plot.appendChild(bars);
621
+ figure.appendChild(plot);
622
+ const axis = el('div', 'gh-days-axis');
623
+ axis.setAttribute('aria-hidden', 'true');
624
+ axis.appendChild(el('span', 'gh-days-axis-label', formatted.day(days[0].date)));
625
+ if (days.length > 1) axis.appendChild(el('span', 'gh-days-axis-label', formatted.day(days[days.length - 1].date)));
626
+ figure.appendChild(axis);
627
+
628
+ const table = el('details', 'gh-days-table');
629
+ table.appendChild(el('summary', 'gh-days-table-toggle', 'Each day as a table'));
630
+ const grid = el('table', 'gh-table');
631
+ const head = el('thead');
632
+ const headRow = el('tr');
633
+ headRow.appendChild(headCell('Day', false));
634
+ headRow.appendChild(headCell('Runs', true));
635
+ head.appendChild(headRow);
636
+ grid.appendChild(head);
637
+ const body = el('tbody');
638
+ days.forEach(function (entry) {
639
+ const row = el('tr');
640
+ row.appendChild(cell(formatted.day(entry.date), false));
641
+ row.appendChild(cell(formatted.count(entry.runs), true));
642
+ body.appendChild(row);
643
+ });
644
+ grid.appendChild(body);
645
+ table.appendChild(grid);
646
+ figure.appendChild(table);
647
+ return figure;
648
+ }
649
+
650
+ function appTable(usage, formatted) {
651
+ const scroller = el('div', 'gh-table-scroll');
652
+ scroller.tabIndex = 0;
653
+ scroller.setAttribute('role', 'region');
654
+ scroller.setAttribute('aria-label', 'Usage by app');
655
+ const table = el('table', 'gh-table');
656
+ const head = el('thead');
657
+ const headRow = el('tr');
658
+ headRow.appendChild(headCell('App', false));
659
+ headRow.appendChild(headCell('Runs', true));
660
+ headRow.appendChild(headCell('Tokens in', true));
661
+ headRow.appendChild(headCell('Tokens out', true));
662
+ headRow.appendChild(headCell('Cost (estimate)', true));
663
+ head.appendChild(headRow);
664
+ table.appendChild(head);
665
+ const body = el('tbody');
666
+ usage.byApp.forEach(function (app) {
667
+ const row = el('tr');
668
+ row.dataset.appId = app.appId;
669
+ row.appendChild(cell(app.appName, false));
670
+ row.appendChild(cell(formatted.count(app.runs), true));
671
+ row.appendChild(cell(formatted.count(app.inputTokens), true));
672
+ row.appendChild(cell(formatted.count(app.outputTokens), true));
673
+ row.appendChild(cell(formatted.money(app.costEstimate, usage.currency), true));
674
+ body.appendChild(row);
675
+ });
676
+ table.appendChild(body);
677
+ /* The period's own totals, exactly, which the tiles above round. */
678
+ const foot = el('tfoot');
679
+ const total = el('tr', 'gh-table-total');
680
+ total.appendChild(cell('All apps', false));
681
+ total.appendChild(cell(formatted.count(usage.runs), true));
682
+ total.appendChild(cell(formatted.count(usage.inputTokens), true));
683
+ total.appendChild(cell(formatted.count(usage.outputTokens), true));
684
+ total.appendChild(cell(formatted.money(usage.costEstimate, usage.currency), true));
685
+ foot.appendChild(total);
686
+ table.appendChild(foot);
687
+ scroller.appendChild(table);
688
+ return scroller;
689
+ }
690
+
691
+ class UsageSummary {
692
+ /* `usage` is one usage summary. `options.headingLevel` (2 to 6, default
693
+ * 3) is the level of the period's name. */
694
+ constructor(container, usage, options) {
695
+ this.container = container;
696
+ this.usage = usage;
697
+ this.options = options || {};
698
+ }
699
+
700
+ render() {
701
+ clear(this.container);
702
+ const block = el('section', 'gh-block gh-usage');
703
+ this.container.appendChild(block);
704
+ const read = readUsageSummary(this.usage);
705
+ if (read.refusal) {
706
+ block.appendChild(refusalNote('This usage could not be shown. ' + read.refusal));
707
+ return;
708
+ }
709
+ const usage = read.value;
710
+ const formatted = formats(this.options);
711
+
712
+ const head = el('header', 'gh-usage-head');
713
+ head.appendChild(el('h' + headingLevel(this.options), 'gh-usage-title', usage.period.label));
714
+ head.appendChild(el('p', 'gh-usage-dates', formatted.day(usage.period.start) + ' – ' + formatted.day(usage.period.end)));
715
+ block.appendChild(head);
716
+
717
+ const stats = el('dl', 'gh-usage-stats');
718
+ stats.appendChild(stat('Runs', formatted.figure(usage.runs), plural(usage.runsDone, 'finished', 'finished')));
719
+ stats.appendChild(stat('Tokens in', formatted.figure(usage.inputTokens)));
720
+ stats.appendChild(stat('Tokens out', formatted.figure(usage.outputTokens)));
721
+ /* Named as an estimate where it is drawn, the way the run page labels a
722
+ * runner's `cost_usd`: a figure on a dashboard is read as a bill unless
723
+ * it says otherwise. */
724
+ stats.appendChild(stat('Estimated cost', formatted.money(usage.costEstimate, usage.currency), 'An estimate, not a bill'));
725
+ block.appendChild(stats);
726
+
727
+ const caps = el('div', 'gh-caps');
728
+ if (usage.caps.runsPerDay !== null && usage.caps.runsUsed !== null) {
729
+ caps.appendChild(capRow(
730
+ usage.caps.runsUsed + ' of ' + plural(usage.caps.runsPerDay, 'run', 'runs') + ' in the last 24 hours' +
731
+ (usage.caps.runsUsed >= usage.caps.runsPerDay ? ' — the limit is reached' : ''),
732
+ usage.caps.runsUsed,
733
+ usage.caps.runsPerDay
734
+ ));
735
+ }
736
+ if (usage.caps.spendPerPeriod !== null) {
737
+ caps.appendChild(capRow(
738
+ formatted.money(usage.costEstimate, usage.currency) + ' of ' +
739
+ formatted.money(usage.caps.spendPerPeriod, usage.currency) + ' estimated spend this period' +
740
+ (usage.costEstimate >= usage.caps.spendPerPeriod ? ' — the cap is reached' : ''),
741
+ usage.costEstimate,
742
+ usage.caps.spendPerPeriod
743
+ ));
744
+ }
745
+ if (caps.childNodes.length) block.appendChild(caps);
746
+
747
+ if (usage.byDay.length) block.appendChild(dayChart(usage.byDay, formatted));
748
+ if (usage.byApp.length) block.appendChild(appTable(usage, formatted));
749
+ }
750
+
751
+ update(usage) {
752
+ this.usage = usage;
753
+ this.render();
754
+ }
755
+ }
756
+
757
+ root.Gatehouse = Object.assign({}, root.Gatehouse, {
758
+ AppCard,
759
+ AppList,
760
+ RunHistory,
761
+ UsageSummary,
762
+ hostData: { VERSION, readAppSummary, readRunRow, readUsageSummary },
763
+ });
764
+
765
+ /* `SigrixRun` is the name this package was born under, inside one host. It
766
+ * is kept pointing at the same object so that host keeps working across the
767
+ * extraction, and because a global is the one part of a browser package a
768
+ * consumer cannot alias for itself. Deprecated; removed at 1.0. */
769
+ root.SigrixRun = root.Gatehouse;
770
+ })(typeof window !== 'undefined' ? window : globalThis);
@@ -31,6 +31,13 @@
31
31
  return 'k-' + Date.now() + '-' + Math.random().toString(16).slice(2);
32
32
  }
33
33
 
34
+ /* How many renderers this copy of the file has made. An id is unique to the
35
+ * document, not to the container it is drawn in, so two renderers on one
36
+ * page that both wrote `run-field-prompt` would bind each `<label>` to the
37
+ * first page's field. Each renderer writes its ids under a scope of its own
38
+ * instead, numbered in the order they were made. */
39
+ let renderersMade = 0;
40
+
34
41
  class RunRenderer {
35
42
  /* `container` is where the page is drawn; `client` is any object with the
36
43
  * four verbs, so a caller may pass its own. `options.composition` is the
@@ -64,6 +71,15 @@
64
71
  this.idempotencyKey = '';
65
72
  this.onRunStateChange = settings.onRunStateChange || function () {};
66
73
  this.nodes = {};
74
+ renderersMade += 1;
75
+ this.idScope = 'run-' + renderersMade;
76
+ }
77
+
78
+ /* An id inside this renderer's scope. A host looking for a field finds it
79
+ * by its `name`, which is the input's key, inside the container it handed
80
+ * in; the id is this renderer's own business. */
81
+ scopedId(part) {
82
+ return this.idScope + '-' + part;
67
83
  }
68
84
 
69
85
  async load() {
@@ -197,7 +213,7 @@
197
213
  this.nodes.choiceAbout = null;
198
214
  vm.fields.forEach(function (field) {
199
215
  const wrap = el('div', 'run-field');
200
- const id = 'run-field-' + field.key;
216
+ const id = self.scopedId('field-' + field.key);
201
217
  const label = el('label', 'run-field-label', field.label + (field.required ? ' *' : ''));
202
218
  label.htmlFor = id;
203
219
  wrap.appendChild(label);
@@ -316,11 +332,11 @@
316
332
  const gate = el('div', 'run-write-gate');
317
333
  const box = el('input', 'run-write-check');
318
334
  box.type = 'checkbox';
319
- box.id = 'run-write-confirm';
335
+ box.id = this.scopedId('write-confirm');
320
336
  const label = el('label', 'run-write-label',
321
337
  'This agent can ' + vm.capabilities.writeTools.join(', ') +
322
338
  '. Runs cost money and write outside this page; stopping a run or closing the tab cancels it but does not undo it.');
323
- label.htmlFor = 'run-write-confirm';
339
+ label.htmlFor = box.id;
324
340
  box.addEventListener('change', function () {
325
341
  self.writeToolsAccepted = box.checked;
326
342
  self.syncRunEnabled();
@@ -82,6 +82,24 @@
82
82
  return value === null || value === undefined ? '' : String(value);
83
83
  }
84
84
 
85
+ /* A link the page may draw: an absolute `http:` or `https:` address, and
86
+ * nothing else. `signup_url` is a runner author's prose, and the schema's
87
+ * `"format": "uri"` is satisfied by a `javascript:` URI as readily as by a
88
+ * web page; an anchor is the one element through which a string becomes
89
+ * something a click runs. Anything else draws no link. `host_blocks.js`
90
+ * applies the same rule to the same member, and one case table holds both. */
91
+ function webLink(value) {
92
+ const candidate = text(value).trim();
93
+ if (!candidate) return '';
94
+ let parsed;
95
+ try {
96
+ parsed = new URL(candidate);
97
+ } catch (err) {
98
+ return '';
99
+ }
100
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : '';
101
+ }
102
+
85
103
  /* SPEC 4.1.3 and 7: a `describe` carrying a credential *value* is
86
104
  * nonconformant, and a client meeting one SHOULD refuse to proceed. This one
87
105
  * refuses — returning the reason rather than throwing, so the page can say
@@ -432,7 +450,7 @@
432
450
  return {
433
451
  env,
434
452
  purpose: text(entry.purpose),
435
- signupUrl: text(entry.signup_url),
453
+ signupUrl: webLink(entry.signup_url),
436
454
  satisfied: missing.indexOf(env) === -1,
437
455
  };
438
456
  });
@@ -612,6 +630,7 @@
612
630
  limitsView,
613
631
  updateNotice,
614
632
  credentialLeak,
633
+ webLink,
615
634
  },
616
635
  });
617
636