piroboros 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +39 -0
  4. package/README.md +140 -2
  5. package/agents/astrelia.md +31 -0
  6. package/agents/avaritia.md +31 -0
  7. package/agents/elaria.md +31 -0
  8. package/agents/nytheria.md +32 -0
  9. package/agents/raskreia.md +32 -0
  10. package/agents/samaela.md +40 -0
  11. package/agents/vaelia.md +35 -0
  12. package/agents/vesperia.md +45 -0
  13. package/bin/piroboros.mjs +17 -0
  14. package/dist/auth.js +105 -0
  15. package/dist/base.js +19 -0
  16. package/dist/chat/budget.js +87 -0
  17. package/dist/chat/compactloop.js +63 -0
  18. package/dist/chat/compactor.js +530 -0
  19. package/dist/chat/extension.js +36 -0
  20. package/dist/chat/hook.js +40 -0
  21. package/dist/chat/log.js +317 -0
  22. package/dist/chat/outbound.js +114 -0
  23. package/dist/chat/plan.js +64 -0
  24. package/dist/chat/prompt.js +115 -0
  25. package/dist/chat/status.js +37 -0
  26. package/dist/chat/stuck.js +83 -0
  27. package/dist/chat/tools.js +163 -0
  28. package/dist/chat/tree.js +73 -0
  29. package/dist/chat/turn.js +305 -0
  30. package/dist/chat/view.js +163 -0
  31. package/dist/conclave/agents.js +113 -0
  32. package/dist/conclave/pipeline.js +715 -0
  33. package/dist/conclave/report.js +43 -0
  34. package/dist/config.js +614 -0
  35. package/dist/durable.js +177 -0
  36. package/dist/guard.js +346 -0
  37. package/dist/lock.js +56 -0
  38. package/dist/main.js +348 -0
  39. package/dist/memory/akashic/api.js +121 -0
  40. package/dist/memory/akashic/confusables.js +41 -0
  41. package/dist/memory/akashic/scanner.js +67 -0
  42. package/dist/memory/akashic/snapshot.js +31 -0
  43. package/dist/memory/akashic/store.js +1254 -0
  44. package/dist/memory/akashic/tools.js +168 -0
  45. package/dist/memory/akashic/vault.js +984 -0
  46. package/dist/memory/host.js +124 -0
  47. package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
  48. package/dist/memory/mnemosia/adapters/contract.js +219 -0
  49. package/dist/memory/mnemosia/agents.js +387 -0
  50. package/dist/memory/mnemosia/brief.js +890 -0
  51. package/dist/memory/mnemosia/claims.js +609 -0
  52. package/dist/memory/mnemosia/conflicts.js +769 -0
  53. package/dist/memory/mnemosia/escalation.js +257 -0
  54. package/dist/memory/mnemosia/feedback.js +108 -0
  55. package/dist/memory/mnemosia/filters.js +248 -0
  56. package/dist/memory/mnemosia/intent.js +221 -0
  57. package/dist/memory/mnemosia/open.js +34 -0
  58. package/dist/memory/mnemosia/orchestrator.js +926 -0
  59. package/dist/memory/mnemosia/plan.js +266 -0
  60. package/dist/memory/mnemosia/policy.js +426 -0
  61. package/dist/memory/mnemosia/progressive.js +550 -0
  62. package/dist/memory/mnemosia/provenance.js +458 -0
  63. package/dist/memory/mnemosia/qualifiers.js +428 -0
  64. package/dist/memory/mnemosia/rank.js +525 -0
  65. package/dist/memory/mnemosia/relations.js +156 -0
  66. package/dist/memory/mnemosia/requirements.js +138 -0
  67. package/dist/memory/mnemosia/rerank.js +253 -0
  68. package/dist/memory/mnemosia/retention.js +174 -0
  69. package/dist/memory/mnemosia/rollback.js +337 -0
  70. package/dist/memory/mnemosia/select.js +607 -0
  71. package/dist/memory/mnemosia/similarity.js +164 -0
  72. package/dist/memory/mnemosia/situation.js +251 -0
  73. package/dist/memory/mnemosia/task.js +418 -0
  74. package/dist/memory/mnemosia/temporal.js +136 -0
  75. package/dist/memory/mnemosia/tokens.js +66 -0
  76. package/dist/memory/mnemosia/tools.js +160 -0
  77. package/dist/memory/mnemosia/trace.js +306 -0
  78. package/dist/memory/mnemosia/types.js +298 -0
  79. package/dist/models.js +360 -0
  80. package/dist/paths.js +103 -0
  81. package/dist/redact.js +79 -0
  82. package/dist/runtime.js +378 -0
  83. package/dist/search-format.js +102 -0
  84. package/dist/search.js +351 -0
  85. package/dist/setup.js +366 -0
  86. package/dist/shell.js +110 -0
  87. package/dist/skills.js +311 -0
  88. package/dist/telemetry.js +84 -0
  89. package/dist/tui/app.js +1011 -0
  90. package/dist/tui/commands.js +121 -0
  91. package/dist/tui/keys.js +83 -0
  92. package/dist/tui/pane.js +387 -0
  93. package/dist/tui/panel.js +60 -0
  94. package/dist/tui/picker.js +25 -0
  95. package/dist/tui/sanitize.js +59 -0
  96. package/dist/tui/settings.js +198 -0
  97. package/dist/tui/setup.js +256 -0
  98. package/dist/tui/theme.js +26 -0
  99. package/dist/tui/thinking/parse.js +1094 -0
  100. package/dist/tui/thinking/select.js +86 -0
  101. package/dist/tui/thinking/state.js +137 -0
  102. package/dist/tui/thinking/types.js +3 -0
  103. package/dist/tui/thinking/view.js +74 -0
  104. package/dist/tui/viewport.js +208 -0
  105. package/dist/undo.js +258 -0
  106. package/dist/web.js +933 -0
  107. package/docs/conclave.md +21 -0
  108. package/docs/configuration.md +48 -0
  109. package/docs/development.md +25 -0
  110. package/docs/interface.md +33 -0
  111. package/docs/memory.md +11 -0
  112. package/docs/privacy.md +13 -0
  113. package/docs/tools.md +20 -0
  114. package/docs/web.md +38 -0
  115. package/models.json.example +34 -0
  116. package/package.json +76 -4
  117. package/settings.json.example +29 -0
  118. package/skills/conclave/SKILL.md +76 -0
@@ -0,0 +1,86 @@
1
+ // Ported from pi-thinking-steps 1.0.17 (MIT, see NOTICE): render.ts pickCollapsedStep, stepHasEventType and
2
+ // selectSummarySteps. Pure and deterministic; no rendering here.
3
+ export function pickCollapsedStep(steps, activeStepId) {
4
+ if (steps.length === 0)
5
+ return undefined;
6
+ if (activeStepId) {
7
+ const active = steps.find((step) => step.id === activeStepId);
8
+ if (active)
9
+ return active;
10
+ }
11
+ let latestFailureIndex = -1;
12
+ let latestSuccessAfterFailureIndex = -1;
13
+ for (let index = 0; index < steps.length; index += 1) {
14
+ const step = steps[index];
15
+ if (step.hasExplicitFailure) {
16
+ latestFailureIndex = index;
17
+ latestSuccessAfterFailureIndex = -1;
18
+ }
19
+ if (latestFailureIndex !== -1 && step.hasExplicitSuccess && index > latestFailureIndex) {
20
+ latestSuccessAfterFailureIndex = index;
21
+ }
22
+ }
23
+ if (latestSuccessAfterFailureIndex !== -1)
24
+ return steps[latestSuccessAfterFailureIndex];
25
+ if (latestFailureIndex !== -1)
26
+ return steps[latestFailureIndex];
27
+ return [...steps]
28
+ .sort((left, right) => (right.collapsedPriority ?? 0) - (left.collapsedPriority ?? 0) || right.blockIndex - left.blockIndex || right.stepIndex - left.stepIndex)[0];
29
+ }
30
+ function stepHasEventType(step, type) {
31
+ return step.summaryEvents?.some((event) => event.type === type) ?? false;
32
+ }
33
+ export function selectSummarySteps(steps, activeStepId) {
34
+ if (steps.length <= 5)
35
+ return steps;
36
+ const indexed = steps.map((step, index) => ({ step, index }));
37
+ const selected = new Set();
38
+ const activeIndex = activeStepId ? steps.findIndex((step) => step.id === activeStepId) : -1;
39
+ let latestFailureIndex = -1;
40
+ let latestSuccessAfterFailureIndex = -1;
41
+ for (let index = 0; index < steps.length; index += 1) {
42
+ const step = steps[index];
43
+ if (step.hasExplicitFailure) {
44
+ latestFailureIndex = index;
45
+ latestSuccessAfterFailureIndex = -1;
46
+ }
47
+ if (latestFailureIndex !== -1 && step.hasExplicitSuccess && index > latestFailureIndex) {
48
+ latestSuccessAfterFailureIndex = index;
49
+ }
50
+ }
51
+ if (activeIndex !== -1)
52
+ selected.add(activeIndex);
53
+ if (latestFailureIndex !== -1)
54
+ selected.add(latestFailureIndex);
55
+ if (latestSuccessAfterFailureIndex !== -1)
56
+ selected.add(latestSuccessAfterFailureIndex);
57
+ const scoreEntry = ({ step, index }) => {
58
+ let score = step.collapsedPriority ?? 0;
59
+ const isStaleSuccessBeforeLatestFailure = step.hasExplicitSuccess && latestFailureIndex !== -1 && index < latestFailureIndex;
60
+ if (index === latestFailureIndex && latestSuccessAfterFailureIndex === -1)
61
+ score += 120;
62
+ if (index === latestSuccessAfterFailureIndex)
63
+ score += 110;
64
+ if (stepHasEventType(step, "decision") || stepHasEventType(step, "plan_change"))
65
+ score += 80;
66
+ if (step.hasExplicitFailure)
67
+ score += 50;
68
+ if (step.hasExplicitSuccess && !isStaleSuccessBeforeLatestFailure)
69
+ score += 45;
70
+ if (isStaleSuccessBeforeLatestFailure)
71
+ score -= 200;
72
+ if (stepHasEventType(step, "focus") && !stepHasEventType(step, "decision") && !stepHasEventType(step, "plan_change") && !step.hasExplicitFailure && !step.hasExplicitSuccess)
73
+ score -= 15;
74
+ return score + (index / 100);
75
+ };
76
+ const targetCount = Math.min(5, steps.length);
77
+ for (const entry of [...indexed].sort((left, right) => scoreEntry(right) - scoreEntry(left))) {
78
+ if (selected.size >= targetCount)
79
+ break;
80
+ selected.add(entry.index);
81
+ }
82
+ return [...selected]
83
+ .sort((left, right) => left - right)
84
+ .map((index) => steps[index])
85
+ .slice(0, targetCount);
86
+ }
@@ -0,0 +1,137 @@
1
+ import { deriveThinkingSteps } from "./parse.js";
2
+ // The thinking panel's state: the step memo (N14) and the display mode (D23). Source text comes from committed
3
+ // state only: the thinking blocks of the live partial while a response streams, of the `pi.assistant` entry after.
4
+ export const MEMO_MAX = 256;
5
+ export const LIVE_INTERVAL_MS = 100;
6
+ export const LIVE_TAIL_CODE_POINTS = 32_000;
7
+ export const MODES = ["collapsed", "summary", "expanded"];
8
+ export const DEFAULT_MODE = "summary";
9
+ /** The thinking blocks of an assistant message that have something to show: text, or a redacted marker. */
10
+ export function thinkingBlocksOf(message) {
11
+ const content = message?.content;
12
+ if (!Array.isArray(content))
13
+ return [];
14
+ const out = [];
15
+ content.forEach((block, contentIndex) => {
16
+ if (block?.type !== "thinking")
17
+ return;
18
+ const text = typeof block.thinking === "string" ? block.thinking : "";
19
+ const redacted = block.redacted === true;
20
+ if (redacted || text.trim() !== "")
21
+ out.push({ contentIndex, text, ...(redacted ? { redacted } : {}) });
22
+ });
23
+ return out;
24
+ }
25
+ /** The last `max` code points of `text`; the text itself when it is not longer. */
26
+ export function tailOf(text, max = LIVE_TAIL_CODE_POINTS) {
27
+ if (text.length <= max)
28
+ return text;
29
+ const points = Array.from(text);
30
+ return points.length <= max ? text : points.slice(-max).join("");
31
+ }
32
+ /**
33
+ * Step derivation with a memo. Key: (conversation, entry id or "live:"+attempt, block ordinal, text length), in an
34
+ * LRU of MEMO_MAX entries. A live block is re-derived at most every LIVE_INTERVAL_MS and from its trailing
35
+ * LIVE_TAIL_CODE_POINTS only; a final entry is parsed once, in full.
36
+ */
37
+ export class StepMemo {
38
+ /** Parser runs so far; tests read it. */
39
+ derives = 0;
40
+ lru = new Map();
41
+ now;
42
+ constructor(now = Date.now) {
43
+ this.now = now;
44
+ }
45
+ get size() {
46
+ return this.lru.size;
47
+ }
48
+ touch(key) {
49
+ const hit = this.lru.get(key);
50
+ if (hit === undefined)
51
+ return undefined;
52
+ this.lru.delete(key);
53
+ this.lru.set(key, hit);
54
+ return hit;
55
+ }
56
+ put(key, value) {
57
+ this.lru.delete(key);
58
+ this.lru.set(key, value);
59
+ while (this.lru.size > MEMO_MAX)
60
+ this.lru.delete(this.lru.keys().next().value);
61
+ }
62
+ /** Steps of every non-redacted block of one message, in order. `id` is the entry id, or "live:"+attempt while streaming. */
63
+ steps(conversation, id, blocks, live) {
64
+ const out = [];
65
+ let ordinal = 0;
66
+ for (const block of blocks) {
67
+ if (block.redacted === true && block.text.trim() === "")
68
+ continue;
69
+ const blockIndex = ordinal++;
70
+ const key = `${conversation}|${id}|${blockIndex}|${block.text.length}`;
71
+ let steps = this.touch(key);
72
+ if (steps === undefined) {
73
+ const markKey = `live|${conversation}|${id}|${blockIndex}`;
74
+ const mark = live ? this.touch(markKey) : undefined;
75
+ if (mark !== undefined && this.now() - mark.at < LIVE_INTERVAL_MS)
76
+ steps = mark.steps;
77
+ else {
78
+ this.derives += 1;
79
+ const text = live ? tailOf(block.text) : block.text;
80
+ steps = deriveThinkingSteps([{ contentIndex: block.contentIndex, text }]).map((step) => ({ ...step, blockIndex }));
81
+ this.put(key, steps);
82
+ if (live)
83
+ this.put(markKey, { at: this.now(), steps });
84
+ }
85
+ }
86
+ out.push(...steps);
87
+ }
88
+ return out;
89
+ }
90
+ }
91
+ /**
92
+ * The display mode. Held in memory for the session; the global value is settings tui.thinkingSteps (default summary).
93
+ * Restore order: session, then global, then summary.
94
+ */
95
+ export class ThinkingState {
96
+ memo;
97
+ session;
98
+ listeners = new Set();
99
+ readGlobal;
100
+ writeGlobal;
101
+ constructor(options) {
102
+ this.readGlobal = options.global;
103
+ this.writeGlobal = options.write;
104
+ this.memo = new StepMemo(options.now);
105
+ }
106
+ mode() {
107
+ return this.session ?? this.readGlobal() ?? DEFAULT_MODE;
108
+ }
109
+ set(mode) {
110
+ this.session = mode;
111
+ this.notify();
112
+ }
113
+ /** Drops the session override, so the global setting shows again. */
114
+ clearSession() {
115
+ this.session = undefined;
116
+ this.notify();
117
+ }
118
+ cycle() {
119
+ const next = MODES[(MODES.indexOf(this.mode()) + 1) % MODES.length];
120
+ this.set(next);
121
+ return next;
122
+ }
123
+ /** Writes the global setting first; the session mode follows only when the write succeeded. `clear` restores the default. */
124
+ setGlobal(value) {
125
+ this.writeGlobal(value);
126
+ this.session = value === "clear" ? DEFAULT_MODE : value;
127
+ this.notify();
128
+ }
129
+ subscribe(listener) {
130
+ this.listeners.add(listener);
131
+ return () => this.listeners.delete(listener);
132
+ }
133
+ notify() {
134
+ for (const listener of this.listeners)
135
+ listener();
136
+ }
137
+ }
@@ -0,0 +1,3 @@
1
+ // Types used by the ported thinking-step parser (pi-thinking-steps 1.0.17, MIT; see NOTICE). Only the
2
+ // parser's own types are kept; the upstream export, review and theme types are not used here.
3
+ export {};
@@ -0,0 +1,74 @@
1
+ import { THEME } from "../theme.js";
2
+ import { spanLine, wrap } from "../viewport.js";
3
+ import { pickCollapsedStep, selectSummarySteps } from "./select.js";
4
+ // The thinking panel. thinkingRows() is what the panel says for a message in a mode. thinkingLines() wraps those rows
5
+ // to a width, so the app can count them; wrap and clip sanitize the text (D17) and the app draws every row through safe().
6
+ export const INDICATOR = {
7
+ waiting: "Waiting for thinking content",
8
+ none: "No thinking content supplied",
9
+ hidden: "Reasoning is hidden by the provider",
10
+ };
11
+ const colorOf = (step) => (step.role === "error" ? THEME.error : step.role === "verify" ? THEME.ok : undefined);
12
+ /** Expanded text, normalized: trailing blanks trimmed on each line and runs of blank lines folded into one. */
13
+ const bodyLines = (body) => body.replace(/\r\n?/gu, "\n").split("\n").map((line) => line.trimEnd()).filter((line, i, all) => line !== "" || (i > 0 && all[i - 1] !== ""));
14
+ export function thinkingRows(view, maxRows = Number.POSITIVE_INFINITY) {
15
+ if (view.suppressed === true)
16
+ return [];
17
+ const rows = [];
18
+ const hidden = view.blocks.some((block) => block.redacted === true);
19
+ if (hidden)
20
+ rows.push({ key: "hidden", text: INDICATOR.hidden, dim: true });
21
+ const steps = view.steps;
22
+ if (steps.length === 0) {
23
+ if (!hidden)
24
+ rows.push({ key: "none", text: view.streaming ? INDICATOR.waiting : INDICATOR.none, dim: true });
25
+ return rows.slice(0, maxRows);
26
+ }
27
+ const activeId = view.streaming ? steps[steps.length - 1].id : undefined;
28
+ if (view.mode === "collapsed") {
29
+ const step = pickCollapsedStep(steps, activeId);
30
+ rows.push({ key: "c", text: `│ Thinking ${step.icon} ${step.summary}`, truncate: true, ...(colorOf(step) === undefined ? {} : { color: colorOf(step) }) });
31
+ return rows.slice(0, maxRows);
32
+ }
33
+ rows.push({ key: "h", text: `┆ Thinking Steps · ${view.mode === "summary" ? "Summary" : "Expanded"}`, dim: true });
34
+ const shown = view.mode === "summary" ? selectSummarySteps(steps, activeId) : steps;
35
+ shown.forEach((step, i) => {
36
+ const last = i === shown.length - 1;
37
+ const color = colorOf(step);
38
+ rows.push({ key: `s${step.id}`, text: `${last ? "└─" : "├─"} ${step.icon} ${step.summary}`, ...(color === undefined ? {} : { color }) });
39
+ if (view.mode === "expanded")
40
+ bodyLines(step.body).forEach((line, j) => rows.push({ key: `b${step.id}-${j}`, text: `${last ? " " : "│ "}${line}`, dim: true }));
41
+ });
42
+ return rows.slice(0, maxRows);
43
+ }
44
+ /** The tree gutters. A wrapped row repeats the gutter of its step, and 3 spaces sit under the last step. */
45
+ const GUTTER = { "├─ ": "│ ", "└─ ": " ", "│ ": "│ ", " ": " " };
46
+ /**
47
+ * The panel for one message as rows of at most `width` columns, ready to draw. Collapsed and `truncate` rows are cut to
48
+ * one row each; the others wrap, and wrapped rows keep the gutter. Nothing when the panel is suppressed.
49
+ */
50
+ export function thinkingLines(view, width, options = {}) {
51
+ const out = [];
52
+ const w = Math.max(4, width);
53
+ for (const row of thinkingRows(view, options.maxRows)) {
54
+ const style = { ...(row.dim === true ? { dim: true } : {}), ...(row.color === undefined ? {} : { color: row.color }) };
55
+ // The gutter characters are muted, the step text keeps its own color.
56
+ const color = row.color ?? (row.dim === true ? THEME.muted : undefined);
57
+ const body = (text) => ({ text, ...(color === undefined ? {} : { color }) });
58
+ const gutterSpan = (text) => ({ text, color: THEME.muted });
59
+ if (row.truncate === true || options.truncate === true) {
60
+ const glyph = /^(?:├─|└─|│)/u.exec(row.text)?.[0] ?? "";
61
+ out.push({ ...spanLine([...(glyph === "" ? [] : [gutterSpan(glyph)]), body(row.text.slice(glyph.length))], w), ...style });
62
+ continue;
63
+ }
64
+ const lead = row.text.slice(0, 3);
65
+ const gutter = GUTTER[lead];
66
+ if (gutter === undefined) {
67
+ for (const text of wrap(row.text, w))
68
+ out.push({ text, spans: [body(text)], ...style });
69
+ continue;
70
+ }
71
+ wrap(row.text.slice(3), w - 3).forEach((text, i) => { const g = i === 0 ? lead : gutter; out.push({ text: g + text, spans: [gutterSpan(g), body(text)], ...style }); });
72
+ }
73
+ return options.maxRows === undefined ? out : out.slice(0, options.maxRows);
74
+ }
@@ -0,0 +1,208 @@
1
+ import stringWidth from "string-width";
2
+ import { sanitizeTerminal } from "./sanitize.js";
3
+ import { THEME } from "./theme.js";
4
+ // Pure layout helpers for the setup screens. Nothing here touches Ink or the terminal.
5
+ const segmenter = new Intl.Segmenter();
6
+ /** Split `text` after the longest run of whole characters that fits `width` columns; `force` takes one character even when it is wider. */
7
+ function takeColumns(text, width, force = false) {
8
+ let used = 0;
9
+ let head = "";
10
+ for (const { segment } of segmenter.segment(text)) {
11
+ const w = stringWidth(segment);
12
+ if (used + w > width && !(force && head === ""))
13
+ break;
14
+ used += w;
15
+ head += segment;
16
+ }
17
+ return [head, text.slice(head.length)];
18
+ }
19
+ /**
20
+ * Word-wrap text to `width` columns. Long words are split. Text is sanitized first so control characters cannot change the layout.
21
+ * Indentation and runs of spaces are kept; only the space at a break is dropped. A tab is 4 spaces. Rows after the first repeat
22
+ * the indentation when it is under half the width.
23
+ */
24
+ export function wrap(text, width) {
25
+ const w = Math.max(1, width);
26
+ const out = [];
27
+ for (const raw of sanitizeTerminal(text).split("\n")) {
28
+ const paragraph = raw.replace(/\t/gu, " ");
29
+ const lead = /^ */u.exec(paragraph)[0];
30
+ const indent = lead.length * 2 < w ? lead : "";
31
+ const parts = paragraph.slice(lead.length).split(/( +)/u); // words and the space runs between them, alternating
32
+ let line = indent;
33
+ let filled = false;
34
+ for (let i = 0; i < parts.length; i += 2) {
35
+ let rest = parts[i];
36
+ if (rest === "")
37
+ continue;
38
+ let gap = i === 0 ? "" : parts[i - 1];
39
+ if (filled && stringWidth(line) + gap.length + stringWidth(rest) > w) {
40
+ out.push(line);
41
+ line = indent;
42
+ filled = false;
43
+ }
44
+ if (!filled)
45
+ gap = "";
46
+ while (stringWidth(line) + stringWidth(rest) > w) {
47
+ const [head, more] = takeColumns(rest, Math.max(1, w - stringWidth(line)), true);
48
+ if (more === "") {
49
+ rest = head;
50
+ break;
51
+ } // a wide character wider than the line
52
+ out.push(line + head);
53
+ line = indent;
54
+ rest = more;
55
+ }
56
+ line += gap + rest;
57
+ filled = true;
58
+ }
59
+ out.push(filled ? line : "");
60
+ }
61
+ return out;
62
+ }
63
+ /** The last columns of `text` that fit `width`, with newlines shown as spaces. The input row uses it so a long draft shows its end. */
64
+ export function tail(text, width) {
65
+ const parts = [...segmenter.segment(sanitizeTerminal(text).replace(/\n/gu, " "))].map((part) => part.segment);
66
+ let used = 0;
67
+ let from = parts.length;
68
+ while (from > 0) {
69
+ const w = stringWidth(parts[from - 1]);
70
+ if (used + w > width)
71
+ break;
72
+ used += w;
73
+ from -= 1;
74
+ }
75
+ return parts.slice(from).join("");
76
+ }
77
+ /** Cut one line to `width` columns, ending in an ellipsis when it was shortened. */
78
+ export function clip(line, width) {
79
+ const text = sanitizeTerminal(line).replace(/\n/gu, " ");
80
+ if (stringWidth(text) <= width)
81
+ return text;
82
+ return width <= 1 ? takeColumns(text, width)[0] : `${takeColumns(text, width - 1)[0]}…`;
83
+ }
84
+ /** Case-insensitive substring filter on the label. */
85
+ export function filterByLabel(items, filter) {
86
+ const needle = filter.toLowerCase();
87
+ return needle === "" ? [...items] : items.filter((item) => item.label.toLowerCase().includes(needle));
88
+ }
89
+ /** Keep `index` inside a window of `height` rows starting at `offset`. `end` is exclusive. */
90
+ export function windowFor(total, index, offset, height) {
91
+ const h = Math.max(1, height);
92
+ let o = Math.min(Math.max(0, offset), Math.max(0, total - h));
93
+ if (index < o)
94
+ o = index;
95
+ else if (index >= o + h)
96
+ o = index - h + 1;
97
+ o = Math.min(Math.max(0, o), Math.max(0, total - h));
98
+ return { offset: o, start: total === 0 ? 0 : o, end: Math.min(total, o + h) };
99
+ }
100
+ /** "12-30 of 45", or "no matches". */
101
+ export function indicator(start, end, total) {
102
+ return total === 0 ? "no matches" : `${start + 1}-${end} of ${total}`;
103
+ }
104
+ /** `text` without its last whole character (a grapheme: an emoji or a letter with a mark goes at once). */
105
+ export function dropLast(text) {
106
+ const parts = [...segmenter.segment(text)];
107
+ return parts.slice(0, -1).map((part) => part.segment).join("");
108
+ }
109
+ /** The spans of a row: its own, or one span with the row's style (dim is the muted color). */
110
+ export function spansOf(line) {
111
+ if (line.spans !== undefined)
112
+ return line.spans;
113
+ const color = line.color ?? (line.dim === true ? THEME.muted : undefined);
114
+ return [{ text: line.text, ...(color === undefined ? {} : { color }), ...(line.bold === true ? { bold: true } : {}) }];
115
+ }
116
+ /**
117
+ * Cut spans to `width` columns exactly as clip() cuts their joined text, and give the ellipsis to the span where the cut lands.
118
+ * Each span is sanitized first, so offsets match what is drawn. Spans are only made at boundaries the caller chooses
119
+ * (label, gap, value), so a cluster never straddles two spans and the cut can be mapped back by length.
120
+ */
121
+ export function spanRow(spans, width) {
122
+ const clean = spans.map((span) => ({ ...span, text: sanitizeTerminal(span.text).replace(/\n/gu, " ") }));
123
+ const text = clean.map((span) => span.text).join("");
124
+ if (stringWidth(text) <= width)
125
+ return clean;
126
+ const head = takeColumns(text, width <= 1 ? width : width - 1)[0];
127
+ const ellipsis = width <= 1 ? "" : "…";
128
+ const out = [];
129
+ let left = head.length;
130
+ for (const span of clean) {
131
+ if (left <= 0)
132
+ break;
133
+ const piece = span.text.slice(0, left);
134
+ left -= piece.length;
135
+ if (piece !== "")
136
+ out.push({ ...span, text: piece });
137
+ }
138
+ if (ellipsis === "")
139
+ return out;
140
+ const last = out.at(-1) ?? clean[0];
141
+ if (last === undefined)
142
+ return [];
143
+ if (out.length === 0)
144
+ out.push({ ...last, text: "" });
145
+ out[out.length - 1] = { ...out[out.length - 1], text: out[out.length - 1].text + ellipsis };
146
+ return out;
147
+ }
148
+ /** A row drawn from spans, cut to `width`. */
149
+ export function spanLine(spans, width) {
150
+ const cut = spanRow(spans, width);
151
+ return { text: cut.map((span) => span.text).join(""), spans: cut };
152
+ }
153
+ /**
154
+ * Split the terminal height between the parts of the frame. The frame is at most `rows - 1` lines, because Ink clears a
155
+ * Windows console when a frame is as tall as the terminal. Each step takes what it wants from what is left, in this
156
+ * order: input, status, the chrome (header and box borders), a reserve of 3 chat rows, the command list, alerts (2 at most), replies (newest first), standing
157
+ * rows, queued items (3 at most), the key hint (only with 3 spare rows), then the chat takes the rest.
158
+ */
159
+ export function allocate(rows, want) {
160
+ let left = Math.max(0, rows - 1);
161
+ const take = (n, cap = Number.POSITIVE_INFINITY) => { const got = Math.max(0, Math.min(n, cap, left)); left -= got; return got; };
162
+ const input = take(1);
163
+ const status = take(1);
164
+ take(want.chrome ?? 0);
165
+ const reserve = take(3);
166
+ const picker = take(want.picker);
167
+ const alerts = take(want.alerts, 2);
168
+ const notes = want.notes.map(() => 0);
169
+ for (let i = want.notes.length - 1; i >= 0; i -= 1)
170
+ notes[i] = take(want.notes[i]);
171
+ const standing = want.standing.map((n) => take(n));
172
+ const queued = take(want.queued, 3);
173
+ const hint = left >= 3 ? take(Math.min(1, want.hint)) : 0;
174
+ let chat = reserve + left;
175
+ let pane = 0;
176
+ if (want.stacked && chat - 6 >= 2) {
177
+ pane = Math.min(want.pane, chat - 6);
178
+ if (pane >= 2)
179
+ chat -= pane + 1;
180
+ else
181
+ pane = 0;
182
+ }
183
+ // The live rows come after the pane and keep the chat at 4 rows or more.
184
+ let live = 0;
185
+ if ((want.live ?? 0) >= 2 && chat >= 6) {
186
+ live = 2;
187
+ chat -= 2;
188
+ }
189
+ return { input, status, chat, picker, alerts, notes, standing, queued, hint, pane, live };
190
+ }
191
+ /** Which of `total` chat rows show in `height` rows when the view is `offset` rows above the bottom. At height 2 or more the top row is the indicator. */
192
+ export function chatWindow(total, height, offset) {
193
+ if (total <= height)
194
+ return { start: 0, end: total, offset: 0, earlier: 0, newer: 0, indicator: false };
195
+ const indicator = height >= 2;
196
+ const content = Math.max(0, indicator ? height - 1 : height);
197
+ const o = Math.min(Math.max(0, offset), total - content);
198
+ const end = total - o;
199
+ const start = Math.max(0, end - content);
200
+ return { start, end, offset: o, earlier: start, newer: o, indicator };
201
+ }
202
+ /** The indicator row of a chat that is longer than its space. */
203
+ export function chatIndicator(earlier, newer) {
204
+ const count = (n, word) => `${n} ${word} ${n === 1 ? "line" : "lines"}`;
205
+ if (newer === 0)
206
+ return `${count(earlier, "earlier")}, PgUp scrolls`;
207
+ return earlier === 0 ? `${count(newer, "newer")}, End returns` : `${count(earlier, "earlier")}, ${count(newer, "newer")}, End returns`;
208
+ }