@mnmal-ai/substrate-tui 1.0.0-alpha.2 → 1.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @mnmal-ai/substrate-tui
2
2
 
3
- A terminal UI for Substrate: ask questions in natural language, browse the federated schema, watch service status and metrics, and, with an unlocked admin identity, run admin operations. Install it with `pnpm add -g @mnmal-ai/substrate-tui`, then run `substrate-tui` in an interactive terminal with `SUBSTRATE_URL` set.
3
+ A terminal UI for Substrate: ask questions in natural language, browse the federated schema, watch service status and metrics, and, with an unlocked admin identity, run admin operations. Install it with `pnpm add -g @mnmal-ai/substrate-tui@next`, then run `substrate-tui` in an interactive terminal with `SUBSTRATE_URL` set.
4
4
 
5
5
  Without an admin identity it is read-only.
6
6
 
@@ -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,16 +17,36 @@ 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
27
48
 
28
- `● LIVE`, `● OFFLINE` or `● RECONNECTING` (polled from `/health` every 10 s), the service version, the agent kid (`anon` when unauthenticated, `anon?` when whoami fails) and the active namespace.
49
+ `● LIVE`, `● OFFLINE` or `● RECONNECTING` (polled from `/health` every 10 s), the service version, the agent kid (key id; `anon` when unauthenticated, `anon?` when whoami fails) and the active namespace.
29
50
 
30
51
  ## Environment
31
52
 
@@ -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`. |
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { i as isKeyRejection, t as adminCapabilityOf } from "./session-C1D5Ermr.js";
3
3
  import { resolve } from "node:path";
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 } from "@mnmal-ai/substrate/client";
5
- import { createApp, defineModule, sanitise } from "@mnmal-ai/surface-core";
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, substrateFetch, tokenAudience } from "@mnmal-ai/substrate/client";
5
+ import { createApp, defineModule, listPager, 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";
@@ -76,6 +77,7 @@ function adminModule(deps, io = {}) {
76
77
  kid
77
78
  }, {
78
79
  capabilities: adminClaimCapabilities(deps.adminEnv),
80
+ audience: tokenAudience(deps.endpoint),
79
81
  ...passphrase !== void 0 ? { passphrase } : {}
80
82
  });
81
83
  return verifyAndUnlock(() => `Bearer ${getToken()}`, keyPath, kid, getToken);
@@ -215,6 +217,185 @@ function adapt(draft, cursor, s) {
215
217
  };
216
218
  }
217
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
+
218
399
  //#endregion
219
400
  //#region src/ask/render.tsx
220
401
  const KIND = {
@@ -223,6 +404,7 @@ const KIND = {
223
404
  recall: "substrate.recall",
224
405
  clarify: "substrate.clarify",
225
406
  refuse: "substrate.refuse",
407
+ unknown: "substrate.unknown",
226
408
  error: "substrate.error"
227
409
  };
228
410
  const str = (v) => v === void 0 || v === null ? "" : sanitise(String(v));
@@ -231,9 +413,10 @@ const errorLines = (errors) => (errors ?? []).map((e) => {
231
413
  const x = e;
232
414
  return sanitise(`${x.code ?? "error"}${x.message !== void 0 ? `: ${x.message}` : ""}`);
233
415
  });
416
+ const droppedLines = (dropped) => (dropped ?? []).map((d) => sanitise(`dropped "${d.span}": ${d.reason}`));
234
417
  function outcomeChips(o) {
235
418
  if (o.kind !== "rows") return [];
236
- const rejected = !Array.isArray(o.data);
419
+ const rejected = o.data === void 0;
237
420
  return [
238
421
  {
239
422
  label: `▸ ${frameKey(o)}`,
@@ -244,11 +427,76 @@ function outcomeChips(o) {
244
427
  tone: o.source === "handoff" ? "warn" : "dim"
245
428
  },
246
429
  {
247
- label: rejected ? "rejected" : `${o.data.length} 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`,
248
431
  tone: rejected ? "error" : "dim"
249
432
  }
250
433
  ];
251
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);
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 detailList(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)}`);
499
+ }
252
500
  const COLS = {
253
501
  id: 6,
254
502
  status: 10,
@@ -257,9 +505,183 @@ const COLS = {
257
505
  minTitle: 12
258
506
  };
259
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: declaredDetails(r, row, view)
535
+ };
536
+ });
537
+ 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));
538
+ const ordinal = (i) => /* @__PURE__ */ jsx(Text, {
539
+ color: theme.color.dim,
540
+ children: ` ${padCells(String(i + 1), ordW, true)} `
541
+ });
542
+ const details = (det) => det.length > 0 ? /* @__PURE__ */ jsx(Text, {
543
+ wrap: "truncate",
544
+ color: theme.color.dim,
545
+ children: indent + truncateCells(det.join(" · "), detailW)
546
+ }) : null;
547
+ return items.map(({ title, tags, det }, i) => {
548
+ const value = values[i] ?? "";
549
+ if (!wide) {
550
+ const second = [...tags, value].filter((x) => x !== "");
551
+ return /* @__PURE__ */ jsxs(Box, {
552
+ flexDirection: "column",
553
+ children: [
554
+ /* @__PURE__ */ jsxs(Text, {
555
+ wrap: "truncate",
556
+ children: [ordinal(i), /* @__PURE__ */ jsx(Text, {
557
+ bold: true,
558
+ color: theme.color.text,
559
+ children: truncateCells(title, Math.max(1, columns - prefixW))
560
+ })]
561
+ }),
562
+ second.length > 0 ? /* @__PURE__ */ jsx(Text, {
563
+ wrap: "truncate",
564
+ color: theme.color.dim,
565
+ children: indent + truncateCells(second.join(" · "), detailW)
566
+ }) : null,
567
+ details(det)
568
+ ]
569
+ }, i);
570
+ }
571
+ const titleCell = truncateCells(title, leftW);
572
+ const room = leftW - cellWidth(titleCell);
573
+ const rest = tags.length > 0 && room > 0 ? ` ${tags.join(" ")}` : "";
574
+ const pad = valW > 0;
575
+ const restCell = pad ? padCells(rest, room) : truncateCells(rest, room);
576
+ return /* @__PURE__ */ jsxs(Box, {
577
+ flexDirection: "column",
578
+ children: [/* @__PURE__ */ jsxs(Text, {
579
+ wrap: "truncate",
580
+ children: [
581
+ ordinal(i),
582
+ /* @__PURE__ */ jsx(Text, {
583
+ bold: true,
584
+ color: theme.color.text,
585
+ children: titleCell
586
+ }),
587
+ /* @__PURE__ */ jsx(Text, {
588
+ color: theme.color.dim,
589
+ children: restCell
590
+ }),
591
+ pad ? /* @__PURE__ */ jsx(Text, {
592
+ color: theme.color.text,
593
+ children: ` ${padCells(truncateCells(value || "—", valW), valW, true)}`
594
+ }) : null
595
+ ]
596
+ }), details(det)]
597
+ }, i);
598
+ });
599
+ }
600
+ /** Below this width a grouped aggregate puts each value on the line under its key. */
601
+ const STACK_GROUPS_AT = 40;
260
602
  const rows = ({ data, theme, size }) => {
261
603
  const titleCols = titleWidth(size.columns);
262
604
  const o = data;
605
+ const view = o.tui;
606
+ const lost = droppedLines(o.dropped).map((l, i) => /* @__PURE__ */ jsx(Text, {
607
+ color: theme.color.warn,
608
+ children: ` ${l}`
609
+ }, `d${i}`));
610
+ const agg = o.aggregate;
611
+ if (agg !== void 0) {
612
+ const head = `${Object.hasOwn(FN_LABEL, agg.fn) ? FN_LABEL[agg.fn] : str(agg.fn)} ${str(agg.field)}`;
613
+ const errs = errorLines(o.errors).map((l, i) => /* @__PURE__ */ jsx(Text, {
614
+ color: theme.color.error,
615
+ children: ` ${l}`
616
+ }, `e${i}`));
617
+ if (agg.groups === void 0) return /* @__PURE__ */ jsxs(Box, {
618
+ flexDirection: "column",
619
+ children: [
620
+ /* @__PURE__ */ jsx(Text, {
621
+ color: theme.color.text,
622
+ children: `${head} = ${aggValue(agg.value, view, agg.field)}`
623
+ }),
624
+ errs,
625
+ lost
626
+ ]
627
+ });
628
+ const keyCols = Math.min(30, Math.max(COLS.minTitle, Math.floor(size.columns / 3)));
629
+ const groups = agg.groups.filter((g) => g.key === null || g.value !== null);
630
+ const values = groups.map((g) => aggValue(g.value, view, agg.field));
631
+ const valW = valueWidth(values, size.columns);
632
+ return /* @__PURE__ */ jsxs(Box, {
633
+ flexDirection: "column",
634
+ children: [
635
+ /* @__PURE__ */ jsx(Text, {
636
+ color: theme.color.dim,
637
+ children: `${head} by ${str(agg.by)}`
638
+ }),
639
+ groups.length === 0 ? /* @__PURE__ */ jsx(Text, {
640
+ color: theme.color.dim,
641
+ children: " no groups"
642
+ }) : null,
643
+ groups.map((g, i) => size.columns <= STACK_GROUPS_AT ? /* @__PURE__ */ jsxs(Box, {
644
+ flexDirection: "column",
645
+ children: [/* @__PURE__ */ jsx(Text, {
646
+ wrap: "truncate",
647
+ color: theme.color.dimMid,
648
+ children: ` ${truncateCells(g.key === null ? "(none)" : str(g.key), Math.max(1, size.columns - 2))}`
649
+ }), /* @__PURE__ */ jsx(Text, {
650
+ wrap: "truncate",
651
+ color: theme.color.text,
652
+ children: ` ${truncateCells(values[i] ?? "", Math.max(1, size.columns - 4))}`
653
+ })]
654
+ }, i) : /* @__PURE__ */ jsxs(Text, {
655
+ wrap: "truncate",
656
+ children: [
657
+ " ",
658
+ /* @__PURE__ */ jsx(Text, {
659
+ color: theme.color.dimMid,
660
+ children: padCells(g.key === null ? "(none)" : str(g.key), keyCols)
661
+ }),
662
+ " ",
663
+ /* @__PURE__ */ jsx(Text, {
664
+ color: theme.color.text,
665
+ children: padCells(truncateCells(values[i] ?? "", valW), valW, true)
666
+ })
667
+ ]
668
+ }, i)),
669
+ agg.truncated === true ? /* @__PURE__ */ jsx(Text, {
670
+ color: theme.color.dim,
671
+ children: " …more groups"
672
+ }) : null,
673
+ errs,
674
+ lost
675
+ ]
676
+ });
677
+ }
678
+ if (!Array.isArray(o.data) && typeof o.count === "number") return /* @__PURE__ */ jsxs(Box, {
679
+ flexDirection: "column",
680
+ children: [/* @__PURE__ */ jsx(Text, {
681
+ color: theme.color.text,
682
+ children: o.count
683
+ }), lost]
684
+ });
263
685
  if (!Array.isArray(o.data)) return /* @__PURE__ */ jsxs(Box, {
264
686
  flexDirection: "column",
265
687
  children: [/* @__PURE__ */ jsxs(Text, {
@@ -271,33 +693,85 @@ const rows = ({ data, theme, size }) => {
271
693
  }, i))]
272
694
  });
273
695
  const list = o.data;
274
- if (list.length === 0) return /* @__PURE__ */ jsx(Text, {
696
+ if (list.length === 0 && lost.length === 0) return /* @__PURE__ */ jsx(Text, {
275
697
  color: theme.color.dim,
276
698
  children: "no rows"
277
699
  });
278
- return /* @__PURE__ */ jsx(Box, {
700
+ if (view?.row !== void 0) return /* @__PURE__ */ jsxs(Box, {
279
701
  flexDirection: "column",
280
- children: list.map((r, i) => /* @__PURE__ */ jsxs(Text, { children: [
281
- /* @__PURE__ */ jsx(Text, {
702
+ children: [declaredRows(list, view.row, view, theme, size.columns), lost]
703
+ });
704
+ if (!list.some((r) => "status" in r || "project" in r)) {
705
+ const asked = askedFields(o.frame);
706
+ const labelCols = Math.min(40, Math.max(COLS.minTitle, Math.floor(size.columns / 3)));
707
+ const detailCols = Math.max(COLS.minTitle, size.columns - (COLS.id + labelCols + 4));
708
+ return /* @__PURE__ */ jsxs(Box, {
709
+ flexDirection: "column",
710
+ children: [list.map((row, i) => {
711
+ const r = withWalked(row);
712
+ const label = labelField(r);
713
+ return /* @__PURE__ */ jsxs(Text, { children: [
714
+ /* @__PURE__ */ jsx(Text, {
715
+ color: theme.color.dim,
716
+ children: padCells(str(r.shortId ?? r.id), COLS.id, true)
717
+ }),
718
+ " ",
719
+ /* @__PURE__ */ jsx(Text, {
720
+ color: theme.color.text,
721
+ children: padCells(label !== void 0 ? shown(r, label, view) : "", labelCols)
722
+ }),
723
+ " ",
724
+ /* @__PURE__ */ jsx(Text, {
725
+ color: theme.color.dimMid,
726
+ children: padCells(detailList(r, asked, label, view).join(" "), detailCols)
727
+ })
728
+ ] }, i);
729
+ }), lost]
730
+ });
731
+ }
732
+ return /* @__PURE__ */ jsxs(Box, {
733
+ flexDirection: "column",
734
+ children: [
735
+ list.length === 0 ? /* @__PURE__ */ jsx(Text, {
282
736
  color: theme.color.dim,
283
- children: padCells(str(r.shortId ?? r.id), COLS.id, true)
284
- }),
285
- " ",
286
- /* @__PURE__ */ jsx(Text, {
287
- color: theme.color.text,
288
- children: padCells(str(r.title ?? r.synopsis ?? r.name ?? r.topic ?? r.subject), titleCols)
289
- }),
290
- " ",
291
- /* @__PURE__ */ jsx(Text, {
292
- color: theme.color.info,
293
- children: padCells(str(r.status), COLS.status)
294
- }),
295
- " ",
296
- /* @__PURE__ */ jsx(Text, {
297
- color: theme.color.dimMid,
298
- children: padCells(str(r.project), COLS.project)
299
- })
300
- ] }, i))
737
+ children: "no rows"
738
+ }) : null,
739
+ list.map((r, i) => /* @__PURE__ */ jsxs(Text, { children: [
740
+ /* @__PURE__ */ jsx(Text, {
741
+ color: theme.color.dim,
742
+ children: padCells(str(r.shortId ?? r.id), COLS.id, true)
743
+ }),
744
+ " ",
745
+ /* @__PURE__ */ jsx(Text, {
746
+ color: theme.color.text,
747
+ children: padCells(str(r.title ?? r.synopsis ?? r.name ?? r.topic ?? r.subject), titleCols)
748
+ }),
749
+ " ",
750
+ /* @__PURE__ */ jsx(Text, {
751
+ color: theme.color.info,
752
+ children: padCells(str(r.status), COLS.status)
753
+ }),
754
+ " ",
755
+ /* @__PURE__ */ jsx(Text, {
756
+ color: theme.color.dimMid,
757
+ children: padCells(str(r.project), COLS.project)
758
+ })
759
+ ] }, i)),
760
+ lost
761
+ ]
762
+ });
763
+ };
764
+ const unknown = ({ data, theme }) => {
765
+ const o = data;
766
+ return /* @__PURE__ */ jsxs(Box, {
767
+ flexDirection: "column",
768
+ children: [/* @__PURE__ */ jsx(Text, {
769
+ color: theme.color.warn,
770
+ children: "? unknown: not answered, because part of it was dropped"
771
+ }), droppedLines(o.dropped).map((l, i) => /* @__PURE__ */ jsx(Text, {
772
+ color: theme.color.warn,
773
+ children: ` ${l}`
774
+ }, i))]
301
775
  });
302
776
  };
303
777
  const recall = ({ data, theme }) => {
@@ -385,8 +859,148 @@ const renderers = {
385
859
  [KIND.recall]: recall,
386
860
  [KIND.clarify]: clarify,
387
861
  [KIND.refuse]: refuse,
862
+ [KIND.unknown]: unknown,
388
863
  [KIND.error]: error
389
864
  };
865
+ /** A declared row's details: its walked values, then each declared detail, labelled when numeric. */
866
+ function declaredDetails(r, row, view) {
867
+ return [...walkedDetails(r), ...row.details.map((e) => {
868
+ const v = cell$1(r, e, view);
869
+ if (v === "") return "";
870
+ const label = e.label ?? (typeof own$1(r, e.field) === "number" || isNumericFormat(own$1(view.formats, e.field)) ? e.field : void 0);
871
+ return label === void 0 ? v : `${sanitise(label)} ${v}`;
872
+ })].filter((d) => d !== "");
873
+ }
874
+ /**
875
+ * A rows answer as a list for the pager, or undefined when it is not a plain list of rows (an
876
+ * aggregate, a count, a rejected frame). Declared rows keep their title, tags, details and value;
877
+ * the rest get a label and the asked-about fields, then the others, as `field=value`.
878
+ */
879
+ function rowsList(o) {
880
+ if (!Array.isArray(o.data) || o.aggregate !== void 0 || o.count !== void 0) return void 0;
881
+ const view = o.tui;
882
+ const asked = askedFields(o.frame);
883
+ const rows = o.data.map((raw, i) => {
884
+ const r = withWalked(raw);
885
+ const key = typeof raw.id === "string" ? raw.id : String(i);
886
+ const decl = view?.row;
887
+ if (view !== void 0 && decl !== void 0) {
888
+ const f = decl.title?.field ?? labelField(r);
889
+ const value = decl.value === void 0 ? "" : cell$1(r, decl.value, view);
890
+ return {
891
+ key,
892
+ name: (f === void 0 ? "" : cell$1(r, decl.title ?? { field: f }, view)) || "—",
893
+ details: [...decl.tags.map((e) => cell$1(r, e, view)).filter((t) => t !== ""), ...declaredDetails(r, decl, view)],
894
+ ...value !== "" ? { value } : {}
895
+ };
896
+ }
897
+ const label = labelField(r);
898
+ return {
899
+ key,
900
+ name: (label !== void 0 ? shown(r, label, view) : "") || str(r.shortId ?? r.id) || "—",
901
+ details: detailList(r, asked, label, view)
902
+ };
903
+ });
904
+ const notes = [...errorLines(o.errors), ...droppedLines(o.dropped)];
905
+ return {
906
+ heading: frameKey(o),
907
+ rows,
908
+ ...notes.length > 0 ? { notes } : {}
909
+ };
910
+ }
911
+
912
+ //#endregion
913
+ //#region src/ask/list.ts
914
+ /** Rows `r` lists: recall's hits about the same idea, the row itself left out. */
915
+ const RELATED_K = 20;
916
+ const META = [
917
+ "status",
918
+ "area",
919
+ "project"
920
+ ];
921
+ const text = (v) => typeof v === "string" ? v : "";
922
+ const scalar = (v) => v !== null && v !== void 0 && v !== "" && typeof v !== "object";
923
+ const nameOf = (row) => typeof row.name === "string" ? row.name : row.name.map((s) => s.text).join("");
924
+ /** A frame's rows; a refused frame throws the server's reason rather than reading as empty. */
925
+ async function rowsOf(deps, key, frame, signal) {
926
+ const env = await deps.query({ [key]: frame }, signal);
927
+ if (!Object.hasOwn(env.data, key)) throw new Error(env.errors?.[0]?.message ?? `${key} was refused`);
928
+ const v = env.data[key];
929
+ return (Array.isArray(v) ? v : [v]).filter((x) => x !== null && typeof x === "object");
930
+ }
931
+ /**
932
+ * Enter and `r` on an NL answer's rows. `open` reads the row's record whole (every scalar field
933
+ * the schema has, else the fields the answer carried); `related` asks recall, over the same type
934
+ * and namespace, for rows about the same idea as the record's label and body.
935
+ */
936
+ function listHooks(deps, ns, type, fields, answered, signal) {
937
+ const records = /* @__PURE__ */ new Map();
938
+ const record = (row) => {
939
+ const known = records.get(row.key);
940
+ if (known !== void 0) return known;
941
+ const seen = answered.get(row.key) ?? {};
942
+ if (typeof seen.id !== "string") return Promise.resolve(seen);
943
+ const names = fields !== void 0 ? Object.entries(fields).filter(([, f]) => f.kind === "scalar" && f.type !== "json").map(([k]) => k) : Object.keys(seen).filter((k) => scalar(seen[k]));
944
+ const read = rowsOf(deps, `${ns}/${type}`, {
945
+ params: {
946
+ where: { id: { eq: row.key } },
947
+ limit: 1
948
+ },
949
+ fields: Object.fromEntries(["id", ...names].map((k) => [k, true]))
950
+ }, signal).then((rows) => {
951
+ const r = rows[0];
952
+ if (r === void 0) throw new Error(`${type} ${row.key} is gone`);
953
+ return r;
954
+ });
955
+ read.catch(() => records.delete(row.key));
956
+ records.set(row.key, read);
957
+ return read;
958
+ };
959
+ return {
960
+ async open(row) {
961
+ const r = await record(row);
962
+ const label = labelField(r);
963
+ const meta = META.map((k) => text(r[k])).filter((v) => v !== "");
964
+ const prose = [text(r.body), text(r.notes)].filter((v) => v !== "");
965
+ const body = prose.length > 0 ? prose.join("\n\n") : Object.keys(r).filter((k) => k !== "id" && k !== label && !META.some((m) => m === k) && scalar(r[k])).map((k) => `${k}: ${String(r[k])}`).join("\n");
966
+ return {
967
+ title: label !== void 0 ? text(r[label]) : nameOf(row),
968
+ ...meta.length > 0 ? { meta: meta.join(" · ") } : {},
969
+ ...body !== "" ? { body } : {}
970
+ };
971
+ },
972
+ async related(row) {
973
+ const r = await record(row);
974
+ const label = labelField(r);
975
+ const title = label !== void 0 ? text(r[label]) : nameOf(row);
976
+ const rows = (await rowsOf(deps, "recall/Hit", {
977
+ params: {
978
+ to: [title, text(r.body)].filter((v) => v !== "").join("\n") || nameOf(row),
979
+ namespace: ns,
980
+ type,
981
+ k: 21
982
+ },
983
+ fields: {
984
+ id: true,
985
+ score: true,
986
+ row: true
987
+ }
988
+ }, signal)).filter((h) => h.id !== row.key).slice(0, 20).map((h) => {
989
+ const hr = h.row !== null && typeof h.row === "object" ? h.row : {};
990
+ const l = labelField(hr);
991
+ return {
992
+ key: String(h.id),
993
+ name: (l !== void 0 ? text(hr[l]) : "") || String(h.id),
994
+ ...typeof h.score === "number" ? { value: h.score.toFixed(2) } : {}
995
+ };
996
+ });
997
+ return {
998
+ heading: `related to ${title}`,
999
+ rows
1000
+ };
1001
+ }
1002
+ };
1003
+ }
390
1004
 
391
1005
  //#endregion
392
1006
  //#region src/ask/module.ts
@@ -408,15 +1022,48 @@ function explain(err, endpoint) {
408
1022
  if (e.status === 401 || e.status === 403) return `not authorised (${e.status}) — check SUBSTRATE_AGENT_KEY_ID / SUBSTRATE_AGENT_KEY_PATH`;
409
1023
  return e.message ?? String(err);
410
1024
  }
411
- function askModule(deps) {
1025
+ /** What the server accepts for `asOf`: a date-time with an explicit offset. */
1026
+ const ISO_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
1027
+ /**
1028
+ * The ask module. A plain list of rows goes to `pager`, whose module the app must also register;
1029
+ * the default is for an app that registers it from here, as the tests do.
1030
+ */
1031
+ function askModule(deps, pager = listPager()) {
412
1032
  let namespace = deps.namespace;
413
1033
  let pack = null;
414
1034
  let forceType;
1035
+ /** The clock relative phrases are read against; undefined = the server's. */
1036
+ let asOf;
415
1037
  let last = { lines: ["no question asked yet"] };
416
1038
  let lastPackNote = "";
1039
+ /** The namespace's `annotations.tui`; empty until read, and when it cannot be. */
1040
+ let present = {
1041
+ types: {},
1042
+ problems: []
1043
+ };
1044
+ /** The namespace's types, for reading a listed row's record whole; empty until read. */
1045
+ let types = {};
417
1046
  const loadPack = (ctx) => {
418
1047
  pack = null;
419
1048
  const ns = namespace;
1049
+ present = {
1050
+ types: {},
1051
+ problems: []
1052
+ };
1053
+ types = {};
1054
+ deps.getJson(`/substrate/v1/schema/${encodeURIComponent(ns)}`, ctx.signal).then((s) => {
1055
+ if (ns !== namespace) return;
1056
+ try {
1057
+ const t = s?.types;
1058
+ if (t !== null && typeof t === "object") types = t;
1059
+ present = parseTui(s?.annotations?.tui);
1060
+ } catch {
1061
+ present = {
1062
+ types: {},
1063
+ problems: [{ text: "tui ignored: unreadable" }]
1064
+ };
1065
+ }
1066
+ }, () => {});
420
1067
  deps.nl.pack(ns, { signal: ctx.signal }).then((p) => {
421
1068
  if (ns === namespace) pack = p;
422
1069
  }, (err) => {
@@ -427,6 +1074,24 @@ function askModule(deps) {
427
1074
  ctx.print(note, "dim");
428
1075
  });
429
1076
  };
1077
+ /** A rows outcome with its frame type's declared view, when the namespace declares one. */
1078
+ const withView = (o) => {
1079
+ const [ns, type] = (Object.keys(o.frame)[0] ?? "").split("/");
1080
+ const view = ns === namespace && type !== void 0 ? own$1(present.types, type) : void 0;
1081
+ return view !== void 0 ? {
1082
+ ...o,
1083
+ tui: view
1084
+ } : o;
1085
+ };
1086
+ /** A rows answer as a list the pager pages, with Enter and `r` wired to the row's type. */
1087
+ const asList = (o, ctx) => {
1088
+ const list = rowsList(o);
1089
+ if (list === void 0) return void 0;
1090
+ const [ns = namespace, type = ""] = (Object.keys(o.frame)[0] ?? "").split("/");
1091
+ const answered = new Map(o.data.map((r, i) => [typeof r.id === "string" ? r.id : String(i), r]));
1092
+ const fields = ns === namespace ? own$1(types, type)?.fields : void 0;
1093
+ return pager.present(list, listHooks(deps, ns, type, fields, answered, ctx.signal));
1094
+ };
430
1095
  const pick = (i) => (s, ctx) => {
431
1096
  const opt = s.options[i];
432
1097
  if (opt === void 0) return void 0;
@@ -439,23 +1104,41 @@ function askModule(deps) {
439
1104
  loadPack(ctx);
440
1105
  ctx.emit("substrate/ns", { namespace });
441
1106
  },
442
- commands: [{
443
- name: "ns",
444
- summary: "switch the namespace questions go to",
445
- args: [{ name: "namespace" }],
446
- run([ns], ctx) {
447
- if (ns === void 0 || ns === "") return ctx.print(`namespace: ${namespace}`);
448
- namespace = ns;
449
- loadPack(ctx);
450
- ctx.emit("substrate/ns", { namespace });
451
- ctx.print(`namespace → ${namespace}`);
1107
+ commands: [
1108
+ {
1109
+ name: "ns",
1110
+ summary: "switch the namespace questions go to",
1111
+ args: [{ name: "namespace" }],
1112
+ run([ns], ctx) {
1113
+ if (ns === void 0 || ns === "") return ctx.print(`namespace: ${namespace}`);
1114
+ namespace = ns;
1115
+ loadPack(ctx);
1116
+ ctx.emit("substrate/ns", { namespace });
1117
+ ctx.print(`namespace → ${namespace}`);
1118
+ }
1119
+ },
1120
+ {
1121
+ name: "asof",
1122
+ summary: "read \"yesterday\", \"past 2 days\" … as of a date-time (ISO-8601 with an offset); off for the server clock",
1123
+ args: [{ name: "datetime|off" }],
1124
+ run([v], ctx) {
1125
+ if (v === void 0 || v === "") return ctx.print(`asOf: ${asOf ?? "server clock"}`);
1126
+ if (v === "off") {
1127
+ asOf = void 0;
1128
+ return ctx.print("asOf → server clock");
1129
+ }
1130
+ 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");
1131
+ asOf = v;
1132
+ ctx.print(`asOf → ${asOf}`);
1133
+ }
1134
+ },
1135
+ {
1136
+ name: "frame",
1137
+ summary: "show the last answer's query frame, evidence and judge trail",
1138
+ args: [],
1139
+ run: (_a, ctx) => ctx.open("frame", last)
452
1140
  }
453
- }, {
454
- name: "frame",
455
- summary: "show the last answer's query frame, evidence and judge trail",
456
- args: [],
457
- run: (_a, ctx) => ctx.open("frame", last)
458
- }],
1141
+ ],
459
1142
  panels: {
460
1143
  clarify: {
461
1144
  view: ({ state }) => [
@@ -490,11 +1173,13 @@ function askModule(deps) {
490
1173
  namespace,
491
1174
  question: text,
492
1175
  project: deps.project,
1176
+ ...asOf !== void 0 ? { asOf } : {},
493
1177
  ...type !== void 0 ? { type } : {}
494
1178
  }, { signal })) switch (ev.event) {
495
1179
  case "parsed": {
496
1180
  const key = ev.data.frame !== void 0 ? Object.keys(ev.data.frame)[0] : void 0;
497
1181
  lines.push(`parse: ${ev.data.status}${ev.data.reason !== void 0 ? ` — ${ev.data.reason}` : ""}`);
1182
+ if (ev.data.asOf !== void 0) lines.push(`asOf: ${ev.data.asOf}`);
498
1183
  if (ev.data.frame !== void 0) lines.push(JSON.stringify(ev.data.frame, null, 2));
499
1184
  for (const e of ev.data.evidence) lines.push(` ${e.span} → ${e.role} (${e.detail})`);
500
1185
  yield {
@@ -524,18 +1209,28 @@ function askModule(deps) {
524
1209
  case "recall":
525
1210
  case "clarify":
526
1211
  case "refuse":
1212
+ case "unknown": {
1213
+ const answered = ev.event === "rows" ? Object.keys(ev.data.frame)[0]?.split("/")[1] : void 0;
1214
+ for (const p of present.problems) if (p.type === void 0 || p.type === answered) lines.push(`tui: ${p.text}`);
527
1215
  last = { lines };
528
1216
  if (ev.event === "clarify" && ev.data.options.length > 0) ctx.open("clarify", ev.data);
529
1217
  else ctx.close();
1218
+ const data = ev.event === "rows" ? withView(ev.data) : ev.data;
1219
+ const listed = ev.event === "rows" ? asList(data, ctx) : void 0;
1220
+ const chips = outcomeChips(ev.data);
530
1221
  yield {
531
1222
  phase: "final",
532
- reply: {
1223
+ reply: listed !== void 0 ? {
1224
+ ...listed,
1225
+ chips
1226
+ } : {
533
1227
  kind: `substrate.${ev.event}`,
534
- data: ev.data,
535
- chips: outcomeChips(ev.data)
1228
+ data,
1229
+ chips
536
1230
  }
537
1231
  };
538
1232
  return;
1233
+ }
539
1234
  case "done": return;
540
1235
  }
541
1236
  } catch (err) {
@@ -1290,7 +1985,7 @@ function doctorModule(deps, io = {}) {
1290
1985
  const deadline = new AbortController();
1291
1986
  const timer = setTimeout(() => deadline.abort(), deadlineMs);
1292
1987
  const signal = AbortSignal.any([ctx.signal, deadline.signal]);
1293
- const fetchWith = ((url, init) => fetch(url, {
1988
+ const fetchWith = ((url, init) => substrateFetch(String(url), {
1294
1989
  ...init,
1295
1990
  signal
1296
1991
  }));
@@ -2072,6 +2767,14 @@ function editView(s, glyph, size) {
2072
2767
  fit(" ↑↓←→ move · space toggle · + add namespace · enter review · esc discard")
2073
2768
  ];
2074
2769
  }
2770
+ /** Every keys panel: a one-column inset on a raised ground, set apart from the input band. */
2771
+ const KEYS_CHROME = {
2772
+ inset: {
2773
+ x: 1,
2774
+ y: 0
2775
+ },
2776
+ ground: marathon.color.raised
2777
+ };
2075
2778
  function editorPanels(deps) {
2076
2779
  const act = (fn) => (s, ctx) => {
2077
2780
  ctx.setDraft("");
@@ -2087,6 +2790,7 @@ function editorPanels(deps) {
2087
2790
  }));
2088
2791
  return {
2089
2792
  edit: {
2793
+ ...KEYS_CHROME,
2090
2794
  view: ({ state, theme, size }) => linesView(toned(editView(state, theme.glyph, size)), theme),
2091
2795
  keymap: [
2092
2796
  {
@@ -2166,6 +2870,7 @@ function editorPanels(deps) {
2166
2870
  } : void 0
2167
2871
  },
2168
2872
  prompt: {
2873
+ ...KEYS_CHROME,
2169
2874
  view: ({ state, theme }) => linesView(toned(promptView(state, theme.glyph)), theme),
2170
2875
  submit: (s, line, ctx) => {
2171
2876
  const text = line.trim();
@@ -2264,6 +2969,7 @@ function editorPanels(deps) {
2264
2969
  }
2265
2970
  },
2266
2971
  review: {
2972
+ ...KEYS_CHROME,
2267
2973
  view: ({ state, theme, armed, size }) => linesView(toned(reviewView(state, theme.glyph, armed, size)), theme),
2268
2974
  confirm: [{
2269
2975
  key: "y",
@@ -2519,6 +3225,7 @@ function keysModule(deps) {
2519
3225
  }],
2520
3226
  panels: {
2521
3227
  keys: {
3228
+ ...KEYS_CHROME,
2522
3229
  view: ({ state, theme, size }) => {
2523
3230
  const w = Math.max(1, size.columns - 2);
2524
3231
  const count = state.rows === null ? "" : ` · ${state.rows.length} active`;
@@ -3660,25 +4367,40 @@ function surgeryModule(deps, io = {}) {
3660
4367
 
3661
4368
  //#endregion
3662
4369
  //#region src/app.ts
4370
+ /** marathon with no overlay fill: an empty `raised` means Ink paints no background, so panels sit on the ground. */
4371
+ const substrateTheme = {
4372
+ ...marathon,
4373
+ color: {
4374
+ ...marathon.color,
4375
+ raised: ""
4376
+ }
4377
+ };
3663
4378
  function buildModules(deps, opts = {}) {
4379
+ const pager = listPager();
3664
4380
  return [
3665
4381
  statusModule(deps, opts),
3666
4382
  adminModule(deps),
3667
4383
  doctorModule(deps, opts.doctorIntervalMs !== void 0 ? { intervalMs: opts.doctorIntervalMs } : {}),
3668
4384
  keysModule(deps),
3669
4385
  surgeryModule(deps),
3670
- askModule(deps),
4386
+ askModule(deps, pager),
4387
+ pager.module,
3671
4388
  schemaModule(deps),
3672
4389
  dashModule(deps, opts.dashIntervalMs !== void 0 ? { intervalMs: opts.dashIntervalMs } : {})
3673
4390
  ];
3674
4391
  }
3675
4392
  function substrateAppOptions(deps, opts = {}) {
3676
4393
  return {
3677
- theme: marathon,
4394
+ theme: substrateTheme,
3678
4395
  modules: buildModules(deps, opts),
3679
4396
  defaultTurn: "substrate.ask:ask",
3680
4397
  band: true,
3681
4398
  gutter: 2,
4399
+ entries: { answer: ({ entry, body, theme }) => createElement(Box, {
4400
+ flexDirection: "column",
4401
+ marginBottom: 1
4402
+ }, entry.mark !== null ? createElement(Text, { color: theme.color.accent }, `↩ ⟨${entry.mark}⟩`) : null, body) },
4403
+ anchored: true,
3682
4404
  terminal: false
3683
4405
  };
3684
4406
  }
@@ -3687,4 +4409,4 @@ function createTui(deps, opts = {}) {
3687
4409
  }
3688
4410
 
3689
4411
  //#endregion
3690
- export { buildModules, createTui, substrateAppOptions };
4412
+ export { buildModules, createTui, substrateAppOptions, substrateTheme };
@@ -1,7 +1,7 @@
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
- import { DEFAULT_CAPABILITIES, makeTokenProvider } from "@mnmal-ai/substrate/client";
4
+ import { DEFAULT_CAPABILITIES, makeTokenProvider, tokenAudience } from "@mnmal-ai/substrate/client";
5
5
  import { trimTrailingSlashes } from "@mnmal-ai/substrate/sdk";
6
6
 
7
7
  //#region src/config.ts
@@ -20,7 +20,10 @@ function readConfig(env, cwd) {
20
20
  token = makeTokenProvider({
21
21
  keyPath,
22
22
  kid
23
- }, { capabilities: raw !== void 0 && raw.length > 0 ? raw : DEFAULT_CAPABILITIES });
23
+ }, {
24
+ capabilities: raw !== void 0 && raw.length > 0 ? raw : DEFAULT_CAPABILITIES,
25
+ audience: tokenAudience(endpoint)
26
+ });
24
27
  } catch (err) {
25
28
  return { error: `agent identity: ${message(err)}` };
26
29
  }
@@ -48,10 +51,10 @@ async function main() {
48
51
  }
49
52
  Object.assign(process.env, colorDepthEnv(process.env));
50
53
  const [{ createTui }, { makeDeps }, { prepareTerminal }, { terminalOptions }] = await Promise.all([
51
- import("../app-BLOyJcBh.js"),
52
- import("../deps-WzqsHHiC.js"),
54
+ import("../app-DJrYKKiD.js"),
55
+ import("../deps-Co_d6ypZ.js"),
53
56
  import("@mnmal-ai/surface-core/pure"),
54
- import("../terminal-CVX2CKWu.js")
57
+ import("../terminal-BAd8sH3d.js")
55
58
  ]);
56
59
  let deps;
57
60
  try {
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { n as adminIdleMs, r as createAdminSession } from "./session-C1D5Ermr.js";
3
- import { SubstrateClient, noRedirectFetch, tokenAudience } from "@mnmal-ai/substrate/client";
3
+ import { SubstrateClient, noRedirectFetch, substrateFetch, tokenAudience } from "@mnmal-ai/substrate/client";
4
4
 
5
5
  //#region src/deps.ts
6
6
  /** An HTTP failure from `getJson`: `status` is what `NetworkError` and `AuthError` also carry. */
@@ -13,7 +13,7 @@ var HttpStatusError = class extends Error {
13
13
  }
14
14
  };
15
15
  const sig = (signal) => signal !== void 0 ? { signal } : {};
16
- function makeDeps(config, fetchImpl = fetch, env = process.env) {
16
+ function makeDeps(config, fetchImpl = substrateFetch, env = process.env) {
17
17
  const token = config.token;
18
18
  if (token !== null || [
19
19
  "SUBSTRATE_ADMIN_TOKEN",
@@ -42,6 +42,7 @@ function makeDeps(config, fetchImpl = fetch, env = process.env) {
42
42
  namespace: config.namespace,
43
43
  nl: client.nl,
44
44
  federatedSchema: () => client.federatedSchema(),
45
+ query: (frame, signal) => client.query(frame, sig(signal)),
45
46
  metrics: (signal) => client.metrics(sig(signal)),
46
47
  errors: (signal) => admin.unlocked() ? admin.run(({ client: c }) => c.errors(sig(signal)), { touch: false }) : client.errors(sig(signal)),
47
48
  admin,
@@ -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.2",
3
+ "version": "1.0.0-alpha.21",
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": {
@@ -10,7 +10,7 @@
10
10
  },
11
11
  "type": "module",
12
12
  "bin": {
13
- "substrate-tui": "dist/bin/tui.js"
13
+ "substrate-tui": "dist/bin/substrate-tui.js"
14
14
  },
15
15
  "files": [
16
16
  "dist"
@@ -20,17 +20,17 @@
20
20
  "access": "public"
21
21
  },
22
22
  "dependencies": {
23
- "@mnmal-ai/substrate": "1.0.0-alpha.2",
24
- "@mnmal-ai/substrate-nl": "1.0.0-alpha.2",
25
- "@mnmal-ai/surface-core": "0.14.5",
26
- "@mnmal-ai/surface-kit": "0.14.5",
27
- "@mnmal-ai/surface-theme": "0.14.5",
28
- "ink": "^7.1.1",
23
+ "@mnmal-ai/substrate": "1.0.0-alpha.21",
24
+ "@mnmal-ai/substrate-nl": "1.0.0-alpha.21",
25
+ "@mnmal-ai/surface-core": "0.17.1",
26
+ "@mnmal-ai/surface-kit": "0.17.1",
27
+ "@mnmal-ai/surface-theme": "0.17.1",
28
+ "ink": "^8.0.0",
29
29
  "react": "^19.3.0"
30
30
  },
31
31
  "devDependencies": {
32
- "@biomejs/biome": "^2.5.15",
33
- "@mnmal-ai/substrate-config": "1.0.0-alpha.2",
32
+ "@biomejs/biome": "2.6.4",
33
+ "@mnmal-ai/substrate-config": "1.0.0-alpha.21",
34
34
  "@types/node": "^26.6.4",
35
35
  "@types/react": "^19.2.0",
36
36
  "ink-testing-library": "^4.0.0",
@@ -40,7 +40,7 @@
40
40
  "vitest": "^5.0.3"
41
41
  },
42
42
  "engines": {
43
- "node": ">=26.2.0"
43
+ "node": ">=26.13.1"
44
44
  },
45
45
  "scripts": {
46
46
  "build": "tsdown",