@mnmal-ai/substrate-tui 1.0.0-alpha.9 → 1.0.0-beta.10

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.
@@ -1,31 +1,209 @@
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, tokenAudience } 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 { complete } from "@mnmal-ai/substrate-nl/complete";
8
- import { Panel, cellWidth, padCells, sparkline, truncateCells } from "@mnmal-ai/surface-kit";
9
7
  import { Box, Text } from "ink";
8
+ import { createElement } from "react";
9
+ import { Panel, cellWidth, cutToWidth, padCells, sparkline, truncateCells } from "@mnmal-ai/surface-kit";
10
10
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
+ import { complete } from "@mnmal-ai/substrate-nl/complete";
11
12
  import { readFile } from "node:fs/promises";
12
13
  import { createHash, createPublicKey } from "node:crypto";
13
14
  import { homedir } from "node:os";
14
15
  import { readFileSync } from "node:fs";
15
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
22
+ //#region src/lines.tsx
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. */
62
+ function linesView(lines, theme) {
63
+ return /* @__PURE__ */ jsx(Box, {
64
+ flexDirection: "column",
65
+ children: lines.map((l, i) => /* @__PURE__ */ jsx(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
74
+ }, i))
75
+ });
76
+ }
77
+
78
+ //#endregion
79
+ //#region src/admin/mutate.ts
80
+ const KEY = /^[A-Za-z_][\w-]*\/[A-Za-z_]\w*$/;
81
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
82
+ const line$3 = (text, tone) => ({
83
+ text: sanitise(text),
84
+ ...tone !== void 0 ? { tone } : {}
85
+ });
86
+ /** JSON, one Line per printed line: what was sent or received, verbatim. */
87
+ const jsonLines = (v, tone) => JSON.stringify(v, null, 2).split("\n").map((t) => line$3(` ${t}`, tone));
88
+ /** The typed text, parsed into a frame whose every key is `<ns>/<mutation>`, or why not. */
89
+ function parseMutateFrame(text) {
90
+ let v;
91
+ try {
92
+ v = JSON.parse(text);
93
+ } catch (err) {
94
+ return { error: `not JSON: ${err instanceof Error ? err.message : String(err)}` };
95
+ }
96
+ if (!isObject(v) || Object.keys(v).length === 0) return { error: "a mutate frame is a non-empty object: { \"<ns>/<mutation>\": { \"params\": … } }" };
97
+ for (const [k, entry] of Object.entries(v)) {
98
+ if (!KEY.test(k)) return { error: `'${k}' is not a qualified <ns>/<mutation> key` };
99
+ const entries = Array.isArray(entry) ? entry : [entry];
100
+ if (entries.length === 0) return { error: `'${k}' is an empty batch` };
101
+ if (!entries.every(isObject)) return { error: `'${k}' must be a { params, fields } object or an array of them` };
102
+ }
103
+ return { frame: v };
104
+ }
105
+ /** The text the operator types to send it: the frame's keys, space-separated. */
106
+ const confirmOf = (frame) => Object.keys(frame).join(" ");
107
+ /** A dry description: which mutation, how many entries, which ids and which params. Sends nothing. */
108
+ function describeMutate(frame, kid) {
109
+ const out = [];
110
+ for (const [k, entry] of Object.entries(frame)) {
111
+ const entries = Array.isArray(entry) ? entry : [entry];
112
+ out.push(line$3(`${k} · ${entries.length === 1 ? "1 entry" : `${entries.length} entries, one transaction`}`));
113
+ for (const e of entries) {
114
+ const params = isObject(e.params) ? e.params : {};
115
+ const id = params.id;
116
+ const rest = Object.keys(params).filter((p) => p !== "id");
117
+ out.push(line$3(` ${id !== void 0 ? `row ${String(id)}` : "no id"} · ${rest.length > 0 ? `params ${rest.join(", ")}` : "no other params"}`, "dim"));
118
+ }
119
+ }
120
+ out.push(line$3(`signed as admin ${kid}; nothing has been sent`, "warn"));
121
+ out.push(line$3("frame:"), ...jsonLines(frame, "dim"));
122
+ return out;
123
+ }
124
+ /** The envelope as received: `errors` first, then each asked-for key absent from `data`, then `data`. */
125
+ function envelopeLines(frame, env) {
126
+ const errors = env.errors ?? [];
127
+ const data = env.data ?? {};
128
+ const absent = Object.keys(frame).filter((k) => !(k in data));
129
+ const lines = [];
130
+ if (errors.length > 0) lines.push(line$3("errors:", "error"), ...jsonLines(errors, "error"));
131
+ for (const k of absent) lines.push(line$3(`${k}: absent from data — not applied`, "error"));
132
+ lines.push(line$3("data:"), ...jsonLines(data));
133
+ return {
134
+ lines,
135
+ ok: errors.length === 0 && absent.length === 0
136
+ };
137
+ }
138
+
139
+ //#endregion
140
+ //#region src/admin/refusal.ts
141
+ /** A server refusal as the server said it: `code: message`, sanitised, never retried. A chunked backfill wraps its failure; the cause is the refusal. */
142
+ function refusalOf(err) {
143
+ const e = err instanceof AdminBackfillError ? err.cause : err;
144
+ const known = e instanceof NetworkError || e instanceof AuthError;
145
+ const code = known ? e.code ?? String(e.status ?? "error") : "error";
146
+ const message = (known ? e.serverMessage : void 0) ?? (e instanceof Error ? e.message : String(e));
147
+ return {
148
+ code: sanitise(code),
149
+ message: sanitise(message),
150
+ ...known && e.body !== void 0 ? { body: e.body } : {}
151
+ };
152
+ }
153
+
154
+ //#endregion
16
155
  //#region src/admin/module.ts
17
156
  /**
18
- * `/admin unlock|lock|status`. Unlock resolves the admin credential the way
157
+ * `/admin unlock|lock|status|mutate`. `mutate` asks for a raw mutate frame, previews it, and sends
158
+ * it signed as admin once its keys are typed (mutate.ts); locked, it is refused. Unlock resolves the admin credential the way
19
159
  * `substrate-admin` does, asks for a passphrase on a masked panel when the key is encrypted, and
20
160
  * verifies the identity with `diagnose` before the session holds anything: a key that is not an
21
161
  * admin fails here, not at the first write.
22
162
  */
23
163
  const STATUS_ID = "admin";
164
+ const lockedLine = {
165
+ text: "admin mutate refused: admin is locked — /admin unlock",
166
+ tone: "error"
167
+ };
24
168
  function badge(deps, now) {
25
169
  const s = deps.admin.state();
26
170
  if (s.kind !== "unlocked") return null;
27
171
  return `admin ${s.kid} · ${Math.max(0, Math.ceil((s.idleUntil - now) / 6e4))}m`;
28
172
  }
173
+ function mutateView(s, theme, size) {
174
+ const w = Math.max(1, size.columns - 2);
175
+ const target = s.frame === null ? "" : sanitise(confirmOf(s.frame));
176
+ const head = { text: `${theme.glyph.title} admin mutate${target ? ` › ${target}` : ""} · ${s.stage}` };
177
+ const body = [...s.preview, ...s.result];
178
+ const foot = [];
179
+ if (s.stage === "frame") foot.push({ text: "paste the mutate frame as JSON, then enter · esc closes" });
180
+ if (s.stage === "preview") foot.push({ text: `type ${target} then enter to send · esc closes` });
181
+ if (s.stage === "applying") foot.push({
182
+ text: "sending…",
183
+ tone: "dim"
184
+ });
185
+ if (s.stage === "done" || s.stage === "refused") foot.push({
186
+ text: "esc closes",
187
+ tone: "dim"
188
+ });
189
+ if (s.error !== null) foot.push({
190
+ text: sanitise(s.error),
191
+ tone: "error"
192
+ });
193
+ const room = Math.max(0, size.rows - 1 - foot.length);
194
+ const shown = body.length <= room ? body : [...body.slice(0, Math.max(0, room - 1)), {
195
+ text: `… ${body.length - room + 1} more`,
196
+ tone: "dim"
197
+ }];
198
+ return linesView([
199
+ head,
200
+ ...shown,
201
+ ...foot
202
+ ].map((l) => ({
203
+ ...l,
204
+ text: truncateCells(l.text, w)
205
+ })), theme);
206
+ }
29
207
  /** The first check that answered no, as one printable line with its fix. */
30
208
  function refusal$1(r) {
31
209
  const no = r.checks.find((c) => c.status === "no");
@@ -41,6 +219,8 @@ function adminModule(deps, io = {}) {
41
219
  let generation = 0;
42
220
  /** Verifications awaiting diagnose, so `/admin lock` can say it cancelled one. */
43
221
  let pending = 0;
222
+ /** Bumped by each `/admin mutate`, so a result lands only in the panel that sent it. */
223
+ let mutateRun = 0;
44
224
  /** Verify, then hold. Resolves to null on success, undefined when abandoned, else the refusal line. */
45
225
  const verifyAndUnlock = async (getAuthorization, label, fallbackKid, getToken) => {
46
226
  const mine = generation;
@@ -86,10 +266,24 @@ function adminModule(deps, io = {}) {
86
266
  name: "admin",
87
267
  summary: "unlock or lock the admin identity",
88
268
  args: [{
89
- name: "unlock|lock|status",
269
+ name: "unlock|lock|status|mutate",
90
270
  optional: true
91
271
  }],
92
272
  async run([action], ctx) {
273
+ if (action === "mutate") {
274
+ if (!deps.admin.unlocked()) return ctx.print("admin mutate refused: admin is locked — /admin unlock", "error");
275
+ mutateRun += 1;
276
+ ctx.setDraft("");
277
+ ctx.open("mutate", {
278
+ run: mutateRun,
279
+ stage: "frame",
280
+ frame: null,
281
+ preview: [],
282
+ result: [],
283
+ error: null
284
+ });
285
+ return;
286
+ }
93
287
  if (action === "lock") {
94
288
  generation += 1;
95
289
  if (!deps.admin.unlocked()) return ctx.print(pending > 0 ? "admin unlock cancelled" : "admin is already locked", "dim");
@@ -132,54 +326,133 @@ function adminModule(deps, io = {}) {
132
326
  if (why !== null && why !== void 0) ctx.print(sanitise(why), "error");
133
327
  }
134
328
  }],
135
- panels: { passphrase: {
136
- mask: true,
137
- view: ({ state, theme }) => [
138
- `${theme.glyph.title} admin unlock · ${sanitise(state.kid)}`,
139
- `passphrase for ${sanitise(state.keyPath)}${state.busy ? " · checking…" : ""}`,
140
- ...state.error !== null ? [sanitise(state.error)] : [],
141
- " type it and press enter · esc cancels"
142
- ].join("\n"),
143
- escape: () => {
144
- generation += 1;
329
+ panels: {
330
+ mutate: {
331
+ view: ({ state, theme, size }) => mutateView(state, theme, size),
332
+ submit: (s, typed, ctx) => {
333
+ if (s.stage === "frame") {
334
+ const st = deps.admin.state();
335
+ if (st.kind !== "unlocked") return {
336
+ ...s,
337
+ error: "admin is locked — /admin unlock"
338
+ };
339
+ const parsed = parseMutateFrame(typed);
340
+ if ("error" in parsed) return {
341
+ ...s,
342
+ error: parsed.error
343
+ };
344
+ const { frame } = parsed;
345
+ return {
346
+ ...s,
347
+ stage: "preview",
348
+ frame,
349
+ preview: describeMutate(frame, st.kid),
350
+ error: null
351
+ };
352
+ }
353
+ if (s.stage !== "preview" || s.frame === null) return void 0;
354
+ if (typed !== confirmOf(s.frame)) return {
355
+ ...s,
356
+ error: "doesn't match"
357
+ };
358
+ const st = deps.admin.state();
359
+ if (st.kind !== "unlocked") return {
360
+ ...s,
361
+ stage: "refused",
362
+ error: null,
363
+ result: [lockedLine]
364
+ };
365
+ const { frame, run } = s;
366
+ const by = `(admin: ${st.kid})`;
367
+ const keys = sanitise(confirmOf(frame));
368
+ const ours = (fn) => ctx.update("mutate", (x) => x.run === run ? fn(x) : x);
369
+ deps.admin.run(({ client }) => client.mutate(frame)).then((env) => {
370
+ const r = envelopeLines(frame, env);
371
+ ctx.print(r.ok ? `✓ admin mutate ${keys} applied ${by}` : `✗ admin mutate ${keys} refused or partial — see errors ${by}`, r.ok ? "ok" : "error");
372
+ ours((x) => ({
373
+ ...x,
374
+ stage: r.ok ? "done" : "refused",
375
+ result: r.lines
376
+ }));
377
+ }, (err) => {
378
+ const r = refusalOf(err);
379
+ ctx.print(`✗ admin mutate ${keys}: ${r.code}: ${r.message} ${by}`, "error");
380
+ ours((x) => ({
381
+ ...x,
382
+ stage: "refused",
383
+ result: [{
384
+ text: `${r.code}: ${r.message}`,
385
+ tone: "error"
386
+ }]
387
+ }));
388
+ });
389
+ return {
390
+ ...s,
391
+ stage: "applying",
392
+ error: null
393
+ };
394
+ }
145
395
  },
146
- submit: (state, line, ctx) => {
147
- if (state.busy) return void 0;
148
- let getToken;
149
- try {
150
- getToken = makeTokenProvider({
151
- keyPath: state.keyPath,
152
- kid: state.kid
153
- }, {
154
- capabilities: adminClaimCapabilities(deps.adminEnv),
155
- passphrase: line
396
+ passphrase: {
397
+ mask: true,
398
+ view: ({ state, theme }) => [
399
+ `${theme.glyph.title} admin unlock · ${sanitise(state.kid)}`,
400
+ `passphrase for ${sanitise(state.keyPath)}${state.busy ? " · checking…" : ""}`,
401
+ ...state.error !== null ? [sanitise(state.error)] : [],
402
+ " type it and press enter · esc cancels"
403
+ ].join("\n"),
404
+ escape: () => {
405
+ generation += 1;
406
+ },
407
+ submit: (state, line, ctx) => {
408
+ if (state.busy) return void 0;
409
+ let getToken;
410
+ try {
411
+ getToken = makeTokenProvider({
412
+ keyPath: state.keyPath,
413
+ kid: state.kid
414
+ }, {
415
+ capabilities: adminClaimCapabilities(deps.adminEnv),
416
+ passphrase: line
417
+ });
418
+ } catch {
419
+ return {
420
+ ...state,
421
+ error: "wrong passphrase, or the key is unreadable"
422
+ };
423
+ }
424
+ verifyAndUnlock(() => `Bearer ${getToken()}`, state.keyPath, state.kid, getToken).then((why) => {
425
+ if (why === void 0) return;
426
+ if (why === null) ctx.close();
427
+ else ctx.update("passphrase", (s) => ({
428
+ ...s,
429
+ busy: false,
430
+ error: why
431
+ }));
156
432
  });
157
- } catch {
158
433
  return {
159
434
  ...state,
160
- error: "wrong passphrase, or the key is unreadable"
435
+ busy: true,
436
+ error: null
161
437
  };
162
438
  }
163
- verifyAndUnlock(() => `Bearer ${getToken()}`, state.keyPath, state.kid, getToken).then((why) => {
164
- if (why === void 0) return;
165
- if (why === null) ctx.close();
166
- else ctx.update("passphrase", (s) => ({
167
- ...s,
168
- busy: false,
169
- error: why
170
- }));
171
- });
172
- return {
173
- ...state,
174
- busy: true,
175
- error: null
176
- };
177
439
  }
178
- } },
440
+ },
179
441
  init(ctx) {
180
442
  const show = () => ctx.status(STATUS_ID, badge(deps, Date.now()), "warn");
181
443
  const off = deps.admin.onChange((s) => {
182
444
  show();
445
+ if (s.kind === "locked") {
446
+ let stage = null;
447
+ ctx.update("mutate", (x) => {
448
+ stage = x.stage;
449
+ return x;
450
+ });
451
+ if (stage !== null) {
452
+ ctx.close();
453
+ ctx.print(stage === "applying" ? "admin mutate closed — admin locked; the write in flight reports its outcome below" : "admin mutate closed — admin locked", "warn");
454
+ }
455
+ }
183
456
  if (s.kind === "locked" && s.reason !== null) ctx.print(sanitise(s.reason.startsWith("admin locked") ? s.reason : `admin locked: ${s.reason}`), "warn");
184
457
  });
185
458
  const tickTimer = setInterval(show, 3e4);
@@ -216,6 +489,185 @@ function adapt(draft, cursor, s) {
216
489
  };
217
490
  }
218
491
 
492
+ //#endregion
493
+ //#region src/ask/present.ts
494
+ /** Keys that would reach or shadow Object.prototype; refused as type and field names. */
495
+ const RESERVED = /* @__PURE__ */ new Set([
496
+ "__proto__",
497
+ "constructor",
498
+ "prototype"
499
+ ]);
500
+ const dict = () => Object.create(null);
501
+ /** `m[k]` when `k` is m's own key. */
502
+ const own$1 = (m, k) => Object.hasOwn(m, k) ? m[k] : void 0;
503
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
504
+ const validCurrency = (c) => {
505
+ try {
506
+ new Intl.NumberFormat("en-US", {
507
+ style: "currency",
508
+ currency: c
509
+ });
510
+ return true;
511
+ } catch {
512
+ return false;
513
+ }
514
+ };
515
+ var Bad = class extends Error {};
516
+ function entry$1(v, where) {
517
+ if (typeof v === "string" && v !== "") return { field: v };
518
+ 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 {
519
+ field: v.field,
520
+ ...v.template !== void 0 ? { template: v.template } : {},
521
+ ...v.label !== void 0 ? { label: v.label } : {}
522
+ };
523
+ throw new Bad(`${where} is not a field name or { field, template?, label? }`);
524
+ }
525
+ /** Why a field cannot be shown, or undefined when it can. A crossRef walk (`card.cardName`) is not carried by NL answer rows. */
526
+ const unusable = (field) => RESERVED.has(field) ? "is a reserved name" : field.includes(".") ? "crosses a reference" : void 0;
527
+ /** The entry, or undefined (noted) when its field cannot be shown. */
528
+ function usable(e, t, where, problems) {
529
+ const why = unusable(e.field);
530
+ if (why === void 0) return e;
531
+ problems.push({
532
+ type: t,
533
+ text: `${where}: ${e.field} ${why}; left out`
534
+ });
535
+ }
536
+ function rowView(t, v, problems) {
537
+ if (!isObj(v)) throw new Bad(`rows.${t} is not an object`);
538
+ const at = (k) => `rows.${t}.${k}`;
539
+ const list = (k) => {
540
+ const raw = v[k];
541
+ if (raw === void 0) return [];
542
+ if (!Array.isArray(raw)) throw new Bad(`${at(k)} is not a list`);
543
+ return raw.map((x, i) => usable(entry$1(x, `${at(k)}[${i}]`), t, at(k), problems)).filter((x) => x !== void 0);
544
+ };
545
+ const one = (k) => v[k] === void 0 ? void 0 : usable(entry$1(v[k], at(k)), t, at(k), problems);
546
+ const title = one("title");
547
+ const value = one("value");
548
+ return {
549
+ ...title !== void 0 ? { title } : {},
550
+ tags: list("tags"),
551
+ ...value !== void 0 ? { value } : {},
552
+ details: list("details")
553
+ };
554
+ }
555
+ function parseTui(raw) {
556
+ const problems = [];
557
+ const types = dict();
558
+ if (raw === void 0) return {
559
+ types,
560
+ problems
561
+ };
562
+ const whole = (why) => ({
563
+ types,
564
+ problems: [{ text: `tui ignored: ${why}` }]
565
+ });
566
+ if (!isObj(raw)) return whole("not an object");
567
+ const currency = raw.currency ?? "USD";
568
+ if (typeof currency !== "string" || !validCurrency(currency)) return whole(`currency ${JSON.stringify(currency)} is not an ISO 4217 code`);
569
+ if (raw.formats !== void 0 && !isObj(raw.formats)) return whole("formats is not an object");
570
+ if (raw.rows !== void 0 && !isObj(raw.rows)) return whole("rows is not an object");
571
+ const dead = /* @__PURE__ */ new Set();
572
+ const view = (t) => {
573
+ if (!Object.hasOwn(types, t)) types[t] = {
574
+ currency,
575
+ formats: dict()
576
+ };
577
+ return types[t];
578
+ };
579
+ for (const [key, fmt] of Object.entries(raw.formats ?? {})) {
580
+ const dot = key.indexOf(".");
581
+ const t = key.slice(0, dot);
582
+ if (dot <= 0 || dot === key.length - 1 || RESERVED.has(t)) {
583
+ problems.push({ text: `formats.${key}: key is not '<Type>.<field>'; left out` });
584
+ continue;
585
+ }
586
+ const field = key.slice(dot + 1);
587
+ const why = unusable(field);
588
+ if (why !== void 0) {
589
+ problems.push({
590
+ type: t,
591
+ text: `formats.${key}: ${field} ${why}; left out`
592
+ });
593
+ continue;
594
+ }
595
+ if (typeof fmt !== "string") {
596
+ problems.push({
597
+ type: t,
598
+ text: `${t} ignored: formats.${key} is not a string`
599
+ });
600
+ dead.add(t);
601
+ continue;
602
+ }
603
+ view(t).formats[field] = fmt;
604
+ }
605
+ for (const [t, spec] of Object.entries(raw.rows ?? {})) {
606
+ if (RESERVED.has(t)) {
607
+ problems.push({ text: `rows.${t}: ${t} is a reserved name; left out` });
608
+ continue;
609
+ }
610
+ try {
611
+ view(t).row = rowView(t, spec, problems);
612
+ } catch (e) {
613
+ if (!(e instanceof Bad)) throw e;
614
+ problems.push({
615
+ type: t,
616
+ text: `${t} ignored: ${e.message}`
617
+ });
618
+ dead.add(t);
619
+ }
620
+ }
621
+ for (const t of dead) delete types[t];
622
+ return {
623
+ types,
624
+ problems
625
+ };
626
+ }
627
+ const pad2 = (n) => String(n).padStart(2, "0");
628
+ const localDay = (d) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
629
+ const DECIMAL = /^\s*-?\d+(\.\d+)?\s*$/;
630
+ const NUMERIC = /* @__PURE__ */ new Set([
631
+ "money",
632
+ "int",
633
+ "number",
634
+ "pct"
635
+ ]);
636
+ /** Whether a format reads its value as a number. */
637
+ const isNumericFormat = (fmt) => fmt !== void 0 && NUMERIC.has(fmt);
638
+ /** `v` under `fmt`, unsanitised; raw `String(v)` when the format is unknown or does not fit the value. */
639
+ function formatValue(v, fmt, currency) {
640
+ const raw = String(v);
641
+ if (fmt === void 0) return raw;
642
+ if (NUMERIC.has(fmt)) {
643
+ const n = typeof v === "number" ? v : typeof v === "string" && DECIMAL.test(v) ? Number(v) : NaN;
644
+ if (!Number.isFinite(n)) return raw;
645
+ if (fmt === "money") return new Intl.NumberFormat("en-US", {
646
+ style: "currency",
647
+ currency,
648
+ signDisplay: "negative"
649
+ }).format(n);
650
+ if (fmt === "int") return new Intl.NumberFormat("en-US", {
651
+ maximumFractionDigits: 0,
652
+ signDisplay: "negative"
653
+ }).format(n);
654
+ const num = new Intl.NumberFormat("en-US", {
655
+ maximumFractionDigits: 2,
656
+ signDisplay: "negative"
657
+ }).format(n);
658
+ return fmt === "pct" ? `${num}%` : num;
659
+ }
660
+ if (fmt === "date" || fmt === "datetime") {
661
+ if (typeof v !== "string" && typeof v !== "number") return raw;
662
+ if (fmt === "date" && typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v)) return v;
663
+ const d = new Date(v);
664
+ if (Number.isNaN(d.getTime())) return raw;
665
+ if (fmt === "date" && d.getTime() % 864e5 === 0) return d.toISOString().slice(0, 10);
666
+ return fmt === "date" ? localDay(d) : `${localDay(d)} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
667
+ }
668
+ return raw;
669
+ }
670
+
219
671
  //#endregion
220
672
  //#region src/ask/render.tsx
221
673
  const KIND = {
@@ -224,6 +676,7 @@ const KIND = {
224
676
  recall: "substrate.recall",
225
677
  clarify: "substrate.clarify",
226
678
  refuse: "substrate.refuse",
679
+ unknown: "substrate.unknown",
227
680
  error: "substrate.error"
228
681
  };
229
682
  const str = (v) => v === void 0 || v === null ? "" : sanitise(String(v));
@@ -232,9 +685,10 @@ const errorLines = (errors) => (errors ?? []).map((e) => {
232
685
  const x = e;
233
686
  return sanitise(`${x.code ?? "error"}${x.message !== void 0 ? `: ${x.message}` : ""}`);
234
687
  });
688
+ const droppedLines = (dropped) => (dropped ?? []).map((d) => sanitise(`dropped "${d.span}": ${d.reason}`));
235
689
  function outcomeChips(o) {
236
690
  if (o.kind !== "rows") return [];
237
- const rejected = !Array.isArray(o.data);
691
+ const rejected = o.data === void 0;
238
692
  return [
239
693
  {
240
694
  label: `▸ ${frameKey(o)}`,
@@ -245,11 +699,76 @@ function outcomeChips(o) {
245
699
  tone: o.source === "handoff" ? "warn" : "dim"
246
700
  },
247
701
  {
248
- label: rejected ? "rejected" : `${o.count ?? o.data.length} rows`,
702
+ label: rejected ? "rejected" : o.aggregate !== void 0 ? "aggregate" : typeof o.count === "number" ? `count ${o.count}` : `${Array.isArray(o.data) ? o.data.length : 0} rows`,
249
703
  tone: rejected ? "error" : "dim"
250
704
  }
251
705
  ];
252
706
  }
707
+ /** The first label-like field a row has: the usual handles, then any `…Name` / `…Title` string. */
708
+ const LABELS = [
709
+ "title",
710
+ "synopsis",
711
+ "name",
712
+ "topic",
713
+ "subject"
714
+ ];
715
+ function labelField(r) {
716
+ const own = LABELS.find((k) => typeof r[k] === "string" && r[k] !== "");
717
+ if (own !== void 0) return own;
718
+ return Object.keys(r).find((k) => /(Name|Title)$/.test(k) && typeof r[k] === "string" && r[k] !== "");
719
+ }
720
+ /** Fields the question filtered or ordered on, in the order they appear in the frame. */
721
+ function askedFields(frame) {
722
+ const params = Object.values(frame)[0]?.params ?? {};
723
+ const out = [];
724
+ const add = (k) => {
725
+ if (!out.includes(k)) out.push(k);
726
+ };
727
+ const walk = (w) => {
728
+ if (w === null || typeof w !== "object") return;
729
+ 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);
730
+ else if (!k.startsWith("_")) add(k);
731
+ };
732
+ for (const o of params.orderBy ?? []) for (const k of Object.keys(o)) add(k);
733
+ walk(params.where);
734
+ return out;
735
+ }
736
+ /** A row's walked values (`_agg.<name>`, such as a hop ordering's) as fields beside its own. */
737
+ const withWalked = (r) => {
738
+ const a = own$1(r, "_agg");
739
+ return a !== null && typeof a === "object" && !Array.isArray(a) ? {
740
+ ...a,
741
+ ...r
742
+ } : r;
743
+ };
744
+ /** `name value` for each walked value a row carries. */
745
+ const walkedDetails = (r) => {
746
+ const a = own$1(r, "_agg");
747
+ if (a === null || typeof a !== "object" || Array.isArray(a)) return [];
748
+ return Object.entries(a).filter(([, v]) => !empty(v)).map(([k, v]) => `${sanitise(k)} ${str(v)}`);
749
+ };
750
+ const empty = (v) => v === null || v === void 0 || v === "" || typeof v === "object";
751
+ /** A row's own field as the view formats it, sanitised; '' when empty. */
752
+ const shown = (r, field, view) => {
753
+ const v = own$1(r, field);
754
+ return empty(v) ? "" : view === void 0 ? str(v) : sanitise(formatValue(v, own$1(view.formats, field), view.currency));
755
+ };
756
+ /** An entry's cell: its template around the formatted value; '' when the value is empty. */
757
+ const cell$1 = (r, e, view) => {
758
+ const v = shown(r, e.field, view);
759
+ return v === "" || e.template === void 0 ? v : sanitise(e.template.replaceAll("{}", () => v));
760
+ };
761
+ /** Width of a right-aligned value column: the widest value, capped at a third of the line. */
762
+ const valueWidth = (values, columns) => Math.min(Math.max(0, ...values.map(cellWidth)), Math.max(8, Math.floor(columns / 3)));
763
+ const SKIP = /* @__PURE__ */ new Set(["id", "shortId"]);
764
+ /** `field=value` for a row's scalar fields: the asked-about ones first, then the rest. */
765
+ function detailList(r, asked, label, view) {
766
+ const scalar = (k) => {
767
+ const v = r[k];
768
+ return v !== null && v !== void 0 && v !== "" && typeof v !== "object";
769
+ };
770
+ 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)}`);
771
+ }
253
772
  const COLS = {
254
773
  id: 6,
255
774
  status: 10,
@@ -258,9 +777,185 @@ const COLS = {
258
777
  minTitle: 12
259
778
  };
260
779
  const titleWidth = (columns) => Math.max(COLS.minTitle, columns - (COLS.id + COLS.status + COLS.project + COLS.gaps));
780
+ const FN_LABEL = {
781
+ count: "count",
782
+ avg: "average",
783
+ sum: "total",
784
+ min: "min",
785
+ max: "max"
786
+ };
787
+ 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);
788
+ /**
789
+ * A declared type's list. Wide: per row a dim ordinal, the bold title, dim tag chips and the value
790
+ * right-aligned in one column down the list, then an optional dim `·`-joined details line.
791
+ * Stacked, when the title would get less than max(20, 40%) of line 1: the title alone, then
792
+ * `tags · value`, then details. One layout for the whole list, so it stays aligned. Rows truncate.
793
+ */
794
+ function declaredRows(list, row, view, theme, columns) {
795
+ const ordW = String(list.length).length;
796
+ const prefixW = 1 + ordW + 2;
797
+ const indent = " ".repeat(prefixW + 2);
798
+ const detailW = Math.max(1, columns - indent.length);
799
+ const values = list.map((r) => row.value === void 0 ? "" : cell$1(r, row.value, view));
800
+ const valW = row.value === void 0 ? 0 : valueWidth(values.map((v) => v || "—"), columns);
801
+ const leftW = Math.max(1, columns - prefixW - (valW > 0 ? valW + 2 : 0));
802
+ const items = list.map((r) => {
803
+ const f = row.title?.field ?? labelField(r);
804
+ return {
805
+ title: (f === void 0 ? "" : cell$1(r, row.title ?? { field: f }, view)) || "—",
806
+ tags: row.tags.map((e) => cell$1(r, e, view)).filter((t) => t !== ""),
807
+ det: declaredDetails(r, row, view)
808
+ };
809
+ });
810
+ 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));
811
+ const ordinal = (i) => /* @__PURE__ */ jsx(Text, {
812
+ color: theme.color.dim,
813
+ children: ` ${padCells(String(i + 1), ordW, true)} `
814
+ });
815
+ const details = (det) => det.length > 0 ? /* @__PURE__ */ jsx(Text, {
816
+ wrap: "truncate",
817
+ color: theme.color.dim,
818
+ children: indent + truncateCells(det.join(" · "), detailW)
819
+ }) : null;
820
+ return items.map(({ title, tags, det }, i) => {
821
+ const value = values[i] ?? "";
822
+ if (!wide) {
823
+ const second = [...tags, value].filter((x) => x !== "");
824
+ return /* @__PURE__ */ jsxs(Box, {
825
+ flexDirection: "column",
826
+ children: [
827
+ /* @__PURE__ */ jsxs(Text, {
828
+ wrap: "truncate",
829
+ children: [ordinal(i), /* @__PURE__ */ jsx(Text, {
830
+ bold: true,
831
+ color: theme.color.text,
832
+ children: truncateCells(title, Math.max(1, columns - prefixW))
833
+ })]
834
+ }),
835
+ second.length > 0 ? /* @__PURE__ */ jsx(Text, {
836
+ wrap: "truncate",
837
+ color: theme.color.dim,
838
+ children: indent + truncateCells(second.join(" · "), detailW)
839
+ }) : null,
840
+ details(det)
841
+ ]
842
+ }, i);
843
+ }
844
+ const titleCell = truncateCells(title, leftW);
845
+ const room = leftW - cellWidth(titleCell);
846
+ const rest = tags.length > 0 && room > 0 ? ` ${tags.join(" ")}` : "";
847
+ const pad = valW > 0;
848
+ const restCell = pad ? padCells(rest, room) : truncateCells(rest, room);
849
+ return /* @__PURE__ */ jsxs(Box, {
850
+ flexDirection: "column",
851
+ children: [/* @__PURE__ */ jsxs(Text, {
852
+ wrap: "truncate",
853
+ children: [
854
+ ordinal(i),
855
+ /* @__PURE__ */ jsx(Text, {
856
+ bold: true,
857
+ color: theme.color.text,
858
+ children: titleCell
859
+ }),
860
+ /* @__PURE__ */ jsx(Text, {
861
+ color: theme.color.dim,
862
+ children: restCell
863
+ }),
864
+ pad ? /* @__PURE__ */ jsx(Text, {
865
+ color: theme.color.text,
866
+ children: ` ${padCells(truncateCells(value || "—", valW), valW, true)}`
867
+ }) : null
868
+ ]
869
+ }), details(det)]
870
+ }, i);
871
+ });
872
+ }
873
+ /** Below this width a grouped aggregate puts each value on the line under its key. */
874
+ const STACK_GROUPS_AT = 40;
261
875
  const rows = ({ data, theme, size }) => {
262
876
  const titleCols = titleWidth(size.columns);
263
877
  const o = data;
878
+ const view = o.tui;
879
+ const lost = droppedLines(o.dropped).map((l, i) => /* @__PURE__ */ jsx(Text, {
880
+ color: theme.color.warn,
881
+ children: ` ${l}`
882
+ }, `d${i}`));
883
+ const agg = o.aggregate;
884
+ if (agg !== void 0) {
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)}`;
887
+ const errs = errorLines(o.errors).map((l, i) => /* @__PURE__ */ jsx(Text, {
888
+ color: theme.color.error,
889
+ children: ` ${l}`
890
+ }, `e${i}`));
891
+ if (agg.groups === void 0) return /* @__PURE__ */ jsxs(Box, {
892
+ flexDirection: "column",
893
+ children: [
894
+ /* @__PURE__ */ jsx(Text, {
895
+ color: theme.color.text,
896
+ children: `${head} = ${aggValue(agg.value, view, agg.field)}`
897
+ }),
898
+ errs,
899
+ lost
900
+ ]
901
+ });
902
+ const keyCols = Math.min(30, Math.max(COLS.minTitle, Math.floor(size.columns / 3)));
903
+ const groups = agg.groups.filter((g) => g.key === null || g.value !== null);
904
+ const values = groups.map((g) => aggValue(g.value, view, agg.field));
905
+ const valW = valueWidth(values, size.columns);
906
+ return /* @__PURE__ */ jsxs(Box, {
907
+ flexDirection: "column",
908
+ children: [
909
+ /* @__PURE__ */ jsx(Text, {
910
+ color: theme.color.dim,
911
+ children: `${head} by ${str(agg.by)}`
912
+ }),
913
+ groups.length === 0 ? /* @__PURE__ */ jsx(Text, {
914
+ color: theme.color.dim,
915
+ children: " no groups"
916
+ }) : null,
917
+ groups.map((g, i) => size.columns <= STACK_GROUPS_AT ? /* @__PURE__ */ jsxs(Box, {
918
+ flexDirection: "column",
919
+ children: [/* @__PURE__ */ jsx(Text, {
920
+ wrap: "truncate",
921
+ color: theme.color.dimMid,
922
+ children: ` ${truncateCells(g.key === null ? "(none)" : str(g.key), Math.max(1, size.columns - 2))}`
923
+ }), /* @__PURE__ */ jsx(Text, {
924
+ wrap: "truncate",
925
+ color: theme.color.text,
926
+ children: ` ${truncateCells(values[i] ?? "", Math.max(1, size.columns - 4))}`
927
+ })]
928
+ }, i) : /* @__PURE__ */ jsxs(Text, {
929
+ wrap: "truncate",
930
+ children: [
931
+ " ",
932
+ /* @__PURE__ */ jsx(Text, {
933
+ color: theme.color.dimMid,
934
+ children: padCells(g.key === null ? "(none)" : str(g.key), keyCols)
935
+ }),
936
+ " ",
937
+ /* @__PURE__ */ jsx(Text, {
938
+ color: theme.color.text,
939
+ children: padCells(truncateCells(values[i] ?? "", valW), valW, true)
940
+ })
941
+ ]
942
+ }, i)),
943
+ agg.truncated === true ? /* @__PURE__ */ jsx(Text, {
944
+ color: theme.color.dim,
945
+ children: " …more groups"
946
+ }) : null,
947
+ errs,
948
+ lost
949
+ ]
950
+ });
951
+ }
952
+ if (!Array.isArray(o.data) && typeof o.count === "number") return /* @__PURE__ */ jsxs(Box, {
953
+ flexDirection: "column",
954
+ children: [/* @__PURE__ */ jsx(Text, {
955
+ color: theme.color.text,
956
+ children: o.count
957
+ }), lost]
958
+ });
264
959
  if (!Array.isArray(o.data)) return /* @__PURE__ */ jsxs(Box, {
265
960
  flexDirection: "column",
266
961
  children: [/* @__PURE__ */ jsxs(Text, {
@@ -272,33 +967,85 @@ const rows = ({ data, theme, size }) => {
272
967
  }, i))]
273
968
  });
274
969
  const list = o.data;
275
- if (list.length === 0) return /* @__PURE__ */ jsx(Text, {
970
+ if (list.length === 0 && lost.length === 0) return /* @__PURE__ */ jsx(Text, {
276
971
  color: theme.color.dim,
277
972
  children: "no rows"
278
973
  });
279
- return /* @__PURE__ */ jsx(Box, {
974
+ if (view?.row !== void 0) return /* @__PURE__ */ jsxs(Box, {
975
+ flexDirection: "column",
976
+ children: [declaredRows(list, view.row, view, theme, size.columns), lost]
977
+ });
978
+ if (!list.some((r) => "status" in r || "project" in r)) {
979
+ const asked = askedFields(o.frame);
980
+ const labelCols = Math.min(40, Math.max(COLS.minTitle, Math.floor(size.columns / 3)));
981
+ const detailCols = Math.max(COLS.minTitle, size.columns - (COLS.id + labelCols + 4));
982
+ return /* @__PURE__ */ jsxs(Box, {
983
+ flexDirection: "column",
984
+ children: [list.map((row, i) => {
985
+ const r = withWalked(row);
986
+ const label = labelField(r);
987
+ return /* @__PURE__ */ jsxs(Text, { children: [
988
+ /* @__PURE__ */ jsx(Text, {
989
+ color: theme.color.dim,
990
+ children: padCells(str(r.shortId ?? r.id), COLS.id, true)
991
+ }),
992
+ " ",
993
+ /* @__PURE__ */ jsx(Text, {
994
+ color: theme.color.text,
995
+ children: padCells(label !== void 0 ? shown(r, label, view) : "", labelCols)
996
+ }),
997
+ " ",
998
+ /* @__PURE__ */ jsx(Text, {
999
+ color: theme.color.dimMid,
1000
+ children: padCells(detailList(r, asked, label, view).join(" "), detailCols)
1001
+ })
1002
+ ] }, i);
1003
+ }), lost]
1004
+ });
1005
+ }
1006
+ return /* @__PURE__ */ jsxs(Box, {
280
1007
  flexDirection: "column",
281
- children: list.map((r, i) => /* @__PURE__ */ jsxs(Text, { children: [
282
- /* @__PURE__ */ jsx(Text, {
1008
+ children: [
1009
+ list.length === 0 ? /* @__PURE__ */ jsx(Text, {
283
1010
  color: theme.color.dim,
284
- children: padCells(str(r.shortId ?? r.id), COLS.id, true)
285
- }),
286
- " ",
287
- /* @__PURE__ */ jsx(Text, {
288
- color: theme.color.text,
289
- children: padCells(str(r.title ?? r.synopsis ?? r.name ?? r.topic ?? r.subject), titleCols)
290
- }),
291
- " ",
292
- /* @__PURE__ */ jsx(Text, {
293
- color: theme.color.info,
294
- children: padCells(str(r.status), COLS.status)
295
- }),
296
- " ",
297
- /* @__PURE__ */ jsx(Text, {
298
- color: theme.color.dimMid,
299
- children: padCells(str(r.project), COLS.project)
300
- })
301
- ] }, i))
1011
+ children: "no rows"
1012
+ }) : null,
1013
+ list.map((r, i) => /* @__PURE__ */ jsxs(Text, { children: [
1014
+ /* @__PURE__ */ jsx(Text, {
1015
+ color: theme.color.dim,
1016
+ children: padCells(str(r.shortId ?? r.id), COLS.id, true)
1017
+ }),
1018
+ " ",
1019
+ /* @__PURE__ */ jsx(Text, {
1020
+ color: theme.color.text,
1021
+ children: padCells(str(r.title ?? r.synopsis ?? r.name ?? r.topic ?? r.subject), titleCols)
1022
+ }),
1023
+ " ",
1024
+ /* @__PURE__ */ jsx(Text, {
1025
+ color: theme.color.info,
1026
+ children: padCells(str(r.status), COLS.status)
1027
+ }),
1028
+ " ",
1029
+ /* @__PURE__ */ jsx(Text, {
1030
+ color: theme.color.dimMid,
1031
+ children: padCells(str(r.project), COLS.project)
1032
+ })
1033
+ ] }, i)),
1034
+ lost
1035
+ ]
1036
+ });
1037
+ };
1038
+ const unknown = ({ data, theme }) => {
1039
+ const o = data;
1040
+ return /* @__PURE__ */ jsxs(Box, {
1041
+ flexDirection: "column",
1042
+ children: [/* @__PURE__ */ jsx(Text, {
1043
+ color: theme.color.warn,
1044
+ children: "? unknown: not answered, because part of it was dropped"
1045
+ }), droppedLines(o.dropped).map((l, i) => /* @__PURE__ */ jsx(Text, {
1046
+ color: theme.color.warn,
1047
+ children: ` ${l}`
1048
+ }, i))]
302
1049
  });
303
1050
  };
304
1051
  const recall = ({ data, theme }) => {
@@ -386,8 +1133,148 @@ const renderers = {
386
1133
  [KIND.recall]: recall,
387
1134
  [KIND.clarify]: clarify,
388
1135
  [KIND.refuse]: refuse,
1136
+ [KIND.unknown]: unknown,
389
1137
  [KIND.error]: error
390
1138
  };
1139
+ /** A declared row's details: its walked values, then each declared detail, labelled when numeric. */
1140
+ function declaredDetails(r, row, view) {
1141
+ return [...walkedDetails(r), ...row.details.map((e) => {
1142
+ const v = cell$1(r, e, view);
1143
+ if (v === "") return "";
1144
+ const label = e.label ?? (typeof own$1(r, e.field) === "number" || isNumericFormat(own$1(view.formats, e.field)) ? e.field : void 0);
1145
+ return label === void 0 ? v : `${sanitise(label)} ${v}`;
1146
+ })].filter((d) => d !== "");
1147
+ }
1148
+ /**
1149
+ * A rows answer as a list for the pager, or undefined when it is not a plain list of rows (an
1150
+ * aggregate, a count, a rejected frame). Declared rows keep their title, tags, details and value;
1151
+ * the rest get a label and the asked-about fields, then the others, as `field=value`.
1152
+ */
1153
+ function rowsList(o) {
1154
+ if (!Array.isArray(o.data) || o.aggregate !== void 0 || o.count !== void 0) return void 0;
1155
+ const view = o.tui;
1156
+ const asked = askedFields(o.frame);
1157
+ const rows = o.data.map((raw, i) => {
1158
+ const r = withWalked(raw);
1159
+ const key = typeof raw.id === "string" ? raw.id : String(i);
1160
+ const decl = view?.row;
1161
+ if (view !== void 0 && decl !== void 0) {
1162
+ const f = decl.title?.field ?? labelField(r);
1163
+ const value = decl.value === void 0 ? "" : cell$1(r, decl.value, view);
1164
+ return {
1165
+ key,
1166
+ name: (f === void 0 ? "" : cell$1(r, decl.title ?? { field: f }, view)) || "—",
1167
+ details: [...decl.tags.map((e) => cell$1(r, e, view)).filter((t) => t !== ""), ...declaredDetails(r, decl, view)],
1168
+ ...value !== "" ? { value } : {}
1169
+ };
1170
+ }
1171
+ const label = labelField(r);
1172
+ return {
1173
+ key,
1174
+ name: (label !== void 0 ? shown(r, label, view) : "") || str(r.shortId ?? r.id) || "—",
1175
+ details: detailList(r, asked, label, view)
1176
+ };
1177
+ });
1178
+ const notes = [...errorLines(o.errors), ...droppedLines(o.dropped)];
1179
+ return {
1180
+ heading: frameKey(o),
1181
+ rows,
1182
+ ...notes.length > 0 ? { notes } : {}
1183
+ };
1184
+ }
1185
+
1186
+ //#endregion
1187
+ //#region src/ask/list.ts
1188
+ /** Rows `r` lists: recall's hits about the same idea, the row itself left out. */
1189
+ const RELATED_K = 20;
1190
+ const META = [
1191
+ "status",
1192
+ "area",
1193
+ "project"
1194
+ ];
1195
+ const text = (v) => typeof v === "string" ? v : "";
1196
+ const scalar = (v) => v !== null && v !== void 0 && v !== "" && typeof v !== "object";
1197
+ const nameOf = (row) => typeof row.name === "string" ? row.name : row.name.map((s) => s.text).join("");
1198
+ /** A frame's rows; a refused frame throws the server's reason rather than reading as empty. */
1199
+ async function rowsOf(deps, key, frame, signal) {
1200
+ const env = await deps.query({ [key]: frame }, signal);
1201
+ if (!Object.hasOwn(env.data, key)) throw new Error(env.errors?.[0]?.message ?? `${key} was refused`);
1202
+ const v = env.data[key];
1203
+ return (Array.isArray(v) ? v : [v]).filter((x) => x !== null && typeof x === "object");
1204
+ }
1205
+ /**
1206
+ * Enter and `r` on an NL answer's rows. `open` reads the row's record whole (every scalar field
1207
+ * the schema has, else the fields the answer carried); `related` asks recall, over the same type
1208
+ * and namespace, for rows about the same idea as the record's label and body.
1209
+ */
1210
+ function listHooks(deps, ns, type, fields, answered, signal) {
1211
+ const records = /* @__PURE__ */ new Map();
1212
+ const record = (row) => {
1213
+ const known = records.get(row.key);
1214
+ if (known !== void 0) return known;
1215
+ const seen = answered.get(row.key) ?? {};
1216
+ if (typeof seen.id !== "string") return Promise.resolve(seen);
1217
+ 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]));
1218
+ const read = rowsOf(deps, `${ns}/${type}`, {
1219
+ params: {
1220
+ where: { id: { eq: row.key } },
1221
+ limit: 1
1222
+ },
1223
+ fields: Object.fromEntries(["id", ...names].map((k) => [k, true]))
1224
+ }, signal).then((rows) => {
1225
+ const r = rows[0];
1226
+ if (r === void 0) throw new Error(`${type} ${row.key} is gone`);
1227
+ return r;
1228
+ });
1229
+ read.catch(() => records.delete(row.key));
1230
+ records.set(row.key, read);
1231
+ return read;
1232
+ };
1233
+ return {
1234
+ async open(row) {
1235
+ const r = await record(row);
1236
+ const label = labelField(r);
1237
+ const meta = META.map((k) => text(r[k])).filter((v) => v !== "");
1238
+ const prose = [text(r.body), text(r.notes)].filter((v) => v !== "");
1239
+ 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");
1240
+ return {
1241
+ title: label !== void 0 ? text(r[label]) : nameOf(row),
1242
+ ...meta.length > 0 ? { meta: meta.join(" · ") } : {},
1243
+ ...body !== "" ? { body } : {}
1244
+ };
1245
+ },
1246
+ async related(row) {
1247
+ const r = await record(row);
1248
+ const label = labelField(r);
1249
+ const title = label !== void 0 ? text(r[label]) : nameOf(row);
1250
+ const rows = (await rowsOf(deps, "recall/Hit", {
1251
+ params: {
1252
+ to: [title, text(r.body)].filter((v) => v !== "").join("\n") || nameOf(row),
1253
+ namespace: ns,
1254
+ type,
1255
+ k: 21
1256
+ },
1257
+ fields: {
1258
+ id: true,
1259
+ score: true,
1260
+ row: true
1261
+ }
1262
+ }, signal)).filter((h) => h.id !== row.key).slice(0, 20).map((h) => {
1263
+ const hr = h.row !== null && typeof h.row === "object" ? h.row : {};
1264
+ const l = labelField(hr);
1265
+ return {
1266
+ key: String(h.id),
1267
+ name: (l !== void 0 ? text(hr[l]) : "") || String(h.id),
1268
+ ...typeof h.score === "number" ? { value: h.score.toFixed(2) } : {}
1269
+ };
1270
+ });
1271
+ return {
1272
+ heading: `related to ${title}`,
1273
+ rows
1274
+ };
1275
+ }
1276
+ };
1277
+ }
391
1278
 
392
1279
  //#endregion
393
1280
  //#region src/ask/module.ts
@@ -409,15 +1296,48 @@ function explain(err, endpoint) {
409
1296
  if (e.status === 401 || e.status === 403) return `not authorised (${e.status}) — check SUBSTRATE_AGENT_KEY_ID / SUBSTRATE_AGENT_KEY_PATH`;
410
1297
  return e.message ?? String(err);
411
1298
  }
412
- function askModule(deps) {
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})$/;
1301
+ /**
1302
+ * The ask module. A plain list of rows goes to `pager`, whose module the app must also register;
1303
+ * the default is for an app that registers it from here, as the tests do.
1304
+ */
1305
+ function askModule(deps, pager = listPager()) {
413
1306
  let namespace = deps.namespace;
414
1307
  let pack = null;
415
1308
  let forceType;
1309
+ /** The clock relative phrases are read against; undefined = the server's. */
1310
+ let asOf;
416
1311
  let last = { lines: ["no question asked yet"] };
417
1312
  let lastPackNote = "";
1313
+ /** The namespace's `annotations.tui`; empty until read, and when it cannot be. */
1314
+ let present = {
1315
+ types: {},
1316
+ problems: []
1317
+ };
1318
+ /** The namespace's types, for reading a listed row's record whole; empty until read. */
1319
+ let types = {};
418
1320
  const loadPack = (ctx) => {
419
1321
  pack = null;
420
1322
  const ns = namespace;
1323
+ present = {
1324
+ types: {},
1325
+ problems: []
1326
+ };
1327
+ types = {};
1328
+ deps.getJson(`/substrate/v1/schema/${encodeURIComponent(ns)}`, ctx.signal).then((s) => {
1329
+ if (ns !== namespace) return;
1330
+ try {
1331
+ const t = s?.types;
1332
+ if (t !== null && typeof t === "object") types = t;
1333
+ present = parseTui(s?.annotations?.tui);
1334
+ } catch {
1335
+ present = {
1336
+ types: {},
1337
+ problems: [{ text: "tui ignored: unreadable" }]
1338
+ };
1339
+ }
1340
+ }, () => {});
421
1341
  deps.nl.pack(ns, { signal: ctx.signal }).then((p) => {
422
1342
  if (ns === namespace) pack = p;
423
1343
  }, (err) => {
@@ -428,6 +1348,24 @@ function askModule(deps) {
428
1348
  ctx.print(note, "dim");
429
1349
  });
430
1350
  };
1351
+ /** A rows outcome with its frame type's declared view, when the namespace declares one. */
1352
+ const withView = (o) => {
1353
+ const [ns, type] = (Object.keys(o.frame)[0] ?? "").split("/");
1354
+ const view = ns === namespace && type !== void 0 ? own$1(present.types, type) : void 0;
1355
+ return view !== void 0 ? {
1356
+ ...o,
1357
+ tui: view
1358
+ } : o;
1359
+ };
1360
+ /** A rows answer as a list the pager pages, with Enter and `r` wired to the row's type. */
1361
+ const asList = (o, ctx) => {
1362
+ const list = rowsList(o);
1363
+ if (list === void 0) return void 0;
1364
+ const [ns = namespace, type = ""] = (Object.keys(o.frame)[0] ?? "").split("/");
1365
+ const answered = new Map(o.data.map((r, i) => [typeof r.id === "string" ? r.id : String(i), r]));
1366
+ const fields = ns === namespace ? own$1(types, type)?.fields : void 0;
1367
+ return pager.present(list, listHooks(deps, ns, type, fields, answered, ctx.signal));
1368
+ };
431
1369
  const pick = (i) => (s, ctx) => {
432
1370
  const opt = s.options[i];
433
1371
  if (opt === void 0) return void 0;
@@ -440,23 +1378,41 @@ function askModule(deps) {
440
1378
  loadPack(ctx);
441
1379
  ctx.emit("substrate/ns", { namespace });
442
1380
  },
443
- commands: [{
444
- name: "ns",
445
- summary: "switch the namespace questions go to",
446
- args: [{ name: "namespace" }],
447
- run([ns], ctx) {
448
- if (ns === void 0 || ns === "") return ctx.print(`namespace: ${namespace}`);
449
- namespace = ns;
450
- loadPack(ctx);
451
- ctx.emit("substrate/ns", { namespace });
452
- ctx.print(`namespace → ${namespace}`);
1381
+ commands: [
1382
+ {
1383
+ name: "ns",
1384
+ summary: "switch the namespace questions go to",
1385
+ args: [{ name: "namespace" }],
1386
+ run([ns], ctx) {
1387
+ if (ns === void 0 || ns === "") return ctx.print(`namespace: ${namespace}`);
1388
+ namespace = ns;
1389
+ loadPack(ctx);
1390
+ ctx.emit("substrate/ns", { namespace });
1391
+ ctx.print(`namespace → ${namespace}`);
1392
+ }
1393
+ },
1394
+ {
1395
+ name: "asof",
1396
+ summary: "read \"yesterday\", \"past 2 days\" … as of a date-time (ISO-8601 with an offset); off for the server clock",
1397
+ args: [{ name: "datetime|off" }],
1398
+ run([v], ctx) {
1399
+ if (v === void 0 || v === "") return ctx.print(`asOf: ${asOf ?? "server clock"}`);
1400
+ if (v === "off") {
1401
+ asOf = void 0;
1402
+ return ctx.print("asOf → server clock");
1403
+ }
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");
1405
+ asOf = v;
1406
+ ctx.print(`asOf → ${asOf}`);
1407
+ }
1408
+ },
1409
+ {
1410
+ name: "frame",
1411
+ summary: "show the last answer's query frame, evidence and judge trail",
1412
+ args: [],
1413
+ run: (_a, ctx) => ctx.open("frame", last)
453
1414
  }
454
- }, {
455
- name: "frame",
456
- summary: "show the last answer's query frame, evidence and judge trail",
457
- args: [],
458
- run: (_a, ctx) => ctx.open("frame", last)
459
- }],
1415
+ ],
460
1416
  panels: {
461
1417
  clarify: {
462
1418
  view: ({ state }) => [
@@ -491,11 +1447,13 @@ function askModule(deps) {
491
1447
  namespace,
492
1448
  question: text,
493
1449
  project: deps.project,
1450
+ ...asOf !== void 0 ? { asOf } : {},
494
1451
  ...type !== void 0 ? { type } : {}
495
1452
  }, { signal })) switch (ev.event) {
496
1453
  case "parsed": {
497
1454
  const key = ev.data.frame !== void 0 ? Object.keys(ev.data.frame)[0] : void 0;
498
1455
  lines.push(`parse: ${ev.data.status}${ev.data.reason !== void 0 ? ` — ${ev.data.reason}` : ""}`);
1456
+ if (ev.data.asOf !== void 0) lines.push(`asOf: ${ev.data.asOf}`);
499
1457
  if (ev.data.frame !== void 0) lines.push(JSON.stringify(ev.data.frame, null, 2));
500
1458
  for (const e of ev.data.evidence) lines.push(` ${e.span} → ${e.role} (${e.detail})`);
501
1459
  yield {
@@ -525,18 +1483,28 @@ function askModule(deps) {
525
1483
  case "recall":
526
1484
  case "clarify":
527
1485
  case "refuse":
1486
+ case "unknown": {
1487
+ const answered = ev.event === "rows" ? Object.keys(ev.data.frame)[0]?.split("/")[1] : void 0;
1488
+ for (const p of present.problems) if (p.type === void 0 || p.type === answered) lines.push(`tui: ${p.text}`);
528
1489
  last = { lines };
529
1490
  if (ev.event === "clarify" && ev.data.options.length > 0) ctx.open("clarify", ev.data);
530
1491
  else ctx.close();
1492
+ const data = ev.event === "rows" ? withView(ev.data) : ev.data;
1493
+ const listed = ev.event === "rows" ? asList(data, ctx) : void 0;
1494
+ const chips = outcomeChips(ev.data);
531
1495
  yield {
532
1496
  phase: "final",
533
- reply: {
1497
+ reply: listed !== void 0 ? {
1498
+ ...listed,
1499
+ chips
1500
+ } : {
534
1501
  kind: `substrate.${ev.event}`,
535
- data: ev.data,
536
- chips: outcomeChips(ev.data)
1502
+ data,
1503
+ chips
537
1504
  }
538
1505
  };
539
1506
  return;
1507
+ }
540
1508
  case "done": return;
541
1509
  }
542
1510
  } catch (err) {
@@ -555,11 +1523,6 @@ function askModule(deps) {
555
1523
  });
556
1524
  }
557
1525
 
558
- //#endregion
559
- //#region src/text.ts
560
- /** Server text on one line: no escape or control bytes, and line breaks collapsed to a space. */
561
- const clean = (s) => sanitise(s.replace(/[\r\n]+/g, " "));
562
-
563
1526
  //#endregion
564
1527
  //#region src/dash/derive.ts
565
1528
  /** Polls kept per sparkline. */
@@ -1291,7 +2254,7 @@ function doctorModule(deps, io = {}) {
1291
2254
  const deadline = new AbortController();
1292
2255
  const timer = setTimeout(() => deadline.abort(), deadlineMs);
1293
2256
  const signal = AbortSignal.any([ctx.signal, deadline.signal]);
1294
- const fetchWith = ((url, init) => fetch(url, {
2257
+ const fetchWith = ((url, init) => substrateFetch(String(url), {
1295
2258
  ...init,
1296
2259
  signal
1297
2260
  }));
@@ -1471,34 +2434,6 @@ function doctorModule(deps, io = {}) {
1471
2434
  });
1472
2435
  }
1473
2436
 
1474
- //#endregion
1475
- //#region src/admin/refusal.ts
1476
- /** A server refusal as the server said it: `code: message`, sanitised, never retried. A chunked backfill wraps its failure; the cause is the refusal. */
1477
- function refusalOf(err) {
1478
- const e = err instanceof AdminBackfillError ? err.cause : err;
1479
- const known = e instanceof NetworkError || e instanceof AuthError;
1480
- const code = known ? e.code ?? String(e.status ?? "error") : "error";
1481
- const message = (known ? e.serverMessage : void 0) ?? (e instanceof Error ? e.message : String(e));
1482
- return {
1483
- code: sanitise(code),
1484
- message: sanitise(message),
1485
- ...known && e.body !== void 0 ? { body: e.body } : {}
1486
- };
1487
- }
1488
-
1489
- //#endregion
1490
- //#region src/lines.tsx
1491
- /** Lines as a column of `Text`, each in its tone: a joined string view has no tone to give them. */
1492
- function linesView(lines, theme) {
1493
- return /* @__PURE__ */ jsx(Box, {
1494
- flexDirection: "column",
1495
- children: lines.map((l, i) => /* @__PURE__ */ jsx(Text, {
1496
- ...l.tone !== void 0 ? { color: theme.color[l.tone] } : {},
1497
- children: l.text
1498
- }, i))
1499
- });
1500
- }
1501
-
1502
2437
  //#endregion
1503
2438
  //#region src/keys/grant.ts
1504
2439
  const SHORT = {
@@ -1531,6 +2466,13 @@ function compactGrant(namespaces, capabilities) {
1531
2466
  if (grant.size === 0) return "(none)";
1532
2467
  return [...grant].map(([ns, caps]) => `${ns}:${canonicalCaps(caps).map((c) => SHORT[c] ?? c).join("+")}`).join(",");
1533
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
+ }
1534
2476
  /** A stored row's grant, or null when it does not parse (the table still renders it). */
1535
2477
  function rowGrant(row) {
1536
2478
  try {
@@ -2073,6 +3015,14 @@ function editView(s, glyph, size) {
2073
3015
  fit(" ↑↓←→ move · space toggle · + add namespace · enter review · esc discard")
2074
3016
  ];
2075
3017
  }
3018
+ /** Every keys panel: a one-column inset on a raised ground, set apart from the input band. */
3019
+ const KEYS_CHROME = {
3020
+ inset: {
3021
+ x: 1,
3022
+ y: 0
3023
+ },
3024
+ ground: marathon.color.raised
3025
+ };
2076
3026
  function editorPanels(deps) {
2077
3027
  const act = (fn) => (s, ctx) => {
2078
3028
  ctx.setDraft("");
@@ -2088,6 +3038,7 @@ function editorPanels(deps) {
2088
3038
  }));
2089
3039
  return {
2090
3040
  edit: {
3041
+ ...KEYS_CHROME,
2091
3042
  view: ({ state, theme, size }) => linesView(toned(editView(state, theme.glyph, size)), theme),
2092
3043
  keymap: [
2093
3044
  {
@@ -2167,6 +3118,7 @@ function editorPanels(deps) {
2167
3118
  } : void 0
2168
3119
  },
2169
3120
  prompt: {
3121
+ ...KEYS_CHROME,
2170
3122
  view: ({ state, theme }) => linesView(toned(promptView(state, theme.glyph)), theme),
2171
3123
  submit: (s, line, ctx) => {
2172
3124
  const text = line.trim();
@@ -2265,6 +3217,7 @@ function editorPanels(deps) {
2265
3217
  }
2266
3218
  },
2267
3219
  review: {
3220
+ ...KEYS_CHROME,
2268
3221
  view: ({ state, theme, armed, size }) => linesView(toned(reviewView(state, theme.glyph, armed, size)), theme),
2269
3222
  confirm: [{
2270
3223
  key: "y",
@@ -2470,36 +3423,350 @@ function editorPanels(deps) {
2470
3423
  }
2471
3424
  }
2472
3425
 
3426
+ //#endregion
3427
+ //#region src/keys/layout.ts
3428
+ const NO_HOST = "(no host)";
3429
+ const isRevoked = (r) => typeof r.revokedAt === "string";
3430
+ /** `agent@host` → [agent, host]; a kid without `@` has no host. */
3431
+ function splitKid(kid) {
3432
+ const at = kid.lastIndexOf("@");
3433
+ return at <= 0 ? [kid, NO_HOST] : [kid.slice(0, at), kid.slice(at + 1)];
3434
+ }
3435
+ const byText = (a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }) || (a < b ? -1 : a > b ? 1 : 0);
3436
+ /** Display order: active keys by host then agent, then revoked keys, most recently revoked first. */
3437
+ function orderForView(rows) {
3438
+ const active = rows.filter((r) => !isRevoked(r));
3439
+ const revoked = rows.filter(isRevoked);
3440
+ active.sort((a, b) => {
3441
+ const [aa, ah] = splitKid(a.kid);
3442
+ const [ba, bh] = splitKid(b.kid);
3443
+ return (bh === NO_HOST ? 1 : 0) - (ah === NO_HOST ? 1 : 0) || byText(ah.toLowerCase(), bh.toLowerCase()) || byText(aa.toLowerCase(), ba.toLowerCase());
3444
+ });
3445
+ revoked.sort((a, b) => String(b.revokedAt).localeCompare(String(a.revokedAt)) || byText(a.kid, b.kid));
3446
+ return [...active, ...revoked];
3447
+ }
3448
+ /** Namespaces in column order: `*` first, then the most widely granted, then by name. */
3449
+ function namespaceColumns(grants) {
3450
+ const count = /* @__PURE__ */ new Map();
3451
+ for (const g of grants) for (const ns of g?.keys() ?? []) count.set(ns, (count.get(ns) ?? 0) + 1);
3452
+ return [...count.keys()].sort((a, b) => (b === "*" ? 1 : 0) - (a === "*" ? 1 : 0) || (count.get(b) ?? 0) - (count.get(a) ?? 0) || byText(a, b));
3453
+ }
3454
+ /** The widest a name may be before it truncates with `…`. */
3455
+ const NAME_CAP = 22;
3456
+ const BAND_END = 50;
3457
+ const GUTTER = " ";
3458
+ /** Terminal cells the parts take. */
3459
+ const len = (parts) => parts.reduce((n, p) => n + cellWidth(p.text), 0);
3460
+ /** A gap is one space: an empty Ink `Text` renders no row at all. */
3461
+ const pad = (n) => n > 0 ? [{ text: " ".repeat(n) }] : [];
3462
+ /** `── label ──── count`, the count ending at one shared column. */
3463
+ function band(label, count, width, kind) {
3464
+ const l = clean(label);
3465
+ const n = String(count);
3466
+ const rule = Math.max(2, Math.min(width, BAND_END) - (4 + cellWidth(l) + 2 + cellWidth(n)));
3467
+ return {
3468
+ parts: truncateParts([
3469
+ {
3470
+ text: " ── ",
3471
+ tone: "dim"
3472
+ },
3473
+ kind === "band" ? {
3474
+ text: l,
3475
+ tone: "text",
3476
+ bold: true
3477
+ } : {
3478
+ text: l,
3479
+ tone: "dimMid",
3480
+ bold: true
3481
+ },
3482
+ { text: " " },
3483
+ {
3484
+ text: "─".repeat(rule),
3485
+ tone: "dim"
3486
+ },
3487
+ { text: " " },
3488
+ {
3489
+ text: n,
3490
+ tone: "dimMid"
3491
+ }
3492
+ ], width),
3493
+ kind
3494
+ };
3495
+ }
3496
+ /** The majority spelling of each host (lowercased), a tie going to the spelling that sorts first. */
3497
+ function hostLabels(rows) {
3498
+ const spellings = /* @__PURE__ */ new Map();
3499
+ for (const r of rows) {
3500
+ if (isRevoked(r)) continue;
3501
+ const h = splitKid(r.kid)[1];
3502
+ const m = spellings.get(h.toLowerCase()) ?? /* @__PURE__ */ new Map();
3503
+ m.set(h, (m.get(h) ?? 0) + 1);
3504
+ spellings.set(h.toLowerCase(), m);
3505
+ }
3506
+ return new Map([...spellings].map(([k, m]) => [k, [...m].sort((a, b) => b[1] - a[1] || byText(a[0], b[0]))[0]?.[0] ?? k]));
3507
+ }
3508
+ /** A hostless key's name and a dimMid short id sized to the cap; its kid when it has no name. */
3509
+ function hostlessName(name, kid) {
3510
+ if (name === "") return [{
3511
+ text: kid,
3512
+ tone: "text"
3513
+ }];
3514
+ const n = Math.min(8, 22 - cellWidth(name) - 2);
3515
+ return n < 4 ? [{
3516
+ text: name,
3517
+ tone: "text"
3518
+ }] : [
3519
+ {
3520
+ text: name,
3521
+ tone: "text"
3522
+ },
3523
+ { text: " " },
3524
+ {
3525
+ text: `${cutToWidth(kid, n)}…`,
3526
+ tone: "dimMid"
3527
+ }
3528
+ ];
3529
+ }
3530
+ const capPart = (c) => c === "a" ? {
3531
+ text: c,
3532
+ tone: "warn",
3533
+ bold: true
3534
+ } : {
3535
+ text: c,
3536
+ tone: "text"
3537
+ };
3538
+ /** The ordered rows as display lines, each truncated to `width` (the view adds the cursor). */
3539
+ function listLines(rows, width) {
3540
+ const grants = rows.map((r) => {
3541
+ const g = rowGrant(r);
3542
+ return g === null ? null : new Map([...g].map(([ns, caps]) => [clean(ns), shortCaps(caps).map(clean)]));
3543
+ });
3544
+ const active = rows.flatMap((r, i) => isRevoked(r) ? [] : [i]);
3545
+ const cols = namespaceColumns(active.map((i) => grants[i] ?? null));
3546
+ const colW = cols.map((ns) => cellWidth(ns) + 1 + Math.max(1, ...active.map((i) => cellWidth(grants[i]?.get(ns)?.join("") ?? ""))));
3547
+ const labels = hostLabels(rows);
3548
+ const names = /* @__PURE__ */ new Map();
3549
+ for (const i of active) {
3550
+ const r = rows[i];
3551
+ const [agent, host] = splitKid(r.kid);
3552
+ const parts = host === NO_HOST ? hostlessName(clean(r.name), clean(r.kid)) : [{
3553
+ text: clean(agent),
3554
+ tone: "text"
3555
+ }, ...host === labels.get(host.toLowerCase()) ? [] : [{
3556
+ text: `@${clean(host)}`,
3557
+ tone: "dimMid"
3558
+ }]];
3559
+ names.set(i, truncateParts(parts, 22));
3560
+ }
3561
+ const nameW = Math.max(4, ...[...names.values()].map(len));
3562
+ const grantParts = (i) => {
3563
+ const r = rows[i];
3564
+ const g = grants[i];
3565
+ if (g === null || g === void 0) return [{
3566
+ text: clean(compactGrant(r.namespaces, r.capabilities)),
3567
+ tone: "text"
3568
+ }];
3569
+ if (g.size === 0) return [{
3570
+ text: "(none)",
3571
+ tone: "dim"
3572
+ }];
3573
+ const last = cols.findLastIndex((ns) => g.has(ns));
3574
+ const out = [];
3575
+ cols.slice(0, last + 1).forEach((ns, k) => {
3576
+ const caps = g.get(ns);
3577
+ if (k > 0) out.push({ text: " " });
3578
+ if (caps === void 0) {
3579
+ out.push(...pad(colW[k]));
3580
+ return;
3581
+ }
3582
+ const star = ns === "*";
3583
+ out.push({
3584
+ text: clean(ns),
3585
+ tone: star ? "warn" : "dimMid",
3586
+ ...star ? { bold: true } : {}
3587
+ });
3588
+ out.push({ text: " " }, ...caps.map(capPart));
3589
+ if (k < last) out.push(...pad(colW[k] - cellWidth(ns) - 1 - cellWidth(caps.join(""))));
3590
+ });
3591
+ return out;
3592
+ };
3593
+ const lines = [];
3594
+ const push = (l) => lines.push({
3595
+ ...l,
3596
+ parts: truncateParts(l.parts, width)
3597
+ });
3598
+ const revokedCount = rows.length - active.length;
3599
+ let host;
3600
+ rows.forEach((r, i) => {
3601
+ if (isRevoked(r)) {
3602
+ if (lines.every((l) => l.kind !== "revoked-band")) {
3603
+ if (lines.length > 0) push({
3604
+ parts: [{ text: " " }],
3605
+ kind: "gap"
3606
+ });
3607
+ lines.push(band("revoked", revokedCount, width, "revoked-band"));
3608
+ }
3609
+ push({
3610
+ parts: [
3611
+ { text: GUTTER },
3612
+ {
3613
+ text: clean(r.kid),
3614
+ tone: "dim",
3615
+ strike: true
3616
+ },
3617
+ {
3618
+ text: ` ${clean(String(r.revokedAt).slice(0, 10))}`,
3619
+ tone: "dim"
3620
+ }
3621
+ ],
3622
+ row: i,
3623
+ kind: "revoked"
3624
+ });
3625
+ return;
3626
+ }
3627
+ const key = splitKid(r.kid)[1].toLowerCase();
3628
+ if (key !== host) {
3629
+ if (host !== void 0) push({
3630
+ parts: [{ text: " " }],
3631
+ kind: "gap"
3632
+ });
3633
+ const count = active.filter((j) => splitKid(rows[j].kid)[1].toLowerCase() === key).length;
3634
+ lines.push(band(labels.get(key) ?? key, count, width, "band"));
3635
+ host = key;
3636
+ }
3637
+ const name = names.get(i);
3638
+ push({
3639
+ parts: [
3640
+ { text: GUTTER },
3641
+ ...name,
3642
+ ...pad(nameW - len(name) + 2),
3643
+ ...grantParts(i)
3644
+ ],
3645
+ row: i,
3646
+ kind: "key"
3647
+ });
3648
+ });
3649
+ return lines;
3650
+ }
3651
+ /** A line as the cursor row: a `glyph` gutter, then a selection band padded out to `width`. */
3652
+ function selectLine(line, cursorGlyph, width = 0) {
3653
+ const body = line.parts.slice(1).map((p) => ({
3654
+ text: p.text,
3655
+ bg: "selection",
3656
+ tone: "surface",
3657
+ bold: true,
3658
+ ...p.strike ? { strike: true } : {}
3659
+ }));
3660
+ const fill = width - cellWidth(`${cursorGlyph} `) - len(body);
3661
+ const last = body[body.length - 1];
3662
+ if (last !== void 0 && fill > 0) body[body.length - 1] = {
3663
+ ...last,
3664
+ text: last.text + " ".repeat(fill)
3665
+ };
3666
+ return [{
3667
+ text: `${cursorGlyph} `,
3668
+ tone: "selection"
3669
+ }, ...body];
3670
+ }
3671
+
2473
3672
  //#endregion
2474
3673
  //#region src/keys/module.ts
2475
3674
  /**
2476
- * `/keys`: the active key table. Unlocked it reads as the admin identity: Enter edits a
3675
+ * `/keys`: the active key table; `r` toggles revoked keys in, dimmed with their revocation time
3676
+ * and read-only. Unlocked it reads as the admin identity: Enter edits a
2477
3677
  * row's grant (editor.tsx), `x` revokes it, `i` mints an invite and `n` registers a new key, each
2478
3678
  * through a review. Locked, it reads as the agent, which a 403 turns into "admin required", and
2479
3679
  * Enter shows a row's grant read-only. Locking closes the table and every editor panel.
2480
3680
  */
3681
+ const count = (s) => {
3682
+ if (s.rows === null) return "";
3683
+ const gone = s.rows.filter(isRevoked).length;
3684
+ return ` · ${s.rows.length - gone} active${s.revoked ? ` · ${gone} revoked` : ""}`;
3685
+ };
3686
+ /** The head line: accent glyph, bold `keys`, then the counts and source in dimMid. */
3687
+ function headParts(state, titleGlyph) {
3688
+ return [
3689
+ {
3690
+ text: titleGlyph,
3691
+ tone: "accent"
3692
+ },
3693
+ { text: " " },
3694
+ {
3695
+ text: "keys",
3696
+ tone: "text",
3697
+ bold: true
3698
+ },
3699
+ {
3700
+ text: `${count(state)} · ${state.source}`,
3701
+ tone: "dimMid"
3702
+ }
3703
+ ];
3704
+ }
3705
+ /** The grant legend, dim with its `a` in warn bold. */
3706
+ function legendParts() {
3707
+ return [
3708
+ {
3709
+ text: ` ${GRANT_LEGEND.slice(0, GRANT_LEGEND.lastIndexOf("a="))}`,
3710
+ tone: "dim"
3711
+ },
3712
+ {
3713
+ text: "a",
3714
+ tone: "warn",
3715
+ bold: true
3716
+ },
3717
+ {
3718
+ text: GRANT_LEGEND.slice(GRANT_LEGEND.lastIndexOf("a=") + 1),
3719
+ tone: "dim"
3720
+ }
3721
+ ];
3722
+ }
3723
+ /** Key hints: key names text, actions dimMid, `·` separators dim. */
3724
+ function hintParts(pairs) {
3725
+ return [{ text: " " }, ...pairs.flatMap(([key, action], i) => [
3726
+ ...i > 0 ? [{
3727
+ text: " · ",
3728
+ tone: "dim"
3729
+ }] : [],
3730
+ {
3731
+ text: key,
3732
+ tone: "text"
3733
+ },
3734
+ {
3735
+ text: ` ${action}`,
3736
+ tone: "dimMid"
3737
+ }
3738
+ ])];
3739
+ }
3740
+ /** The rows the editor flows judge against: a revoked key holds no grant. */
3741
+ const live = (rows) => rows.filter((r) => !isRevoked(r));
2481
3742
  /** Opens the table and reads it; `select` is a kid whose row takes the cursor once the read lands. */
2482
- async function loadKeys(ctx, deps, select) {
3743
+ async function loadKeys(ctx, deps, select, revoked = false) {
2483
3744
  const source = deps.admin.unlocked() ? "admin" : "agent";
2484
3745
  ctx.open("keys", {
2485
3746
  source,
2486
3747
  rows: null,
2487
3748
  note: null,
2488
3749
  cursor: 0,
2489
- detail: false
3750
+ detail: false,
3751
+ revoked
2490
3752
  });
3753
+ const filter = revoked ? "all" : "active";
2491
3754
  try {
2492
- const rows = source === "admin" ? await deps.admin.run(({ client }) => client.admin.keys({ signal: ctx.signal })) : await deps.keys(ctx.signal);
3755
+ const rows = orderForView(source === "admin" ? await deps.admin.run(({ client }) => client.admin.keys({
3756
+ signal: ctx.signal,
3757
+ filter
3758
+ })) : await deps.keys(ctx.signal, filter));
2493
3759
  const at = select === void 0 ? -1 : rows.findIndex((r) => r.kid === select);
2494
3760
  const cursor = Math.max(0, at);
2495
- ctx.update("keys", (s) => s.source === source ? {
3761
+ const mine = (s) => s.source === source && s.revoked === revoked;
3762
+ ctx.update("keys", (s) => mine(s) ? {
2496
3763
  ...s,
2497
3764
  rows,
2498
3765
  cursor
2499
3766
  } : s);
2500
3767
  } catch (err) {
2501
3768
  const note = source === "admin" && err instanceof AuthError && err.code !== void 0 && err.code !== "forbidden" ? `could not read keys: ${err.code}: ${err.serverMessage ?? err.message}` : err instanceof AuthError ? "admin required — /admin unlock" : `could not read keys: ${err instanceof Error ? err.message : String(err)}`;
2502
- ctx.update("keys", (s) => s.source === source ? {
3769
+ ctx.update("keys", (s) => s.source === source && s.revoked === revoked ? {
2503
3770
  ...s,
2504
3771
  rows: null,
2505
3772
  note
@@ -2520,33 +3787,48 @@ function keysModule(deps) {
2520
3787
  }],
2521
3788
  panels: {
2522
3789
  keys: {
3790
+ ...KEYS_CHROME,
2523
3791
  view: ({ state, theme, size }) => {
2524
- const w = Math.max(1, size.columns - 2);
2525
- const count = state.rows === null ? "" : ` · ${state.rows.length} active`;
2526
- const head = `${theme.glyph.title} keys${count} · ${state.source}`;
2527
- if (state.note !== null) return [head, ` ${sanitise(state.note)}`].join("\n");
2528
- if (state.rows === null) return [head, " reading…"].join("\n");
3792
+ const w = size.columns;
3793
+ const headLine = partsLine(truncateParts(headParts(state, theme.glyph.title), w));
3794
+ if (state.note !== null) return linesView([headLine, { text: ` ${sanitise(state.note)}` }], theme);
3795
+ if (state.rows === null) return linesView([headLine, { text: " reading…" }], theme);
2529
3796
  const pick = state.rows[state.cursor];
2530
- if (state.detail && pick !== void 0) return [
2531
- head,
2532
- truncateCells(sanitise(` ${pick.kid} ${pick.name} ${pick.algorithm}`), w),
2533
- ...describeGrant(pick.namespaces, pick.capabilities).map((g) => truncateCells(sanitise(` ${g}`), w)),
2534
- " backspace back · esc close"
2535
- ].join("\n");
2536
- const kidW = Math.min(40, Math.max(4, ...state.rows.map((r) => r.kid.length)));
2537
- const nameW = Math.min(24, Math.max(4, ...state.rows.map((r) => r.name.length)));
3797
+ if (state.detail && pick !== void 0) {
3798
+ const detail = [
3799
+ truncateCells(clean(` ${pick.kid} ${pick.name} ${pick.algorithm}`), w),
3800
+ ...isRevoked(pick) ? [truncateCells(clean(` revoked ${pick.revokedAt}`), w)] : [],
3801
+ ...describeGrant(pick.namespaces, pick.capabilities).map((g) => truncateCells(clean(` ${g}`), w)),
3802
+ " backspace back · esc close"
3803
+ ];
3804
+ return linesView([headLine, ...detail.map((text) => ({ text }))], theme);
3805
+ }
3806
+ const all = listLines(state.rows, w);
2538
3807
  const max = Math.max(1, size.rows - 3);
2539
- const start = Math.max(0, Math.min(state.cursor - max + 1, state.rows.length - max));
2540
- return [
2541
- head,
2542
- ...state.rows.slice(start, start + max).map((r, k) => {
2543
- const mark = start + k === state.cursor ? theme.glyph.cursor : " ";
2544
- const grant = compactGrant(r.namespaces, r.capabilities);
2545
- return truncateCells(sanitise(`${mark} ${r.kid.padEnd(kidW)} ${r.name.padEnd(nameW)} ${grant}`), w);
2546
- }),
2547
- truncateCells(` ${GRANT_LEGEND}`, w),
2548
- state.source === "admin" && deps.admin.unlocked() ? " ↑↓/jk move · enter edit · x revoke · i invite · n register · esc close" : " ↑↓/jk move · enter grant · esc close"
2549
- ].join("\n");
3808
+ const at = Math.max(0, all.findIndex((l) => l.row === state.cursor));
3809
+ const start = Math.max(0, Math.min(at - max + 1, all.length - max));
3810
+ 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));
3811
+ const toggle = state.revoked ? "hide revoked" : "show revoked";
3812
+ const hints = state.source === "admin" && deps.admin.unlocked() ? [
3813
+ ["↑↓/jk", "move"],
3814
+ ["enter", "edit"],
3815
+ ["x", "revoke"],
3816
+ ["i", "invite"],
3817
+ ["n", "register"],
3818
+ ["r", toggle],
3819
+ ["esc", "close"]
3820
+ ] : [
3821
+ ["↑↓/jk", "move"],
3822
+ ["enter", "grant"],
3823
+ ["r", toggle],
3824
+ ["esc", "close"]
3825
+ ];
3826
+ return linesView([
3827
+ headLine,
3828
+ ...lines,
3829
+ partsLine(truncateParts(legendParts(), w)),
3830
+ partsLine(truncateParts(hintParts(hints), w))
3831
+ ], theme);
2550
3832
  },
2551
3833
  keymap: [
2552
3834
  {
@@ -2584,6 +3866,10 @@ function keysModule(deps) {
2584
3866
  {
2585
3867
  key: "x",
2586
3868
  act: "revoke"
3869
+ },
3870
+ {
3871
+ key: "r",
3872
+ act: "toggleRevoked"
2587
3873
  }
2588
3874
  ],
2589
3875
  on: {
@@ -2591,11 +3877,12 @@ function keysModule(deps) {
2591
3877
  down: move(1),
2592
3878
  in: (s, ctx) => {
2593
3879
  if (s.rows === null || s.rows.length === 0) return void 0;
2594
- if (deps.admin.unlocked() && s.source === "admin") {
3880
+ const row = s.rows[s.cursor];
3881
+ if (deps.admin.unlocked() && s.source === "admin" && !isRevoked(row)) {
2595
3882
  openEditor(ctx, deps, {
2596
3883
  kind: "update",
2597
- row: s.rows[s.cursor]
2598
- }, s.rows);
3884
+ row
3885
+ }, live(s.rows));
2599
3886
  return;
2600
3887
  }
2601
3888
  return {
@@ -2607,6 +3894,10 @@ function keysModule(deps) {
2607
3894
  ...s,
2608
3895
  detail: false
2609
3896
  } : void 0,
3897
+ toggleRevoked: (s, ctx) => {
3898
+ if (s.detail || s.rows === null && s.note === null) return void 0;
3899
+ loadKeys(ctx, deps, s.rows?.[s.cursor]?.kid, !s.revoked);
3900
+ },
2610
3901
  register: (s, ctx) => {
2611
3902
  if (!(deps.admin.unlocked() && s.source === "admin" && s.rows !== null && !s.detail)) return;
2612
3903
  ctx.setDraft("");
@@ -2615,17 +3906,18 @@ function keysModule(deps) {
2615
3906
  label: "kid to register",
2616
3907
  error: null,
2617
3908
  back: null,
2618
- table: s.rows
3909
+ table: live(s.rows)
2619
3910
  });
2620
3911
  },
2621
3912
  invite: (s, ctx) => {
2622
3913
  if (!(deps.admin.unlocked() && s.source === "admin" && s.rows !== null && !s.detail)) return;
2623
- openEditor(ctx, deps, { kind: "invite" }, s.rows);
3914
+ openEditor(ctx, deps, { kind: "invite" }, live(s.rows));
2624
3915
  },
2625
3916
  revoke: (s, ctx) => {
2626
3917
  if (!(deps.admin.unlocked() && s.source === "admin" && s.rows !== null && !s.detail)) return;
2627
3918
  const row = s.rows[s.cursor];
2628
- if (row === void 0) return void 0;
3919
+ if (row === void 0 || isRevoked(row)) return void 0;
3920
+ const table = live(s.rows);
2629
3921
  ctx.setDraft("");
2630
3922
  switchTo(ctx, deps, "review", {
2631
3923
  flow: {
@@ -2636,13 +3928,13 @@ function keysModule(deps) {
2636
3928
  next: null,
2637
3929
  verdict: revokeVerdict({
2638
3930
  kid: row.kid,
2639
- table: s.rows,
3931
+ table,
2640
3932
  adminCapability: adminCapabilityOf(deps.adminEnv).adminCapability ?? "admin"
2641
3933
  }),
2642
3934
  stage: "review",
2643
3935
  error: null,
2644
3936
  mismatch: false,
2645
- table: s.rows
3937
+ table
2646
3938
  });
2647
3939
  }
2648
3940
  }
@@ -3670,13 +4962,15 @@ const substrateTheme = {
3670
4962
  }
3671
4963
  };
3672
4964
  function buildModules(deps, opts = {}) {
4965
+ const pager = listPager();
3673
4966
  return [
3674
4967
  statusModule(deps, opts),
3675
4968
  adminModule(deps),
3676
4969
  doctorModule(deps, opts.doctorIntervalMs !== void 0 ? { intervalMs: opts.doctorIntervalMs } : {}),
3677
4970
  keysModule(deps),
3678
4971
  surgeryModule(deps),
3679
- askModule(deps),
4972
+ askModule(deps, pager),
4973
+ pager.module,
3680
4974
  schemaModule(deps),
3681
4975
  dashModule(deps, opts.dashIntervalMs !== void 0 ? { intervalMs: opts.dashIntervalMs } : {})
3682
4976
  ];
@@ -3688,6 +4982,10 @@ function substrateAppOptions(deps, opts = {}) {
3688
4982
  defaultTurn: "substrate.ask:ask",
3689
4983
  band: true,
3690
4984
  gutter: 2,
4985
+ entries: { answer: ({ entry, body, theme }) => createElement(Box, {
4986
+ flexDirection: "column",
4987
+ marginBottom: 1
4988
+ }, entry.mark !== null ? createElement(Text, { color: theme.color.accent }, `↩ ⟨${entry.mark}⟩`) : null, body) },
3691
4989
  anchored: true,
3692
4990
  terminal: false
3693
4991
  };