@sigrix-io/gatehouse 0.2.0 → 0.4.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,3 +1,10 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/sigrix-io/gatehouse/main/.github/assets/logo-on-dark.svg">
4
+ <img src="https://raw.githubusercontent.com/sigrix-io/gatehouse/main/.github/assets/logo.svg" alt="Gatehouse" width="120">
5
+ </picture>
6
+ </p>
7
+
1
8
  # Gatehouse
2
9
 
3
10
  [![npm](https://img.shields.io/npm/v/@sigrix-io/gatehouse)](https://www.npmjs.com/package/@sigrix-io/gatehouse)
@@ -8,7 +15,9 @@ A browser client for [Postern](https://github.com/sigrix-io/postern). Given a ru
8
15
 
9
16
  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
17
 
11
- Five scripts and a stylesheet. No build step, no runtime dependency, no second origin.
18
+ And one block for a playbook, a process a business runs by hand and sells as files: handed its `playbook.json`, it draws what is inside, the files in the order a person works through them and the placeholders a buyer fills in, and never a file's text.
19
+
20
+ Six scripts and a stylesheet. No build step, no runtime dependency, no second origin.
12
21
 
13
22
  > **0.x.** Nothing is stable before 1.0; pin the minor. See `VERSIONING.md`.
14
23
 
@@ -18,7 +27,7 @@ Five scripts and a stylesheet. No build step, no runtime dependency, no second o
18
27
  npm install @sigrix-io/gatehouse
19
28
  ```
20
29
 
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:
30
+ Serve the seven 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:
22
31
 
23
32
  ```html
24
33
  <link rel="stylesheet" href="gatehouse.css">
@@ -44,11 +53,11 @@ Each script is an IIFE that adds to one global, `window.Gatehouse`. `window.Sigr
44
53
  | Constructor | Arguments |
45
54
  | --- | --- |
46
55
  | `PosternClient(baseUrl, options)` | `baseUrl`: where the runner (or the proxy) answers; every request goes to it under `/postern/v0`. `options.headers`: extra headers for every request. `options.fetchImpl`: a `fetch` to use instead of the page's. |
47
- | `RunRenderer(container, client, options)` | `container`: the element to draw into. `client`: anything with the four verbs. `options.composition`, `options.choice`, `options.hosted`: below. |
56
+ | `RunRenderer(container, client, options)` | `container`: the element to draw into. `client`: anything with the four verbs. `options.composition`, `options.choice`, `options.hosted`, `options.conversation`: below. |
48
57
 
49
58
  `renderer.load()` reads `describe` and `status` and draws the page. Running, stopping and retrying are the page's own buttons.
50
59
 
51
- A page of apps loads `host_blocks.js`, alone or after the four; see [Host blocks](#host-blocks).
60
+ A page of apps loads `host_blocks.js`, alone or after the four; see [Host blocks](#host-blocks). A page showing a playbook loads `playbook_contents.js`, alone or beside the others; see [A playbook's contents](#a-playbooks-contents).
52
61
 
53
62
  ## The rules that are easy to erode
54
63
 
@@ -58,7 +67,7 @@ Each is held by a test rather than by memory (`tests/contract.test.js` and the s
58
67
  - **No markup from the agent.** `innerHTML` appears nowhere. Agent output and every streamed `delta.text` reach the page through `textContent`.
59
68
  - **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`.
60
69
  - **Zero imports, and no distributor.** Nothing here names a marketplace or a listing.
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.
70
+ - **Documents are handed in.** The composition and the choice arrive as data from whoever mounted the page, and so does everything the host blocks and the playbook block draw. Fetching them here would be reaching for a fifth verb, and Postern has four.
62
71
  - **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.
63
72
 
64
73
  ## The composition
@@ -91,6 +100,18 @@ The form shows only the chosen option's inputs; a chosen option's `required` add
91
100
 
92
101
  `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.
93
102
 
103
+ ## A conversation
104
+
105
+ No verb takes a run's `run_id` (SPEC §4.5), so a client cannot point a run at the one before it, and a page that sends one brief and shows one answer gives a reader nothing to answer an agent's question with; each new brief replaces the last answer. `options.conversation: true` keeps the exchange on the page instead:
106
+
107
+ - **Each brief and its answer become a turn**, drawn above the form, oldest first, the answer as the result panel would draw it (structure in the `markdown` output mode, text otherwise). The box empties for the reply, and the result panel is emptied rather than showing the answer twice.
108
+ - **A reply carries the turns before it.** The reserved `prompt` input is sent as one brief holding the earlier turns, oldest first and each said by whom, then the new message: `Gatehouse.viewModel.conversationBrief(turns, message, limit)` composes it, so the agent reads the whole exchange as its brief. Every other input is sent as it is.
109
+ - **What a reply carries is bounded**: by the brief's own `max_length`, which the runner enforces, and by `options.conversation.maxChars` (`{ maxChars: 8000 }`), or 16,000 characters when neither is set (`CONVERSATION_MAX_CHARS`). The oldest turns are left out first, every turn stays on the page, and a note says how many no longer fit. The new message is never cut.
110
+ - **Only an answer the page can show as text is a turn.** A refusal, a stop, a file or an output type this client cannot draw leaves the brief in its box to send again.
111
+ - **The page holds it, and nothing else does.** The turns live in the renderer, so leaving the page forgets them; a reader starts over sooner with **New conversation**.
112
+
113
+ A runner whose `describe` declares no text `prompt` has nothing to reply into, and its page stays the one-run page whatever the host asked for.
114
+
94
115
  ## Several apps on one page
95
116
 
96
117
  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.
@@ -188,9 +209,44 @@ Each carries `"v": 1`. A block refuses a document in a version it does not read,
188
209
  - **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
210
  - **Nothing is fetched.** A test spies on `fetch` while every block draws.
190
211
 
212
+ ## A playbook's contents
213
+
214
+ A playbook is a process a business runs by hand, sold as the files a person works through: the steps, the copy to send, the checklists, an offline tool or two. Its `playbook.json`, in the Muster format, says what each file is for and which placeholders a buyer fills in. This block draws that document, so a page can show what is inside a playbook to someone deciding whether to buy it, without handing over a file.
215
+
216
+ ```html
217
+ <link rel="stylesheet" href="gatehouse.css">
218
+ <div id="inside"></div>
219
+
220
+ <script src="playbook_contents.js"></script>
221
+ <script>
222
+ new Gatehouse.PlaybookContents(document.getElementById('inside'), playbookJson, {
223
+ fileNotes: { 'tools/reconcile.html': 'Its scripts run under a policy that blocks every network request.' },
224
+ }).render();
225
+ </script>
226
+ ```
227
+
228
+ | Constructor | Draws | Options |
229
+ | --- | --- | --- |
230
+ | `PlaybookContents(container, playbook, options)` | the files in `order`, each with its role, then the placeholders by when a buyer fills them in | `headingLevel` (2 to 6, default 3; the placeholders' kinds take the level below), `fileNotes` |
231
+
232
+ It has `render()` and `update(playbook)`, as the host blocks do. `Gatehouse.playbookData.readPlaybook` answers `{ value }` or `{ refusal }` as the block reads a document, so a host can test what it hands in.
233
+
234
+ ### The document
235
+
236
+ A playbook's own `playbook.json`, parsed, in format 0.x. The block reads `format_version`, `files` (each one's `path`, `role`, `same_as` and `self_contained`), `order` and the two lists of `slots`, `setup` and `message`, and ignores every other member, as a reader of the format may: a minor version only adds members an earlier reader can ignore, so any 0.x is drawn, and a major it does not know is refused whole, saying so.
237
+
238
+ - **The files, in `order`.** Each with its role in words (`guide`, `steps`, `checklist`, `copy`, `reference`, `tool`, `license`, `changelog`; a role it does not know is shown as spelled). A file that is another form of one (`same_as`) says which, and an `.html` file says it opens in a browser, and that it works offline only when the document calls it `self_contained`.
239
+ - **The placeholders, by when they are filled in.** `setup` once, for the buyer's business, and `message` each time the playbook is used, each token as the files write it beside its label. Two tokens one case apart, `[NAME]` and `[name]`, are two placeholders, and the block says so.
240
+ - **What it refuses.** A document in another major, or one whose `files`, `order` or `slots` are missing or not what the format says they are, or whose `order` and `same_as` name a file `files` does not list (paths match exactly, as in the format). It checks what drawing needs and no more: whether the files really say what the document claims is a checker's question, asked of the files, which the block never has.
241
+ - **`fileNotes`.** A sentence of the host's own about a file, keyed by its path and drawn beside it: something the host knows that the document does not say, such as what it found when it read the file. A note for a path the playbook does not hold is not drawn.
242
+
243
+ ### What it keeps
244
+
245
+ The host blocks' rules: every string reaches the page through `textContent`, no attribute is written from the document, and nothing is fetched. And one of its own: it never reads or draws a file's text, only what the document says the files are.
246
+
191
247
  ## Styling
192
248
 
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.
249
+ `gatehouse.css` styles every class the scripts draw, the run page's `run-*` and the 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 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
250
 
195
251
  ## Where it fits
196
252
 
@@ -200,6 +256,7 @@ Gatehouse is one of the open-source projects [Sigrix](https://sigrix.io) publish
200
256
  - **[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
257
  - **[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
258
  - **[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.
259
+ - **[Muster](https://github.com/sigrix-io/muster)**, the format a playbook's `playbook.json` is written in, which the playbook block reads. Its schema is at [sigrix.io/schemas/muster/0.1/playbook.schema.json](https://sigrix.io/schemas/muster/0.1/playbook.schema.json).
203
260
 
204
261
  Every project Sigrix publishes, and a map of how they connect: [sigrix.io/open-source](https://sigrix.io/open-source).
205
262
 
@@ -210,7 +267,7 @@ npm ci
210
267
  npm test
211
268
  ```
212
269
 
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.
270
+ 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, and `tests/fixtures/playbooks/` holds a `playbook.json` as an author writes one.
214
271
 
215
272
  ## Licence
216
273
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sigrix-io/gatehouse",
3
- "version": "0.2.0",
3
+ "version": "0.4.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",
@@ -15,6 +15,7 @@
15
15
  "agent",
16
16
  "mcp",
17
17
  "sse",
18
+ "playbook",
18
19
  "browser",
19
20
  "no-build"
20
21
  ],
@@ -29,6 +30,7 @@
29
30
  "./refusal_copy.js": "./src/refusal_copy.js",
30
31
  "./run_renderer.js": "./src/run_renderer.js",
31
32
  "./host_blocks.js": "./src/host_blocks.js",
33
+ "./playbook_contents.js": "./src/playbook_contents.js",
32
34
  "./gatehouse.css": "./src/gatehouse.css",
33
35
  "./package.json": "./package.json"
34
36
  },
@@ -39,7 +41,7 @@
39
41
  "test": "vitest run"
40
42
  },
41
43
  "devDependencies": {
42
- "jsdom": "30.1.1",
43
- "vitest": "5.0.3"
44
+ "jsdom": "30.1.3",
45
+ "vitest": "5.0.5"
44
46
  }
45
47
  }
package/src/gatehouse.css CHANGED
@@ -38,12 +38,12 @@
38
38
  .run-shell {
39
39
  display: grid;
40
40
  grid-template-columns: minmax(0, 1fr) 300px;
41
- grid-template-areas: "head rail" "form rail" "controls rail" "output rail";
41
+ grid-template-areas: "head rail" "conversation rail" "form rail" "controls rail" "output rail";
42
42
  gap: 0 24px;
43
43
  align-items: start;
44
44
  }
45
45
  @media (max-width: 960px) {
46
- .run-shell { grid-template-columns: minmax(0, 1fr); grid-template-areas: "head" "rail" "form" "controls" "output"; }
46
+ .run-shell { grid-template-columns: minmax(0, 1fr); grid-template-areas: "head" "rail" "conversation" "form" "controls" "output"; }
47
47
  }
48
48
  /* Stated here rather than left to a host's reset, which a page linking only
49
49
  * this file does not have. A browser draws `select` border-box and `input` and
@@ -153,6 +153,45 @@
153
153
  * write — they should not read as the same voice. */
154
154
  .run-field-help { font-size: 12.5px; color: var(--run-text-2); margin: 6px 0 0; max-width: 64ch; }
155
155
 
156
+ /* ---------- conversation ----------
157
+ *
158
+ * Above the form, oldest first, so the newest answer sits just over the box
159
+ * the reply is typed into. A page that asked for no conversation draws no
160
+ * section, and its grid row is empty and takes no height. */
161
+ .run-conversation { grid-area: conversation; margin-bottom: 18px; min-width: 0; }
162
+ .run-conversation[hidden] { display: none; }
163
+ .run-turns { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; }
164
+ .run-turn {
165
+ background: var(--run-surface); border: 1px solid var(--run-line);
166
+ border-radius: 14px; padding: 14px 16px; min-width: 0;
167
+ }
168
+ .run-turn-who {
169
+ font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em;
170
+ color: var(--run-text-3); margin: 0 0 4px;
171
+ }
172
+ /* What the reader typed, as typed: their line breaks kept, and a long word
173
+ * (a URL, a key) broken rather than pushing the card wider than its column. */
174
+ .run-turn-brief {
175
+ white-space: pre-wrap; overflow-wrap: anywhere; margin: 0 0 14px;
176
+ font-size: 14px; line-height: 1.55; color: var(--run-text-2);
177
+ }
178
+ .run-turn-answer { font-size: 14px; line-height: 1.62; overflow-wrap: anywhere; min-width: 0; }
179
+ .run-turn-text { white-space: pre-wrap; margin: 0; max-width: 72ch; }
180
+ .run-turn-answer .run-download { margin-top: 10px; }
181
+ .run-conversation-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; margin-top: 10px; }
182
+ .run-conversation-note { font-size: 12px; color: var(--run-text-3); margin: 0; max-width: 64ch; flex: 1 1 260px; }
183
+ .run-conversation-reset {
184
+ font: inherit; font-size: 12.5px; font-weight: 600; cursor: pointer;
185
+ border-radius: 10px; padding: 0 12px; height: 32px; min-height: 0;
186
+ background: var(--run-surface); color: var(--run-text); border: 1px solid var(--run-line);
187
+ }
188
+ .run-conversation-reset:disabled { opacity: 0.45; cursor: not-allowed; }
189
+ /* A host may floor every button at 44px for a thumb; given back here, after
190
+ * the opt-out above, for the same reason the write gate's box is. */
191
+ @media (pointer: coarse) {
192
+ .run-conversation-reset { min-height: 44px; }
193
+ }
194
+
156
195
  /* ---------- controls ---------- */
157
196
  .run-controls { grid-area: controls; margin-top: 18px; }
158
197
  .run-actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
@@ -349,6 +388,43 @@ tbody tr:first-child > .gh-table-cell { border-top: 0; }
349
388
  .gh-days-table > .gh-table { margin-top: 8px; border: 1px solid var(--run-line); }
350
389
  .gh-days-table-toggle { cursor: pointer; color: var(--run-text-2); }
351
390
 
391
+ /* ---------- a playbook ----------
392
+ *
393
+ * Its files in order, then its placeholders. A path, a token and a label are
394
+ * someone's typing and may be one long word, so each wraps anywhere rather
395
+ * than pushing the block past a phone's edge. */
396
+ .gh-playbook { display: grid; gap: 22px; min-width: 0; }
397
+ .gh-playbook-part { display: grid; gap: 8px; min-width: 0; }
398
+ .gh-playbook-heading { font-size: 16px; font-weight: 650; letter-spacing: -0.01em; margin: 0; }
399
+ .gh-playbook-subheading { font-size: 12.5px; font-weight: 600; color: var(--run-text-2); margin: 8px 0 0; }
400
+ .gh-playbook-lead { font-size: 12.5px; line-height: 1.5; color: var(--run-text-2); margin: 0; max-width: 72ch; }
401
+ /* The browser's own numbers, so each file keeps its place in the order
402
+ * however its row wraps. A list item laid out as a flex row is drawn with no
403
+ * number, so the row's parts sit in a box of their own. */
404
+ .gh-playbook-files { margin: 0; padding: 0 0 0 1.8em; }
405
+ .gh-playbook-file { padding: 9px 0; border-top: 1px solid var(--run-line); min-width: 0; }
406
+ .gh-playbook-file:first-child { border-top: 0; }
407
+ .gh-playbook-file::marker { font-size: 12px; color: var(--run-text-3); font-variant-numeric: tabular-nums; }
408
+ .gh-playbook-file-body { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; min-width: 0; }
409
+ .gh-playbook-path { font-family: var(--run-mono); font-size: 12.5px; color: var(--run-text); min-width: 0; overflow-wrap: anywhere; }
410
+ .gh-playbook-role {
411
+ font-size: 11px; font-weight: 600; letter-spacing: 0.02em; color: var(--run-text-2); white-space: nowrap;
412
+ background: var(--run-surface-2); border: 1px solid var(--run-line); border-radius: 999px; padding: 1px 8px;
413
+ }
414
+ /* A sentence of its own under the path, on a line the flex row gives it. */
415
+ .gh-playbook-about, .gh-playbook-note { flex: 1 1 100%; font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; }
416
+ .gh-playbook-about { color: var(--run-text-3); }
417
+ .gh-playbook-note { color: var(--run-text-2); }
418
+ .gh-playbook-slot-group { display: grid; gap: 6px; min-width: 0; }
419
+ .gh-playbook-slots { margin: 0; display: grid; gap: 6px; }
420
+ .gh-playbook-slot { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 10px; min-width: 0; }
421
+ .gh-playbook-slot-name { margin: 0; min-width: 0; }
422
+ .gh-playbook-token {
423
+ font-family: var(--run-mono); font-size: 12px; color: var(--run-text); overflow-wrap: anywhere;
424
+ background: var(--run-surface-2); border: 1px solid var(--run-line); border-radius: 6px; padding: 1px 6px;
425
+ }
426
+ .gh-playbook-slot-label { margin: 0; flex: 1 1 16ch; min-width: 0; font-size: 12.5px; line-height: 1.5; color: var(--run-text-2); overflow-wrap: anywhere; }
427
+
352
428
  [data-theme="dark"] .run-shell, [data-theme="dark"] .gh-block {
353
429
  --run-line: var(--sx-line, #232936);
354
430
  --run-surface: var(--sx-surface, #14181F);
@@ -0,0 +1,329 @@
1
+ /* What is inside a playbook: its files, in the order a person works through
2
+ * them, with what each one is for, and the placeholders a buyer fills in.
3
+ *
4
+ * A playbook is a process a business runs by hand, sold as the files a person
5
+ * works through, and described by a `playbook.json` in the Muster format. The
6
+ * host hands that document in, parsed, and the block draws it. There is
7
+ * nothing to run and nothing to fetch: the block never reads a file and never
8
+ * draws a file's text, only what the document says the files are, so a page
9
+ * may show a playbook's contents to someone who has not bought it.
10
+ *
11
+ * It reads format 0.x. A minor version only adds members an earlier reader can
12
+ * ignore, so any 0.x is read and a member this file does not name is ignored;
13
+ * a major version it does not know is refused, whole, saying why.
14
+ *
15
+ * **Nothing here uses `innerHTML`.** A path, a placeholder's label and a
16
+ * host's note are someone's typing, and all of it reaches the page through
17
+ * `textContent`. No attribute is written from the document.
18
+ */
19
+ (function (global) {
20
+ const root = global || (typeof window !== 'undefined' ? window : {});
21
+
22
+ /* The major version of the format this file reads. */
23
+ const FORMAT_MAJOR = 0;
24
+
25
+ /* What each role the format names is called here. A role this client has
26
+ * not heard of is shown as the document spells it, rather than guessed into
27
+ * one of these. */
28
+ const ROLES = {
29
+ guide: 'Guide',
30
+ steps: 'Steps',
31
+ checklist: 'Checklist',
32
+ copy: 'Copy',
33
+ reference: 'Reference',
34
+ tool: 'Tool',
35
+ license: 'License',
36
+ changelog: 'Changelog',
37
+ };
38
+
39
+ /* The kinds of placeholder the format names, by when a buyer fills them in,
40
+ * in the format's order. A kind a later minor adds is ignored, as the
41
+ * format lets a reader ignore what it does not know. */
42
+ const SLOT_KINDS = [
43
+ ['setup', 'Once, for your business'],
44
+ ['message', 'Each time you use it'],
45
+ ];
46
+
47
+ function el(tag, className, textContent) {
48
+ const node = document.createElement(tag);
49
+ if (className) node.className = className;
50
+ if (textContent !== undefined && textContent !== null) node.textContent = String(textContent);
51
+ return node;
52
+ }
53
+
54
+ function clear(node) {
55
+ while (node.firstChild) node.removeChild(node.firstChild);
56
+ }
57
+
58
+ function isObject(value) {
59
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
60
+ }
61
+
62
+ function has(table, key) {
63
+ return Object.prototype.hasOwnProperty.call(table, key);
64
+ }
65
+
66
+ /* ---------- reading the document ----------
67
+ *
68
+ * The reader answers `{ value }` or `{ refusal }`, never both. A refusal is
69
+ * one sentence naming what was wrong, for whoever built the host's data. The
70
+ * block checks only what drawing needs: that the members it reads are what
71
+ * the format says they are, and that `order` and `same_as` name the files
72
+ * `files` lists, matched exactly, as the format matches them. Whether the
73
+ * files really say what the document claims is a checker's question, asked
74
+ * of the files, which this block never has. */
75
+
76
+ class Fault extends Error {}
77
+
78
+ function formatOf(doc) {
79
+ const value = doc.format_version;
80
+ if (value === undefined || value === null) {
81
+ throw new Fault('It carries no "format_version", and this client reads format ' + FORMAT_MAJOR + '.x.');
82
+ }
83
+ if (typeof value !== 'string' || !/^\d+\.\d+$/.test(value)) {
84
+ throw new Fault('"format_version" is not a version such as 0.1.');
85
+ }
86
+ if (Number(value.split('.')[0]) !== FORMAT_MAJOR) {
87
+ throw new Fault('It is in format ' + value + ', and this client reads format ' + FORMAT_MAJOR + '.x.');
88
+ }
89
+ return value;
90
+ }
91
+
92
+ function textMember(doc, key, required) {
93
+ const value = doc[key];
94
+ if (value === undefined || value === null) {
95
+ if (required) throw new Fault('"' + key + '" is missing.');
96
+ return '';
97
+ }
98
+ if (typeof value !== 'string') throw new Fault('"' + key + '" is not text.');
99
+ if (required && !value.trim()) throw new Fault('"' + key + '" is empty.');
100
+ return value;
101
+ }
102
+
103
+ function listMember(doc, key, where) {
104
+ const value = doc[key];
105
+ const name = where ? where + '.' + key : key;
106
+ if (value === undefined || value === null) throw new Fault('"' + name + '" is missing.');
107
+ if (!Array.isArray(value)) throw new Fault('"' + name + '" is not a list.');
108
+ return value;
109
+ }
110
+
111
+ function readFiles(doc) {
112
+ const entries = listMember(doc, 'files');
113
+ if (!entries.length) throw new Fault('"files" lists no file.');
114
+ const byPath = new Map();
115
+ entries.forEach(function (entry) {
116
+ if (!isObject(entry)) throw new Fault('"files" holds something other than a file.');
117
+ const path = textMember(entry, 'path', true);
118
+ if (byPath.has(path)) throw new Fault('"files" lists ' + path + ' twice.');
119
+ byPath.set(path, {
120
+ path,
121
+ role: textMember(entry, 'role', true),
122
+ sameAs: textMember(entry, 'same_as', false),
123
+ selfContained: entry.self_contained === true,
124
+ });
125
+ });
126
+ byPath.forEach(function (file) {
127
+ if (file.sameAs && (file.sameAs === file.path || !byPath.has(file.sameAs))) {
128
+ throw new Fault(file.path + ' is the same as ' + file.sameAs + ', which is not another file in "files".');
129
+ }
130
+ });
131
+
132
+ /* Drawn in `order`, which names every file once: the order a person works
133
+ * through them is part of what the playbook is. */
134
+ const seen = new Set();
135
+ const ordered = listMember(doc, 'order').map(function (path) {
136
+ if (typeof path !== 'string') throw new Fault('"order" holds something other than a path.');
137
+ if (!byPath.has(path)) throw new Fault('"order" names ' + path + ', which "files" does not.');
138
+ if (seen.has(path)) throw new Fault('"order" names ' + path + ' twice.');
139
+ seen.add(path);
140
+ return byPath.get(path);
141
+ });
142
+ byPath.forEach(function (file) {
143
+ if (!seen.has(file.path)) throw new Fault('"order" leaves out ' + file.path + '.');
144
+ });
145
+ return ordered;
146
+ }
147
+
148
+ function readSlots(doc) {
149
+ if (!isObject(doc.slots)) throw new Fault('"slots" is missing.');
150
+ return SLOT_KINDS.map(function (kind) {
151
+ const entries = listMember(doc.slots, kind[0], 'slots');
152
+ return {
153
+ kind: kind[0],
154
+ heading: kind[1],
155
+ slots: entries.map(function (entry) {
156
+ if (!isObject(entry)) throw new Fault('"slots.' + kind[0] + '" holds something other than a placeholder.');
157
+ return { placeholder: textMember(entry, 'placeholder', true), label: textMember(entry, 'label', true) };
158
+ }),
159
+ };
160
+ });
161
+ }
162
+
163
+ function readPlaybook(doc) {
164
+ try {
165
+ if (!isObject(doc)) throw new Fault('The document is not an object.');
166
+ const formatVersion = formatOf(doc);
167
+ return { value: { formatVersion, files: readFiles(doc), slotGroups: readSlots(doc) } };
168
+ } catch (err) {
169
+ if (err instanceof Fault) return { refusal: err.message };
170
+ throw err;
171
+ }
172
+ }
173
+
174
+ /* ---------- writing it down ---------- */
175
+
176
+ function headingLevel(options) {
177
+ const level = Number(options && options.headingLevel);
178
+ return Number.isInteger(level) && level >= 2 && level <= 6 ? level : 3;
179
+ }
180
+
181
+ function plural(count, one, many) {
182
+ return count + ' ' + (count === 1 ? one : many);
183
+ }
184
+
185
+ /* `a`, `a and b`, `a, b and c`. */
186
+ function and(items) {
187
+ return items.length === 1 ? items[0] : items.slice(0, -1).join(', ') + ' and ' + items[items.length - 1];
188
+ }
189
+
190
+ /* What a file adds to its role: the file it is another form of, and, for a
191
+ * page, that it opens in a browser and loads nothing. Only an `.html` file
192
+ * the document calls self-contained is said to work offline. */
193
+ function about(file) {
194
+ const parts = [];
195
+ if (file.sameAs) parts.push('Another form of ' + file.sameAs + '.');
196
+ if (/\.html$/i.test(file.path)) {
197
+ parts.push(file.selfContained ? 'Opens in a browser, and works offline.' : 'Opens in a browser.');
198
+ }
199
+ return parts.join(' ');
200
+ }
201
+
202
+ /* A sentence the host adds to one file, keyed by its path: something the
203
+ * host knows that the document does not say, such as what it found when it
204
+ * read the file. Drawn as text, beside the file it names; a note for a path
205
+ * the playbook does not hold is not drawn. */
206
+ function hostNote(options, path) {
207
+ const notes = options && options.fileNotes;
208
+ if (!isObject(notes) || !has(notes, path)) return '';
209
+ const note = notes[path];
210
+ return typeof note === 'string' ? note.trim() : '';
211
+ }
212
+
213
+ /* Two placeholders one case apart are two placeholders, which a reader
214
+ * replacing them by eye could take for one, so the block says so. */
215
+ function caseNote(groups) {
216
+ const folded = new Map();
217
+ groups.forEach(function (group) {
218
+ group.slots.forEach(function (slot) {
219
+ const key = slot.placeholder.toLowerCase();
220
+ if (!folded.has(key)) folded.set(key, []);
221
+ if (folded.get(key).indexOf(slot.placeholder) === -1) folded.get(key).push(slot.placeholder);
222
+ });
223
+ });
224
+ const pairs = [];
225
+ folded.forEach(function (spellings) {
226
+ if (spellings.length > 1) pairs.push(and(spellings) + ' are different placeholders');
227
+ });
228
+ return pairs.length ? 'Case matters: ' + pairs.join('; ') + '.' : '';
229
+ }
230
+
231
+ function filesPart(files, level, options) {
232
+ const part = el('div', 'gh-playbook-part');
233
+ part.appendChild(el('h' + level, 'gh-playbook-heading', 'The files'));
234
+ part.appendChild(el('p', 'gh-playbook-lead', plural(files.length, 'file', 'files') + ', in the order you work through them.'));
235
+ const list = el('ol', 'gh-playbook-files');
236
+ files.forEach(function (file) {
237
+ /* The row's parts sit in a box of their own, so the item stays a list
238
+ * item and keeps the number the browser gives it: an item laid out as
239
+ * a flex row is drawn with none. */
240
+ const item = el('li', 'gh-playbook-file');
241
+ const body = el('div', 'gh-playbook-file-body');
242
+ body.appendChild(el('code', 'gh-playbook-path', file.path));
243
+ body.appendChild(el('span', 'gh-playbook-role', has(ROLES, file.role) ? ROLES[file.role] : file.role));
244
+ const sentence = about(file);
245
+ if (sentence) body.appendChild(el('span', 'gh-playbook-about', sentence));
246
+ const note = hostNote(options, file.path);
247
+ if (note) body.appendChild(el('span', 'gh-playbook-note', note));
248
+ item.appendChild(body);
249
+ list.appendChild(item);
250
+ });
251
+ part.appendChild(list);
252
+ return part;
253
+ }
254
+
255
+ function placeholdersPart(groups, level) {
256
+ const part = el('div', 'gh-playbook-part');
257
+ part.appendChild(el('h' + level, 'gh-playbook-heading', 'The placeholders'));
258
+ const total = groups.reduce((sum, group) => sum + group.slots.length, 0);
259
+ if (!total) {
260
+ part.appendChild(el('p', 'gh-playbook-lead', 'None. Every file is used as it is.'));
261
+ return part;
262
+ }
263
+ part.appendChild(el('p', 'gh-playbook-lead', total === 1
264
+ ? 'One placeholder, in square brackets. Replace it with your own words wherever it appears.'
265
+ : total + ' placeholders, each in square brackets. Replace each with your own words wherever it appears.'));
266
+ const note = caseNote(groups);
267
+ if (note) part.appendChild(el('p', 'gh-playbook-lead', note));
268
+ /* Hoisted rather than written in the call, so the stylesheet's test, which
269
+ * reads the class beside the first comma, sees this one too. */
270
+ const subheading = 'h' + Math.min(level + 1, 6);
271
+ groups.forEach(function (group) {
272
+ if (!group.slots.length) return;
273
+ const section = el('div', 'gh-playbook-slot-group');
274
+ section.dataset.slotKind = group.kind;
275
+ section.appendChild(el(subheading, 'gh-playbook-subheading', group.heading));
276
+ const list = el('dl', 'gh-playbook-slots');
277
+ group.slots.forEach(function (slot) {
278
+ const row = el('div', 'gh-playbook-slot');
279
+ const name = el('dt', 'gh-playbook-slot-name');
280
+ name.appendChild(el('code', 'gh-playbook-token', slot.placeholder));
281
+ row.appendChild(name);
282
+ row.appendChild(el('dd', 'gh-playbook-slot-label', slot.label));
283
+ list.appendChild(row);
284
+ });
285
+ section.appendChild(list);
286
+ part.appendChild(section);
287
+ });
288
+ return part;
289
+ }
290
+
291
+ class PlaybookContents {
292
+ /* `playbook` is a playbook's `playbook.json`, parsed. `options.headingLevel`
293
+ * (2 to 6, default 3) is the level of the block's two headings, and the
294
+ * placeholders' kinds take the level below. `options.fileNotes` maps a
295
+ * file's path to a sentence of the host's own, drawn beside that file. */
296
+ constructor(container, playbook, options) {
297
+ this.container = container;
298
+ this.playbook = playbook;
299
+ this.options = options || {};
300
+ }
301
+
302
+ render() {
303
+ clear(this.container);
304
+ const block = el('section', 'gh-block gh-playbook');
305
+ this.container.appendChild(block);
306
+ const read = readPlaybook(this.playbook);
307
+ if (read.refusal) {
308
+ block.appendChild(el('p', 'gh-refuse', 'This playbook could not be shown. ' + read.refusal));
309
+ return;
310
+ }
311
+ const level = headingLevel(this.options);
312
+ block.appendChild(filesPart(read.value.files, level, this.options));
313
+ block.appendChild(placeholdersPart(read.value.slotGroups, level));
314
+ }
315
+
316
+ update(playbook) {
317
+ this.playbook = playbook;
318
+ this.render();
319
+ }
320
+ }
321
+
322
+ root.Gatehouse = Object.assign({}, root.Gatehouse, {
323
+ PlaybookContents,
324
+ playbookData: { FORMAT_MAJOR, ROLES: Object.keys(ROLES), readPlaybook },
325
+ });
326
+
327
+ /* The deprecated alias the other scripts keep; see `host_blocks.js`. */
328
+ root.SigrixRun = root.Gatehouse;
329
+ })(typeof window !== 'undefined' ? window : globalThis);
@@ -25,6 +25,17 @@
25
25
  while (node.firstChild) node.removeChild(node.firstChild);
26
26
  }
27
27
 
28
+ /* `options.conversation`: `true`, or `{ maxChars }` to bound what a reply
29
+ * carries. Anything else is no conversation: the one-run page this file has
30
+ * always drawn. */
31
+ function conversationSettings(option) {
32
+ if (option === true) return { maxChars: null };
33
+ if (option && typeof option === 'object') {
34
+ return { maxChars: typeof option.maxChars === 'number' && option.maxChars > 0 ? option.maxChars : null };
35
+ }
36
+ return null;
37
+ }
38
+
28
39
  function randomKey() {
29
40
  /* An idempotency key only has to be unique to this client (SPEC 4.2). */
30
41
  if (root.crypto && typeof root.crypto.randomUUID === 'function') return root.crypto.randomUUID();
@@ -49,7 +60,9 @@
49
60
  * `reportFailure`). `options.choice` says one select input chooses which
50
61
  * of the others apply (`inputChoice` in the view model has its shape): a
51
62
  * fact the host read about this runner, handed in for the composition's
52
- * reason. Nothing else is read. */
63
+ * reason. `options.conversation` keeps each brief and answer on the page
64
+ * and sends them with the next brief (`renderConversation`). Nothing else
65
+ * is read. */
53
66
  constructor(container, client, options) {
54
67
  const settings = options || {};
55
68
  this.container = container;
@@ -70,6 +83,12 @@
70
83
  this.lastInputsKey = '';
71
84
  this.idempotencyKey = '';
72
85
  this.onRunStateChange = settings.onRunStateChange || function () {};
86
+ this.conversation = conversationSettings(settings.conversation);
87
+ /* Held here and nowhere else: the page forgets the conversation when it
88
+ * is left, and a runner is only ever sent it inside a brief. */
89
+ this.turns = [];
90
+ this.lastDropped = 0;
91
+ this.lastAnswer = null;
73
92
  this.nodes = {};
74
93
  renderersMade += 1;
75
94
  this.idScope = 'run-' + renderersMade;
@@ -110,6 +129,8 @@
110
129
  shell.appendChild(this.renderReadiness(vm));
111
130
  const templates = this.renderTemplates(vm);
112
131
  if (templates) shell.appendChild(templates);
132
+ const conversation = this.renderConversation(vm);
133
+ if (conversation) shell.appendChild(conversation);
113
134
  shell.appendChild(this.renderForm(vm));
114
135
  shell.appendChild(this.renderControls(vm));
115
136
  shell.appendChild(this.renderOutput());
@@ -205,6 +226,122 @@
205
226
  return section;
206
227
  }
207
228
 
229
+ /* The field a conversation carries: the reserved brief, where the runner
230
+ * declares it as text. A runner with none has nothing to reply into, so
231
+ * its page stays the one-run page whatever the host asked for. */
232
+ conversationField() {
233
+ if (!this.conversation || !this.viewModel) return null;
234
+ const key = NS.viewModel.PROMPT_KEY;
235
+ return this.viewModel.fields.find(field => field.key === key && field.type === 'text') || null;
236
+ }
237
+
238
+ /* The characters a reply may carry: the brief's own `max_length`, which the
239
+ * runner enforces, and the host's bound or the view model's under it. */
240
+ conversationLimit(field) {
241
+ const bounds = [this.conversation.maxChars || NS.viewModel.CONVERSATION_MAX_CHARS];
242
+ if (field.maxLength !== null) bounds.push(field.maxLength);
243
+ return Math.min.apply(Math, bounds);
244
+ }
245
+
246
+ /* A conversation, above the form: each brief sent and the answer it got,
247
+ * oldest first. No verb takes a `run_id` (SPEC 4.5), so a run cannot be
248
+ * pointed at the one before it: the agent sees what came before because
249
+ * the next brief carries it, which `conversationBrief` composes, and the
250
+ * note says so. */
251
+ renderConversation(vm) {
252
+ if (!this.conversationField()) return null;
253
+ const self = this;
254
+ const section = el('section', 'run-conversation');
255
+ section.setAttribute('aria-label', 'Conversation');
256
+ this.nodes.turns = el('ol', 'run-turns');
257
+ section.appendChild(this.nodes.turns);
258
+ const foot = el('div', 'run-conversation-foot');
259
+ this.nodes.conversationNote = el('p', 'run-conversation-note');
260
+ foot.appendChild(this.nodes.conversationNote);
261
+ const reset = el('button', 'run-conversation-reset', 'New conversation');
262
+ reset.type = 'button';
263
+ reset.addEventListener('click', function () { self.resetConversation(); });
264
+ foot.appendChild(reset);
265
+ section.appendChild(foot);
266
+ this.nodes.conversation = section;
267
+ this.nodes.conversationReset = reset;
268
+ this.turns.forEach(function (turn) { self.appendTurn(turn, vm); });
269
+ this.syncConversation();
270
+ return section;
271
+ }
272
+
273
+ appendTurn(turn, vm) {
274
+ const item = el('li', 'run-turn');
275
+ item.appendChild(el('p', 'run-turn-who', 'You'));
276
+ item.appendChild(el('p', 'run-turn-brief', turn.brief));
277
+ item.appendChild(el('p', 'run-turn-who', vm.header.name || 'The agent'));
278
+ const answer = el('div', 'run-turn-answer');
279
+ /* Drawn as the result panel draws it, so a turn reads the same before
280
+ * and after it moves up: structure for `markdown`, text for the rest. */
281
+ if (vm.output.mode === 'markdown') this.renderMarkdown(turn.answer, answer);
282
+ else answer.appendChild(el('p', 'run-turn-text', turn.answer));
283
+ if (vm.output.mode === 'file') answer.appendChild(this.textDownloadLink(turn.answer));
284
+ item.appendChild(answer);
285
+ this.nodes.turns.appendChild(item);
286
+ }
287
+
288
+ syncConversation() {
289
+ if (!this.nodes.conversation) return;
290
+ this.nodes.conversation.hidden = this.turns.length === 0;
291
+ this.nodes.conversationReset.disabled = Boolean(this.abortController);
292
+ const dropped = this.lastDropped;
293
+ this.nodes.conversationNote.textContent = dropped
294
+ ? 'A reply sends the conversation above with it, except the ' +
295
+ (dropped === 1 ? 'first message, which no longer fits' : dropped + ' oldest messages, which no longer fit') +
296
+ '. The page forgets it when you leave.'
297
+ : 'A reply sends the conversation above with it, so the agent can build on it. The page forgets it when you leave.';
298
+ }
299
+
300
+ recordTurn(message, answer) {
301
+ const field = this.conversationField();
302
+ const turn = { brief: message, answer: answer };
303
+ this.turns.push(turn);
304
+ this.appendTurn(turn, this.viewModel);
305
+ /* The answer lives in the conversation now, so the result panel is
306
+ * emptied rather than left showing it twice. The usage line and the
307
+ * timeline stay: they are about the run that has just ended. */
308
+ this.nodes.result.textContent = '';
309
+ this.clearRendered();
310
+ this.values[field.key] = '';
311
+ const control = this.nodes.inputs[field.key];
312
+ if (control) control.value = '';
313
+ this.lastDropped = NS.viewModel.conversationBrief(this.turns, '', this.conversationLimit(field)).dropped;
314
+ this.syncConversation();
315
+ if (control) control.focus();
316
+ }
317
+
318
+ /* Reached only from its button, which `syncConversation` disables while a
319
+ * run is in flight, so a run never records into a conversation it did not
320
+ * start from. */
321
+ resetConversation() {
322
+ this.turns = [];
323
+ this.lastDropped = 0;
324
+ if (this.nodes.turns) {
325
+ this.revokeDownloads(this.nodes.turns);
326
+ clear(this.nodes.turns);
327
+ }
328
+ this.syncConversation();
329
+ const field = this.conversationField();
330
+ if (field && this.nodes.inputs[field.key]) this.nodes.inputs[field.key].focus();
331
+ }
332
+
333
+ revokeDownloads(scope) {
334
+ Array.prototype.slice.call(scope.querySelectorAll('.run-download')).forEach(function (node) {
335
+ URL.revokeObjectURL(node.href);
336
+ node.parentNode.removeChild(node);
337
+ });
338
+ }
339
+
340
+ clearRendered() {
341
+ this.revokeDownloads(this.nodes.rendered);
342
+ clear(this.nodes.rendered);
343
+ }
344
+
208
345
  renderForm(vm) {
209
346
  const section = el('section', 'run-form');
210
347
  const self = this;
@@ -397,6 +534,7 @@
397
534
  * content only, so headings and lists cannot be built inside it. */
398
535
  this.nodes.rendered = el('div', 'run-result-rendered');
399
536
  this.nodes.usage = el('p', 'run-usage');
537
+ this.nodes.output = section;
400
538
  section.appendChild(this.nodes.notice);
401
539
  section.appendChild(this.nodes.timeline);
402
540
  section.appendChild(this.nodes.result);
@@ -441,6 +579,16 @@
441
579
  if (!vm.level.canRun || this.abortController) return;
442
580
 
443
581
  const inputs = NS.viewModel.runInputs(vm.fields, this.values, vm.choice);
582
+ /* In a conversation the brief carries the turns before it. What was
583
+ * typed is kept apart, because that, not the composed whole, is the
584
+ * turn the page records. */
585
+ const brief = this.conversationField();
586
+ const message = brief && this.values[brief.key] !== undefined ? String(this.values[brief.key]) : '';
587
+ if (brief && this.turns.length && Object.prototype.hasOwnProperty.call(inputs, brief.key)) {
588
+ const reply = NS.viewModel.conversationBrief(this.turns, message, this.conversationLimit(brief));
589
+ inputs[brief.key] = reply.value;
590
+ this.lastDropped = reply.dropped;
591
+ }
444
592
  const inputsKey = JSON.stringify(inputs);
445
593
  if (vm.capabilities.idempotentRetry) {
446
594
  /* A replay is free only for the same inputs under the same key. Edited
@@ -459,13 +607,10 @@
459
607
  /* A download link is appended beside the result rather than inside it,
460
608
  * so clearing the result does not remove it — two `bytes` runs would
461
609
  * otherwise leave two links, the older one pointing at the earlier
462
- * result and no way to tell them apart. */
463
- Array.prototype.slice
464
- .call(this.container.querySelectorAll('.run-download'))
465
- .forEach(function (node) {
466
- URL.revokeObjectURL(node.href);
467
- node.parentNode.removeChild(node);
468
- });
610
+ * result and no way to tell them apart. Only the result panel's: a turn
611
+ * of the conversation keeps the link to its own answer. */
612
+ this.revokeDownloads(this.nodes.output);
613
+ this.lastAnswer = null;
469
614
  /* And a field marked invalid by the last refusal stops being marked, or
470
615
  * a corrected input keeps wearing the error that has just been fixed. */
471
616
  Object.keys(this.nodes.inputs || {}).forEach(key => {
@@ -476,18 +621,30 @@
476
621
  this.nodes.stop.disabled = false;
477
622
  this.nodes.retry.disabled = true;
478
623
  this.syncRunEnabled();
624
+ this.syncConversation();
479
625
  this.onRunStateChange('running');
480
626
 
627
+ /* A turn is recorded only for an answer the page could show as text: a
628
+ * refusal, a stop, a file or a type this client cannot draw leaves the
629
+ * brief in its field, to send again or change. */
630
+ let recorded = false;
481
631
  try {
482
632
  if (vm.level.streams) await this.runStreamed(inputs);
483
633
  else await this.runWhole(inputs);
634
+ if (brief && this.lastAnswer !== null) {
635
+ this.recordTurn(message, this.lastAnswer);
636
+ recorded = true;
637
+ }
484
638
  } catch (err) {
485
639
  this.reportFailure(err);
486
640
  } finally {
487
641
  this.abortController = null;
488
642
  this.nodes.stop.disabled = true;
489
- this.nodes.retry.disabled = false;
643
+ /* Nothing to retry once the answer is a turn: its brief has left the
644
+ * field, and a reply is the next thing to send. */
645
+ this.nodes.retry.disabled = recorded;
490
646
  this.syncRunEnabled();
647
+ this.syncConversation();
491
648
  this.onRunStateChange('idle');
492
649
  }
493
650
  }
@@ -601,6 +758,7 @@
601
758
  }
602
759
 
603
760
  const value = output.value === undefined || output.value === null ? '' : String(output.value);
761
+ this.lastAnswer = value;
604
762
  if (plan.mode === 'markdown') {
605
763
  /* Structure only, and built node by node — see `outputBlocks`. The
606
764
  * `<pre>` is emptied rather than left carrying the stream's plain copy
@@ -618,8 +776,8 @@
618
776
  }
619
777
  }
620
778
 
621
- renderMarkdown(value) {
622
- const target = this.nodes.rendered;
779
+ renderMarkdown(value, into) {
780
+ const target = into || this.nodes.rendered;
623
781
  NS.viewModel.outputBlocks(value).forEach(function (block) {
624
782
  if (block.kind === 'heading') {
625
783
  /* Clamped to h2..h4: the page's own `<h1>` is the agent's name, and
@@ -643,10 +801,14 @@
643
801
  }
644
802
 
645
803
  offerTextDownload(value) {
804
+ this.nodes.rendered.appendChild(this.textDownloadLink(value));
805
+ }
806
+
807
+ textDownloadLink(value) {
646
808
  const link = el('a', 'run-download', 'Download the result');
647
809
  link.href = URL.createObjectURL(new Blob([value], { type: 'text/plain' }));
648
810
  link.download = 'result.txt';
649
- this.nodes.rendered.appendChild(link);
811
+ return link;
650
812
  }
651
813
 
652
814
  offerDownload(output) {
@@ -426,6 +426,40 @@
426
426
  /* SPEC 4.1.2: a client SHOULD surface `write_tools` and MAY require a
427
427
  * confirmation. This one requires it, once per session, because the tools
428
428
  * named here are the ones that spend money or reach past the workspace. */
429
+ /* How much of a conversation a reply carries when the host names no bound
430
+ * and the brief declares no `max_length`: about four thousand tokens of
431
+ * text, enough for several exchanges and a cap on what a long one costs. */
432
+ const CONVERSATION_MAX_CHARS = 16000;
433
+
434
+ /* A reply in a conversation, as the one brief a run takes. No verb takes a
435
+ * `run_id` (SPEC 4.5), so a client cannot point a run at an earlier one, and
436
+ * the way an agent sees what was said before is for the client to send it.
437
+ * The earlier turns come first, oldest first, then the new message, each
438
+ * under a line saying whose words they are, in plain text the agent reads as
439
+ * its brief.
440
+ *
441
+ * `limit` bounds the whole in characters. The oldest turns are the ones
442
+ * left out when it would pass it, and the answer says how many were, so the
443
+ * page can say so rather than let a reader think the agent saw them. The new
444
+ * message is never cut: the field's own `max_length` bounds it as typed. */
445
+ function conversationBrief(turns, message, limit) {
446
+ const said = text(message);
447
+ const all = asArray(turns).filter(isObject);
448
+ const cap = typeof limit === 'number' && limit > 0 ? limit : CONVERSATION_MAX_CHARS;
449
+ for (let first = 0; first < all.length; first++) {
450
+ const kept = all.slice(first);
451
+ const parts = ['This continues an earlier exchange with you. What was said before, oldest first:'];
452
+ kept.forEach(function (turn) {
453
+ parts.push('The user wrote:\n' + text(turn.brief));
454
+ parts.push('You answered:\n' + text(turn.answer));
455
+ });
456
+ parts.push('Now the user writes, and this is the message to answer:\n' + said);
457
+ const value = parts.join('\n\n');
458
+ if (value.length <= cap) return { value, sent: kept.length, dropped: first };
459
+ }
460
+ return { value: said, sent: 0, dropped: all.length };
461
+ }
462
+
429
463
  function capabilities(describe) {
430
464
  const declared = isObject(describe && describe.capabilities) ? describe.capabilities : {};
431
465
  const writeTools = asArray(declared.write_tools).map(text).filter(Boolean);
@@ -621,6 +655,8 @@
621
655
  formFields,
622
656
  runInputs,
623
657
  initialValues,
658
+ conversationBrief,
659
+ CONVERSATION_MAX_CHARS,
624
660
  examples,
625
661
  outputPlan,
626
662
  capabilities,