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,25 @@
1
+ import { THEME } from "./theme.js";
2
+ import { clip, indicator, windowFor } from "./viewport.js";
3
+ // Layout of the command list shown above the input. Pure: the same inputs give the same lines.
4
+ export const PICKER_MAX_ROWS = 8;
5
+ /**
6
+ * The lines of the list in at most `maxLines` rows: a window of entries that keeps the selection in view, plus an
7
+ * "n-m of total" line when the list is longer than the rows. Every line is at most `cols - 1` wide. Returns the new scroll offset.
8
+ */
9
+ export function buildPicker(list, index, offset, cols, maxLines) {
10
+ const width = Math.max(10, cols - 1);
11
+ const height = list.length <= maxLines ? Math.max(1, maxLines) : Math.max(1, maxLines - 1);
12
+ const selected = Math.min(Math.max(0, index), Math.max(0, list.length - 1));
13
+ const win = windowFor(list.length, selected, offset, height);
14
+ const labelWidth = Math.min(Math.max(...list.map((entry) => [...entry.label].length), 0), Math.floor(width / 2));
15
+ const lines = [];
16
+ for (let i = win.start; i < win.end; i += 1) {
17
+ const entry = list[i];
18
+ const label = `${entry.label}${entry.disabled === undefined ? "" : ` (unavailable: ${entry.disabled})`}`;
19
+ const text = `${i === selected ? ">" : " "} ${[...label].length >= labelWidth || entry.detail === undefined ? label : label.padEnd(labelWidth)}${entry.detail === undefined ? "" : ` ${entry.detail}`}`;
20
+ lines.push({ text: clip(text, width), ...(i === selected ? { color: THEME.accentText, bold: true } : { dim: entry.disabled !== undefined || entry.hint === true }) });
21
+ }
22
+ if (list.length > height && maxLines >= 2)
23
+ lines.push({ text: clip(indicator(win.start, win.end, list.length), width), dim: true });
24
+ return { lines, offset: win.offset };
25
+ }
@@ -0,0 +1,59 @@
1
+ import { createElement } from "react";
2
+ import { Text } from "ink";
3
+ import { THEME } from "./theme.js";
4
+ // The one render boundary. Every string that came from a model, a tool, a provider or a file passes
5
+ // through sanitizeTerminal() before it reaches the terminal, and Ink's Text is used only here.
6
+ // Fail-visible: a control character is shown as a placeholder instead of being dropped, so an attempt
7
+ // to drive the terminal is noticeable. ESC is shown as the symbol U+241B, other controls as U+XXXX.
8
+ const hex = (code) => `⟦U+${code.toString(16).toUpperCase().padStart(4, "0")}⟧`;
9
+ // C0 except tab and newline, DEL, C1, bidi controls, zero-width and format characters, and tag characters.
10
+ // A zero-width joiner passes only between two pictographs (a modifier or variation selector may precede it); anywhere else it is marked.
11
+ const UNSAFE = /[\u0000-\u0008\u000B-\u001A\u001C-\u001F\u007F-\u009F\u{AD}\u{61C}\u{200B}\u{200C}\u{200E}\u{200F}\u{202A}-\u{202E}\u{2060}-\u{2064}\u{2066}-\u{2069}\u{FEFF}]|[\u{E0000}-\u{E007F}]|(?<!\p{Extended_Pictographic}[\u{FE0F}\u{1F3FB}-\u{1F3FF}]?)\u{200D}|\u{200D}(?!\p{Extended_Pictographic})/gu;
12
+ export function sanitizeTerminal(text) {
13
+ return text
14
+ .replace(/\r\n?/gu, "\n")
15
+ .replace(/\u001B/gu, "␛")
16
+ .replace(UNSAFE, (char) => hex(char.codePointAt(0)));
17
+ }
18
+ /** Renders text after sanitizing it. Pass strings only; nested elements are not accepted. */
19
+ export function SafeText({ children, ...props }) {
20
+ const text = Array.isArray(children) ? children.join("") : String(children);
21
+ return createElement(Text, props, sanitizeTerminal(text));
22
+ }
23
+ /**
24
+ * An OAuth URL is shown and opened only when it parses as https, or as http on a loopback host. Only the
25
+ * parsed `href` is passed to the launcher, never the original string.
26
+ */
27
+ export function safeAuthUrl(value) {
28
+ let url;
29
+ try {
30
+ url = new URL(value);
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ if (url.username !== "" || url.password !== "")
36
+ return undefined;
37
+ if (url.protocol === "https:")
38
+ return url.href;
39
+ if (url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/u.test(url.hostname)))
40
+ return url.href;
41
+ return undefined;
42
+ }
43
+ /** One Text per frame row, each drawn on a single row: an empty row is a space (an empty Text may take no row), and a row that is too wide is cut. */
44
+ export function rowsOf(lines, prefix) {
45
+ return lines.map((line, i) => {
46
+ const key = `${prefix}${i}`;
47
+ if (line.text === "")
48
+ return safe(" ", { key, wrap: "truncate-end" });
49
+ // One outer Text decides the truncation; the span Texts nest inside it and carry only a color and bold.
50
+ if (line.spans !== undefined)
51
+ return createElement(Text, { key, wrap: "truncate-end" }, ...line.spans.map((span, j) => createElement(Text, { key: j, ...(span.color === undefined ? {} : { color: span.color }), ...(span.bg === undefined ? {} : { backgroundColor: span.bg }), ...(span.bold === true ? { bold: true } : {}) }, sanitizeTerminal(span.text))));
52
+ const color = line.color ?? (line.dim === true ? THEME.muted : undefined);
53
+ return safe(line.text, { key, wrap: "truncate-end", ...(line.bold === true ? { bold: true } : {}), ...(color === undefined ? {} : { color }) });
54
+ });
55
+ }
56
+ /** createElement helper: `safe(text, props)` is Text with sanitized content. */
57
+ export function safe(text, props = {}) {
58
+ return createElement(Text, props, sanitizeTerminal(text));
59
+ }
@@ -0,0 +1,198 @@
1
+ import { CONCLAVE_MEMBERS, SETTING_FIELDS, SettingsError, getSetting, previewSettings, securityChanges, settingDefault, settingPatch } from "../config.js";
2
+ import { DEFAULT_MAX_TURNS } from "../conclave/pipeline.js";
3
+ import { hasSearchKey, isLoopbackHost, pickModel, resolveBaseHost, webKeyStep } from "../setup.js";
4
+ import { SEARCH_KEYS } from "../web.js";
5
+ // /settings: browse the keys of settings.json, edit one by its type, and save through rt.updateSettings (the checked
6
+ // write). A change to a security-relevant key shows its old and new value and asks first. The same question guards /model.
7
+ export const SECURITY_CONFIRM = "Apply this change to security-relevant settings?";
8
+ const RESET = "__reset";
9
+ const ADD = "__add";
10
+ const APPLIES = {
11
+ turn: "applies at the next turn",
12
+ now: "applies right away",
13
+ run: "applies at the next Conclave run",
14
+ start: "applies at the next start",
15
+ };
16
+ const FIELD_HELP = {
17
+ cacheRetention: ' "short" keeps the prompt cache for about 5 minutes. "long" keeps it for an hour and costs more per cache write, so it pays off when you pause longer than 5 minutes between turns.',
18
+ };
19
+ const ENTRY_HELP = { env: "an environment variable name such as GIT_SSH_COMMAND", host: 'a lower case host name such as "docs.example.org"', path: "an absolute path" };
20
+ const MEMBER = /^conclave\.members\.([a-z]+)$/u;
21
+ function show(value) {
22
+ if (value === undefined)
23
+ return "not set";
24
+ if (Array.isArray(value))
25
+ return value.length === 0 ? "none" : value.join(", ");
26
+ return typeof value === "string" ? value : JSON.stringify(value);
27
+ }
28
+ // conclave.maxTurns has no single default: the seat decides (pipeline.ts).
29
+ const MAX_TURNS = "conclave.maxTurns";
30
+ const SEAT_DEFAULT = `per-seat default (${DEFAULT_MAX_TURNS.other}; Vesperia ${DEFAULT_MAX_TURNS.vesperia})`;
31
+ /** The value a key has now, or its default marked as such, or "not set". */
32
+ function valueText(settings, path) {
33
+ const value = getSetting(settings, path);
34
+ if (value !== undefined)
35
+ return show(value);
36
+ if (path === MAX_TURNS)
37
+ return SEAT_DEFAULT;
38
+ const fallback = settingDefault(path);
39
+ if (fallback !== undefined)
40
+ return `${show(fallback)} (default)`;
41
+ return SETTING_FIELDS.find((f) => f.path === path)?.type === "list" ? "none (default)" : "not set";
42
+ }
43
+ const fieldOption = (rt, f, label = f.path) => ({ id: f.path, label: `${label} ${valueText(rt.settings(), f.path)}${f.security ? " [asks first]" : ""}` });
44
+ function keyOptions(rt) {
45
+ const out = [];
46
+ const seen = new Set();
47
+ for (const f of SETTING_FIELDS) {
48
+ const member = /^conclave\.members\.([a-z]+)\./u.exec(f.path)?.[1];
49
+ if (member === undefined)
50
+ out.push(fieldOption(rt, f));
51
+ else if (!seen.has(member)) {
52
+ seen.add(member);
53
+ out.push({ id: `conclave.members.${member}`, label: `conclave.members.${member} model ${valueText(rt.settings(), `conclave.members.${member}.model`)}, then limits` });
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+ const memberFields = (name) => SETTING_FIELDS.filter((f) => f.path.startsWith(`conclave.members.${name}.`));
59
+ async function memberField(rt, io, name) {
60
+ const fields = memberFields(name);
61
+ const picked = await io.choose(`conclave.members.${name}`, fields.map((f) => fieldOption(rt, f, f.path.slice(`conclave.members.${name}.`.length))));
62
+ return fields.find((f) => f.path === picked);
63
+ }
64
+ /** A hint for a key that does not exist: the keys that contain the text, or a pointer to the list. */
65
+ function unknownKey(arg) {
66
+ const near = SETTING_FIELDS.map((f) => f.path).filter((path) => path.toLowerCase().includes(arg.toLowerCase())).slice(0, 5);
67
+ return `unknown setting ${arg}; ${near.length === 0 ? "use /settings to browse the keys" : `did you mean ${near.join(", ")}?`}`;
68
+ }
69
+ /** One question at a time; returns the reply text for the chat. Esc anywhere cancels with SetupCancelled. */
70
+ export async function runSettings(rt, io, signal, arg) {
71
+ if (rt.settings().main !== rt.stored().main)
72
+ io.notify("info", `This run uses ${rt.settings().main ?? "no main model"} from --model. settings.json holds ${rt.stored().main ?? "no main model"}; a change to main is saved there and applies when piroboros starts without --model.`);
73
+ let f;
74
+ if (arg === "") {
75
+ const picked = await io.choose("Settings (type to filter)", keyOptions(rt));
76
+ const member = MEMBER.exec(picked)?.[1];
77
+ f = member === undefined ? SETTING_FIELDS.find((candidate) => candidate.path === picked) : await memberField(rt, io, member);
78
+ }
79
+ else {
80
+ const member = MEMBER.exec(arg)?.[1];
81
+ f = member !== undefined && CONCLAVE_MEMBERS.includes(member) ? await memberField(rt, io, member) : SETTING_FIELDS.find((candidate) => candidate.path === arg);
82
+ if (f === undefined)
83
+ return unknownKey(arg);
84
+ }
85
+ return editField(rt, io, signal, f);
86
+ }
87
+ /** Why the change would be refused (the text names the key and the allowed range), or undefined when it is valid. */
88
+ function problemWith(rt, change) {
89
+ try {
90
+ previewSettings(rt.stored(), change);
91
+ return undefined;
92
+ }
93
+ catch (error) {
94
+ if (!(error instanceof SettingsError))
95
+ throw error;
96
+ return error.issues.join("\n");
97
+ }
98
+ }
99
+ async function editField(rt, io, signal, f) {
100
+ const stored = getSetting(rt.stored(), f.path);
101
+ const fallback = f.path === MAX_TURNS ? undefined : settingDefault(f.path);
102
+ const resetLabel = `Reset to default (${f.path === MAX_TURNS ? SEAT_DEFAULT : fallback === undefined ? (f.type === "list" ? "none" : "not set") : show(fallback)})`;
103
+ io.notify("info", `${f.path}: now ${valueText(rt.settings(), f.path)}. The value ${APPLIES[f.applies]}.${FIELD_HELP[f.path] ?? ""}${f.security ? " It is security-relevant, so saving asks first." : ""}`);
104
+ const unset = { unset: f.path };
105
+ const setTo = (value) => ({ set: settingPatch(f.path, value) });
106
+ if (f.type === "enum" || f.type === "bool") {
107
+ const values = f.type === "bool" ? ["true", "false"] : [...(f.values ?? [])];
108
+ const current = stored === undefined ? undefined : String(stored);
109
+ const picked = await io.choose(`Set ${f.path}`, [...values.map((value) => ({ id: value, label: value === current ? `${value} (current)` : value })), { id: RESET, label: resetLabel }], current ?? (fallback === undefined ? undefined : String(fallback)));
110
+ if (picked === RESET)
111
+ return commit(rt, io, f, unset);
112
+ const value = f.type === "bool" ? picked === "true" : picked;
113
+ if (f.path === "web.search.provider" && !hasSearchKey(rt.setupEnv(), picked)) {
114
+ const label = SEARCH_KEYS[picked].label;
115
+ if (await io.confirm(`No ${label} key is stored or set in ${SEARCH_KEYS[picked].env}. Enter one now?`, true))
116
+ await webKeyStep(rt.setupEnv(), io, picked, signal);
117
+ else
118
+ io.notify("warn", `Search stays unavailable until a ${label} key is stored (/login web-${picked}).`);
119
+ }
120
+ return commit(rt, io, f, setTo(value));
121
+ }
122
+ if (f.type === "int") {
123
+ for (;;) {
124
+ const answer = (await io.text(`${f.path}: a whole number${f.min === undefined ? "" : ` from ${f.min}`}${f.max === undefined ? "" : ` to ${f.max}`}, or "default" to reset`, signal, undefined, stored === undefined ? (fallback === undefined ? "" : String(fallback)) : String(stored))).trim();
125
+ if (answer === "")
126
+ return `${f.path} not changed`;
127
+ if (answer.toLowerCase() === "default")
128
+ return commit(rt, io, f, unset);
129
+ const change = setTo(/^-?\d+$/u.test(answer) ? Number(answer) : answer);
130
+ const problem = problemWith(rt, change);
131
+ if (problem === undefined)
132
+ return commit(rt, io, f, change);
133
+ io.notify("error", problem);
134
+ }
135
+ }
136
+ if (f.type === "ref") {
137
+ const picked = await pickModel(rt.setupEnv(), io, f.role ?? "main", `Model for ${f.path}`, typeof stored === "string" ? stored : undefined, true, signal, resetLabel);
138
+ if (picked === "keep")
139
+ return `${f.path} not changed`;
140
+ if (picked === "skip")
141
+ return commit(rt, io, f, unset);
142
+ let change = setTo(picked);
143
+ if (f.path === "compactor.model") {
144
+ const host = resolveBaseHost(rt.models, picked);
145
+ if (host !== undefined && !isLoopbackHost(host)) {
146
+ if (!(await io.confirm(`The compactor will send chat text to ${host}. Allow it?`, false)))
147
+ return `${f.path} not changed`;
148
+ change = { set: { compactor: { model: picked, allowThirdParty: true } } };
149
+ }
150
+ }
151
+ return commit(rt, io, f, change);
152
+ }
153
+ // list: entries are removed by picking them, so commas and spaces in paths are safe.
154
+ const current = Array.isArray(stored) ? stored : [];
155
+ const picked = await io.choose(`${f.path} (${current.length} ${current.length === 1 ? "entry" : "entries"}); pick one to remove it`, [
156
+ ...current.map((entry, i) => ({ id: `rm:${i}`, label: `Remove ${entry}` })),
157
+ { id: ADD, label: "Add an entry" },
158
+ { id: RESET, label: resetLabel },
159
+ ]);
160
+ if (picked === RESET)
161
+ return commit(rt, io, f, unset);
162
+ if (picked.startsWith("rm:")) {
163
+ const rest = current.filter((_, i) => `rm:${i}` !== picked);
164
+ return commit(rt, io, f, rest.length === 0 ? unset : setTo(rest));
165
+ }
166
+ for (;;) {
167
+ const entry = (await io.text(`New entry for ${f.path}: ${ENTRY_HELP[f.entry ?? "env"]}`, signal)).trim();
168
+ if (entry === "")
169
+ return `${f.path} not changed`;
170
+ const change = setTo([...current, entry]);
171
+ const problem = problemWith(rt, change);
172
+ if (problem === undefined)
173
+ return commit(rt, io, f, change);
174
+ io.notify("error", problem);
175
+ }
176
+ }
177
+ /** Confirm a security-relevant change, then write it through the checked write. */
178
+ async function commit(rt, io, f, change) {
179
+ let lines;
180
+ try {
181
+ lines = securityChanges(rt.stored(), change);
182
+ }
183
+ catch (error) {
184
+ if (error instanceof SettingsError)
185
+ return `${f.path} not saved: ${error.issues.join("; ")}`;
186
+ throw error;
187
+ }
188
+ if (lines.length > 0) {
189
+ io.notify("warn", lines.join("\n"));
190
+ if (!(await io.confirm(SECURITY_CONFIRM, false)))
191
+ return `${f.path} not changed`;
192
+ }
193
+ const result = rt.updateSettings(change);
194
+ if (!result.ok)
195
+ return `${f.path} not saved: ${result.error}`;
196
+ const what = "unset" in change ? "reset to default" : `set to ${show(getSetting(change.set, f.path))}`;
197
+ return `${f.path} ${what}; the value ${APPLIES[f.applies]}${result.note === undefined ? "" : `. Note: ${result.note}`}`;
198
+ }
@@ -0,0 +1,256 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createElement, useEffect, useState } from "react";
3
+ import { Box, render, useInput, useStdout } from "ink";
4
+ import { SetupCancelled, runSetup } from "../setup.js";
5
+ import { rowsOf } from "./sanitize.js";
6
+ import { THEME } from "./theme.js";
7
+ import { clip, filterByLabel, indicator, windowFor, wrap } from "./viewport.js";
8
+ export function openBrowserArgv(href, platform = process.platform) {
9
+ if (platform === "win32")
10
+ return { command: "rundll32", args: ["url.dll,FileProtocolHandler", href] };
11
+ if (platform === "darwin")
12
+ return { command: "open", args: [href] };
13
+ return { command: "xdg-open", args: [href] };
14
+ }
15
+ export function launchBrowser(href) {
16
+ const { command, args } = openBrowserArgv(href);
17
+ try {
18
+ const child = spawn(command, args, { stdio: "ignore", detached: true, windowsHide: true });
19
+ child.on("error", () => { });
20
+ child.unref();
21
+ }
22
+ catch {
23
+ // The address is also shown on screen, so the user can open it by hand.
24
+ }
25
+ }
26
+ export const visibleOptions = (r) => filterByLabel(r.options, r.filter);
27
+ /** `onCancel` runs when Ctrl+C or Esc finds no open question, so a wait with nothing to answer can still be cancelled. */
28
+ export function createSetupDriver(launch = launchBrowser, onCancel) {
29
+ let state = { request: undefined, log: [], scrollUp: 0 };
30
+ const listeners = new Set();
31
+ const set = (next) => {
32
+ state = { ...state, ...next };
33
+ for (const listener of listeners)
34
+ listener();
35
+ };
36
+ const ask = (make) => new Promise((resolve, reject) => {
37
+ set({ scrollUp: 0, request: make((value) => { set({ request: undefined }); resolve(value); }, (error) => { set({ request: undefined }); reject(error); }) });
38
+ });
39
+ const io = {
40
+ choose: (title, options, defaultId) => {
41
+ const index = Math.max(0, options.findIndex((option) => option.id === defaultId));
42
+ return ask((resolve, reject) => ({ kind: "choose", title, options, filter: "", index, offset: 0, resolve, reject }));
43
+ },
44
+ // An abort rejects only the request it was made for, never a later one.
45
+ secret: (message, signal) => {
46
+ const pending = ask((resolve, reject) => ({ kind: "secret", message, value: "", resolve, reject }));
47
+ const mine = state.request;
48
+ signal.addEventListener("abort", () => { if (state.request === mine)
49
+ mine?.reject(new SetupCancelled()); }, { once: true });
50
+ return pending;
51
+ },
52
+ text: (message, signal, _placeholder, initial) => {
53
+ const pending = ask((resolve, reject) => ({ kind: "text", message, value: initial ?? "", resolve, reject }));
54
+ const mine = state.request;
55
+ signal.addEventListener("abort", () => { if (state.request === mine)
56
+ mine?.reject(new SetupCancelled()); }, { once: true });
57
+ return pending;
58
+ },
59
+ confirm: (message, defaultValue) => ask((resolve, reject) => ({ kind: "confirm", message, value: defaultValue, resolve, reject })),
60
+ notify: (kind, text) => set({ scrollUp: 0, log: [...state.log, { kind, text }].slice(-40) }),
61
+ openUrl: (href, instructions) => {
62
+ set({ scrollUp: 0, log: [...state.log, { kind: "info", text: `Open this address to sign in: ${href}${instructions ? `\n${instructions}` : ""}` }].slice(-40) });
63
+ launch(href);
64
+ },
65
+ };
66
+ return {
67
+ io,
68
+ state: () => state,
69
+ subscribe: (listener) => { listeners.add(listener); return () => listeners.delete(listener); },
70
+ cancelAll: () => { onCancel?.(); state.request?.reject(new SetupCancelled()); },
71
+ submit: () => {
72
+ const r = state.request;
73
+ if (r === undefined)
74
+ return;
75
+ if (r.kind === "choose") {
76
+ const option = visibleOptions(r)[r.index];
77
+ if (option !== undefined && option.disabled === undefined)
78
+ r.resolve(option.id);
79
+ }
80
+ else
81
+ r.resolve(r.value);
82
+ },
83
+ escape: () => {
84
+ const r = state.request;
85
+ if (r?.kind === "choose" && r.filter !== "") {
86
+ r.filter = "";
87
+ r.index = 0;
88
+ r.offset = 0;
89
+ set({});
90
+ return;
91
+ }
92
+ if (r === undefined)
93
+ onCancel?.();
94
+ else
95
+ r.reject(new SetupCancelled());
96
+ },
97
+ touch: () => set({}),
98
+ reset: () => set({ log: [], scrollUp: 0 }),
99
+ };
100
+ }
101
+ /** What a key means for the open request. Pure. Ctrl+C is not handled here: each caller keeps its own meaning for it. */
102
+ export function overlayKey(kind, input, key) {
103
+ if (kind === undefined)
104
+ return { t: "none" };
105
+ if (key.escape)
106
+ return { t: "escape" };
107
+ const to = key.upArrow ? "up" : key.downArrow ? "down" : key.pageUp ? "pageUp" : key.pageDown ? "pageDown" : key.home ? "home" : key.end ? "end" : undefined;
108
+ if (to !== undefined)
109
+ return { t: "move", to };
110
+ if (kind === "confirm" && !key.return) {
111
+ if (input === "y" || input === "Y")
112
+ return { t: "answer", yes: true };
113
+ if (input === "n" || input === "N")
114
+ return { t: "answer", yes: false };
115
+ return { t: "none" };
116
+ }
117
+ if (key.return)
118
+ return { t: "submit" };
119
+ if (key.backspace || key.delete)
120
+ return { t: "backspace" };
121
+ if (input.length > 0 && !key.ctrl && !key.meta && !key.tab)
122
+ return { t: "type", text: input };
123
+ return { t: "none" };
124
+ }
125
+ /** Apply an overlayKey action to the driver. `page` is the number of rows a PgUp or PgDn moves. */
126
+ export function applyOverlay(driver, action, page) {
127
+ const state = driver.state();
128
+ const r = state.request;
129
+ if (r === undefined || action.t === "none")
130
+ return;
131
+ if (action.t === "escape") {
132
+ driver.escape();
133
+ return;
134
+ }
135
+ if (action.t === "submit") {
136
+ driver.submit();
137
+ return;
138
+ }
139
+ if (action.t === "answer") {
140
+ if (r.kind === "confirm") {
141
+ r.value = action.yes;
142
+ driver.submit();
143
+ }
144
+ return;
145
+ }
146
+ if (r.kind === "choose") {
147
+ const last = Math.max(0, visibleOptions(r).length - 1);
148
+ if (action.t === "move") {
149
+ r.index = action.to === "up" ? Math.max(0, r.index - 1) : action.to === "down" ? Math.min(last, r.index + 1) : action.to === "pageUp" ? Math.max(0, r.index - page) : action.to === "pageDown" ? Math.min(last, r.index + page) : action.to === "home" ? 0 : last;
150
+ }
151
+ else {
152
+ r.filter = action.t === "backspace" ? r.filter.slice(0, -1) : r.filter + action.text;
153
+ r.index = 0;
154
+ r.offset = 0;
155
+ }
156
+ }
157
+ else if (action.t === "move") {
158
+ // Scrolling the notices works for every other kind of request.
159
+ const delta = action.to === "up" ? 1 : action.to === "down" ? -1 : action.to === "pageUp" ? page : action.to === "pageDown" ? -page : 0;
160
+ state.scrollUp = action.to === "home" ? Number.MAX_SAFE_INTEGER : action.to === "end" ? 0 : Math.max(0, state.scrollUp + delta);
161
+ }
162
+ else if (r.kind !== "confirm")
163
+ r.value = action.t === "backspace" ? r.value.slice(0, -1) : r.value + action.text;
164
+ driver.touch();
165
+ }
166
+ /* --- layout -------------------------------------------------------------------------------------------- */
167
+ /** A secret shows as this mask once something is typed, so a frame never holds the secret or its length. */
168
+ const SECRET_MASK = "********";
169
+ const HINT_CHOOSE = "Up/Down move PgUp/PgDn/Home/End jump type to filter Enter pick Esc clear/cancel";
170
+ const HINT_OTHER = "Up/Down/PgUp/PgDn/Home/End scroll Enter confirm Esc cancel";
171
+ /**
172
+ * Build the visible lines for the current request. The result never has more than `rows - 1` lines and no
173
+ * line is wider than `cols - 1` columns. The long list (or the long notice text) takes the space that is
174
+ * left after the title, the filter line and the two footer lines.
175
+ */
176
+ export function buildFrame(state, cols, rows) {
177
+ const width = Math.max(10, cols - 1);
178
+ const avail = Math.max(6, rows - 1);
179
+ const request = state.request;
180
+ const logLines = state.log.flatMap((entry) => wrap(entry.text, width).map((text) => ({ text, color: entry.kind === "error" ? THEME.error : entry.kind === "warn" ? THEME.warn : undefined })));
181
+ const out = [];
182
+ const footer = (indicatorText, hint) => [{ text: clip(indicatorText, width), dim: true }, { text: clip(hint, width), dim: true }];
183
+ if (request?.kind === "choose") {
184
+ const title = wrap(request.title, width).slice(0, 2).map((text) => ({ text, bold: true }));
185
+ const logCap = Math.max(0, Math.min(Math.floor(avail / 4), avail - title.length - 4));
186
+ const shown = logCap === 0 ? [] : logLines.slice(Math.max(0, logLines.length - logCap - state.scrollUp), logLines.length - state.scrollUp).slice(-logCap);
187
+ const list = visibleOptions(request);
188
+ const filterLine = { text: clip(request.filter === "" ? "Filter: (type to search)" : `Filter: ${request.filter}`, width), dim: request.filter === "" };
189
+ const height = Math.max(1, avail - shown.length - title.length - 1 - 2);
190
+ const index = Math.min(request.index, Math.max(0, list.length - 1));
191
+ const win = windowFor(list.length, index, request.offset, height);
192
+ request.offset = win.offset;
193
+ request.index = index;
194
+ out.push(...shown, ...title, filterLine);
195
+ for (let i = win.start; i < win.end; i += 1) {
196
+ const option = list[i];
197
+ out.push({ text: clip(`${i === index ? ">" : " "} ${option.label}${option.disabled ? ` (unavailable: ${option.disabled})` : ""}`, width), ...(i === index ? { color: THEME.accentText, bold: true } : { dim: option.disabled !== undefined }) });
198
+ }
199
+ out.push(...footer(indicator(win.start, win.end, list.length), HINT_CHOOSE));
200
+ return out.slice(0, avail);
201
+ }
202
+ const pinned = [];
203
+ if (request?.kind === "secret" || request?.kind === "text") {
204
+ const shown = request.kind === "secret" ? (request.value === "" ? "" : SECRET_MASK) : request.value;
205
+ const tail = [...shown].slice(-(width - 3)).join("");
206
+ pinned.push(...wrap(request.message, width).slice(0, 2).map((text) => ({ text, bold: true })), { text: `> ${tail}` });
207
+ }
208
+ else if (request?.kind === "confirm")
209
+ pinned.push(...wrap(`${request.message} [${request.value ? "Y/n" : "y/N"}]`, width).slice(0, 3).map((text) => ({ text, bold: true })));
210
+ const height = Math.max(1, avail - pinned.length - 2);
211
+ const total = logLines.length;
212
+ const end = Math.max(Math.min(height, total), total - state.scrollUp);
213
+ const start = Math.max(0, end - height);
214
+ out.push(...logLines.slice(start, end), ...pinned);
215
+ out.push(...footer(total > height ? indicator(start, end, total) : "", request === undefined ? "" : HINT_OTHER));
216
+ return out.slice(0, avail);
217
+ }
218
+ /* --- Ink view ---------------------------------------------------------------------------------------------- */
219
+ export function SetupView({ driver }) {
220
+ const [, force] = useState(0);
221
+ const { stdout: rawStdout } = useStdout();
222
+ const stdout = rawStdout;
223
+ const [size, setSize] = useState({ cols: stdout.columns ?? 80, rows: stdout.rows ?? 24 });
224
+ useEffect(() => driver.subscribe(() => force((n) => n + 1)), [driver]);
225
+ useEffect(() => {
226
+ const onResize = () => setSize({ cols: stdout.columns ?? 80, rows: stdout.rows ?? 24 });
227
+ stdout.on("resize", onResize);
228
+ return () => { stdout.off("resize", onResize); };
229
+ }, [stdout]);
230
+ useInput((input, key) => {
231
+ if (key.ctrl && input === "c") {
232
+ driver.cancelAll();
233
+ return;
234
+ }
235
+ applyOverlay(driver, overlayKey(driver.state().request?.kind, input, key), Math.max(1, size.rows - 8));
236
+ });
237
+ const lines = buildFrame(driver.state(), size.cols, size.rows);
238
+ return createElement(Box, { flexDirection: "column" }, ...rowsOf(lines, "l"));
239
+ }
240
+ /** Run the wizard in the terminal. Resolves when setup finishes or is cancelled. */
241
+ export async function runSetupTui(env, options = {}) {
242
+ const controller = new AbortController();
243
+ const driver = createSetupDriver(options.launch, () => controller.abort());
244
+ const app = render(createElement(SetupView, { driver }), { exitOnCtrlC: false, stdout: options.stdout, stdin: options.stdin, patchConsole: false });
245
+ // A sign-in that waits for a callback has no question open, so a cancel there ends the wait through the signal.
246
+ const cancelled = new Promise((resolve) => controller.signal.addEventListener("abort", () => resolve({ status: "cancelled" }), { once: true }));
247
+ try {
248
+ const run = runSetup(env, driver.io, controller.signal);
249
+ run.catch(() => { });
250
+ return await Promise.race([run, cancelled]);
251
+ }
252
+ finally {
253
+ controller.abort();
254
+ app.unmount();
255
+ }
256
+ }
@@ -0,0 +1,26 @@
1
+ // The palette. Body text sets no color and uses the terminal default (white, set with OSC 10 in main.ts).
2
+ // Labels, state words and the picker selection use accentText; borders, bars and the prompt use accent.
3
+ // Contrast on #1A1A1A: accent 2.27 (decoration only), accentText 4.87, muted 5.18, ok 9.85, warn 9.36, error 5.85.
4
+ export const ACCENT_TEXT = "#EC4D73";
5
+ export const THEME = {
6
+ accent: "#A4133C",
7
+ accentText: ACCENT_TEXT,
8
+ muted: "#8C8C8C",
9
+ border: "#3A3A3A",
10
+ ok: "#3DDC97",
11
+ warn: "#E5B84B",
12
+ error: "#FF5C7A",
13
+ };
14
+ /**
15
+ * The terminal default colors as OSC 10 (foreground) and OSC 11 (background), and the sequences that reset them.
16
+ * Undefined when there is no terminal, or colors are off: the same rule as bin/piroboros.mjs (NO_COLOR with FORCE_COLOR unset,
17
+ * or FORCE_COLOR 0 or false, which chalk reads as level 0).
18
+ */
19
+ export function themeSequences(env, tty) {
20
+ if (!tty || env.FORCE_COLOR === "0" || env.FORCE_COLOR === "false")
21
+ return undefined;
22
+ if (env.NO_COLOR !== undefined && env.NO_COLOR !== "" && env.FORCE_COLOR === undefined)
23
+ return undefined;
24
+ const osc = (body) => `\u{1B}]${body}\u{7}`;
25
+ return { start: `${osc("10;rgb:ff/ff/ff")}${osc("11;rgb:1a/1a/1a")}`, end: `${osc("110")}${osc("111")}` };
26
+ }