@mnmal-ai/substrate-tui 1.0.0-beta.2 → 1.0.0-beta.20

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,7 +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
+ - `/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, in years 1000 to 9998, 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.
13
13
  - `/schema [namespace] [type]` opens the schema browser: namespaces, then types, then fields.
14
14
  - `/dash` shows service, traffic and engine metrics, live while open.
15
15
  - `/doctor` runs live checks against this deployment.
@@ -6,7 +6,7 @@ import { createApp, defineModule, listPager, sanitise } from "@mnmal-ai/surface-
6
6
  import { marathon } from "@mnmal-ai/surface-theme";
7
7
  import { Box, Text } from "ink";
8
8
  import { createElement } from "react";
9
- import { Panel, cellWidth, padCells, sparkline, truncateCells } from "@mnmal-ai/surface-kit";
9
+ import { Panel, cellWidth, cutToWidth, padCells, sparkline, truncateCells } from "@mnmal-ai/surface-kit";
10
10
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
11
  import { complete } from "@mnmal-ai/substrate-nl/complete";
12
12
  import { readFile } from "node:fs/promises";
@@ -14,14 +14,63 @@ import { createHash, createPublicKey } from "node:crypto";
14
14
  import { homedir } from "node:os";
15
15
  import { readFileSync } from "node:fs";
16
16
 
17
+ //#region src/text.ts
18
+ /** Server text on one line: no escape or control bytes, and each run of line breaks one space. */
19
+ const clean = (s) => sanitise(s.replace(/[\n\v\f\r\u0085\u2028\u2029]+/g, " "));
20
+
21
+ //#endregion
17
22
  //#region src/lines.tsx
18
- /** Lines as a column of `Text`, each in its tone: a joined string view has no tone to give them. */
23
+ /** A column of toned or styled text lines, shared by the panels that render one (surgery, `/keys`). */
24
+ /** A line of styled parts, each sanitised onto one line (idempotent), whoever built it. */
25
+ function partsLine(parts) {
26
+ const safe = parts.map((p) => ({
27
+ ...p,
28
+ text: clean(p.text)
29
+ }));
30
+ return {
31
+ text: safe.map((p) => p.text).join(""),
32
+ parts: safe
33
+ };
34
+ }
35
+ /** Cut parts to `max` cells with a trailing `…`, keeping each kept part's styling. */
36
+ function truncateParts(parts, max) {
37
+ const joined = parts.map((p) => p.text).join("");
38
+ const cut = truncateCells(joined, max);
39
+ if (cut === joined) return [...parts];
40
+ let left = cut.length - 1;
41
+ const out = [];
42
+ for (const p of parts) {
43
+ if (left <= 0) break;
44
+ if (p.text.length > left) {
45
+ out.push({
46
+ ...p,
47
+ text: `${p.text.slice(0, left)}…`
48
+ });
49
+ return out;
50
+ }
51
+ out.push(p);
52
+ left -= p.text.length;
53
+ }
54
+ const last = out[out.length - 1];
55
+ out.push(last !== void 0 ? {
56
+ ...last,
57
+ text: "…"
58
+ } : { text: "…" });
59
+ return out;
60
+ }
61
+ /** Lines as a column of `Text`, each in its tone or parts: a joined string view has none to give. */
19
62
  function linesView(lines, theme) {
20
63
  return /* @__PURE__ */ jsx(Box, {
21
64
  flexDirection: "column",
22
65
  children: lines.map((l, i) => /* @__PURE__ */ jsx(Text, {
23
- ...l.tone !== void 0 ? { color: theme.color[l.tone] } : {},
24
- children: l.text
66
+ ...l.tone !== void 0 && l.parts === void 0 ? { color: theme.color[l.tone] } : {},
67
+ children: l.parts !== void 0 ? l.parts.map((p, j) => /* @__PURE__ */ jsx(Text, {
68
+ ...p.tone !== void 0 ? { color: theme.color[p.tone] } : {},
69
+ ...p.bg !== void 0 ? { backgroundColor: theme.color[p.bg] } : {},
70
+ ...p.bold ? { bold: true } : {},
71
+ ...p.strike ? { strikethrough: true } : {},
72
+ children: p.text
73
+ }, j)) : l.text
25
74
  }, i))
26
75
  });
27
76
  }
@@ -729,6 +778,7 @@ const COLS = {
729
778
  };
730
779
  const titleWidth = (columns) => Math.max(COLS.minTitle, columns - (COLS.id + COLS.status + COLS.project + COLS.gaps));
731
780
  const FN_LABEL = {
781
+ count: "count",
732
782
  avg: "average",
733
783
  sum: "total",
734
784
  min: "min",
@@ -832,7 +882,8 @@ const rows = ({ data, theme, size }) => {
832
882
  }, `d${i}`));
833
883
  const agg = o.aggregate;
834
884
  if (agg !== void 0) {
835
- const head = `${Object.hasOwn(FN_LABEL, agg.fn) ? FN_LABEL[agg.fn] : str(agg.fn)} ${str(agg.field)}`;
885
+ const fnLabel = Object.hasOwn(FN_LABEL, agg.fn) ? FN_LABEL[agg.fn] : str(agg.fn);
886
+ const head = agg.fn === "count" ? fnLabel : `${fnLabel} ${str(agg.field)}`;
836
887
  const errs = errorLines(o.errors).map((l, i) => /* @__PURE__ */ jsx(Text, {
837
888
  color: theme.color.error,
838
889
  children: ` ${l}`
@@ -1245,8 +1296,8 @@ function explain(err, endpoint) {
1245
1296
  if (e.status === 401 || e.status === 403) return `not authorised (${e.status}) — check SUBSTRATE_AGENT_KEY_ID / SUBSTRATE_AGENT_KEY_PATH`;
1246
1297
  return e.message ?? String(err);
1247
1298
  }
1248
- /** What the server accepts for `asOf`: a date-time with an explicit offset. */
1249
- const ISO_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
1299
+ /** What the server accepts for `asOf`: a date-time with an explicit offset, in years 1000 to 9998. */
1300
+ const ISO_WITH_OFFSET = /^(?!9999)[1-9]\d{3}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
1250
1301
  /**
1251
1302
  * The ask module. A plain list of rows goes to `pager`, whose module the app must also register;
1252
1303
  * the default is for an app that registers it from here, as the tests do.
@@ -1350,7 +1401,7 @@ function askModule(deps, pager = listPager()) {
1350
1401
  asOf = void 0;
1351
1402
  return ctx.print("asOf → server clock");
1352
1403
  }
1353
- 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");
1404
+ if (!ISO_WITH_OFFSET.test(v) || Number.isNaN(Date.parse(v))) return ctx.print("asOf needs an ISO-8601 date-time with an offset, in years 1000 to 9998, e.g. 2026-10-24T23:59:59-05:00");
1354
1405
  asOf = v;
1355
1406
  ctx.print(`asOf → ${asOf}`);
1356
1407
  }
@@ -1472,11 +1523,6 @@ function askModule(deps, pager = listPager()) {
1472
1523
  });
1473
1524
  }
1474
1525
 
1475
- //#endregion
1476
- //#region src/text.ts
1477
- /** Server text on one line: no escape or control bytes, and line breaks collapsed to a space. */
1478
- const clean = (s) => sanitise(s.replace(/[\r\n]+/g, " "));
1479
-
1480
1526
  //#endregion
1481
1527
  //#region src/dash/derive.ts
1482
1528
  /** Polls kept per sparkline. */
@@ -2420,6 +2466,13 @@ function compactGrant(namespaces, capabilities) {
2420
2466
  if (grant.size === 0) return "(none)";
2421
2467
  return [...grant].map(([ns, caps]) => `${ns}:${canonicalCaps(caps).map((c) => SHORT[c] ?? c).join("+")}`).join(",");
2422
2468
  }
2469
+ /**
2470
+ * A namespace's capabilities as tokens in canonical order: read, mutate, admin → `r`, `m`, `a`, and
2471
+ * one with no short form spelled out as `(name)`.
2472
+ */
2473
+ function shortCaps(caps) {
2474
+ return canonicalCaps(caps).map((c) => SHORT[c] ?? `(${c})`);
2475
+ }
2423
2476
  /** A stored row's grant, or null when it does not parse (the table still renders it). */
2424
2477
  function rowGrant(row) {
2425
2478
  try {
@@ -2727,17 +2780,31 @@ function readInviteTtl(text) {
2727
2780
  if (ttlMs === void 0) return {};
2728
2781
  return ttlMs > MAX_INVITE_TTL_MS ? { error: "at most 30 days" } : { ttlMs };
2729
2782
  }
2783
+ /** The server's rule for a named invite's kid (substrate-compose `kidProblem`), which still decides. */
2784
+ const INVITE_KID = /^[A-Za-z0-9][A-Za-z0-9._-]*(@[A-Za-z0-9][A-Za-z0-9._-]*)?$/;
2785
+ /** The invite-kid prompt's reading: a kid (absent for a random one), or why not. */
2786
+ function readInviteKid(text) {
2787
+ const kid = text.trim();
2788
+ if (kid === "") return {};
2789
+ return kid.length <= 128 && INVITE_KID.test(kid) ? { kid } : { error: "name or name@host, of letters, digits, '.', '_' and '-'" };
2790
+ }
2730
2791
  const NS_NAME = /^(\*|[A-Za-z0-9_.-]+)$/;
2731
2792
  const refusal = (text) => ({ error: text });
2732
- /** As the shared toned lines: a refusal in the error tone, anything else untoned. */
2733
- const toned = (lines) => lines.map((l) => typeof l === "string" ? { text: l } : {
2793
+ /** As the shared toned lines: a refusal in the error tone, a heading bold, anything else untoned. */
2794
+ const toned = (lines) => lines.map((l) => typeof l === "string" ? { text: l } : "error" in l ? {
2734
2795
  text: l.error,
2735
2796
  tone: "error"
2797
+ } : {
2798
+ text: l.bold,
2799
+ parts: [{
2800
+ text: l.bold,
2801
+ bold: true
2802
+ }]
2736
2803
  });
2737
2804
  function promptView(s, glyph) {
2738
2805
  return [
2739
2806
  `${glyph.title} keys › ${sanitise(s.label)}`,
2740
- ...s.kid !== void 0 ? [` ${sanitise(s.kid)}`] : [],
2807
+ ...s.kid !== void 0 ? [{ bold: ` ${sanitise(s.kid)}` }] : [],
2741
2808
  ...s.algorithm !== void 0 && s.fingerprint !== void 0 ? [` ${s.algorithm} · ${s.fingerprint}`] : [],
2742
2809
  ...s.error !== null ? [refusal(` ${sanitise(s.error)}`)] : [],
2743
2810
  " enter accept · esc back"
@@ -2770,13 +2837,14 @@ function verdictOf(deps, s, next) {
2770
2837
  adminCapability
2771
2838
  });
2772
2839
  }
2773
- function reviewOf(s, next, verdict, ttlMs) {
2840
+ function reviewOf(s, next, verdict, ttlMs, inviteKid) {
2774
2841
  return {
2775
2842
  flow: s.flow,
2776
2843
  edit: s,
2777
2844
  next,
2778
2845
  verdict,
2779
2846
  ...ttlMs !== void 0 ? { ttlMs } : {},
2847
+ ...inviteKid !== void 0 ? { inviteKid } : {},
2780
2848
  stage: "review",
2781
2849
  error: null,
2782
2850
  mismatch: false,
@@ -2834,7 +2902,7 @@ function reviewView(s, glyph, armed, size) {
2834
2902
  body.push(` register ${f.kid} · ${f.algorithm} · ${f.fingerprint}`, ` grant ${grantLine(next)}`);
2835
2903
  break;
2836
2904
  case "invite":
2837
- body.push(` invite for ${grantLine(next)}`, ` expires in ${s.ttlMs !== void 0 ? ttlText(s.ttlMs) : "the server default"}`);
2905
+ body.push(s.inviteKid !== void 0 ? ` invite for ${s.inviteKid} · ${grantLine(next)}` : ` invite for ${grantLine(next)}`, ` expires in ${s.ttlMs !== void 0 ? ttlText(s.ttlMs) : "the server default"}`);
2838
2906
  break;
2839
2907
  case "revoke": body.push(` ${f.row.kid} loses access immediately`);
2840
2908
  }
@@ -2855,14 +2923,15 @@ function reviewView(s, glyph, armed, size) {
2855
2923
  " esc back"
2856
2924
  ];
2857
2925
  break;
2858
- case "done": tail = s.inviteCode !== void 0 ? [
2859
- ...wrapCode(sanitise(s.inviteCode), w),
2860
- " give it to the invitee; it is not shown again",
2926
+ case "done": tail = s.inviteToken !== void 0 ? [
2927
+ ...wrapCode(sanitise(s.inviteToken), w),
2928
+ ` redeems at ${sanitise(s.inviteOrigin ?? "")} — the invitee's machine must reach that URL`,
2929
+ " give it to the invitee to paste into substrate federate join; it is not shown again",
2861
2930
  " esc close"
2862
2931
  ] : [" esc close"];
2863
2932
  }
2864
2933
  const head = fit(`${glyph.title} keys › ${target} · review`);
2865
- const fitLine = (l) => typeof l === "string" ? fit(l) : refusal(fit(l.error));
2934
+ const fitLine = (l) => typeof l === "string" ? fit(l) : "error" in l ? refusal(fit(l.error)) : { bold: fit(l.bold) };
2866
2935
  return [
2867
2936
  head,
2868
2937
  ...body.map(fit),
@@ -2937,7 +3006,7 @@ function editView(s, glyph, size) {
2937
3006
  const label = (ns) => ns === "*" ? "* every namespace" : ns;
2938
3007
  const nsW = Math.min(24, Math.max(9, ...m.rows.map((ns) => label(ns).length)) + 2);
2939
3008
  const granted = result(m);
2940
- const visible = Math.max(1, size.rows - 6);
3009
+ const visible = Math.max(1, size.rows - 7);
2941
3010
  const start = Math.max(0, Math.min(m.row - visible + 1, m.rows.length - visible));
2942
3011
  const grid = m.rows.slice(start, start + visible).map((ns, k) => {
2943
3012
  const at = start + k === m.row;
@@ -2954,7 +3023,8 @@ function editView(s, glyph, size) {
2954
3023
  const foot = s.note !== null ? [s.note === EMPTY_NOTE ? refusal(fit(` ${s.note}`)) : fit(` ${s.note}`)] : s.discardArmed ? [" discard changes? esc again"] : [];
2955
3024
  return [
2956
3025
  fit(`${glyph.title} keys › ${subject} · editing`),
2957
- fit(` ${"namespace".padEnd(nsW)} r m a`),
3026
+ " ",
3027
+ { bold: fit(` ${"namespace".padEnd(nsW)} r m a`) },
2958
3028
  ...grid,
2959
3029
  fit(` before ${before}`),
2960
3030
  fit(` after ${grantLine(granted)}`),
@@ -2962,11 +3032,11 @@ function editView(s, glyph, size) {
2962
3032
  fit(" ↑↓←→ move · space toggle · + add namespace · enter review · esc discard")
2963
3033
  ];
2964
3034
  }
2965
- /** Every keys panel: a one-column inset on a raised ground, set apart from the input band. */
3035
+ /** Every keys panel: two columns and one row of inset on a raised ground, set apart from the input band. */
2966
3036
  const KEYS_CHROME = {
2967
3037
  inset: {
2968
- x: 1,
2969
- y: 0
3038
+ x: 2,
3039
+ y: 1
2970
3040
  },
2971
3041
  ground: marathon.color.raised
2972
3042
  };
@@ -3047,8 +3117,8 @@ function editorPanels(deps) {
3047
3117
  };
3048
3118
  if (s.flow.kind === "invite") {
3049
3119
  switchTo(ctx, deps, "prompt", {
3050
- purpose: "invite-ttl",
3051
- label: "expires in (e.g. 30m, 12h, 7d; enter for the server default)",
3120
+ purpose: "invite-kid",
3121
+ label: "key name (e.g. repo-claude@host-a; enter for a random one)",
3052
3122
  error: null,
3053
3123
  back: s,
3054
3124
  table: s.table
@@ -3145,6 +3215,23 @@ function editorPanels(deps) {
3145
3215
  ...text !== "" ? { name: text } : {}
3146
3216
  }, s.table, "prompt");
3147
3217
  return;
3218
+ case "invite-kid": {
3219
+ if (s.back === null) return void 0;
3220
+ const named = readInviteKid(line);
3221
+ if ("error" in named) return {
3222
+ ...s,
3223
+ error: named.error
3224
+ };
3225
+ switchTo(ctx, deps, "prompt", {
3226
+ purpose: "invite-ttl",
3227
+ label: "expires in (e.g. 30m, 12h, 7d; enter for the server default)",
3228
+ error: null,
3229
+ back: s.back,
3230
+ ...named.kid !== void 0 ? { kid: named.kid } : {},
3231
+ table: s.table
3232
+ });
3233
+ return;
3234
+ }
3148
3235
  case "invite-ttl": {
3149
3236
  if (s.back === null) return void 0;
3150
3237
  const ttl = readInviteTtl(line);
@@ -3153,7 +3240,7 @@ function editorPanels(deps) {
3153
3240
  error: ttl.error
3154
3241
  };
3155
3242
  const next = result(s.back.matrix);
3156
- switchTo(ctx, deps, "review", reviewOf(s.back, next, verdictOf(deps, s.back, next), ttl.ttlMs));
3243
+ switchTo(ctx, deps, "review", reviewOf(s.back, next, verdictOf(deps, s.back, next), ttl.ttlMs, s.kid));
3157
3244
  return;
3158
3245
  }
3159
3246
  }
@@ -3328,27 +3415,29 @@ function editorPanels(deps) {
3328
3415
  }
3329
3416
  const out = await client.admin.invite({
3330
3417
  ...w,
3331
- ...s.ttlMs !== void 0 ? { ttlMs: s.ttlMs } : {}
3418
+ ...s.ttlMs !== void 0 ? { ttlMs: s.ttlMs } : {},
3419
+ ...s.inviteKid !== void 0 ? { kid: s.inviteKid } : {}
3332
3420
  });
3333
3421
  return {
3334
- line: `✓ invite minted for ${shown}, expires ${out.expiresAt}`,
3335
- code: out.code
3422
+ line: `✓ invite minted for ${s.inviteKid !== void 0 ? `${s.inviteKid} ${shown}` : shown}, expires ${out.expiresAt}`,
3423
+ token: out.token
3336
3424
  };
3337
3425
  }).then((r) => {
3338
3426
  ctx.print(sanitise(`${r.line} (admin: ${who})`), "ok");
3339
3427
  let open = false;
3340
3428
  ctx.update("review", (x) => {
3341
3429
  open = true;
3342
- return r.code !== void 0 ? {
3430
+ return r.token !== void 0 ? {
3343
3431
  ...x,
3344
3432
  stage: "done",
3345
- inviteCode: r.code
3433
+ inviteToken: r.token,
3434
+ inviteOrigin: deps.endpoint
3346
3435
  } : {
3347
3436
  ...x,
3348
3437
  stage: "done"
3349
3438
  };
3350
3439
  });
3351
- if (open && r.code === void 0 && deps.admin.unlocked()) loadKeys(ctx, deps, r.select);
3440
+ if (open && r.token === void 0 && deps.admin.unlocked()) loadKeys(ctx, deps, r.select);
3352
3441
  }, (err) => {
3353
3442
  const error = refusalOf(err);
3354
3443
  let open = false;
@@ -3370,6 +3459,252 @@ function editorPanels(deps) {
3370
3459
  }
3371
3460
  }
3372
3461
 
3462
+ //#endregion
3463
+ //#region src/keys/layout.ts
3464
+ const NO_HOST = "(no host)";
3465
+ const isRevoked = (r) => typeof r.revokedAt === "string";
3466
+ /** `agent@host` → [agent, host]; a kid without `@` has no host. */
3467
+ function splitKid(kid) {
3468
+ const at = kid.lastIndexOf("@");
3469
+ return at <= 0 ? [kid, NO_HOST] : [kid.slice(0, at), kid.slice(at + 1)];
3470
+ }
3471
+ const byText = (a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }) || (a < b ? -1 : a > b ? 1 : 0);
3472
+ /** Display order: active keys by host then agent, then revoked keys, most recently revoked first. */
3473
+ function orderForView(rows) {
3474
+ const active = rows.filter((r) => !isRevoked(r));
3475
+ const revoked = rows.filter(isRevoked);
3476
+ active.sort((a, b) => {
3477
+ const [aa, ah] = splitKid(a.kid);
3478
+ const [ba, bh] = splitKid(b.kid);
3479
+ return (bh === NO_HOST ? 1 : 0) - (ah === NO_HOST ? 1 : 0) || byText(ah.toLowerCase(), bh.toLowerCase()) || byText(aa.toLowerCase(), ba.toLowerCase());
3480
+ });
3481
+ revoked.sort((a, b) => String(b.revokedAt).localeCompare(String(a.revokedAt)) || byText(a.kid, b.kid));
3482
+ return [...active, ...revoked];
3483
+ }
3484
+ /** Namespaces in column order: `*` first, then the most widely granted, then by name. */
3485
+ function namespaceColumns(grants) {
3486
+ const count = /* @__PURE__ */ new Map();
3487
+ for (const g of grants) for (const ns of g?.keys() ?? []) count.set(ns, (count.get(ns) ?? 0) + 1);
3488
+ return [...count.keys()].sort((a, b) => (b === "*" ? 1 : 0) - (a === "*" ? 1 : 0) || (count.get(b) ?? 0) - (count.get(a) ?? 0) || byText(a, b));
3489
+ }
3490
+ /** The widest a name may be before it truncates with `…`. */
3491
+ const NAME_CAP = 22;
3492
+ const BAND_END = 50;
3493
+ const GUTTER = " ";
3494
+ /** Terminal cells the parts take. */
3495
+ const len = (parts) => parts.reduce((n, p) => n + cellWidth(p.text), 0);
3496
+ /** A gap is one space: an empty Ink `Text` renders no row at all. */
3497
+ const pad = (n) => n > 0 ? [{ text: " ".repeat(n) }] : [];
3498
+ /** `── label ──── count`, the count ending at one shared column. */
3499
+ function band(label, count, width, kind) {
3500
+ const l = clean(label);
3501
+ const n = String(count);
3502
+ const rule = Math.max(2, Math.min(width, BAND_END) - (4 + cellWidth(l) + 2 + cellWidth(n)));
3503
+ return {
3504
+ parts: truncateParts([
3505
+ {
3506
+ text: " ── ",
3507
+ tone: "dim"
3508
+ },
3509
+ kind === "band" ? {
3510
+ text: l,
3511
+ tone: "text",
3512
+ bold: true
3513
+ } : {
3514
+ text: l,
3515
+ tone: "dimMid",
3516
+ bold: true
3517
+ },
3518
+ { text: " " },
3519
+ {
3520
+ text: "─".repeat(rule),
3521
+ tone: "dim"
3522
+ },
3523
+ { text: " " },
3524
+ {
3525
+ text: n,
3526
+ tone: "dimMid"
3527
+ }
3528
+ ], width),
3529
+ kind
3530
+ };
3531
+ }
3532
+ /** The majority spelling of each host (lowercased), a tie going to the spelling that sorts first. */
3533
+ function hostLabels(rows) {
3534
+ const spellings = /* @__PURE__ */ new Map();
3535
+ for (const r of rows) {
3536
+ if (isRevoked(r)) continue;
3537
+ const h = splitKid(r.kid)[1];
3538
+ const m = spellings.get(h.toLowerCase()) ?? /* @__PURE__ */ new Map();
3539
+ m.set(h, (m.get(h) ?? 0) + 1);
3540
+ spellings.set(h.toLowerCase(), m);
3541
+ }
3542
+ return new Map([...spellings].map(([k, m]) => [k, [...m].sort((a, b) => b[1] - a[1] || byText(a[0], b[0]))[0]?.[0] ?? k]));
3543
+ }
3544
+ /** A hostless key's name and a dimMid short id sized to the cap; its kid when it has no name. */
3545
+ function hostlessName(name, kid) {
3546
+ if (name === "") return [{
3547
+ text: kid,
3548
+ tone: "text"
3549
+ }];
3550
+ const n = Math.min(8, 22 - cellWidth(name) - 2);
3551
+ return n < 4 ? [{
3552
+ text: name,
3553
+ tone: "text"
3554
+ }] : [
3555
+ {
3556
+ text: name,
3557
+ tone: "text"
3558
+ },
3559
+ { text: " " },
3560
+ {
3561
+ text: `${cutToWidth(kid, n)}…`,
3562
+ tone: "dimMid"
3563
+ }
3564
+ ];
3565
+ }
3566
+ const capPart = (c) => c === "a" ? {
3567
+ text: c,
3568
+ tone: "warn",
3569
+ bold: true
3570
+ } : {
3571
+ text: c,
3572
+ tone: "text"
3573
+ };
3574
+ /** The ordered rows as display lines, each truncated to `width` (the view adds the cursor). */
3575
+ function listLines(rows, width) {
3576
+ const grants = rows.map((r) => {
3577
+ const g = rowGrant(r);
3578
+ return g === null ? null : new Map([...g].map(([ns, caps]) => [clean(ns), shortCaps(caps).map(clean)]));
3579
+ });
3580
+ const active = rows.flatMap((r, i) => isRevoked(r) ? [] : [i]);
3581
+ const cols = namespaceColumns(active.map((i) => grants[i] ?? null));
3582
+ const colW = cols.map((ns) => cellWidth(ns) + 1 + Math.max(1, ...active.map((i) => cellWidth(grants[i]?.get(ns)?.join("") ?? ""))));
3583
+ const labels = hostLabels(rows);
3584
+ const names = /* @__PURE__ */ new Map();
3585
+ for (const i of active) {
3586
+ const r = rows[i];
3587
+ const [agent, host] = splitKid(r.kid);
3588
+ const parts = host === NO_HOST ? hostlessName(clean(r.name), clean(r.kid)) : [{
3589
+ text: clean(agent),
3590
+ tone: "text"
3591
+ }, ...host === labels.get(host.toLowerCase()) ? [] : [{
3592
+ text: `@${clean(host)}`,
3593
+ tone: "dimMid"
3594
+ }]];
3595
+ names.set(i, truncateParts(parts, 22));
3596
+ }
3597
+ const nameW = Math.max(4, ...[...names.values()].map(len));
3598
+ const grantParts = (i) => {
3599
+ const r = rows[i];
3600
+ const g = grants[i];
3601
+ if (g === null || g === void 0) return [{
3602
+ text: clean(compactGrant(r.namespaces, r.capabilities)),
3603
+ tone: "text"
3604
+ }];
3605
+ if (g.size === 0) return [{
3606
+ text: "(none)",
3607
+ tone: "dim"
3608
+ }];
3609
+ const last = cols.findLastIndex((ns) => g.has(ns));
3610
+ const out = [];
3611
+ cols.slice(0, last + 1).forEach((ns, k) => {
3612
+ const caps = g.get(ns);
3613
+ if (k > 0) out.push({ text: " " });
3614
+ if (caps === void 0) {
3615
+ out.push(...pad(colW[k]));
3616
+ return;
3617
+ }
3618
+ const star = ns === "*";
3619
+ out.push({
3620
+ text: clean(ns),
3621
+ tone: star ? "warn" : "dimMid",
3622
+ ...star ? { bold: true } : {}
3623
+ });
3624
+ out.push({ text: " " }, ...caps.map(capPart));
3625
+ if (k < last) out.push(...pad(colW[k] - cellWidth(ns) - 1 - cellWidth(caps.join(""))));
3626
+ });
3627
+ return out;
3628
+ };
3629
+ const lines = [];
3630
+ const push = (l) => lines.push({
3631
+ ...l,
3632
+ parts: truncateParts(l.parts, width)
3633
+ });
3634
+ const revokedCount = rows.length - active.length;
3635
+ let host;
3636
+ rows.forEach((r, i) => {
3637
+ if (isRevoked(r)) {
3638
+ if (lines.every((l) => l.kind !== "revoked-band")) {
3639
+ if (lines.length > 0) push({
3640
+ parts: [{ text: " " }],
3641
+ kind: "gap"
3642
+ });
3643
+ lines.push(band("revoked", revokedCount, width, "revoked-band"));
3644
+ }
3645
+ push({
3646
+ parts: [
3647
+ { text: GUTTER },
3648
+ {
3649
+ text: clean(r.kid),
3650
+ tone: "dim",
3651
+ strike: true
3652
+ },
3653
+ {
3654
+ text: ` ${clean(String(r.revokedAt).slice(0, 10))}`,
3655
+ tone: "dim"
3656
+ }
3657
+ ],
3658
+ row: i,
3659
+ kind: "revoked"
3660
+ });
3661
+ return;
3662
+ }
3663
+ const key = splitKid(r.kid)[1].toLowerCase();
3664
+ if (key !== host) {
3665
+ if (host !== void 0) push({
3666
+ parts: [{ text: " " }],
3667
+ kind: "gap"
3668
+ });
3669
+ const count = active.filter((j) => splitKid(rows[j].kid)[1].toLowerCase() === key).length;
3670
+ lines.push(band(labels.get(key) ?? key, count, width, "band"));
3671
+ host = key;
3672
+ }
3673
+ const name = names.get(i);
3674
+ push({
3675
+ parts: [
3676
+ { text: GUTTER },
3677
+ ...name,
3678
+ ...pad(nameW - len(name) + 2),
3679
+ ...grantParts(i)
3680
+ ],
3681
+ row: i,
3682
+ kind: "key"
3683
+ });
3684
+ });
3685
+ return lines;
3686
+ }
3687
+ /** A line as the cursor row: a `glyph` gutter, then a selection band padded out to `width`. */
3688
+ function selectLine(line, cursorGlyph, width = 0) {
3689
+ const body = line.parts.slice(1).map((p) => ({
3690
+ text: p.text,
3691
+ bg: "selection",
3692
+ tone: "surface",
3693
+ bold: true,
3694
+ ...p.strike ? { strike: true } : {}
3695
+ }));
3696
+ const fill = width - cellWidth(`${cursorGlyph} `) - len(body);
3697
+ const last = body[body.length - 1];
3698
+ if (last !== void 0 && fill > 0) body[body.length - 1] = {
3699
+ ...last,
3700
+ text: last.text + " ".repeat(fill)
3701
+ };
3702
+ return [{
3703
+ text: `${cursorGlyph} `,
3704
+ tone: "selection"
3705
+ }, ...body];
3706
+ }
3707
+
3373
3708
  //#endregion
3374
3709
  //#region src/keys/module.ts
3375
3710
  /**
@@ -3379,7 +3714,65 @@ function editorPanels(deps) {
3379
3714
  * through a review. Locked, it reads as the agent, which a 403 turns into "admin required", and
3380
3715
  * Enter shows a row's grant read-only. Locking closes the table and every editor panel.
3381
3716
  */
3382
- const isRevoked = (r) => typeof r.revokedAt === "string";
3717
+ const count = (s) => {
3718
+ if (s.rows === null) return "";
3719
+ const gone = s.rows.filter(isRevoked).length;
3720
+ return ` · ${s.rows.length - gone} active${s.revoked ? ` · ${gone} revoked` : ""}`;
3721
+ };
3722
+ /** The head line: accent glyph, bold `keys`, then the counts and source in dimMid. */
3723
+ function headParts(state, titleGlyph) {
3724
+ return [
3725
+ {
3726
+ text: titleGlyph,
3727
+ tone: "accent"
3728
+ },
3729
+ { text: " " },
3730
+ {
3731
+ text: "keys",
3732
+ tone: "text",
3733
+ bold: true
3734
+ },
3735
+ {
3736
+ text: `${count(state)} · ${state.source}`,
3737
+ tone: "dimMid"
3738
+ }
3739
+ ];
3740
+ }
3741
+ /** The grant legend, dim with its `a` in warn bold. */
3742
+ function legendParts() {
3743
+ return [
3744
+ {
3745
+ text: ` ${GRANT_LEGEND.slice(0, GRANT_LEGEND.lastIndexOf("a="))}`,
3746
+ tone: "dim"
3747
+ },
3748
+ {
3749
+ text: "a",
3750
+ tone: "warn",
3751
+ bold: true
3752
+ },
3753
+ {
3754
+ text: GRANT_LEGEND.slice(GRANT_LEGEND.lastIndexOf("a=") + 1),
3755
+ tone: "dim"
3756
+ }
3757
+ ];
3758
+ }
3759
+ /** Key hints: key names text, actions dimMid, `·` separators dim. */
3760
+ function hintParts(pairs) {
3761
+ return [{ text: " " }, ...pairs.flatMap(([key, action], i) => [
3762
+ ...i > 0 ? [{
3763
+ text: " · ",
3764
+ tone: "dim"
3765
+ }] : [],
3766
+ {
3767
+ text: key,
3768
+ tone: "text"
3769
+ },
3770
+ {
3771
+ text: ` ${action}`,
3772
+ tone: "dimMid"
3773
+ }
3774
+ ])];
3775
+ }
3383
3776
  /** The rows the editor flows judge against: a revoked key holds no grant. */
3384
3777
  const live = (rows) => rows.filter((r) => !isRevoked(r));
3385
3778
  /** Opens the table and reads it; `select` is a kid whose row takes the cursor once the read lands. */
@@ -3395,10 +3788,10 @@ async function loadKeys(ctx, deps, select, revoked = false) {
3395
3788
  });
3396
3789
  const filter = revoked ? "all" : "active";
3397
3790
  try {
3398
- const rows = source === "admin" ? await deps.admin.run(({ client }) => client.admin.keys({
3791
+ const rows = orderForView(source === "admin" ? await deps.admin.run(({ client }) => client.admin.keys({
3399
3792
  signal: ctx.signal,
3400
3793
  filter
3401
- })) : await deps.keys(ctx.signal, filter);
3794
+ })) : await deps.keys(ctx.signal, filter));
3402
3795
  const at = select === void 0 ? -1 : rows.findIndex((r) => r.kid === select);
3403
3796
  const cursor = Math.max(0, at);
3404
3797
  const mine = (s) => s.source === source && s.revoked === revoked;
@@ -3432,40 +3825,45 @@ function keysModule(deps) {
3432
3825
  keys: {
3433
3826
  ...KEYS_CHROME,
3434
3827
  view: ({ state, theme, size }) => {
3435
- const w = Math.max(1, size.columns - 2);
3436
- const gone = state.rows === null ? 0 : state.rows.filter(isRevoked).length;
3437
- const count = state.rows === null ? "" : ` · ${state.rows.length - gone} active${state.revoked ? ` · ${gone} revoked` : ""}`;
3438
- const head = `${theme.glyph.title} keys${count} · ${state.source}`;
3439
- if (state.note !== null) return [head, ` ${sanitise(state.note)}`].join("\n");
3440
- if (state.rows === null) return [head, " reading…"].join("\n");
3828
+ const w = size.columns;
3829
+ const headLine = partsLine(truncateParts(headParts(state, theme.glyph.title), w));
3830
+ if (state.note !== null) return linesView([headLine, { text: ` ${sanitise(state.note)}` }], theme);
3831
+ if (state.rows === null) return linesView([headLine, { text: " reading…" }], theme);
3441
3832
  const pick = state.rows[state.cursor];
3442
- if (state.detail && pick !== void 0) return [
3443
- head,
3444
- truncateCells(sanitise(` ${pick.kid} ${pick.name} ${pick.algorithm}`), w),
3445
- ...isRevoked(pick) ? [truncateCells(sanitise(` revoked ${pick.revokedAt}`), w)] : [],
3446
- ...describeGrant(pick.namespaces, pick.capabilities).map((g) => truncateCells(sanitise(` ${g}`), w)),
3447
- " backspace back · esc close"
3448
- ].join("\n");
3449
- const kidW = Math.min(40, Math.max(4, ...state.rows.map((r) => r.kid.length)));
3450
- const nameW = Math.min(24, Math.max(4, ...state.rows.map((r) => r.name.length)));
3833
+ if (state.detail && pick !== void 0) {
3834
+ const detail = [
3835
+ truncateCells(clean(` ${pick.kid} ${pick.name} ${pick.algorithm}`), w),
3836
+ ...isRevoked(pick) ? [truncateCells(clean(` revoked ${pick.revokedAt}`), w)] : [],
3837
+ ...describeGrant(pick.namespaces, pick.capabilities).map((g) => truncateCells(clean(` ${g}`), w)),
3838
+ " backspace back · esc close"
3839
+ ];
3840
+ return linesView([headLine, ...detail.map((text) => ({ text }))], theme);
3841
+ }
3842
+ const all = listLines(state.rows, w);
3451
3843
  const max = Math.max(1, size.rows - 3);
3452
- const start = Math.max(0, Math.min(state.cursor - max + 1, state.rows.length - max));
3453
- const lines = state.rows.slice(start, start + max).map((r, k) => {
3454
- const mark = start + k === state.cursor ? theme.glyph.cursor : " ";
3455
- const grant = compactGrant(r.namespaces, r.capabilities);
3456
- const gone = isRevoked(r);
3457
- const text = truncateCells(sanitise(`${mark} ${r.kid.padEnd(kidW)} ${r.name.padEnd(nameW)} ${gone ? `revoked ${r.revokedAt} ` : ""}${grant}`), w);
3458
- return gone ? {
3459
- text,
3460
- tone: "dim"
3461
- } : { text };
3462
- });
3463
- const toggle = state.revoked ? "r hide revoked" : "r show revoked";
3844
+ const at = Math.max(0, all.findIndex((l) => l.row === state.cursor));
3845
+ const start = Math.max(0, Math.min(at - max + 1, all.length - max));
3846
+ const lines = all.slice(start, start + max).map((l) => partsLine(l.row !== void 0 && l.row === state.cursor ? selectLine(l, theme.glyph.cursor, w) : l.parts));
3847
+ const toggle = state.revoked ? "hide revoked" : "show revoked";
3848
+ const hints = state.source === "admin" && deps.admin.unlocked() ? [
3849
+ ["↑↓/jk", "move"],
3850
+ ["enter", "edit"],
3851
+ ["x", "revoke"],
3852
+ ["i", "invite"],
3853
+ ["n", "register"],
3854
+ ["r", toggle],
3855
+ ["esc", "close"]
3856
+ ] : [
3857
+ ["↑↓/jk", "move"],
3858
+ ["enter", "grant"],
3859
+ ["r", toggle],
3860
+ ["esc", "close"]
3861
+ ];
3464
3862
  return linesView([
3465
- { text: head },
3863
+ headLine,
3466
3864
  ...lines,
3467
- { text: truncateCells(` ${GRANT_LEGEND}`, w) },
3468
- { text: state.source === "admin" && deps.admin.unlocked() ? ` ↑↓/jk move · enter edit · x revoke · i invite · n register · ${toggle} · esc close` : ` ↑↓/jk move · enter grant · ${toggle} · esc close` }
3865
+ partsLine(truncateParts(legendParts(), w)),
3866
+ partsLine(truncateParts(hintParts(hints), w))
3469
3867
  ], theme);
3470
3868
  },
3471
3869
  keymap: [
@@ -3592,7 +3990,7 @@ function keysModule(deps) {
3592
3990
  "prompt",
3593
3991
  "review"
3594
3992
  ]) ctx.update(p, (x) => {
3595
- if (!(p === "review" && "inviteCode" in x && x.inviteCode !== void 0)) adminOpen = true;
3993
+ if (!(p === "review" && "inviteToken" in x && x.inviteToken !== void 0)) adminOpen = true;
3596
3994
  return x;
3597
3995
  });
3598
3996
  if (adminOpen) {
@@ -51,7 +51,7 @@ 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-h4FA6Urt.js"),
54
+ import("../app-79WsRXNr.js"),
55
55
  import("../deps-CMPHUv70.js"),
56
56
  import("@mnmal-ai/surface-core/pure"),
57
57
  import("../terminal-BAd8sH3d.js")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mnmal-ai/substrate-tui",
3
- "version": "1.0.0-beta.2",
3
+ "version": "1.0.0-beta.20",
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,8 +20,8 @@
20
20
  "access": "public"
21
21
  },
22
22
  "dependencies": {
23
- "@mnmal-ai/substrate": "1.0.0-beta.2",
24
- "@mnmal-ai/substrate-nl": "1.0.0-beta.2",
23
+ "@mnmal-ai/substrate": "1.0.0-beta.20",
24
+ "@mnmal-ai/substrate-nl": "1.0.0-beta.20",
25
25
  "@mnmal-ai/surface-core": "0.17.1",
26
26
  "@mnmal-ai/surface-kit": "0.17.1",
27
27
  "@mnmal-ai/surface-theme": "0.17.1",
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "devDependencies": {
32
32
  "@biomejs/biome": "2.6.4",
33
- "@mnmal-ai/substrate-config": "1.0.0-beta.2",
33
+ "@mnmal-ai/substrate-config": "1.0.0-beta.20",
34
34
  "@types/node": "^26.6.4",
35
35
  "@types/react": "^19.2.0",
36
36
  "ink-testing-library": "^4.0.0",