@mnmal-ai/substrate-tui 1.0.0-alpha.13 → 1.0.0-alpha.15

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
@@ -9,6 +9,7 @@ Without an admin identity it is read-only.
9
9
  - Free text is a natural-language question, answered by `substrate-nl` (streamed). Tab completes types, fields and values.
10
10
  - `/ns <namespace>` switches the namespace that questions, completion and the status row use. The schema browser always lists every namespace.
11
11
  - `/frame` shows the Substrate frame behind the last answer.
12
+ - `/asof <date-time>` reads relative phrases ("yesterday", "past 2 days") as of that moment, for the questions that follow. It must be ISO-8601 with an offset, e.g. `2026-10-24T23:59:59-05:00`. `/asof off` returns to the server clock, and `/asof` alone shows which is in use. `/frame` shows the clock the server read the last question against.
12
13
  - `/schema [namespace] [type]` opens the schema browser: namespaces, then types, then fields.
13
14
  - `/dash` shows service, traffic and engine metrics, live while open.
14
15
  - `/doctor` runs live checks against this deployment.
@@ -16,11 +17,31 @@ Without an admin identity it is read-only.
16
17
  - `/admin unlock|lock|status` unlocks or locks the admin identity. It relocks after `SUBSTRATE_TUI_ADMIN_IDLE_MINUTES` of idle time (default 15).
17
18
  - With admin unlocked: `/drop-namespace` and `/drop-type` (preview first, then type the target to confirm), `/backfill` (write a field from a JSON file of row id → value), `/normalise` (migrate a field's aliases to canonical values), `/reindex` (re-embed the embedded types, page by page).
18
19
 
20
+ ## Shaping answer rows (for plugin authors)
21
+
22
+ A namespace can say how its rows look in an answer, with no TUI code. Put a `tui` key in its `defineNamespace` annotations:
23
+
24
+ ```ts
25
+ annotations: { tui: {
26
+ formats: { 'Item.price': 'money', 'Item.stock': 'int', 'Item.seenAt': 'date' },
27
+ rows: { Item: { title: 'name', tags: [{ field: 'grade', template: 'G{}' }], value: 'price',
28
+ details: [{ field: 'ask', label: 'ask' }, 'supplier'] } }
29
+ } }
30
+ ```
31
+
32
+ Each `Item` row then renders as a numbered line with the bold `title`, dim `tags` and the `value` right-aligned, followed by a dim `·`-joined `details` line (`ask $412.00 · Acme`). Empty values show as `—` or are left out. When the terminal is too narrow for the title to keep at least 20 columns (or 40% of the width) on that first line, the whole list stacks instead: the title alone, then `tags · value`, then the details.
33
+
34
+ - An entry is a field name or `{ field, template?, label? }`. `template` puts the formatted value where `{}` is. `label` comes before a detail, and a numeric detail is labelled with its field name by default.
35
+ - `formats` maps `'<Type>.<field>'` to `money` (in `currency`, default `USD`, with its usual decimal places), `int`, `number`, `pct` (the value is already a percent), `date` or `datetime` (local time). They apply wherever the value appears, including the generic `field=value` view and aggregates.
36
+ - Only the type's own fields can be used. An entry that follows a reference (`a.b`) is left out, as is one named `__proto__`, `constructor` or `prototype`. A long value is cut to a third of the line.
37
+ - A malformed block, or a malformed entry for a type, is ignored, and that type falls back to the generic view. `/frame` says what was ignored.
38
+
19
39
  ## Keys
20
40
 
21
41
  - Tab completes the token under the cursor.
22
42
  - `1`-`9` answer a clarify question.
23
43
  - Esc cancels the newest in-flight question, or closes the open panel.
44
+ - PgUp / PgDn scroll the conversation; the input stays where it is. End jumps back to the bottom while scrolled up, and otherwise moves to the end of the line.
24
45
  - ctrl+c twice exits.
25
46
 
26
47
  ## Status row
@@ -38,5 +59,6 @@ Without an admin identity it is read-only.
38
59
  | `SUBSTRATE_ADMIN_KEY_PATH`, `SUBSTRATE_ADMIN_KEY_ID`, `SUBSTRATE_ADMIN_TOKEN` | Admin identity used by `/admin unlock`. |
39
60
  | `SUBSTRATE_TUI_ADMIN_IDLE_MINUTES` | Minutes of idle before admin relocks (default 15). |
40
61
  | `SUBSTRATE_TUI_BACKGROUND` | Background colour, `#rrggbb` or `none`. |
41
- | `SUBSTRATE_TUI_CLEAR` | `0` keeps what was on screen at start. |
62
+ | `SUBSTRATE_TUI_CLEAR` | `0` keeps what was on screen at start (inline layout only). |
42
63
  | `SUBSTRATE_TUI_COLOR` | `256` for terminals without 24-bit colour. |
64
+ | `SURFACE_FULLSCREEN` | `off` keeps the inline layout, with the conversation in the terminal's own scrollback. Default `on`. |
@@ -4,9 +4,10 @@ import { resolve } from "node:path";
4
4
  import { AdminBackfillError, AuthError, CURRENT_MARK, NetworkError, STEP_MARKS, adminClaimCapabilities, capabilitiesFor, checkRevocable, checkUpdatable, currentStep, decodeList, describeGrant, diagnose, encodeGrant, flattenGrant, grantEntriesConfer, isActiveAdminKeyRow, isEncryptedKey, makeTokenProvider, parseGrantEntries, planOnboarding, resolveAdminCredential, tokenAudience } from "@mnmal-ai/substrate/client";
5
5
  import { createApp, defineModule, sanitise } from "@mnmal-ai/surface-core";
6
6
  import { marathon } from "@mnmal-ai/surface-theme";
7
+ import { Box, Text } from "ink";
8
+ import { createElement } from "react";
7
9
  import { complete } from "@mnmal-ai/substrate-nl/complete";
8
10
  import { Panel, cellWidth, padCells, sparkline, truncateCells } from "@mnmal-ai/surface-kit";
9
- import { Box, Text } from "ink";
10
11
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
12
  import { readFile } from "node:fs/promises";
12
13
  import { createHash, createPublicKey } from "node:crypto";
@@ -216,6 +217,185 @@ function adapt(draft, cursor, s) {
216
217
  };
217
218
  }
218
219
 
220
+ //#endregion
221
+ //#region src/ask/present.ts
222
+ /** Keys that would reach or shadow Object.prototype; refused as type and field names. */
223
+ const RESERVED = /* @__PURE__ */ new Set([
224
+ "__proto__",
225
+ "constructor",
226
+ "prototype"
227
+ ]);
228
+ const dict = () => Object.create(null);
229
+ /** `m[k]` when `k` is m's own key. */
230
+ const own$1 = (m, k) => Object.hasOwn(m, k) ? m[k] : void 0;
231
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
232
+ const validCurrency = (c) => {
233
+ try {
234
+ new Intl.NumberFormat("en-US", {
235
+ style: "currency",
236
+ currency: c
237
+ });
238
+ return true;
239
+ } catch {
240
+ return false;
241
+ }
242
+ };
243
+ var Bad = class extends Error {};
244
+ function entry$1(v, where) {
245
+ if (typeof v === "string" && v !== "") return { field: v };
246
+ if (isObj(v) && typeof v.field === "string" && v.field !== "" && (v.template === void 0 || typeof v.template === "string") && (v.label === void 0 || typeof v.label === "string")) return {
247
+ field: v.field,
248
+ ...v.template !== void 0 ? { template: v.template } : {},
249
+ ...v.label !== void 0 ? { label: v.label } : {}
250
+ };
251
+ throw new Bad(`${where} is not a field name or { field, template?, label? }`);
252
+ }
253
+ /** Why a field cannot be shown, or undefined when it can. A crossRef walk (`card.cardName`) is not carried by NL answer rows. */
254
+ const unusable = (field) => RESERVED.has(field) ? "is a reserved name" : field.includes(".") ? "crosses a reference" : void 0;
255
+ /** The entry, or undefined (noted) when its field cannot be shown. */
256
+ function usable(e, t, where, problems) {
257
+ const why = unusable(e.field);
258
+ if (why === void 0) return e;
259
+ problems.push({
260
+ type: t,
261
+ text: `${where}: ${e.field} ${why}; left out`
262
+ });
263
+ }
264
+ function rowView(t, v, problems) {
265
+ if (!isObj(v)) throw new Bad(`rows.${t} is not an object`);
266
+ const at = (k) => `rows.${t}.${k}`;
267
+ const list = (k) => {
268
+ const raw = v[k];
269
+ if (raw === void 0) return [];
270
+ if (!Array.isArray(raw)) throw new Bad(`${at(k)} is not a list`);
271
+ return raw.map((x, i) => usable(entry$1(x, `${at(k)}[${i}]`), t, at(k), problems)).filter((x) => x !== void 0);
272
+ };
273
+ const one = (k) => v[k] === void 0 ? void 0 : usable(entry$1(v[k], at(k)), t, at(k), problems);
274
+ const title = one("title");
275
+ const value = one("value");
276
+ return {
277
+ ...title !== void 0 ? { title } : {},
278
+ tags: list("tags"),
279
+ ...value !== void 0 ? { value } : {},
280
+ details: list("details")
281
+ };
282
+ }
283
+ function parseTui(raw) {
284
+ const problems = [];
285
+ const types = dict();
286
+ if (raw === void 0) return {
287
+ types,
288
+ problems
289
+ };
290
+ const whole = (why) => ({
291
+ types,
292
+ problems: [{ text: `tui ignored: ${why}` }]
293
+ });
294
+ if (!isObj(raw)) return whole("not an object");
295
+ const currency = raw.currency ?? "USD";
296
+ if (typeof currency !== "string" || !validCurrency(currency)) return whole(`currency ${JSON.stringify(currency)} is not an ISO 4217 code`);
297
+ if (raw.formats !== void 0 && !isObj(raw.formats)) return whole("formats is not an object");
298
+ if (raw.rows !== void 0 && !isObj(raw.rows)) return whole("rows is not an object");
299
+ const dead = /* @__PURE__ */ new Set();
300
+ const view = (t) => {
301
+ if (!Object.hasOwn(types, t)) types[t] = {
302
+ currency,
303
+ formats: dict()
304
+ };
305
+ return types[t];
306
+ };
307
+ for (const [key, fmt] of Object.entries(raw.formats ?? {})) {
308
+ const dot = key.indexOf(".");
309
+ const t = key.slice(0, dot);
310
+ if (dot <= 0 || dot === key.length - 1 || RESERVED.has(t)) {
311
+ problems.push({ text: `formats.${key}: key is not '<Type>.<field>'; left out` });
312
+ continue;
313
+ }
314
+ const field = key.slice(dot + 1);
315
+ const why = unusable(field);
316
+ if (why !== void 0) {
317
+ problems.push({
318
+ type: t,
319
+ text: `formats.${key}: ${field} ${why}; left out`
320
+ });
321
+ continue;
322
+ }
323
+ if (typeof fmt !== "string") {
324
+ problems.push({
325
+ type: t,
326
+ text: `${t} ignored: formats.${key} is not a string`
327
+ });
328
+ dead.add(t);
329
+ continue;
330
+ }
331
+ view(t).formats[field] = fmt;
332
+ }
333
+ for (const [t, spec] of Object.entries(raw.rows ?? {})) {
334
+ if (RESERVED.has(t)) {
335
+ problems.push({ text: `rows.${t}: ${t} is a reserved name; left out` });
336
+ continue;
337
+ }
338
+ try {
339
+ view(t).row = rowView(t, spec, problems);
340
+ } catch (e) {
341
+ if (!(e instanceof Bad)) throw e;
342
+ problems.push({
343
+ type: t,
344
+ text: `${t} ignored: ${e.message}`
345
+ });
346
+ dead.add(t);
347
+ }
348
+ }
349
+ for (const t of dead) delete types[t];
350
+ return {
351
+ types,
352
+ problems
353
+ };
354
+ }
355
+ const pad2 = (n) => String(n).padStart(2, "0");
356
+ const localDay = (d) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
357
+ const DECIMAL = /^\s*-?\d+(\.\d+)?\s*$/;
358
+ const NUMERIC = /* @__PURE__ */ new Set([
359
+ "money",
360
+ "int",
361
+ "number",
362
+ "pct"
363
+ ]);
364
+ /** Whether a format reads its value as a number. */
365
+ const isNumericFormat = (fmt) => fmt !== void 0 && NUMERIC.has(fmt);
366
+ /** `v` under `fmt`, unsanitised; raw `String(v)` when the format is unknown or does not fit the value. */
367
+ function formatValue(v, fmt, currency) {
368
+ const raw = String(v);
369
+ if (fmt === void 0) return raw;
370
+ if (NUMERIC.has(fmt)) {
371
+ const n = typeof v === "number" ? v : typeof v === "string" && DECIMAL.test(v) ? Number(v) : NaN;
372
+ if (!Number.isFinite(n)) return raw;
373
+ if (fmt === "money") return new Intl.NumberFormat("en-US", {
374
+ style: "currency",
375
+ currency,
376
+ signDisplay: "negative"
377
+ }).format(n);
378
+ if (fmt === "int") return new Intl.NumberFormat("en-US", {
379
+ maximumFractionDigits: 0,
380
+ signDisplay: "negative"
381
+ }).format(n);
382
+ const num = new Intl.NumberFormat("en-US", {
383
+ maximumFractionDigits: 2,
384
+ signDisplay: "negative"
385
+ }).format(n);
386
+ return fmt === "pct" ? `${num}%` : num;
387
+ }
388
+ if (fmt === "date" || fmt === "datetime") {
389
+ if (typeof v !== "string" && typeof v !== "number") return raw;
390
+ if (fmt === "date" && typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v)) return v;
391
+ const d = new Date(v);
392
+ if (Number.isNaN(d.getTime())) return raw;
393
+ if (fmt === "date" && d.getTime() % 864e5 === 0) return d.toISOString().slice(0, 10);
394
+ return fmt === "date" ? localDay(d) : `${localDay(d)} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
395
+ }
396
+ return raw;
397
+ }
398
+
219
399
  //#endregion
220
400
  //#region src/ask/render.tsx
221
401
  const KIND = {
@@ -247,11 +427,76 @@ function outcomeChips(o) {
247
427
  tone: o.source === "handoff" ? "warn" : "dim"
248
428
  },
249
429
  {
250
- label: rejected ? "rejected" : `${o.count ?? (Array.isArray(o.data) ? o.data.length : 0)} rows`,
430
+ label: rejected ? "rejected" : o.aggregate !== void 0 ? "aggregate" : typeof o.count === "number" ? `count ${o.count}` : `${Array.isArray(o.data) ? o.data.length : 0} rows`,
251
431
  tone: rejected ? "error" : "dim"
252
432
  }
253
433
  ];
254
434
  }
435
+ /** The first label-like field a row has: the usual handles, then any `…Name` / `…Title` string. */
436
+ const LABELS = [
437
+ "title",
438
+ "synopsis",
439
+ "name",
440
+ "topic",
441
+ "subject"
442
+ ];
443
+ function labelField(r) {
444
+ const own = LABELS.find((k) => typeof r[k] === "string" && r[k] !== "");
445
+ if (own !== void 0) return own;
446
+ return Object.keys(r).find((k) => /(Name|Title)$/.test(k) && typeof r[k] === "string" && r[k] !== "");
447
+ }
448
+ /** Fields the question filtered or ordered on, in the order they appear in the frame. */
449
+ function askedFields(frame) {
450
+ const params = Object.values(frame)[0]?.params ?? {};
451
+ const out = [];
452
+ const add = (k) => {
453
+ if (!out.includes(k)) out.push(k);
454
+ };
455
+ const walk = (w) => {
456
+ if (w === null || typeof w !== "object") return;
457
+ for (const [k, v] of Object.entries(w)) if (k === "AND" || k === "OR" || k === "NOT") for (const c of Array.isArray(v) ? v : [v]) walk(c);
458
+ else if (!k.startsWith("_")) add(k);
459
+ };
460
+ for (const o of params.orderBy ?? []) for (const k of Object.keys(o)) add(k.replace(/^\$/, ""));
461
+ walk(params.where);
462
+ return out;
463
+ }
464
+ /** A row's walked values (`_agg.<name>`, such as a hop ordering's) as fields beside its own. */
465
+ const withWalked = (r) => {
466
+ const a = own$1(r, "_agg");
467
+ return a !== null && typeof a === "object" && !Array.isArray(a) ? {
468
+ ...a,
469
+ ...r
470
+ } : r;
471
+ };
472
+ /** `name value` for each walked value a row carries. */
473
+ const walkedDetails = (r) => {
474
+ const a = own$1(r, "_agg");
475
+ if (a === null || typeof a !== "object" || Array.isArray(a)) return [];
476
+ return Object.entries(a).filter(([, v]) => !empty(v)).map(([k, v]) => `${sanitise(k)} ${str(v)}`);
477
+ };
478
+ const empty = (v) => v === null || v === void 0 || v === "" || typeof v === "object";
479
+ /** A row's own field as the view formats it, sanitised; '' when empty. */
480
+ const shown = (r, field, view) => {
481
+ const v = own$1(r, field);
482
+ return empty(v) ? "" : view === void 0 ? str(v) : sanitise(formatValue(v, own$1(view.formats, field), view.currency));
483
+ };
484
+ /** An entry's cell: its template around the formatted value; '' when the value is empty. */
485
+ const cell$1 = (r, e, view) => {
486
+ const v = shown(r, e.field, view);
487
+ return v === "" || e.template === void 0 ? v : sanitise(e.template.replaceAll("{}", () => v));
488
+ };
489
+ /** Width of a right-aligned value column: the widest value, capped at a third of the line. */
490
+ const valueWidth = (values, columns) => Math.min(Math.max(0, ...values.map(cellWidth)), Math.max(8, Math.floor(columns / 3)));
491
+ const SKIP = /* @__PURE__ */ new Set(["id", "shortId"]);
492
+ /** `field=value` for a row's scalar fields: the asked-about ones first, then the rest. */
493
+ function details(r, asked, label, view) {
494
+ const scalar = (k) => {
495
+ const v = r[k];
496
+ return v !== null && v !== void 0 && v !== "" && typeof v !== "object";
497
+ };
498
+ return [...asked.filter((k) => k in r), ...Object.keys(r).filter((k) => !asked.includes(k))].filter((k) => !SKIP.has(k) && k !== label && scalar(k)).map((k) => `${sanitise(k)}=${shown(r, k, view)}`).join(" ");
499
+ }
255
500
  const COLS = {
256
501
  id: 6,
257
502
  status: 10,
@@ -260,13 +505,181 @@ const COLS = {
260
505
  minTitle: 12
261
506
  };
262
507
  const titleWidth = (columns) => Math.max(COLS.minTitle, columns - (COLS.id + COLS.status + COLS.project + COLS.gaps));
508
+ const FN_LABEL = {
509
+ avg: "average",
510
+ sum: "total",
511
+ min: "min",
512
+ max: "max"
513
+ };
514
+ const aggValue = (v, view, field) => v === null || v === void 0 ? "—" : view !== void 0 && field !== void 0 && own$1(view.formats, field) !== void 0 ? sanitise(formatValue(v, own$1(view.formats, field), view.currency)) : typeof v === "number" && !Number.isInteger(v) ? String(Math.abs(v) >= .01 ? Math.round(v * 100) / 100 : Number(v.toPrecision(3))) : str(v);
515
+ /**
516
+ * A declared type's list. Wide: per row a dim ordinal, the bold title, dim tag chips and the value
517
+ * right-aligned in one column down the list, then an optional dim `·`-joined details line.
518
+ * Stacked, when the title would get less than max(20, 40%) of line 1: the title alone, then
519
+ * `tags · value`, then details. One layout for the whole list, so it stays aligned. Rows truncate.
520
+ */
521
+ function declaredRows(list, row, view, theme, columns) {
522
+ const ordW = String(list.length).length;
523
+ const prefixW = 1 + ordW + 2;
524
+ const indent = " ".repeat(prefixW + 2);
525
+ const detailW = Math.max(1, columns - indent.length);
526
+ const values = list.map((r) => row.value === void 0 ? "" : cell$1(r, row.value, view));
527
+ const valW = row.value === void 0 ? 0 : valueWidth(values.map((v) => v || "—"), columns);
528
+ const leftW = Math.max(1, columns - prefixW - (valW > 0 ? valW + 2 : 0));
529
+ const items = list.map((r) => {
530
+ const f = row.title?.field ?? labelField(r);
531
+ return {
532
+ title: (f === void 0 ? "" : cell$1(r, row.title ?? { field: f }, view)) || "—",
533
+ tags: row.tags.map((e) => cell$1(r, e, view)).filter((t) => t !== ""),
534
+ det: [...walkedDetails(r), ...row.details.map((e) => {
535
+ const v = cell$1(r, e, view);
536
+ if (v === "") return "";
537
+ const label = e.label ?? (typeof own$1(r, e.field) === "number" || isNumericFormat(own$1(view.formats, e.field)) ? e.field : void 0);
538
+ return label === void 0 ? v : `${sanitise(label)} ${v}`;
539
+ })].filter((d) => d !== "")
540
+ };
541
+ });
542
+ const wide = leftW - Math.max(0, ...items.map((x) => x.tags.length > 0 ? cellWidth(` ${x.tags.join(" ")}`) : 0)) >= Math.max(20, Math.ceil(columns * .4));
543
+ const ordinal = (i) => /* @__PURE__ */ jsx(Text, {
544
+ color: theme.color.dim,
545
+ children: ` ${padCells(String(i + 1), ordW, true)} `
546
+ });
547
+ const details = (det) => det.length > 0 ? /* @__PURE__ */ jsx(Text, {
548
+ wrap: "truncate",
549
+ color: theme.color.dim,
550
+ children: indent + truncateCells(det.join(" · "), detailW)
551
+ }) : null;
552
+ return items.map(({ title, tags, det }, i) => {
553
+ const value = values[i] ?? "";
554
+ if (!wide) {
555
+ const second = [...tags, value].filter((x) => x !== "");
556
+ return /* @__PURE__ */ jsxs(Box, {
557
+ flexDirection: "column",
558
+ children: [
559
+ /* @__PURE__ */ jsxs(Text, {
560
+ wrap: "truncate",
561
+ children: [ordinal(i), /* @__PURE__ */ jsx(Text, {
562
+ bold: true,
563
+ color: theme.color.text,
564
+ children: truncateCells(title, Math.max(1, columns - prefixW))
565
+ })]
566
+ }),
567
+ second.length > 0 ? /* @__PURE__ */ jsx(Text, {
568
+ wrap: "truncate",
569
+ color: theme.color.dim,
570
+ children: indent + truncateCells(second.join(" · "), detailW)
571
+ }) : null,
572
+ details(det)
573
+ ]
574
+ }, i);
575
+ }
576
+ const titleCell = truncateCells(title, leftW);
577
+ const room = leftW - cellWidth(titleCell);
578
+ const rest = tags.length > 0 && room > 0 ? ` ${tags.join(" ")}` : "";
579
+ const pad = valW > 0;
580
+ const restCell = pad ? padCells(rest, room) : truncateCells(rest, room);
581
+ return /* @__PURE__ */ jsxs(Box, {
582
+ flexDirection: "column",
583
+ children: [/* @__PURE__ */ jsxs(Text, {
584
+ wrap: "truncate",
585
+ children: [
586
+ ordinal(i),
587
+ /* @__PURE__ */ jsx(Text, {
588
+ bold: true,
589
+ color: theme.color.text,
590
+ children: titleCell
591
+ }),
592
+ /* @__PURE__ */ jsx(Text, {
593
+ color: theme.color.dim,
594
+ children: restCell
595
+ }),
596
+ pad ? /* @__PURE__ */ jsx(Text, {
597
+ color: theme.color.text,
598
+ children: ` ${padCells(truncateCells(value || "—", valW), valW, true)}`
599
+ }) : null
600
+ ]
601
+ }), details(det)]
602
+ }, i);
603
+ });
604
+ }
605
+ /** Below this width a grouped aggregate puts each value on the line under its key. */
606
+ const STACK_GROUPS_AT = 40;
263
607
  const rows = ({ data, theme, size }) => {
264
608
  const titleCols = titleWidth(size.columns);
265
609
  const o = data;
610
+ const view = o.tui;
266
611
  const lost = droppedLines(o.dropped).map((l, i) => /* @__PURE__ */ jsx(Text, {
267
612
  color: theme.color.warn,
268
613
  children: ` ${l}`
269
614
  }, `d${i}`));
615
+ const agg = o.aggregate;
616
+ if (agg !== void 0) {
617
+ const head = `${Object.hasOwn(FN_LABEL, agg.fn) ? FN_LABEL[agg.fn] : str(agg.fn)} ${str(agg.field)}`;
618
+ const errs = errorLines(o.errors).map((l, i) => /* @__PURE__ */ jsx(Text, {
619
+ color: theme.color.error,
620
+ children: ` ${l}`
621
+ }, `e${i}`));
622
+ if (agg.groups === void 0) return /* @__PURE__ */ jsxs(Box, {
623
+ flexDirection: "column",
624
+ children: [
625
+ /* @__PURE__ */ jsx(Text, {
626
+ color: theme.color.text,
627
+ children: `${head} = ${aggValue(agg.value, view, agg.field)}`
628
+ }),
629
+ errs,
630
+ lost
631
+ ]
632
+ });
633
+ const keyCols = Math.min(30, Math.max(COLS.minTitle, Math.floor(size.columns / 3)));
634
+ const groups = agg.groups.filter((g) => g.key === null || g.value !== null);
635
+ const values = groups.map((g) => aggValue(g.value, view, agg.field));
636
+ const valW = valueWidth(values, size.columns);
637
+ return /* @__PURE__ */ jsxs(Box, {
638
+ flexDirection: "column",
639
+ children: [
640
+ /* @__PURE__ */ jsx(Text, {
641
+ color: theme.color.dim,
642
+ children: `${head} by ${str(agg.by)}`
643
+ }),
644
+ groups.length === 0 ? /* @__PURE__ */ jsx(Text, {
645
+ color: theme.color.dim,
646
+ children: " no groups"
647
+ }) : null,
648
+ groups.map((g, i) => size.columns <= STACK_GROUPS_AT ? /* @__PURE__ */ jsxs(Box, {
649
+ flexDirection: "column",
650
+ children: [/* @__PURE__ */ jsx(Text, {
651
+ wrap: "truncate",
652
+ color: theme.color.dimMid,
653
+ children: ` ${truncateCells(g.key === null ? "(none)" : str(g.key), Math.max(1, size.columns - 2))}`
654
+ }), /* @__PURE__ */ jsx(Text, {
655
+ wrap: "truncate",
656
+ color: theme.color.text,
657
+ children: ` ${truncateCells(values[i] ?? "", Math.max(1, size.columns - 4))}`
658
+ })]
659
+ }, i) : /* @__PURE__ */ jsxs(Text, {
660
+ wrap: "truncate",
661
+ children: [
662
+ " ",
663
+ /* @__PURE__ */ jsx(Text, {
664
+ color: theme.color.dimMid,
665
+ children: padCells(g.key === null ? "(none)" : str(g.key), keyCols)
666
+ }),
667
+ " ",
668
+ /* @__PURE__ */ jsx(Text, {
669
+ color: theme.color.text,
670
+ children: padCells(truncateCells(values[i] ?? "", valW), valW, true)
671
+ })
672
+ ]
673
+ }, i)),
674
+ agg.truncated === true ? /* @__PURE__ */ jsx(Text, {
675
+ color: theme.color.dim,
676
+ children: " …more groups"
677
+ }) : null,
678
+ errs,
679
+ lost
680
+ ]
681
+ });
682
+ }
270
683
  if (!Array.isArray(o.data) && typeof o.count === "number") return /* @__PURE__ */ jsxs(Box, {
271
684
  flexDirection: "column",
272
685
  children: [/* @__PURE__ */ jsx(Text, {
@@ -289,6 +702,38 @@ const rows = ({ data, theme, size }) => {
289
702
  color: theme.color.dim,
290
703
  children: "no rows"
291
704
  });
705
+ if (view?.row !== void 0) return /* @__PURE__ */ jsxs(Box, {
706
+ flexDirection: "column",
707
+ children: [declaredRows(list, view.row, view, theme, size.columns), lost]
708
+ });
709
+ if (!list.some((r) => "status" in r || "project" in r)) {
710
+ const asked = askedFields(o.frame);
711
+ const labelCols = Math.min(40, Math.max(COLS.minTitle, Math.floor(size.columns / 3)));
712
+ const detailCols = Math.max(COLS.minTitle, size.columns - (COLS.id + labelCols + 4));
713
+ return /* @__PURE__ */ jsxs(Box, {
714
+ flexDirection: "column",
715
+ children: [list.map((row, i) => {
716
+ const r = withWalked(row);
717
+ const label = labelField(r);
718
+ return /* @__PURE__ */ jsxs(Text, { children: [
719
+ /* @__PURE__ */ jsx(Text, {
720
+ color: theme.color.dim,
721
+ children: padCells(str(r.shortId ?? r.id), COLS.id, true)
722
+ }),
723
+ " ",
724
+ /* @__PURE__ */ jsx(Text, {
725
+ color: theme.color.text,
726
+ children: padCells(label !== void 0 ? shown(r, label, view) : "", labelCols)
727
+ }),
728
+ " ",
729
+ /* @__PURE__ */ jsx(Text, {
730
+ color: theme.color.dimMid,
731
+ children: padCells(details(r, asked, label, view), detailCols)
732
+ })
733
+ ] }, i);
734
+ }), lost]
735
+ });
736
+ }
292
737
  return /* @__PURE__ */ jsxs(Box, {
293
738
  flexDirection: "column",
294
739
  children: [
@@ -443,15 +888,39 @@ function explain(err, endpoint) {
443
888
  if (e.status === 401 || e.status === 403) return `not authorised (${e.status}) — check SUBSTRATE_AGENT_KEY_ID / SUBSTRATE_AGENT_KEY_PATH`;
444
889
  return e.message ?? String(err);
445
890
  }
891
+ /** What the server accepts for `asOf`: a date-time with an explicit offset. */
892
+ const ISO_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
446
893
  function askModule(deps) {
447
894
  let namespace = deps.namespace;
448
895
  let pack = null;
449
896
  let forceType;
897
+ /** The clock relative phrases are read against; undefined = the server's. */
898
+ let asOf;
450
899
  let last = { lines: ["no question asked yet"] };
451
900
  let lastPackNote = "";
901
+ /** The namespace's `annotations.tui`; empty until read, and when it cannot be. */
902
+ let present = {
903
+ types: {},
904
+ problems: []
905
+ };
452
906
  const loadPack = (ctx) => {
453
907
  pack = null;
454
908
  const ns = namespace;
909
+ present = {
910
+ types: {},
911
+ problems: []
912
+ };
913
+ deps.getJson(`/substrate/v1/schema/${encodeURIComponent(ns)}`, ctx.signal).then((s) => {
914
+ if (ns !== namespace) return;
915
+ try {
916
+ present = parseTui(s?.annotations?.tui);
917
+ } catch {
918
+ present = {
919
+ types: {},
920
+ problems: [{ text: "tui ignored: unreadable" }]
921
+ };
922
+ }
923
+ }, () => {});
455
924
  deps.nl.pack(ns, { signal: ctx.signal }).then((p) => {
456
925
  if (ns === namespace) pack = p;
457
926
  }, (err) => {
@@ -462,6 +931,15 @@ function askModule(deps) {
462
931
  ctx.print(note, "dim");
463
932
  });
464
933
  };
934
+ /** A rows outcome with its frame type's declared view, when the namespace declares one. */
935
+ const withView = (o) => {
936
+ const [ns, type] = (Object.keys(o.frame)[0] ?? "").split("/");
937
+ const view = ns === namespace && type !== void 0 ? own$1(present.types, type) : void 0;
938
+ return view !== void 0 ? {
939
+ ...o,
940
+ tui: view
941
+ } : o;
942
+ };
465
943
  const pick = (i) => (s, ctx) => {
466
944
  const opt = s.options[i];
467
945
  if (opt === void 0) return void 0;
@@ -474,23 +952,41 @@ function askModule(deps) {
474
952
  loadPack(ctx);
475
953
  ctx.emit("substrate/ns", { namespace });
476
954
  },
477
- commands: [{
478
- name: "ns",
479
- summary: "switch the namespace questions go to",
480
- args: [{ name: "namespace" }],
481
- run([ns], ctx) {
482
- if (ns === void 0 || ns === "") return ctx.print(`namespace: ${namespace}`);
483
- namespace = ns;
484
- loadPack(ctx);
485
- ctx.emit("substrate/ns", { namespace });
486
- ctx.print(`namespace → ${namespace}`);
955
+ commands: [
956
+ {
957
+ name: "ns",
958
+ summary: "switch the namespace questions go to",
959
+ args: [{ name: "namespace" }],
960
+ run([ns], ctx) {
961
+ if (ns === void 0 || ns === "") return ctx.print(`namespace: ${namespace}`);
962
+ namespace = ns;
963
+ loadPack(ctx);
964
+ ctx.emit("substrate/ns", { namespace });
965
+ ctx.print(`namespace → ${namespace}`);
966
+ }
967
+ },
968
+ {
969
+ name: "asof",
970
+ summary: "read \"yesterday\", \"past 2 days\" … as of a date-time (ISO-8601 with an offset); off for the server clock",
971
+ args: [{ name: "datetime|off" }],
972
+ run([v], ctx) {
973
+ if (v === void 0 || v === "") return ctx.print(`asOf: ${asOf ?? "server clock"}`);
974
+ if (v === "off") {
975
+ asOf = void 0;
976
+ return ctx.print("asOf → server clock");
977
+ }
978
+ if (!ISO_WITH_OFFSET.test(v) || Number.isNaN(Date.parse(v))) return ctx.print("asOf needs an ISO-8601 date-time with an offset, e.g. 2026-10-24T23:59:59-05:00");
979
+ asOf = v;
980
+ ctx.print(`asOf → ${asOf}`);
981
+ }
982
+ },
983
+ {
984
+ name: "frame",
985
+ summary: "show the last answer's query frame, evidence and judge trail",
986
+ args: [],
987
+ run: (_a, ctx) => ctx.open("frame", last)
487
988
  }
488
- }, {
489
- name: "frame",
490
- summary: "show the last answer's query frame, evidence and judge trail",
491
- args: [],
492
- run: (_a, ctx) => ctx.open("frame", last)
493
- }],
989
+ ],
494
990
  panels: {
495
991
  clarify: {
496
992
  view: ({ state }) => [
@@ -525,11 +1021,13 @@ function askModule(deps) {
525
1021
  namespace,
526
1022
  question: text,
527
1023
  project: deps.project,
1024
+ ...asOf !== void 0 ? { asOf } : {},
528
1025
  ...type !== void 0 ? { type } : {}
529
1026
  }, { signal })) switch (ev.event) {
530
1027
  case "parsed": {
531
1028
  const key = ev.data.frame !== void 0 ? Object.keys(ev.data.frame)[0] : void 0;
532
1029
  lines.push(`parse: ${ev.data.status}${ev.data.reason !== void 0 ? ` — ${ev.data.reason}` : ""}`);
1030
+ if (ev.data.asOf !== void 0) lines.push(`asOf: ${ev.data.asOf}`);
533
1031
  if (ev.data.frame !== void 0) lines.push(JSON.stringify(ev.data.frame, null, 2));
534
1032
  for (const e of ev.data.evidence) lines.push(` ${e.span} → ${e.role} (${e.detail})`);
535
1033
  yield {
@@ -559,7 +1057,9 @@ function askModule(deps) {
559
1057
  case "recall":
560
1058
  case "clarify":
561
1059
  case "refuse":
562
- case "unknown":
1060
+ case "unknown": {
1061
+ const answered = ev.event === "rows" ? Object.keys(ev.data.frame)[0]?.split("/")[1] : void 0;
1062
+ for (const p of present.problems) if (p.type === void 0 || p.type === answered) lines.push(`tui: ${p.text}`);
563
1063
  last = { lines };
564
1064
  if (ev.event === "clarify" && ev.data.options.length > 0) ctx.open("clarify", ev.data);
565
1065
  else ctx.close();
@@ -567,11 +1067,12 @@ function askModule(deps) {
567
1067
  phase: "final",
568
1068
  reply: {
569
1069
  kind: `substrate.${ev.event}`,
570
- data: ev.data,
1070
+ data: ev.event === "rows" ? withView(ev.data) : ev.data,
571
1071
  chips: outcomeChips(ev.data)
572
1072
  }
573
1073
  };
574
1074
  return;
1075
+ }
575
1076
  case "done": return;
576
1077
  }
577
1078
  } catch (err) {
@@ -3723,6 +4224,10 @@ function substrateAppOptions(deps, opts = {}) {
3723
4224
  defaultTurn: "substrate.ask:ask",
3724
4225
  band: true,
3725
4226
  gutter: 2,
4227
+ entries: { answer: ({ entry, body, theme }) => createElement(Box, {
4228
+ flexDirection: "column",
4229
+ marginBottom: 1
4230
+ }, entry.mark !== null ? createElement(Text, { color: theme.color.accent }, `↩ ⟨${entry.mark}⟩`) : null, body) },
3726
4231
  anchored: true,
3727
4232
  terminal: false
3728
4233
  };
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as colorDepthEnv } from "../terminal-XfKFiD7r.js";
2
+ import { t as colorDepthEnv } from "../terminal-4hKQ29CS.js";
3
3
  import { basename } from "node:path";
4
4
  import { DEFAULT_CAPABILITIES, makeTokenProvider, tokenAudience } from "@mnmal-ai/substrate/client";
5
5
  import { trimTrailingSlashes } from "@mnmal-ai/substrate/sdk";
@@ -51,10 +51,10 @@ async function main() {
51
51
  }
52
52
  Object.assign(process.env, colorDepthEnv(process.env));
53
53
  const [{ createTui }, { makeDeps }, { prepareTerminal }, { terminalOptions }] = await Promise.all([
54
- import("../app-xXFNoDVu.js"),
54
+ import("../app-CQnYeMdE.js"),
55
55
  import("../deps-WzqsHHiC.js"),
56
56
  import("@mnmal-ai/surface-core/pure"),
57
- import("../terminal-CVX2CKWu.js")
57
+ import("../terminal-BAd8sH3d.js")
58
58
  ]);
59
59
  let deps;
60
60
  try {
@@ -1,13 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import { resolveFullscreen } from "@mnmal-ai/surface-core/pure";
3
+
2
4
  //#region src/terminal.ts
3
5
  /**
4
- * How substrate-tui prepares the terminal: a black ground and a fresh, bottom-anchored pane.
5
- * `SUBSTRATE_TUI_BACKGROUND` takes `#rrggbb` or `none`; `SUBSTRATE_TUI_CLEAR=0` keeps what was on screen.
6
+ * How substrate-tui prepares the terminal: a black ground, and full-screen unless
7
+ * `SURFACE_FULLSCREEN=off`, which gives a fresh, bottom-anchored pane instead.
8
+ * `SUBSTRATE_TUI_BACKGROUND` takes `#rrggbb` or `none`; `SUBSTRATE_TUI_CLEAR=0` keeps what was on
9
+ * screen (full-screen never clears: it draws on the alternate screen).
6
10
  */
7
11
  function terminalOptions(env) {
8
12
  return {
9
13
  ...env.SUBSTRATE_TUI_BACKGROUND !== void 0 ? { ground: env.SUBSTRATE_TUI_BACKGROUND } : {},
10
- clear: (env.SUBSTRATE_TUI_CLEAR ?? "").trim() !== "0"
14
+ clear: (env.SUBSTRATE_TUI_CLEAR ?? "").trim() !== "0",
15
+ fullscreen: resolveFullscreen(void 0, env.SURFACE_FULLSCREEN).on
11
16
  };
12
17
  }
13
18
  /**
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { n as terminalOptions, t as colorDepthEnv } from "./terminal-XfKFiD7r.js";
2
+ import { n as terminalOptions, t as colorDepthEnv } from "./terminal-4hKQ29CS.js";
3
3
 
4
4
  export { colorDepthEnv, terminalOptions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mnmal-ai/substrate-tui",
3
- "version": "1.0.0-alpha.13",
3
+ "version": "1.0.0-alpha.15",
4
4
  "description": "Terminal UI for Substrate: ask in natural language, browse the schema, see the service status.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -20,17 +20,17 @@
20
20
  "access": "public"
21
21
  },
22
22
  "dependencies": {
23
- "@mnmal-ai/substrate": "1.0.0-alpha.13",
24
- "@mnmal-ai/substrate-nl": "1.0.0-alpha.13",
25
- "@mnmal-ai/surface-core": "0.15.0",
26
- "@mnmal-ai/surface-kit": "0.15.0",
27
- "@mnmal-ai/surface-theme": "0.15.0",
23
+ "@mnmal-ai/substrate": "1.0.0-alpha.15",
24
+ "@mnmal-ai/substrate-nl": "1.0.0-alpha.15",
25
+ "@mnmal-ai/surface-core": "0.16.0",
26
+ "@mnmal-ai/surface-kit": "0.16.0",
27
+ "@mnmal-ai/surface-theme": "0.16.0",
28
28
  "ink": "^8.0.0",
29
29
  "react": "^19.3.0"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@biomejs/biome": "2.6.4",
33
- "@mnmal-ai/substrate-config": "1.0.0-alpha.13",
33
+ "@mnmal-ai/substrate-config": "1.0.0-alpha.15",
34
34
  "@types/node": "^26.6.4",
35
35
  "@types/react": "^19.2.0",
36
36
  "ink-testing-library": "^4.0.0",