@sigrix-io/gatehouse 0.1.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.
@@ -0,0 +1,731 @@
1
+ /* The page: header, readiness, templates, form, controls, output, usage.
2
+ *
3
+ * **Nothing here uses `innerHTML`.** Every string that came from the agent or
4
+ * from its runner reaches the page through `textContent`, so "agent output is
5
+ * rendered as text, never as markup" is a property of the file rather than a
6
+ * rule somebody has to keep remembering — a source scan holds the line. This
7
+ * repository has paid once already for an escaper that did not escape quotes;
8
+ * the cheapest way not to pay again is to have nothing to escape.
9
+ *
10
+ * The base URL is a constructor argument and no listing identifier reaches
11
+ * this file, so the same renderer serves a proxied runner and a local one.
12
+ */
13
+ (function (global) {
14
+ const root = global || (typeof window !== 'undefined' ? window : {});
15
+ const NS = root.Gatehouse || {};
16
+
17
+ function el(tag, className, textContent) {
18
+ const node = document.createElement(tag);
19
+ if (className) node.className = className;
20
+ if (textContent !== undefined && textContent !== null) node.textContent = String(textContent);
21
+ return node;
22
+ }
23
+
24
+ function clear(node) {
25
+ while (node.firstChild) node.removeChild(node.firstChild);
26
+ }
27
+
28
+ function randomKey() {
29
+ /* An idempotency key only has to be unique to this client (SPEC 4.2). */
30
+ if (root.crypto && typeof root.crypto.randomUUID === 'function') return root.crypto.randomUUID();
31
+ return 'k-' + Date.now() + '-' + Math.random().toString(16).slice(2);
32
+ }
33
+
34
+ class RunRenderer {
35
+ /* `container` is where the page is drawn; `client` is any object with the
36
+ * four verbs, so a caller may pass its own. `options.composition` is the
37
+ * seller's `ui.json` — a *document*, handed in by whoever read the
38
+ * bundle, because reading a file is not one of the four verbs and a
39
+ * renderer that fetched it would be reaching for a fifth.
40
+ * `options.hosted` says the platform operates this runner rather than the
41
+ * person reading, which changes only what a failure may quote back (see
42
+ * `reportFailure`). `options.choice` says one select input chooses which
43
+ * of the others apply (`inputChoice` in the view model has its shape): a
44
+ * fact the host read about this runner, handed in for the composition's
45
+ * reason. Nothing else is read. */
46
+ constructor(container, client, options) {
47
+ const settings = options || {};
48
+ this.container = container;
49
+ this.client = client;
50
+ this.composition = settings.composition || null;
51
+ this.choice = settings.choice || null;
52
+ /* Who operates the runner this page is driving. Self-hosted is the
53
+ * default because that is the deployment this file was written for, and
54
+ * the hosted page states it rather than letting the presence of a proxy
55
+ * base stand in for the statement — a proxy base is a coincidence of
56
+ * that deployment, not a claim about who owns the keys. */
57
+ this.hosted = settings.hosted === true;
58
+ this.viewModel = null;
59
+ this.values = {};
60
+ this.writeToolsAccepted = false;
61
+ this.abortController = null;
62
+ this.lastRunId = '';
63
+ this.lastInputsKey = '';
64
+ this.idempotencyKey = '';
65
+ this.onRunStateChange = settings.onRunStateChange || function () {};
66
+ this.nodes = {};
67
+ }
68
+
69
+ async load() {
70
+ const [describe, status] = await Promise.all([this.client.describe(), this.client.status()]);
71
+ this.describe = describe;
72
+ this.status = status;
73
+ this.viewModel = NS.viewModel.build(describe, status, this.composition, this.choice);
74
+ this.values = Object.assign({}, this.viewModel.initialValues);
75
+ this.render();
76
+ return this.viewModel;
77
+ }
78
+
79
+ render() {
80
+ const vm = this.viewModel;
81
+ clear(this.container);
82
+ this.container.appendChild(el('div', 'run-shell'));
83
+ const shell = this.container.firstChild;
84
+
85
+ /* A nonconformant document stops the page here. SPEC 7 says a client
86
+ * meeting a credential value SHOULD refuse to proceed; this one does,
87
+ * and says why rather than rendering a form that must not be used. */
88
+ if (vm.refuseReason) {
89
+ shell.appendChild(el('p', 'run-refuse', vm.refuseReason));
90
+ return;
91
+ }
92
+
93
+ shell.appendChild(this.renderHeader(vm));
94
+ shell.appendChild(this.renderReadiness(vm));
95
+ const templates = this.renderTemplates(vm);
96
+ if (templates) shell.appendChild(templates);
97
+ shell.appendChild(this.renderForm(vm));
98
+ shell.appendChild(this.renderControls(vm));
99
+ shell.appendChild(this.renderOutput());
100
+ }
101
+
102
+ renderHeader(vm) {
103
+ const section = el('section', 'run-header');
104
+ section.appendChild(el('h1', 'run-title', vm.header.name));
105
+ if (vm.header.summary) section.appendChild(el('p', 'run-summary', vm.header.summary));
106
+ const meta = el('p', 'run-meta');
107
+ /* Verbatim, both of them: the identifier is what the buyer types into
108
+ * `.env`, and a client that prettified it would be describing a
109
+ * different agent from the one the runner names at boot. */
110
+ meta.appendChild(el('code', 'run-agent-id', vm.header.id));
111
+ if (vm.header.version) meta.appendChild(el('span', 'run-version', ' ' + vm.header.version));
112
+ section.appendChild(meta);
113
+ if (vm.updateNotice) section.appendChild(el('p', 'run-update', vm.updateNotice));
114
+ /* Named rather than half-applied. A template this client cannot draw is
115
+ * the one composition member whose fallback changes the whole page
116
+ * rather than one control, so a seller previewing a draft is told why
117
+ * their layout is the plain one instead of left to guess. */
118
+ if (vm.presentation.unrecognisedTemplate) {
119
+ section.appendChild(el('p', 'run-update',
120
+ 'This listing asks for the "' + vm.presentation.unrecognisedTemplate +
121
+ '" layout, which this client does not draw. Showing the standard one.'));
122
+ }
123
+ return section;
124
+ }
125
+
126
+ renderReadiness(vm) {
127
+ const section = el('section', 'run-readiness');
128
+
129
+ const banner = vm.entitlement;
130
+ if (banner.message) {
131
+ section.appendChild(el('p', 'run-entitlement run-entitlement--' + banner.tone, banner.message));
132
+ }
133
+ if (vm.level.note) section.appendChild(el('p', 'run-level', vm.level.note));
134
+ section.appendChild(el('p', 'run-state', 'Runner state: ' + (vm.state || 'unknown')));
135
+
136
+ if (vm.readiness.rows.length) {
137
+ const list = el('ul', 'run-credentials');
138
+ vm.readiness.rows.forEach(function (row) {
139
+ const item = el('li', 'run-credential' + (row.satisfied ? ' is-satisfied' : ' is-missing'));
140
+ item.appendChild(el('code', 'run-credential-env', row.env));
141
+ item.appendChild(el('span', 'run-credential-tick', row.satisfied ? ' set' : ' not set'));
142
+ if (row.purpose) item.appendChild(el('span', 'run-credential-purpose', ' — ' + row.purpose));
143
+ if (row.signupUrl && !row.satisfied) {
144
+ const link = el('a', 'run-credential-link', 'Get a key');
145
+ link.href = row.signupUrl;
146
+ link.rel = 'noopener noreferrer';
147
+ link.target = '_blank';
148
+ item.appendChild(link);
149
+ }
150
+ list.appendChild(item);
151
+ });
152
+ section.appendChild(list);
153
+ if (!vm.readiness.satisfied) section.appendChild(el('p', 'run-credential-where', vm.readiness.where));
154
+ }
155
+ return section;
156
+ }
157
+
158
+ /* The examples the seller captured are the templates: no template format
159
+ * is invented here, and there is no control that edits anything but an
160
+ * input value. Absent examples render nothing at all rather than an empty
161
+ * row — which is what both of this repository's real documents do today. */
162
+ renderTemplates(vm) {
163
+ if (!vm.examples.length) return null;
164
+ const section = el('section', 'run-templates');
165
+ section.appendChild(el('h2', 'run-templates-title', 'Start from an example'));
166
+ const row = el('div', 'run-template-row');
167
+ const self = this;
168
+ vm.examples.forEach(function (example) {
169
+ const chip = el('button', 'run-template-chip', example.label);
170
+ chip.type = 'button';
171
+ chip.addEventListener('click', function () {
172
+ self.values = Object.assign({}, NS.viewModel.initialValues(self.describe, example.index));
173
+ self.syncFormValues();
174
+ /* Editing the inputs makes any held key stale: SPEC 4.2 answers a
175
+ * reused key carrying different inputs with a 409, and there is no
176
+ * reason to trigger it. */
177
+ self.idempotencyKey = '';
178
+ });
179
+ row.appendChild(chip);
180
+ });
181
+ section.appendChild(row);
182
+ const first = vm.examples[0];
183
+ if (first && first.output) {
184
+ const shown = el('details', 'run-template-output');
185
+ shown.appendChild(el('summary', null, 'What a result looks like'));
186
+ shown.appendChild(el('pre', 'run-template-output-body', first.output));
187
+ section.appendChild(shown);
188
+ }
189
+ return section;
190
+ }
191
+
192
+ renderForm(vm) {
193
+ const section = el('section', 'run-form');
194
+ const self = this;
195
+ this.nodes.inputs = {};
196
+ this.nodes.fields = {};
197
+ this.nodes.choiceAbout = null;
198
+ vm.fields.forEach(function (field) {
199
+ const wrap = el('div', 'run-field');
200
+ const id = 'run-field-' + field.key;
201
+ const label = el('label', 'run-field-label', field.label + (field.required ? ' *' : ''));
202
+ label.htmlFor = id;
203
+ wrap.appendChild(label);
204
+
205
+ let control;
206
+ if (field.type === 'select') {
207
+ control = el('select', 'run-field-control');
208
+ field.options.forEach(function (option) {
209
+ const node = el('option', null, option);
210
+ node.value = option;
211
+ control.appendChild(node);
212
+ });
213
+ } else if (field.multiline) {
214
+ control = el('textarea', 'run-field-control run-field-control--large');
215
+ control.rows = 6;
216
+ } else {
217
+ control = el('input', 'run-field-control');
218
+ control.type = field.type === 'number' ? 'number' : 'text';
219
+ if (field.min !== null) control.min = String(field.min);
220
+ if (field.max !== null) control.max = String(field.max);
221
+ }
222
+ control.id = id;
223
+ control.name = field.key;
224
+ if (field.required) control.required = true;
225
+ if (field.maxLength !== null && control.tagName !== 'SELECT') {
226
+ control.maxLength = field.maxLength;
227
+ }
228
+ /* Seller prose, and it reaches the page the only way anything does
229
+ * here: as text. `el()` writes `textContent`, and a placeholder is an
230
+ * attribute the browser never parses as markup. */
231
+ if (field.placeholder && control.tagName !== 'SELECT') control.placeholder = field.placeholder;
232
+ control.value = self.values[field.key] === undefined ? '' : String(self.values[field.key]);
233
+ const chooses = Boolean(vm.choice) && field.key === vm.choice.key;
234
+ control.addEventListener('input', function () {
235
+ self.values[field.key] = control.value;
236
+ self.idempotencyKey = '';
237
+ if (chooses) self.syncChoice();
238
+ });
239
+ control.addEventListener('change', function () {
240
+ self.values[field.key] = control.value;
241
+ self.idempotencyKey = '';
242
+ if (chooses) self.syncChoice();
243
+ });
244
+ wrap.appendChild(control);
245
+
246
+ /* Said rather than hidden. The runner validates again on `run`, so
247
+ * this form's checking is a courtesy — but a type it flattened to a
248
+ * text box is a fact the buyer is entitled to see. */
249
+ if (field.unrecognisedType) {
250
+ wrap.appendChild(el('p', 'run-field-note',
251
+ 'This runner declared type "' + field.declaredType + '", which this client does not know. Showing a text box.'));
252
+ }
253
+ if (field.help) wrap.appendChild(el('p', 'run-field-help', field.help));
254
+ /* What the chosen option does, beneath the control that chooses it,
255
+ * rewritten on every change of it. */
256
+ if (chooses) {
257
+ self.nodes.choiceAbout = el('p', 'run-field-help');
258
+ wrap.appendChild(self.nodes.choiceAbout);
259
+ }
260
+ /* Said, not swallowed. A widget a field's declared type cannot wear is
261
+ * a composition the seller wrote and this page did not apply, and the
262
+ * one place they will see that is the preview they are standing in. */
263
+ if (field.ignoredWidget) {
264
+ wrap.appendChild(el('p', 'run-field-note',
265
+ 'This listing asks for a "' + field.ignoredWidget + '" control, which a ' + field.type +
266
+ ' input cannot be. Showing the ' + field.type + ' control the runner declared.'));
267
+ }
268
+ section.appendChild(wrap);
269
+ self.nodes.inputs[field.key] = control;
270
+ self.nodes.fields[field.key] = wrap;
271
+ });
272
+ this.syncChoice();
273
+ return section;
274
+ }
275
+
276
+ /* Only the chosen option's fields are on show. The others are hidden
277
+ * rather than removed, so what was typed into them is still there if the
278
+ * buyer chooses that option again, and `runInputs` leaves them out of the
279
+ * run either way. */
280
+ syncChoice() {
281
+ const vm = this.viewModel;
282
+ if (!vm || !vm.choice) return;
283
+ const chosen = this.values[vm.choice.key] === undefined ? '' : String(this.values[vm.choice.key]);
284
+ const self = this;
285
+ vm.fields.forEach(function (field) {
286
+ const wrap = self.nodes.fields && self.nodes.fields[field.key];
287
+ if (wrap && field.group) wrap.hidden = field.group !== chosen;
288
+ });
289
+ if (this.nodes.choiceAbout) {
290
+ const about = Object.prototype.hasOwnProperty.call(vm.choice.about, chosen) ? vm.choice.about[chosen] : '';
291
+ this.nodes.choiceAbout.textContent = about;
292
+ this.nodes.choiceAbout.hidden = !about;
293
+ }
294
+ }
295
+
296
+ renderControls(vm) {
297
+ const section = el('section', 'run-controls');
298
+ const self = this;
299
+
300
+ if (vm.capabilities.tools.length) {
301
+ const tools = el('details', 'run-tools');
302
+ tools.appendChild(el('summary', null, 'What this agent can do'));
303
+ const list = el('ul', 'run-tool-list');
304
+ vm.capabilities.tools.forEach(function (tool) {
305
+ list.appendChild(el('li', 'run-tool', tool));
306
+ });
307
+ tools.appendChild(list);
308
+ section.appendChild(tools);
309
+ }
310
+
311
+ /* SPEC 4.1.2 makes surfacing these a SHOULD and the confirmation a MAY.
312
+ * The confirmation is required here, once per session, and it carries
313
+ * the sentence SPEC 4.5 forces: an abort is not a rollback, so money
314
+ * spent before the tab closed stays spent. */
315
+ if (vm.capabilities.needsWriteConfirmation) {
316
+ const gate = el('div', 'run-write-gate');
317
+ const box = el('input', 'run-write-check');
318
+ box.type = 'checkbox';
319
+ box.id = 'run-write-confirm';
320
+ const label = el('label', 'run-write-label',
321
+ 'This agent can ' + vm.capabilities.writeTools.join(', ') +
322
+ '. 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';
324
+ box.addEventListener('change', function () {
325
+ self.writeToolsAccepted = box.checked;
326
+ self.syncRunEnabled();
327
+ });
328
+ gate.appendChild(box);
329
+ gate.appendChild(label);
330
+ section.appendChild(gate);
331
+ this.nodes.writeGate = box;
332
+ }
333
+
334
+ const actions = el('div', 'run-actions');
335
+ /* The seller's word for the action, where they gave one. It is prose
336
+ * bounded and scanned at publish and written here with `textContent`,
337
+ * so the widest thing it can do is be a long word. */
338
+ const runButton = el('button', 'run-go', vm.presentation.runLabel || 'Run');
339
+ runButton.type = 'button';
340
+ runButton.addEventListener('click', function () { self.start({ reuseKey: false }); });
341
+ actions.appendChild(runButton);
342
+
343
+ const stopButton = el('button', 'run-stop', 'Stop');
344
+ stopButton.type = 'button';
345
+ stopButton.disabled = true;
346
+ stopButton.addEventListener('click', function () { self.stop(); });
347
+ actions.appendChild(stopButton);
348
+
349
+ const retryButton = el('button', 'run-retry', 'Retry');
350
+ retryButton.type = 'button';
351
+ retryButton.disabled = true;
352
+ retryButton.addEventListener('click', function () { self.start({ reuseKey: true }); });
353
+ actions.appendChild(retryButton);
354
+ section.appendChild(actions);
355
+
356
+ /* Absent means the runner imposes no bound, and saying nothing is the
357
+ * only honest rendering of that. */
358
+ if (vm.limits.maxRunSeconds !== null) {
359
+ section.appendChild(el('p', 'run-limit', 'This runner stops a run after ' + vm.limits.maxRunSeconds + 's.'));
360
+ }
361
+ if (!vm.capabilities.idempotentRetry) {
362
+ section.appendChild(el('p', 'run-retry-note',
363
+ 'Retry runs the agent again — this runner does not offer free replays.'));
364
+ }
365
+
366
+ this.nodes.run = runButton;
367
+ this.nodes.stop = stopButton;
368
+ this.nodes.retry = retryButton;
369
+ this.syncRunEnabled();
370
+ return section;
371
+ }
372
+
373
+ renderOutput() {
374
+ const section = el('section', 'run-output');
375
+ this.nodes.notice = el('p', 'run-notice');
376
+ this.nodes.timeline = el('ol', 'run-timeline');
377
+ this.nodes.result = el('pre', 'run-result');
378
+ /* A second node rather than a mode switch on the first. The `<pre>` is
379
+ * what a stream fills token by token — partial markdown is not markdown,
380
+ * so it stays plain until the run ends — and `<pre>` accepts phrasing
381
+ * content only, so headings and lists cannot be built inside it. */
382
+ this.nodes.rendered = el('div', 'run-result-rendered');
383
+ this.nodes.usage = el('p', 'run-usage');
384
+ section.appendChild(this.nodes.notice);
385
+ section.appendChild(this.nodes.timeline);
386
+ section.appendChild(this.nodes.result);
387
+ section.appendChild(this.nodes.rendered);
388
+ section.appendChild(this.nodes.usage);
389
+ return section;
390
+ }
391
+
392
+ syncFormValues() {
393
+ const self = this;
394
+ Object.keys(this.nodes.inputs || {}).forEach(function (key) {
395
+ const control = self.nodes.inputs[key];
396
+ const value = self.values[key];
397
+ control.value = value === undefined || value === null ? '' : String(value);
398
+ });
399
+ this.syncChoice();
400
+ }
401
+
402
+ syncRunEnabled() {
403
+ if (!this.nodes.run) return;
404
+ const vm = this.viewModel;
405
+ const blockedByEntitlement = vm.entitlement.tone === 'blocked';
406
+ const blockedByWriteTools = vm.capabilities.needsWriteConfirmation && !this.writeToolsAccepted;
407
+ this.nodes.run.disabled = Boolean(
408
+ !vm.level.canRun || blockedByEntitlement || blockedByWriteTools || this.abortController
409
+ );
410
+ }
411
+
412
+ setNotice(message) {
413
+ this.nodes.notice.textContent = message || '';
414
+ }
415
+
416
+ stop() {
417
+ /* There is no cancel verb and there will not be one: aborting the
418
+ * request *is* the cancellation (SPEC 4.5). */
419
+ if (this.abortController) this.abortController.abort();
420
+ }
421
+
422
+ async start(options) {
423
+ const settings = options || {};
424
+ const vm = this.viewModel;
425
+ if (!vm.level.canRun || this.abortController) return;
426
+
427
+ const inputs = NS.viewModel.runInputs(vm.fields, this.values, vm.choice);
428
+ const inputsKey = JSON.stringify(inputs);
429
+ if (vm.capabilities.idempotentRetry) {
430
+ /* A replay is free only for the same inputs under the same key. Edited
431
+ * inputs already cleared the key; this covers the first run too. */
432
+ if (!settings.reuseKey || !this.idempotencyKey || this.lastInputsKey !== inputsKey) {
433
+ this.idempotencyKey = randomKey();
434
+ }
435
+ } else {
436
+ this.idempotencyKey = '';
437
+ }
438
+ this.lastInputsKey = inputsKey;
439
+
440
+ clear(this.nodes.timeline);
441
+ this.nodes.result.textContent = '';
442
+ this.nodes.usage.textContent = '';
443
+ /* A download link is appended beside the result rather than inside it,
444
+ * so clearing the result does not remove it — two `bytes` runs would
445
+ * otherwise leave two links, the older one pointing at the earlier
446
+ * result and no way to tell them apart. */
447
+ Array.prototype.slice
448
+ .call(this.container.querySelectorAll('.run-download'))
449
+ .forEach(function (node) {
450
+ URL.revokeObjectURL(node.href);
451
+ node.parentNode.removeChild(node);
452
+ });
453
+ /* And a field marked invalid by the last refusal stops being marked, or
454
+ * a corrected input keeps wearing the error that has just been fixed. */
455
+ Object.keys(this.nodes.inputs || {}).forEach(key => {
456
+ this.nodes.inputs[key].classList.remove('is-invalid');
457
+ });
458
+ this.setNotice(vm.level.streams ? 'Running…' : 'Running — this runner returns the whole result at once.');
459
+ this.abortController = new AbortController();
460
+ this.nodes.stop.disabled = false;
461
+ this.nodes.retry.disabled = true;
462
+ this.syncRunEnabled();
463
+ this.onRunStateChange('running');
464
+
465
+ try {
466
+ if (vm.level.streams) await this.runStreamed(inputs);
467
+ else await this.runWhole(inputs);
468
+ } catch (err) {
469
+ this.reportFailure(err);
470
+ } finally {
471
+ this.abortController = null;
472
+ this.nodes.stop.disabled = true;
473
+ this.nodes.retry.disabled = false;
474
+ this.syncRunEnabled();
475
+ this.onRunStateChange('idle');
476
+ }
477
+ }
478
+
479
+ async runWhole(inputs) {
480
+ const body = await this.client.run(inputs, {
481
+ signal: this.abortController.signal,
482
+ idempotencyKey: this.idempotencyKey,
483
+ });
484
+ this.lastRunId = body && body.run_id ? String(body.run_id) : '';
485
+ /* Cleared *before* the result speaks, never after. `showResult` sets its
486
+ * own notice for an output type this client cannot show, and a trailing
487
+ * `setNotice('')` here would wipe exactly that message — leaving a blank
488
+ * page for the one case SPEC 4.1.4 says a client may not pass over. */
489
+ this.setNotice('');
490
+ this.showResult(body && body.output);
491
+ this.showUsage(body && body.usage);
492
+ }
493
+
494
+ async runStreamed(inputs) {
495
+ const self = this;
496
+ let streamed = '';
497
+ let sawDelta = false;
498
+ let done = null;
499
+
500
+ await this.client.stream(inputs, {
501
+ signal: this.abortController.signal,
502
+ idempotencyKey: this.idempotencyKey,
503
+ onEvent: function (event) {
504
+ if (event.name === 'start') {
505
+ self.lastRunId = event.payload && event.payload.run_id ? String(event.payload.run_id) : '';
506
+ self.addTimelineEntry('Run started');
507
+ } else if (event.name === 'step') {
508
+ self.addStep(event.payload);
509
+ } else if (event.name === 'delta') {
510
+ const chunk = event.payload && event.payload.text ? String(event.payload.text) : '';
511
+ streamed += chunk;
512
+ sawDelta = true;
513
+ /* textContent, appended: a delta is agent output and never markup. */
514
+ self.nodes.result.textContent = streamed;
515
+ } else if (event.name === 'done') {
516
+ done = event.payload;
517
+ } else if (event.name === 'error') {
518
+ done = null;
519
+ self.showStreamError(event.payload);
520
+ }
521
+ /* Any other event name is skipped (MUST) — a later minor release may
522
+ * add one, and a client that threw would break on it. */
523
+ },
524
+ });
525
+
526
+ if (done) {
527
+ const output = done.output;
528
+ const finalText = output && output.value !== undefined ? String(output.value) : '';
529
+ this.setNotice('');
530
+ this.showResult(output);
531
+ /* SPEC 4.3's SHOULD, applied in full because this client *can* replace
532
+ * what it rendered: where the concatenated deltas and the final value
533
+ * disagree, the final value wins and the buyer is told the streamed
534
+ * text was superseded rather than left wondering which they read.
535
+ *
536
+ * This cannot collide with the notice `showResult` may have just set:
537
+ * that one fires only for an output type which is not `text`, and this
538
+ * one only for `text`. */
539
+ if (sawDelta && output && output.type === 'text' && streamed !== finalText) {
540
+ this.setNotice('The streamed text was superseded by the final result.');
541
+ }
542
+ this.showUsage(done.usage);
543
+ }
544
+ }
545
+
546
+ addTimelineEntry(label) {
547
+ this.nodes.timeline.appendChild(el('li', 'run-timeline-entry', label));
548
+ }
549
+
550
+ addStep(payload) {
551
+ if (!payload) return;
552
+ const phase = payload.phase ? String(payload.phase) : '';
553
+ const name = payload.name ? String(payload.name) : 'step';
554
+ const parts = [name, phase].filter(Boolean);
555
+ /* `latency_ms` arrives on `finished` only, and `model_id` when a model
556
+ * was called — so both are appended where present rather than assumed. */
557
+ if (typeof payload.latency_ms === 'number') parts.push(payload.latency_ms + 'ms');
558
+ if (payload.model_id) parts.push(String(payload.model_id));
559
+ this.addTimelineEntry(parts.join(' · '));
560
+ }
561
+
562
+ showResult(output) {
563
+ const plan = this.viewModel.output;
564
+ const node = this.nodes.result;
565
+ clear(this.nodes.rendered);
566
+ if (!output) {
567
+ node.textContent = '';
568
+ return;
569
+ }
570
+ const type = output.type ? String(output.type) : plan.type;
571
+
572
+ if (type === 'bytes') {
573
+ /* Never shown as text (MUST). Offered as a file named by its media
574
+ * type, which is the only thing the protocol says about it. */
575
+ node.textContent = '';
576
+ this.offerDownload(output);
577
+ return;
578
+ }
579
+ if (type !== 'text') {
580
+ /* The one unknown a client may not ignore: named, and the run is not
581
+ * reported as failed. */
582
+ node.textContent = '';
583
+ this.setNotice('This agent returned "' + type + '", which this client cannot show. The run itself succeeded.');
584
+ return;
585
+ }
586
+
587
+ const value = output.value === undefined || output.value === null ? '' : String(output.value);
588
+ if (plan.mode === 'markdown') {
589
+ /* Structure only, and built node by node — see `outputBlocks`. The
590
+ * `<pre>` is emptied rather than left carrying the stream's plain copy
591
+ * underneath the rendered one. */
592
+ node.textContent = '';
593
+ this.renderMarkdown(value);
594
+ return;
595
+ }
596
+ node.textContent = value;
597
+ if (plan.mode === 'file') {
598
+ /* Offered *beside* the text, never instead of it. A result the buyer
599
+ * cannot read until they have saved it is a worse page than one they
600
+ * can read and also save. */
601
+ this.offerTextDownload(value);
602
+ }
603
+ }
604
+
605
+ renderMarkdown(value) {
606
+ const target = this.nodes.rendered;
607
+ NS.viewModel.outputBlocks(value).forEach(function (block) {
608
+ if (block.kind === 'heading') {
609
+ /* Clamped to h2..h4: the page's own `<h1>` is the agent's name, and
610
+ * an agent that emits `#` is describing its answer, not the page. */
611
+ const level = Math.min(4, Math.max(2, block.level + 1));
612
+ target.appendChild(el('h' + level, 'run-md-heading', block.text));
613
+ return;
614
+ }
615
+ if (block.kind === 'code') {
616
+ target.appendChild(el('pre', 'run-md-code', block.text));
617
+ return;
618
+ }
619
+ if (block.kind === 'list') {
620
+ const list = el(block.ordered ? 'ol' : 'ul', 'run-md-list');
621
+ block.items.forEach(function (item) { list.appendChild(el('li', 'run-md-item', item)); });
622
+ target.appendChild(list);
623
+ return;
624
+ }
625
+ target.appendChild(el('p', 'run-md-paragraph', block.text));
626
+ });
627
+ }
628
+
629
+ offerTextDownload(value) {
630
+ const link = el('a', 'run-download', 'Download the result');
631
+ link.href = URL.createObjectURL(new Blob([value], { type: 'text/plain' }));
632
+ link.download = 'result.txt';
633
+ this.nodes.rendered.appendChild(link);
634
+ }
635
+
636
+ offerDownload(output) {
637
+ const mediaType = output.media_type ? String(output.media_type) : 'application/octet-stream';
638
+ const link = el('a', 'run-download', 'Download the result (' + mediaType + ')');
639
+ let blob;
640
+ try {
641
+ const binary = root.atob(String(output.value || ''));
642
+ const bytes = new Uint8Array(binary.length);
643
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
644
+ blob = new Blob([bytes], { type: mediaType });
645
+ } catch (err) {
646
+ this.setNotice('This agent returned a file this client could not decode.');
647
+ return;
648
+ }
649
+ link.href = URL.createObjectURL(blob);
650
+ link.download = 'result';
651
+ this.nodes.result.parentNode.insertBefore(link, this.nodes.usage);
652
+ }
653
+
654
+ showUsage(usage) {
655
+ if (!usage) {
656
+ this.nodes.usage.textContent = '';
657
+ return;
658
+ }
659
+ const parts = [];
660
+ if (typeof usage.input_tokens === 'number') parts.push(usage.input_tokens + ' in');
661
+ if (typeof usage.output_tokens === 'number') parts.push(usage.output_tokens + ' out');
662
+ if (typeof usage.cost_usd === 'number') parts.push('$' + usage.cost_usd);
663
+ if (!parts.length) {
664
+ this.nodes.usage.textContent = '';
665
+ return;
666
+ }
667
+ /* SPEC 4.2: `cost_usd` is an estimate a client MUST NOT treat as billed,
668
+ * so the label says so rather than leaving a number to be read as one. */
669
+ this.nodes.usage.textContent = 'Usage (advisory, not a bill): ' + parts.join(' · ');
670
+ }
671
+
672
+ showStreamError(payload) {
673
+ const error = payload && payload.error ? payload.error : {};
674
+ const refusal = new NS.PosternRefusal(0, error.code, error.message, error.detail);
675
+ this.reportFailure(refusal);
676
+ }
677
+
678
+ reportFailure(err) {
679
+ if (err && err.name === 'AbortError') {
680
+ this.setNotice('Stopped. The runner cancels a run when the client disconnects.');
681
+ return;
682
+ }
683
+ if (err instanceof NS.PosternUnreachable) {
684
+ this.setNotice(err.message);
685
+ return;
686
+ }
687
+ const vm = this.viewModel;
688
+ const guidance = NS.refusalGuidance(err, {
689
+ credentials: vm.readiness.rows,
690
+ level: vm.level.level,
691
+ state: vm.state,
692
+ runId: this.lastRunId,
693
+ maxConcurrentRuns: vm.limits.maxConcurrentRuns,
694
+ runInFlight: true,
695
+ hosted: this.hosted,
696
+ });
697
+ /* The runner's own sentence first, verbatim, then the next move. That is
698
+ * right whenever the person reading operates the runner: they own the
699
+ * machine and they set the keys, so the provider's own words are the most
700
+ * useful thing this page can say — it names precisely what to go and fix.
701
+ *
702
+ * A hosted run inverts who the operator is, and `agent_error` is the one
703
+ * refusal whose message carries whatever the provider said about
704
+ * *the operator's* credentials: a 401 quoting the last characters of the
705
+ * operator's own key, and a link to a dashboard the buyer has no account on.
706
+ * Suppressed for that code alone — every other arm describes the request
707
+ * or the runner's own configuration, which a buyer can act on in either
708
+ * deployment.
709
+ *
710
+ * Suppressed here, not dropped: the run trace keeps the sentence, and an
711
+ * admin reads it on the run page's own history. The seller-scoped runs
712
+ * endpoint withholds it too, because on a hosted run the seller does not
713
+ * operate the key either. */
714
+ const relayed = !(this.hosted && err && err.code === 'agent_error');
715
+ const message = relayed && err && err.message ? String(err.message) : '';
716
+ this.setNotice([message, guidance.nextMove].filter(Boolean).join(' '));
717
+ if (guidance.highlightKey && this.nodes.inputs[guidance.highlightKey]) {
718
+ this.nodes.inputs[guidance.highlightKey].classList.add('is-invalid');
719
+ this.nodes.inputs[guidance.highlightKey].focus();
720
+ }
721
+ }
722
+ }
723
+
724
+ root.Gatehouse = Object.assign({}, root.Gatehouse, { RunRenderer });
725
+
726
+ /* `SigrixRun` is the name this package was born under, inside one host. It
727
+ * is kept pointing at the same object so that host keeps working across the
728
+ * extraction, and because a global is the one part of a browser package a
729
+ * consumer cannot alias for itself. Deprecated; removed at 1.0. */
730
+ root.SigrixRun = root.Gatehouse;
731
+ })(typeof window !== 'undefined' ? window : globalThis);