@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,623 @@
1
+ /* `describe` and `status` in; what to draw out. No DOM, no network.
2
+ *
3
+ * The split is the specification's own (SPEC 4.4: limits live in `status`
4
+ * "because they belong to the deployment and not to the agent"). A fact about
5
+ * the agent is read from `describe`, a fact about the moment from `status`,
6
+ * and nothing is inferred from one that the other states — so the level is
7
+ * never guessed from a capability, and a credential's tick never comes from
8
+ * the document that names it.
9
+ *
10
+ * Every rule the protocol writes as a MUST is here rather than in the
11
+ * renderer, so it can be exercised without a page: an unrecognised input type
12
+ * renders as text, an unrecognised validation member is ignored, and an
13
+ * unrecognised output type is named rather than shown and never reported as a
14
+ * failure.
15
+ */
16
+ (function (global) {
17
+ const root = global || (typeof window !== 'undefined' ? window : {});
18
+
19
+ /* SPEC 4.1.1. A type outside this set is not a rejection — it renders as
20
+ * text, because a client that refused would break on the first type a later
21
+ * minor release adds. */
22
+ const KNOWN_INPUT_TYPES = ['text', 'number', 'select'];
23
+ /* The one input key the protocol reserves, and the reason a form has a large
24
+ * box at all: it is the brief, filled in on every run. */
25
+ const PROMPT_KEY = 'prompt';
26
+ /* SPEC 4.1.4's two, and the one place an unknown may not simply be ignored. */
27
+ const KNOWN_OUTPUT_TYPES = ['text', 'bytes'];
28
+ /* The validation members this client understands. Anything else is ignored
29
+ * rather than dropped from the document — the runner still enforces it, and
30
+ * this form's checking is a courtesy, not a gate. */
31
+ const KNOWN_VALIDATION = ['max_length', 'min', 'max', 'pattern', 'options'];
32
+
33
+ /* The seller's presentation composition (`ui.json`). A third document
34
+ * beside `describe` and `status`, and the only one a *seller* authors — so
35
+ * every value it can carry is an enum or a string that renders as text, and
36
+ * this client re-checks the palette rather than trusting the file it was
37
+ * handed. It arrives from a bundle, and a bundle can come from any
38
+ * distributor.
39
+ *
40
+ * **The version is read and never compared.** A first draft gated on the
41
+ * document's version *family* and fell back whole when it did not match,
42
+ * which reads as caution and is not: the family names a distributor, so the
43
+ * gate refused another vendor's document rather than a shape this client
44
+ * cannot draw — and it put that distributor's name in a package whose whole
45
+ * rule is that it holds nothing about one. What actually protects this page
46
+ * is the palette re-check below, which is vendor-neutral: a widget, a mode
47
+ * or a template outside these sets is ignored whoever wrote it, and a member
48
+ * this version has never heard of is ignored the ordinary additive way. */
49
+ const UI_OUTPUT_MODES = ['text', 'markdown', 'file'];
50
+ const UI_TEMPLATES = ['form-to-result'];
51
+ /* Which widgets a declared type can honour. A hint may change the *shape* of
52
+ * a control and never what the field means: the runner validates against
53
+ * `describe`, so a seller who asked for a number box on a text field would
54
+ * be styling a promise this client cannot keep. A hint outside its type's
55
+ * row is reported rather than applied. */
56
+ const UI_WIDGETS_BY_TYPE = { text: ['line', 'box'], number: ['number'], select: ['choice'] };
57
+
58
+ /* Prefixes that identify a live provider key on sight, the same set the
59
+ * deployed-runner probe scans for. SPEC 4.1.3 is a claim about the whole
60
+ * payload rather than about one array, so this looks at the serialised
61
+ * document and not only at `credentials[].value`. */
62
+ const SECRET_PREFIXES = ['sk-', 'sk_live_', 'sk_test_', 'ghp_', 'github_pat_', 'xoxb-', 'AIza', 'AKIA'];
63
+ /* A prefix counts only where a token starts and key characters follow it.
64
+ * `sk-` is inside "risk-free", "task-list" and "Flask-based", which an MCP
65
+ * server's tool descriptions say all the time, and a bare substring test
66
+ * blanked the whole form over a description rather than over a key. */
67
+ const SECRET_SHAPE = new RegExp(
68
+ '(?:^|[^A-Za-z0-9_])(' +
69
+ SECRET_PREFIXES.map(prefix => prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|') +
70
+ ')[A-Za-z0-9_-]{6,}'
71
+ );
72
+
73
+ function isObject(value) {
74
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
75
+ }
76
+
77
+ function asArray(value) {
78
+ return Array.isArray(value) ? value : [];
79
+ }
80
+
81
+ function text(value) {
82
+ return value === null || value === undefined ? '' : String(value);
83
+ }
84
+
85
+ /* SPEC 4.1.3 and 7: a `describe` carrying a credential *value* is
86
+ * nonconformant, and a client meeting one SHOULD refuse to proceed. This one
87
+ * refuses — returning the reason rather than throwing, so the page can say
88
+ * what is wrong instead of rendering nothing. */
89
+ function credentialLeak(describe) {
90
+ const declared = asArray(describe && describe.credentials);
91
+ const named = declared.find(entry => isObject(entry) && 'value' in entry);
92
+ if (named) {
93
+ return 'This runner published a value for ' + text(named.env) +
94
+ '. A credential value must never travel in `describe`, so nothing here will run against it.';
95
+ }
96
+ let serialised = '';
97
+ try {
98
+ serialised = JSON.stringify(describe || {});
99
+ } catch (err) {
100
+ return '';
101
+ }
102
+ const hit = SECRET_SHAPE.exec(serialised);
103
+ if (hit) {
104
+ return 'This runner’s description carries something shaped like a live API key (' + hit[1] +
105
+ '…). A credential value must never travel in `describe`, so nothing here will run against it.';
106
+ }
107
+ return '';
108
+ }
109
+
110
+ /* The form, in declared order (SPEC 4.1.1 — `inputs` is an ordered array and
111
+ * a client renders it in order). */
112
+ /* `ui.json` in, a lookup table out. Nothing here can hide or reorder a
113
+ * field: the form is still built by walking `describe.inputs` and asking
114
+ * this for decoration, which is what makes "a required input the seller left
115
+ * out is appended, never hidden" structural rather than a rule to remember. */
116
+ function presentation(composition) {
117
+ const doc = isObject(composition) ? composition : {};
118
+ const output = isObject(doc.output) ? doc.output : {};
119
+ const blocks = {};
120
+ asArray(doc.inputs).filter(isObject).forEach(function (block) {
121
+ const key = text(block.key);
122
+ /* First mention wins, matching the server's own normaliser: two blocks
123
+ * for one field is a document disagreeing with itself, and merging would
124
+ * decide which half the seller meant. */
125
+ if (!key || Object.prototype.hasOwnProperty.call(blocks, key)) return;
126
+ blocks[key] = {
127
+ widget: text(block.widget),
128
+ help: text(block.help),
129
+ placeholder: text(block.placeholder),
130
+ };
131
+ });
132
+ const mode = text(output.mode);
133
+ const template = text(doc.template);
134
+ return {
135
+ present: Boolean(text(doc.run_label)) || Boolean(mode) || Object.keys(blocks).length > 0,
136
+ /* Carried as data the caller may want to show, never as something this
137
+ * client decides on. */
138
+ version: text(doc.version),
139
+ template: UI_TEMPLATES.indexOf(template) !== -1 ? template : UI_TEMPLATES[0],
140
+ /* The name the seller asked for, not the one that will be drawn — a
141
+ * notice quoting the fallback would name the layout the page is already
142
+ * showing, which reads as a bug rather than as the fallback it is. */
143
+ unrecognisedTemplate: Boolean(template) && UI_TEMPLATES.indexOf(template) === -1 ? template : '',
144
+ runLabel: text(doc.run_label),
145
+ outputMode: UI_OUTPUT_MODES.indexOf(mode) !== -1 ? mode : UI_OUTPUT_MODES[0],
146
+ blocks,
147
+ };
148
+ }
149
+
150
+ /* A host may say that one `select` input chooses which of the others apply:
151
+ * an MCP server's tool, where each tool takes arguments of its own. Nothing
152
+ * in `describe` states that, so the fact arrives the way the composition
153
+ * does, as a document handed in by whoever mounted the page:
154
+ *
155
+ * { key, groups: { <option>: { inputs: [key…], required: [key…], about } } }
156
+ *
157
+ * Re-checked rather than trusted, and it cannot put a field out of reach: a
158
+ * group that is not one of the select's options is ignored, so its inputs
159
+ * stay on the page, and an input named by two groups belongs to the first
160
+ * (the composition's own rule for two blocks naming one key). */
161
+ function inputChoice(describe, choice) {
162
+ const doc = isObject(choice) ? choice : {};
163
+ const key = text(doc.key);
164
+ const declared = asArray(describe && describe.inputs).filter(isObject);
165
+ const chooser = declared.find(entry => text(entry.key) === key && text(entry.type) === 'select');
166
+ const options = chooser && isObject(chooser.validation) ? asArray(chooser.validation.options).map(text) : [];
167
+ if (!key || !options.length || !isObject(doc.groups)) return null;
168
+ const keys = declared.map(entry => text(entry.key)).filter(name => name && name !== key);
169
+ const groupOf = {};
170
+ const required = {};
171
+ const about = {};
172
+ options.forEach(function (option) {
173
+ if (!Object.prototype.hasOwnProperty.call(doc.groups, option) || !isObject(doc.groups[option])) return;
174
+ const group = doc.groups[option];
175
+ about[option] = text(group.about);
176
+ asArray(group.inputs).map(text).forEach(function (name) {
177
+ if (keys.indexOf(name) === -1 || Object.prototype.hasOwnProperty.call(groupOf, name)) return;
178
+ groupOf[name] = option;
179
+ });
180
+ asArray(group.required).map(text).forEach(function (name) {
181
+ if (groupOf[name] === option) required[name] = true;
182
+ });
183
+ });
184
+ return { key, groupOf, required, about };
185
+ }
186
+
187
+ function formFields(describe, composition, choice) {
188
+ const ui = composition && composition.blocks ? composition : presentation(composition);
189
+ const plan = choice && choice.groupOf ? choice : inputChoice(describe, choice);
190
+ return asArray(describe && describe.inputs)
191
+ .filter(isObject)
192
+ .map(function (declared) {
193
+ const declaredType = text(declared.type);
194
+ const known = KNOWN_INPUT_TYPES.indexOf(declaredType) !== -1;
195
+ const validation = isObject(declared.validation) ? declared.validation : {};
196
+ const options = asArray(validation.options).map(text);
197
+ /* A `select` whose options never arrived cannot be a picker — the
198
+ * schema calls `options` REQUIRED for that type, but a client that
199
+ * rendered an empty dropdown would offer a field nobody can fill. */
200
+ const type = known && !(declaredType === 'select' && !options.length) ? declaredType : 'text';
201
+ const key = text(declared.key);
202
+ const block = Object.prototype.hasOwnProperty.call(ui.blocks, key) ? ui.blocks[key] : null;
203
+ const allowed = UI_WIDGETS_BY_TYPE[type] || [];
204
+ const widget = block && allowed.indexOf(block.widget) !== -1 ? block.widget : '';
205
+ /* Absent the seller's say-so, the reserved brief is the big box and
206
+ * everything else is a line — which is exactly the guess this document
207
+ * exists to replace, so a hint overrides it in both directions. */
208
+ const multiline = widget ? widget === 'box' : key === PROMPT_KEY;
209
+ /* The option this field belongs to, or '' for a field every run takes.
210
+ * A choice can add a requirement and never remove one: the runner
211
+ * enforces `describe`'s own either way. */
212
+ const group = plan && Object.prototype.hasOwnProperty.call(plan.groupOf, key) ? plan.groupOf[key] : '';
213
+ return {
214
+ key,
215
+ label: text(declared.label) || text(declared.key),
216
+ type,
217
+ /* Kept so the page can say it is showing a text box for a type it
218
+ * did not recognise, rather than silently flattening the form. */
219
+ declaredType,
220
+ unrecognisedType: !known,
221
+ group,
222
+ required: declared.required === true || Boolean(group && plan.required[key]),
223
+ defaultValue: declared.default === null || declared.default === undefined ? '' : declared.default,
224
+ multiline,
225
+ widget,
226
+ help: block ? block.help : '',
227
+ placeholder: block ? block.placeholder : '',
228
+ /* Named rather than dropped, the same courtesy `ignoredValidation`
229
+ * pays one line down: a hint this field's type cannot wear is a fact
230
+ * the seller previewing the page is entitled to see. */
231
+ ignoredWidget: block && block.widget && !widget ? block.widget : '',
232
+ options,
233
+ maxLength: typeof validation.max_length === 'number' ? validation.max_length : null,
234
+ min: typeof validation.min === 'number' ? validation.min : null,
235
+ max: typeof validation.max === 'number' ? validation.max : null,
236
+ pattern: typeof validation.pattern === 'string' ? validation.pattern : '',
237
+ /* Named, not applied. Reporting them is what makes "ignored" a
238
+ * decision somebody can see rather than an omission. */
239
+ ignoredValidation: Object.keys(validation).filter(name => KNOWN_VALIDATION.indexOf(name) === -1),
240
+ };
241
+ })
242
+ .filter(field => field.key !== '');
243
+ }
244
+
245
+ /* What a run sends: every field no choice governs, and the fields of the
246
+ * option chosen. Another option's fields stay home, because the runner
247
+ * checks every declared input it is handed, and a stale value in a field the
248
+ * buyer cannot see would refuse the run over something they cannot fix.
249
+ *
250
+ * A control holds text, and SPEC 4.1.1's `number` is a JSON number, so a
251
+ * number field's text is sent as the number it spells. Text that spells none
252
+ * is sent as typed, for the runner to refuse by name; an empty one stays
253
+ * empty, which the runner reads as not given. */
254
+ function runInputs(fields, values, choice) {
255
+ const chosen = choice ? text(values[choice.key]) : '';
256
+ const inputs = {};
257
+ asArray(fields).forEach(function (field) {
258
+ if (field.group && field.group !== chosen) return;
259
+ if (!Object.prototype.hasOwnProperty.call(values, field.key)) return;
260
+ const value = values[field.key];
261
+ const spelled = field.type === 'number' && text(value).trim() !== '' ? Number(value) : NaN;
262
+ inputs[field.key] = Number.isFinite(spelled) ? spelled : value;
263
+ });
264
+ return inputs;
265
+ }
266
+
267
+ /* The values a form starts with: an example's inputs where there is one,
268
+ * each field's own default otherwise. SPEC 4.1 offers no template format and
269
+ * needs none — the examples the seller captured are the templates. */
270
+ function initialValues(describe, exampleIndex, composition) {
271
+ const fields = formFields(describe, composition);
272
+ const examples = asArray(describe && describe.examples).filter(isObject);
273
+ const chosen = examples[exampleIndex === undefined ? 0 : exampleIndex];
274
+ const fromExample = chosen && isObject(chosen.inputs) ? chosen.inputs : null;
275
+ const values = {};
276
+ fields.forEach(function (field) {
277
+ if (fromExample && Object.prototype.hasOwnProperty.call(fromExample, field.key)) {
278
+ values[field.key] = text(fromExample[field.key]);
279
+ } else {
280
+ values[field.key] = text(field.defaultValue);
281
+ }
282
+ });
283
+ return values;
284
+ }
285
+
286
+ function examples(describe) {
287
+ return asArray(describe && describe.examples)
288
+ .filter(isObject)
289
+ .map(function (entry, index) {
290
+ const inputs = isObject(entry.inputs) ? entry.inputs : {};
291
+ const first = Object.keys(inputs)[0];
292
+ return {
293
+ index,
294
+ inputs,
295
+ output: text(entry.output),
296
+ /* A chip needs something to say. The first input's value is what a
297
+ * seller would recognise; the ordinal is the fallback so a chip is
298
+ * never blank. */
299
+ label: first && text(inputs[first]) ? text(inputs[first]) : 'Example ' + (index + 1),
300
+ };
301
+ });
302
+ }
303
+
304
+ /* SPEC 4.1.4. The third arm is the point: an unrecognised type is neither
305
+ * shown as text nor treated as a failure. */
306
+ function outputPlan(describe, composition) {
307
+ const ui = composition && composition.blocks ? composition : presentation(composition);
308
+ const declared = isObject(describe && describe.output) ? describe.output : {};
309
+ const type = text(declared.type) || 'text';
310
+ /* The seller's mode is a *presentation* choice over text the runner
311
+ * returns, so it applies to `text` and nothing else. `bytes` is already a
312
+ * download by protocol (SPEC 4.1.4 forbids showing it), and an
313
+ * unrecognised type is named rather than drawn — neither is a surface a
314
+ * composition may repaint. */
315
+ const mode = type === 'text' ? ui.outputMode : 'text';
316
+ if (KNOWN_OUTPUT_TYPES.indexOf(type) !== -1) {
317
+ return { type, mode, unrecognised: false, example: text(declared.example), notice: '' };
318
+ }
319
+ return {
320
+ type,
321
+ mode: 'text',
322
+ unrecognised: true,
323
+ example: text(declared.example),
324
+ notice: 'This agent returns ' + type + ', which this client cannot show. The run itself was fine.',
325
+ };
326
+ }
327
+
328
+ /* Markdown, in the only form a renderer that forbids `innerHTML` can honour:
329
+ * block structure, built from `createElement` and `textContent`.
330
+ *
331
+ * Headings, paragraphs, bullet and numbered lists and fenced code are
332
+ * recognised; **inline markers are left exactly as the agent typed them**.
333
+ * That is a deliberate stop rather than an unfinished parser — inline
334
+ * markdown's useful half is the link, and an anchor whose `href` comes from
335
+ * agent output is precisely the escape hatch `run_renderer.js` is written to
336
+ * make structurally impossible. A seller choosing this mode is choosing
337
+ * structure, and the page says so.
338
+ *
339
+ * The parse lives here rather than in the renderer for the same reason every
340
+ * protocol rule does: it can be exercised without a page. */
341
+ function outputBlocks(value) {
342
+ const lines = String(value === undefined || value === null ? '' : value).split(/\r?\n/);
343
+ const blocks = [];
344
+ let paragraph = [];
345
+ let list = null;
346
+ let code = null;
347
+
348
+ function flushParagraph() {
349
+ if (paragraph.length) blocks.push({ kind: 'paragraph', text: paragraph.join(' ') });
350
+ paragraph = [];
351
+ }
352
+ function flushList() {
353
+ if (list) blocks.push(list);
354
+ list = null;
355
+ }
356
+
357
+ lines.forEach(function (line) {
358
+ if (code !== null) {
359
+ if (/^\s*```/.test(line)) {
360
+ blocks.push({ kind: 'code', text: code.join('\n') });
361
+ code = null;
362
+ } else {
363
+ code.push(line);
364
+ }
365
+ return;
366
+ }
367
+ if (/^\s*```/.test(line)) {
368
+ flushParagraph();
369
+ flushList();
370
+ code = [];
371
+ return;
372
+ }
373
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line);
374
+ if (heading) {
375
+ flushParagraph();
376
+ flushList();
377
+ blocks.push({ kind: 'heading', level: heading[1].length, text: heading[2].trim() });
378
+ return;
379
+ }
380
+ const bullet = /^\s*[-*+]\s+(.*)$/.exec(line);
381
+ const ordered = bullet ? null : /^\s*\d+[.)]\s+(.*)$/.exec(line);
382
+ if (bullet || ordered) {
383
+ flushParagraph();
384
+ const isOrdered = Boolean(ordered);
385
+ if (!list || list.ordered !== isOrdered) {
386
+ flushList();
387
+ list = { kind: 'list', ordered: isOrdered, items: [] };
388
+ }
389
+ list.items.push((bullet ? bullet[1] : ordered[1]).trim());
390
+ return;
391
+ }
392
+ if (!line.trim()) {
393
+ flushParagraph();
394
+ flushList();
395
+ return;
396
+ }
397
+ paragraph.push(line.trim());
398
+ });
399
+
400
+ /* An unterminated fence still yields its block. Refusing it would drop the
401
+ * whole result over a missing three characters at the end of a stream. */
402
+ if (code !== null) blocks.push({ kind: 'code', text: code.join('\n') });
403
+ flushParagraph();
404
+ flushList();
405
+ return blocks;
406
+ }
407
+
408
+ /* SPEC 4.1.2: a client SHOULD surface `write_tools` and MAY require a
409
+ * confirmation. This one requires it, once per session, because the tools
410
+ * named here are the ones that spend money or reach past the workspace. */
411
+ function capabilities(describe) {
412
+ const declared = isObject(describe && describe.capabilities) ? describe.capabilities : {};
413
+ const writeTools = asArray(declared.write_tools).map(text).filter(Boolean);
414
+ return {
415
+ tools: asArray(declared.tools).map(text).filter(Boolean),
416
+ writeTools,
417
+ needsWriteConfirmation: writeTools.length > 0,
418
+ /* Absent and false are read identically (SPEC 4.2), so Retry warns
419
+ * unless the runner has said a replay is free. */
420
+ idempotentRetry: declared.idempotent_retry === true,
421
+ };
422
+ }
423
+
424
+ /* `describe` names the credentials; `status` says which are set. Neither
425
+ * document answers alone, which is why this takes both. */
426
+ function readiness(describe, status) {
427
+ const declared = asArray(describe && describe.credentials).filter(isObject);
428
+ const reported = isObject(status && status.credentials) ? status.credentials : {};
429
+ const missing = asArray(reported.missing).map(text);
430
+ const rows = declared.map(function (entry) {
431
+ const env = text(entry.env);
432
+ return {
433
+ env,
434
+ purpose: text(entry.purpose),
435
+ signupUrl: text(entry.signup_url),
436
+ satisfied: missing.indexOf(env) === -1,
437
+ };
438
+ });
439
+ /* A name `status` reports missing that `describe` never declared still has
440
+ * to appear, or the list contradicts the runner it is describing. */
441
+ missing.forEach(function (env) {
442
+ if (!rows.some(row => row.env === env)) {
443
+ rows.push({ env, purpose: '', signupUrl: '', satisfied: false });
444
+ }
445
+ });
446
+ return {
447
+ rows,
448
+ satisfied: reported.satisfied === true,
449
+ /* Said once, beside the list: this is not a field on this page. */
450
+ where: 'These go in the runner’s own .env file, not here.',
451
+ };
452
+ }
453
+
454
+ /* SPEC 2.2 as the shell reads it, and the one case that is not about a
455
+ * lapsed licence: `unknown` with no `checked_at` is a runner that has never
456
+ * confirmed anything and will answer 503 to a run — worth saying before the
457
+ * buyer clicks rather than after. */
458
+ function entitlementBanner(status) {
459
+ const entitlement = isObject(status && status.entitlement) ? status.entitlement : {};
460
+ const state = text(entitlement.state);
461
+ const checkedAt = text(entitlement.checked_at);
462
+ if (state === 'revoked') {
463
+ return {
464
+ tone: 'blocked',
465
+ state,
466
+ message:
467
+ 'Your access to this agent has ended or could not be confirmed. ' +
468
+ 'Check with the place you bought it.',
469
+ };
470
+ }
471
+ if (state === 'unknown' && !checkedAt) {
472
+ return {
473
+ tone: 'blocked',
474
+ state,
475
+ message:
476
+ 'This runner has never confirmed its licence, so a run will not start. ' +
477
+ 'It needs to reach its distributor once.',
478
+ };
479
+ }
480
+ if (state === 'unknown') {
481
+ const grace = typeof entitlement.grace_seconds === 'number' ? entitlement.grace_seconds : null;
482
+ return {
483
+ tone: 'caution',
484
+ state,
485
+ checkedAt,
486
+ graceSeconds: grace,
487
+ message:
488
+ 'This runner is running through an outage. Its licence was last confirmed at ' +
489
+ checkedAt + (grace === null ? '.' : ', and access is guaranteed for ' + grace + 's from then.'),
490
+ };
491
+ }
492
+ if (state === 'active' || state === 'not_required') {
493
+ return {
494
+ tone: 'quiet',
495
+ state,
496
+ checkedAt,
497
+ message: checkedAt ? 'Licence confirmed at ' + checkedAt + '.' : '',
498
+ };
499
+ }
500
+ /* A state this client has not heard of is reported rather than guessed
501
+ * at — the same posture every other unknown in this protocol gets. */
502
+ return { tone: 'quiet', state, message: state ? 'Entitlement state: ' + state + '.' : '' };
503
+ }
504
+
505
+ /* SPEC 3: the shell MUST NOT assume a level it has not read from `status`. */
506
+ function levelPlan(status) {
507
+ const level = typeof (status && status.level) === 'number' ? status.level : 0;
508
+ if (level >= 3) return { level, canRun: true, streams: true, note: '' };
509
+ if (level === 2) {
510
+ return {
511
+ level,
512
+ canRun: true,
513
+ streams: false,
514
+ note: 'This runner returns the whole result at once rather than streaming it.',
515
+ };
516
+ }
517
+ if (level === 1) {
518
+ return {
519
+ level,
520
+ canRun: false,
521
+ streams: false,
522
+ note: 'This runner describes the agent but cannot run it.',
523
+ };
524
+ }
525
+ return {
526
+ level,
527
+ canRun: false,
528
+ streams: false,
529
+ note: 'This runner did not report a conformance level, so nothing here will try to run it.',
530
+ };
531
+ }
532
+
533
+ /* SPEC 4.4: absent means the runner imposes no such bound, and the shell
534
+ * says nothing rather than inventing a default. */
535
+ function limitsView(status) {
536
+ const limits = isObject(status && status.limits) ? status.limits : {};
537
+ const number = name => (typeof limits[name] === 'number' ? limits[name] : null);
538
+ return {
539
+ maxRunSeconds: number('max_run_seconds'),
540
+ maxConcurrentRuns: number('max_concurrent_runs'),
541
+ maxOutputBytes: number('max_output_bytes'),
542
+ idempotencyRetentionSeconds: number('idempotency_retention_seconds'),
543
+ };
544
+ }
545
+
546
+ /* Not in the specification — one distributor's runner adds it. Treated
547
+ * as any unknown member: ignored when absent, a courtesy line when present.
548
+ * It must never become a requirement, or this stops being a Postern client. */
549
+ function updateNotice(status) {
550
+ const update = isObject(status && status.update) ? status.update : null;
551
+ if (!update || text(update.state) !== 'update_available') return '';
552
+ return 'An update is available (' + text(update.current) + ' → ' + text(update.latest) +
553
+ '). Re-pull to update.';
554
+ }
555
+
556
+ function header(describe) {
557
+ const agent = isObject(describe && describe.agent) ? describe.agent : {};
558
+ return {
559
+ /* Shown verbatim: it is what the buyer puts in `.env` and what the
560
+ * runner prints at boot, so one identifier keeps one spelling. */
561
+ id: text(agent.id),
562
+ name: text(agent.name),
563
+ version: text(agent.version),
564
+ summary: text(agent.summary),
565
+ };
566
+ }
567
+
568
+ function build(describe, status, composition, choice) {
569
+ const ui = presentation(composition);
570
+ const plan = inputChoice(describe, choice);
571
+ return {
572
+ refuseReason: credentialLeak(describe),
573
+ header: header(describe),
574
+ fields: formFields(describe, ui, plan),
575
+ choice: plan,
576
+ initialValues: initialValues(describe, undefined, ui),
577
+ examples: examples(describe),
578
+ output: outputPlan(describe, ui),
579
+ presentation: ui,
580
+ capabilities: capabilities(describe),
581
+ readiness: readiness(describe, status),
582
+ entitlement: entitlementBanner(status),
583
+ level: levelPlan(status),
584
+ limits: limitsView(status),
585
+ updateNotice: updateNotice(status),
586
+ state: text(status && status.state),
587
+ };
588
+ }
589
+
590
+ root.Gatehouse = Object.assign({}, root.Gatehouse, {
591
+ viewModel: {
592
+ PROMPT_KEY,
593
+ KNOWN_INPUT_TYPES,
594
+ KNOWN_OUTPUT_TYPES,
595
+ UI_OUTPUT_MODES,
596
+ UI_TEMPLATES,
597
+ UI_WIDGETS_BY_TYPE,
598
+ build,
599
+ presentation,
600
+ outputBlocks,
601
+ header,
602
+ inputChoice,
603
+ formFields,
604
+ runInputs,
605
+ initialValues,
606
+ examples,
607
+ outputPlan,
608
+ capabilities,
609
+ readiness,
610
+ entitlementBanner,
611
+ levelPlan,
612
+ limitsView,
613
+ updateNotice,
614
+ credentialLeak,
615
+ },
616
+ });
617
+
618
+ /* `SigrixRun` is the name this package was born under, inside one host. It
619
+ * is kept pointing at the same object so that host keeps working across the
620
+ * extraction, and because a global is the one part of a browser package a
621
+ * consumer cannot alias for itself. Deprecated; removed at 1.0. */
622
+ root.SigrixRun = root.Gatehouse;
623
+ })(typeof window !== 'undefined' ? window : globalThis);