piroboros 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/NOTICE +39 -0
- package/README.md +219 -2
- package/agents/astrelia.md +31 -0
- package/agents/avaritia.md +31 -0
- package/agents/elaria.md +31 -0
- package/agents/nytheria.md +32 -0
- package/agents/raskreia.md +32 -0
- package/agents/samaela.md +40 -0
- package/agents/vaelia.md +35 -0
- package/agents/vesperia.md +45 -0
- package/bin/piroboros.mjs +17 -0
- package/dist/auth.js +105 -0
- package/dist/base.js +19 -0
- package/dist/chat/budget.js +87 -0
- package/dist/chat/compactloop.js +63 -0
- package/dist/chat/compactor.js +529 -0
- package/dist/chat/extension.js +36 -0
- package/dist/chat/hook.js +40 -0
- package/dist/chat/log.js +316 -0
- package/dist/chat/outbound.js +114 -0
- package/dist/chat/plan.js +63 -0
- package/dist/chat/prompt.js +115 -0
- package/dist/chat/status.js +37 -0
- package/dist/chat/stuck.js +83 -0
- package/dist/chat/tools.js +163 -0
- package/dist/chat/tree.js +72 -0
- package/dist/chat/turn.js +305 -0
- package/dist/chat/view.js +163 -0
- package/dist/conclave/agents.js +113 -0
- package/dist/conclave/pipeline.js +715 -0
- package/dist/conclave/report.js +43 -0
- package/dist/config.js +608 -0
- package/dist/durable.js +112 -0
- package/dist/guard.js +346 -0
- package/dist/lock.js +56 -0
- package/dist/main.js +354 -0
- package/dist/memory/akashic/api.js +121 -0
- package/dist/memory/akashic/confusables.js +41 -0
- package/dist/memory/akashic/scanner.js +67 -0
- package/dist/memory/akashic/snapshot.js +31 -0
- package/dist/memory/akashic/store.js +1254 -0
- package/dist/memory/akashic/tools.js +168 -0
- package/dist/memory/akashic/vault.js +984 -0
- package/dist/memory/host.js +124 -0
- package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
- package/dist/memory/mnemosia/adapters/contract.js +219 -0
- package/dist/memory/mnemosia/agents.js +387 -0
- package/dist/memory/mnemosia/brief.js +890 -0
- package/dist/memory/mnemosia/claims.js +609 -0
- package/dist/memory/mnemosia/conflicts.js +769 -0
- package/dist/memory/mnemosia/escalation.js +257 -0
- package/dist/memory/mnemosia/feedback.js +108 -0
- package/dist/memory/mnemosia/filters.js +248 -0
- package/dist/memory/mnemosia/intent.js +221 -0
- package/dist/memory/mnemosia/open.js +34 -0
- package/dist/memory/mnemosia/orchestrator.js +926 -0
- package/dist/memory/mnemosia/plan.js +266 -0
- package/dist/memory/mnemosia/policy.js +426 -0
- package/dist/memory/mnemosia/progressive.js +550 -0
- package/dist/memory/mnemosia/provenance.js +458 -0
- package/dist/memory/mnemosia/qualifiers.js +428 -0
- package/dist/memory/mnemosia/rank.js +525 -0
- package/dist/memory/mnemosia/relations.js +156 -0
- package/dist/memory/mnemosia/requirements.js +138 -0
- package/dist/memory/mnemosia/rerank.js +253 -0
- package/dist/memory/mnemosia/retention.js +174 -0
- package/dist/memory/mnemosia/rollback.js +337 -0
- package/dist/memory/mnemosia/select.js +607 -0
- package/dist/memory/mnemosia/similarity.js +164 -0
- package/dist/memory/mnemosia/situation.js +251 -0
- package/dist/memory/mnemosia/task.js +418 -0
- package/dist/memory/mnemosia/temporal.js +136 -0
- package/dist/memory/mnemosia/tokens.js +66 -0
- package/dist/memory/mnemosia/tools.js +160 -0
- package/dist/memory/mnemosia/trace.js +306 -0
- package/dist/memory/mnemosia/types.js +298 -0
- package/dist/models.js +360 -0
- package/dist/paths.js +103 -0
- package/dist/redact.js +79 -0
- package/dist/runtime.js +354 -0
- package/dist/search-format.js +102 -0
- package/dist/search.js +351 -0
- package/dist/setup.js +366 -0
- package/dist/shell.js +110 -0
- package/dist/skills.js +311 -0
- package/dist/tui/app.js +1009 -0
- package/dist/tui/commands.js +120 -0
- package/dist/tui/keys.js +83 -0
- package/dist/tui/pane.js +387 -0
- package/dist/tui/panel.js +60 -0
- package/dist/tui/picker.js +25 -0
- package/dist/tui/sanitize.js +59 -0
- package/dist/tui/settings.js +198 -0
- package/dist/tui/setup.js +256 -0
- package/dist/tui/theme.js +26 -0
- package/dist/tui/thinking/parse.js +1094 -0
- package/dist/tui/thinking/select.js +86 -0
- package/dist/tui/thinking/state.js +137 -0
- package/dist/tui/thinking/types.js +3 -0
- package/dist/tui/thinking/view.js +74 -0
- package/dist/tui/viewport.js +208 -0
- package/dist/undo.js +258 -0
- package/dist/web.js +933 -0
- package/models.json.example +34 -0
- package/package.json +62 -4
- package/settings.json.example +28 -0
- package/skills/conclave/SKILL.md +76 -0
package/dist/tui/app.js
ADDED
|
@@ -0,0 +1,1009 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import stringWidth from "string-width";
|
|
3
|
+
import { createElement, useEffect, useRef, useState } from "react";
|
|
4
|
+
import { Box, render, useApp, useCursor, useInput, usePaste, useStdout } from "ink";
|
|
5
|
+
import { ctx, LiveDoc, recentEntries, ROOT, SessionFailed } from "../durable.js";
|
|
6
|
+
import { PendingDoc } from "../chat/turn.js";
|
|
7
|
+
import { statusText } from "../chat/status.js";
|
|
8
|
+
import { isStuckStop, STUCK_STOP_CODE } from "../chat/stuck.js";
|
|
9
|
+
import { ViewDoc } from "../chat/tree.js";
|
|
10
|
+
import { viewBanner } from "../chat/view.js";
|
|
11
|
+
import { COMMANDS, suggest, unknownCommand } from "./commands.js";
|
|
12
|
+
import { skillsReport } from "../skills.js";
|
|
13
|
+
import { runSettings, SECURITY_CONFIRM } from "./settings.js";
|
|
14
|
+
import { route } from "./keys.js";
|
|
15
|
+
import { ConclavePane, formatDuration, paneLines, paneVisible, pill, rightPanelLines, seatsOf, SIDE_BY_SIDE_MIN_COLUMNS, textOf, toolCallParts, toolCallText, usePane } from "./pane.js";
|
|
16
|
+
import { panelLines, SessionPanel } from "./panel.js";
|
|
17
|
+
import { buildPicker, PICKER_MAX_ROWS } from "./picker.js";
|
|
18
|
+
import { rowsOf } from "./sanitize.js";
|
|
19
|
+
import { applyOverlay, buildFrame, createSetupDriver } from "./setup.js";
|
|
20
|
+
import { THEME } from "./theme.js";
|
|
21
|
+
import { allocate, chatIndicator, chatWindow, clip, dropLast, spanLine, spanRow, spansOf, tail, wrap } from "./viewport.js";
|
|
22
|
+
import { runLogin, SetupCancelled } from "../setup.js";
|
|
23
|
+
import { modelChoices, providerChoices, resolveModel } from "../models.js";
|
|
24
|
+
import { redactSensitive } from "../redact.js";
|
|
25
|
+
import { checkPath } from "../guard.js";
|
|
26
|
+
import { apply, loadRun, plan, preview } from "../undo.js";
|
|
27
|
+
import { CONCLAVE_MEMBERS, securityChanges, THINKING_LEVELS, withDefaults } from "../config.js";
|
|
28
|
+
import { searchKey, VERSION } from "../web.js";
|
|
29
|
+
import { parseThinkingMode } from "./thinking/parse.js";
|
|
30
|
+
import { thinkingBlocksOf } from "./thinking/state.js";
|
|
31
|
+
import { thinkingLines } from "./thinking/view.js";
|
|
32
|
+
/** Provider bodies are often JSON. Show the message inside, and keep the text short. */
|
|
33
|
+
export function friendlyError(raw, max = 240) {
|
|
34
|
+
let text = raw.trim();
|
|
35
|
+
const start = text.indexOf("{");
|
|
36
|
+
if (start >= 0) {
|
|
37
|
+
try {
|
|
38
|
+
const parsed = JSON.parse(text.slice(start));
|
|
39
|
+
const inner = typeof parsed.message === "string" ? parsed.message : typeof parsed.error === "string" ? parsed.error : typeof parsed.error?.message === "string" ? parsed.error.message : undefined;
|
|
40
|
+
if (inner !== undefined)
|
|
41
|
+
text = `${text.slice(0, start).trim()} ${inner}`.trim();
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// Cut-off JSON (a clipped report line, more braces opened than closed): take the message string that is there.
|
|
45
|
+
const json = text.slice(start);
|
|
46
|
+
const cut = (json.match(/\{/gu)?.length ?? 0) > (json.match(/\}/gu)?.length ?? 0) ? /"message"\s*:\s*"((?:[^"\\]|\\.)*)/u.exec(json)?.[1] : undefined;
|
|
47
|
+
if (cut !== undefined) {
|
|
48
|
+
let inner = cut;
|
|
49
|
+
try {
|
|
50
|
+
inner = JSON.parse(`"${cut}"`);
|
|
51
|
+
}
|
|
52
|
+
catch { /* the cut fell inside an escape; keep it as is */ }
|
|
53
|
+
text = `${text.slice(0, start).trim()} ${inner}`.trim();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
text = text.replace(/\s+/gu, " ");
|
|
58
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
59
|
+
}
|
|
60
|
+
export const ERROR_HINT = "use /model to switch models, or /login to sign in";
|
|
61
|
+
/** The next step for a failed turn, from what the provider said. Anything unrecognized gets the general hint. */
|
|
62
|
+
export function errorHint(message) {
|
|
63
|
+
if (/\b(ECONNREFUSED|ECONNRESET|ENOTFOUND|ETIMEDOUT|EAI_AGAIN)\b|fetch failed/iu.test(message))
|
|
64
|
+
return "Could not reach the provider. Check the network, or use /model to pick another.";
|
|
65
|
+
if (/\b(401|403)\b/u.test(message))
|
|
66
|
+
return "Use /login to sign in again.";
|
|
67
|
+
if (/\b429\b|rate limit/iu.test(message))
|
|
68
|
+
return "Wait a moment, then send again.";
|
|
69
|
+
if (/\b404\b|unavailable/iu.test(message))
|
|
70
|
+
return "Use /model to pick another model.";
|
|
71
|
+
return ERROR_HINT;
|
|
72
|
+
}
|
|
73
|
+
/** The parts of the status line, before they are joined. Each flag leaves its part out when false. */
|
|
74
|
+
export function statusParts(input, opts = {}) {
|
|
75
|
+
const parts = [];
|
|
76
|
+
if (input.busy === true)
|
|
77
|
+
parts.push("working (Esc stops)");
|
|
78
|
+
else if (input.failed !== undefined)
|
|
79
|
+
parts.push(`ERROR ${friendlyError(input.failed, 60)}`);
|
|
80
|
+
if (input.last !== undefined) {
|
|
81
|
+
const used = `${input.last.provider}/${input.last.model}`;
|
|
82
|
+
parts.push(input.last.responseModel !== undefined && input.last.responseModel !== input.last.model ? `${used} → ${input.last.responseModel}` : used);
|
|
83
|
+
if (opts.cache !== false)
|
|
84
|
+
parts.push(`cache read ${input.last.cacheRead} write ${input.last.cacheWrite}`);
|
|
85
|
+
}
|
|
86
|
+
else
|
|
87
|
+
parts.push(input.main ?? "no model set");
|
|
88
|
+
if (opts.compactor !== false)
|
|
89
|
+
parts.push(`compactor: ${input.compactor}`);
|
|
90
|
+
if (opts.thinking !== false)
|
|
91
|
+
parts.push(`thinking: ${input.thinking}`);
|
|
92
|
+
if (input.memory?.pendingSync)
|
|
93
|
+
parts.push("vault: sync pending");
|
|
94
|
+
if ((input.memory?.quarantined ?? 0) > 0)
|
|
95
|
+
parts.push(`memory quarantined: ${input.memory.quarantined}`);
|
|
96
|
+
if ((input.memory?.proposed ?? 0) > 0)
|
|
97
|
+
parts.push(`memory proposed: ${input.memory.proposed}`);
|
|
98
|
+
return parts;
|
|
99
|
+
}
|
|
100
|
+
/** What the status line drops, in order, until it fits. */
|
|
101
|
+
const STATUS_STAGES = [[true, true, true], [false, true, true], [false, false, true], [false, false, false]];
|
|
102
|
+
/**
|
|
103
|
+
* The status line. With a width it drops the cache counts, then the compactor, then the thinking level until it fits, and
|
|
104
|
+
* clips what is left. While a turn runs it starts with `working (Esc stops)` and shows no error from an earlier turn.
|
|
105
|
+
* `cache: false` never shows the cache counts (the stat strip shows them).
|
|
106
|
+
*/
|
|
107
|
+
export function formatStatus(input, width, opts = {}) {
|
|
108
|
+
const build = (cache, compactor, thinking) => statusParts(input, { cache: cache && opts.cache !== false, compactor, thinking }).join(" | ");
|
|
109
|
+
if (width === undefined)
|
|
110
|
+
return build(true, true, true);
|
|
111
|
+
for (const [cache, compactor, thinking] of STATUS_STAGES) {
|
|
112
|
+
if (cache && opts.cache === false)
|
|
113
|
+
continue;
|
|
114
|
+
const text = build(cache, compactor, thinking);
|
|
115
|
+
if (stringWidth(text) <= width)
|
|
116
|
+
return text;
|
|
117
|
+
}
|
|
118
|
+
return clip(build(false, false, false), width);
|
|
119
|
+
}
|
|
120
|
+
/** The status row of the framed layout: the parts that fit, muted, joined by an accent bar. */
|
|
121
|
+
function statusSpans(input, width, cache) {
|
|
122
|
+
const spans = (parts) => parts.flatMap((part, i) => [...(i === 0 ? [] : [{ text: " │ ", color: THEME.accent }]), { text: part, color: THEME.muted }]);
|
|
123
|
+
for (const [withCache, compactor, thinking] of STATUS_STAGES) {
|
|
124
|
+
if (withCache && !cache)
|
|
125
|
+
continue;
|
|
126
|
+
const row = spans(statusParts(input, { cache: withCache, compactor, thinking }));
|
|
127
|
+
if (stringWidth(row.map((span) => span.text).join("")) <= width)
|
|
128
|
+
return row;
|
|
129
|
+
}
|
|
130
|
+
return spanRow(spans(statusParts(input, { cache: false, compactor: false, thinking: false })), width);
|
|
131
|
+
}
|
|
132
|
+
const COUNT = (n) => (n < 1000 ? String(n) : `${(Math.round(n / 100) / 10).toFixed(1)}k`);
|
|
133
|
+
/** The stat strip of the last good reply: IN, OUT, CACHE (cache read of the prompt) and CTX (prompt and output of the window). Undefined without a reply. */
|
|
134
|
+
export function statsOf(last, contextWindow) {
|
|
135
|
+
if (last === undefined)
|
|
136
|
+
return undefined;
|
|
137
|
+
const input = last.input ?? 0;
|
|
138
|
+
const output = last.output ?? 0;
|
|
139
|
+
const prompt = input + last.cacheRead + last.cacheWrite;
|
|
140
|
+
const stats = [["IN", COUNT(input)], ["OUT", COUNT(output)]];
|
|
141
|
+
if (prompt > 0)
|
|
142
|
+
stats.push(["CACHE", `${Math.round((last.cacheRead / prompt) * 100)}%`]);
|
|
143
|
+
if (contextWindow !== undefined && contextWindow > 0)
|
|
144
|
+
stats.push(["CTX", `${Math.round(((prompt + output) / contextWindow) * 100)}%`]);
|
|
145
|
+
return stats.flatMap(([label, value], i) => [...(i === 0 ? [] : [{ text: " │ ", color: THEME.accent }]), { text: `${label} `, color: THEME.muted }, { text: value }]);
|
|
146
|
+
}
|
|
147
|
+
/** The dot and words at the right of the header. A running turn wins; then the status; anything else is ready. */
|
|
148
|
+
export function headerWords(running, status) {
|
|
149
|
+
if (running)
|
|
150
|
+
return { color: THEME.accent, words: "working (Esc stops)" };
|
|
151
|
+
switch (status.kind) {
|
|
152
|
+
case "unconfigured": return { color: THEME.error, words: "no model set" };
|
|
153
|
+
case "login_required": return { color: THEME.error, words: "login required" };
|
|
154
|
+
case "turn_failed": return { color: THEME.error, words: `ERROR ${friendlyError(status.message, 40)}` };
|
|
155
|
+
case "error": return { color: THEME.error, words: "error" };
|
|
156
|
+
case "stopped": return { color: THEME.error, words: "stopped" };
|
|
157
|
+
default: return { color: THEME.ok, words: "ready" };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/** What the header drops, in order, until it fits: the version, the member count, the Conclave count. The state words are clipped last. */
|
|
161
|
+
const HEADER_STAGES = [[true, true, true], [false, true, true], [false, false, true], [false, false, false]];
|
|
162
|
+
/** The header row: the name and version at the left, the state, the member count and the Conclave count (while a pipeline is live) at the right. */
|
|
163
|
+
export function headerRow(running, status, conclave, width) {
|
|
164
|
+
const { color, words } = headerWords(running, status);
|
|
165
|
+
const size = (spans) => stringWidth(spans.map((span) => span.text).join(""));
|
|
166
|
+
const build = (version, members, count) => ({
|
|
167
|
+
left: [{ text: "◆ ", color: THEME.accent }, { text: "piroboros", color: THEME.accentText, bold: true }, ...(version ? [{ text: ` v${VERSION}`, color: THEME.muted }] : [])],
|
|
168
|
+
right: [{ text: "● ", color }, { text: words }, ...(members ? [{ text: " │ ", color: THEME.accent }, { text: `${CONCLAVE_MEMBERS.length} members`, color: THEME.muted }] : []), ...(count && conclave !== undefined ? [{ text: ` conclave ${conclave.done}/${conclave.total}`, color: THEME.muted }] : [])],
|
|
169
|
+
});
|
|
170
|
+
const stage = HEADER_STAGES.find(([version, members, count]) => { const { left, right } = build(version, members, count); return size(left) + 2 + size(right) <= width; }) ?? HEADER_STAGES.at(-1);
|
|
171
|
+
const { left, right } = build(stage[0], stage[1], stage[2]);
|
|
172
|
+
return spanLine([...left, { text: " ".repeat(Math.max(2, width - size(left) - size(right))) }, ...right], width);
|
|
173
|
+
}
|
|
174
|
+
/** A full-width rule in the border color. */
|
|
175
|
+
const ruleLine = (width) => spanLine([{ text: "─".repeat(width), color: THEME.border }], width);
|
|
176
|
+
/** The local HH:MM of an epoch time in ms. */
|
|
177
|
+
const clock = (ms) => { const at = new Date(ms); return `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}`; };
|
|
178
|
+
/** The row of the input in the frame: the rows built above it, plus the top border of the input box when framed. */
|
|
179
|
+
export function inputRowIndex(parts, framed) {
|
|
180
|
+
return parts.reduce((sum, rows) => sum + rows, 0) + (framed ? 1 : 0);
|
|
181
|
+
}
|
|
182
|
+
export function linesOf(entries) {
|
|
183
|
+
const out = [];
|
|
184
|
+
// The marker entry before a user entry says which of its blocks are Conclave reports.
|
|
185
|
+
let marker;
|
|
186
|
+
for (const entry of entries.slice().reverse()) {
|
|
187
|
+
if (entry.kind === "piroboros.turn") {
|
|
188
|
+
const items = entry.data?.items;
|
|
189
|
+
marker = Array.isArray(items) ? items : [];
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
const message = entry.model?.[0];
|
|
193
|
+
if (message === undefined)
|
|
194
|
+
continue;
|
|
195
|
+
const failed = message;
|
|
196
|
+
if (failed.role === "assistant" && failed.stopReason === "error") {
|
|
197
|
+
out.push({ key: `${entry.id}e`, role: "error", text: `error: ${failed.provider ?? "?"}/${failed.model ?? "?"}: ${friendlyError(failed.errorMessage ?? "the provider returned an error")}` });
|
|
198
|
+
out.push({ key: `${entry.id}h`, role: "hint", text: errorHint(failed.errorMessage ?? "") });
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (isStuckStop(entry)) {
|
|
202
|
+
out.push({ key: `${entry.id}s`, role: "error", text: `stopped (${STUCK_STOP_CODE}): the same call kept failing, so the turn was ended` });
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
const content = message.content;
|
|
206
|
+
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content.filter((block) => block !== null && typeof block === "object") : [];
|
|
207
|
+
const textOnly = blocks.map((block) => (block.type === "text" ? block.text ?? "" : "")).join("");
|
|
208
|
+
if (message.role === "user") {
|
|
209
|
+
const items = marker;
|
|
210
|
+
marker = undefined;
|
|
211
|
+
let user = [];
|
|
212
|
+
let firstUser = true;
|
|
213
|
+
const flush = (at) => {
|
|
214
|
+
if (user.length > 0)
|
|
215
|
+
out.push({ key: firstUser ? String(entry.id) : `${entry.id}u${at}`, role: "user", text: user.join("\n") });
|
|
216
|
+
if (user.length > 0)
|
|
217
|
+
firstUser = false;
|
|
218
|
+
user = [];
|
|
219
|
+
};
|
|
220
|
+
blocks.forEach((block, k) => {
|
|
221
|
+
const text = block.type === "text" ? block.text ?? "" : "";
|
|
222
|
+
if (text === "")
|
|
223
|
+
return;
|
|
224
|
+
const item = items?.[k];
|
|
225
|
+
if (item?.source !== "conclave") {
|
|
226
|
+
user.push(text);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
flush(k);
|
|
230
|
+
const named = /^\[([^\]\n]*)\] report\n?/u.exec(text);
|
|
231
|
+
const member = typeof item.member === "string" ? item.member : named?.[1] ?? "member";
|
|
232
|
+
const body = named === null ? text : text.slice(named[0].length);
|
|
233
|
+
const [first = "", ...rest] = body.split("\n");
|
|
234
|
+
out.push({ key: `${entry.id}:${k}`, role: "report", member, failed: first.startsWith("FAILED"), text: (first.startsWith("FAILED") ? [friendlyError(first), ...rest] : [first, ...rest]).join("\n") });
|
|
235
|
+
});
|
|
236
|
+
flush(blocks.length);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (message.role === "toolResult") {
|
|
240
|
+
if (textOnly.length === 0)
|
|
241
|
+
continue;
|
|
242
|
+
if (message.isError === true) {
|
|
243
|
+
const detail = textOnly.replace(/<\/?harness>/gu, "").trim().replace(/^\[error\] ?/u, "");
|
|
244
|
+
out.push({ key: String(entry.id), role: "error", bounded: true, text: `tool error (${message.toolName ?? "tool"}): ${detail}`, toolName: message.toolName ?? "tool", detail });
|
|
245
|
+
}
|
|
246
|
+
else
|
|
247
|
+
out.push({ key: String(entry.id), role: "tool", bounded: true, text: textOnly });
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
const callBlocks = blocks.filter((block) => block.type === "toolCall");
|
|
251
|
+
const calls = callBlocks.map((block) => toolCallText(block));
|
|
252
|
+
const text = message.role === "assistant" ? [textOnly, ...calls].filter((part) => part !== "").join("\n") : textOnly;
|
|
253
|
+
if (text.length === 0)
|
|
254
|
+
continue;
|
|
255
|
+
const thinking = message.role === "assistant" ? thinkingBlocksOf(message) : undefined;
|
|
256
|
+
out.push({ key: String(entry.id), role: message.role === "assistant" ? "assistant" : "system", text, ...(message.role === "assistant" ? { body: textOnly, calls: callBlocks.map((block) => toolCallParts(block)) } : {}), ...(thinking === undefined || (textOnly === "" && thinking.length === 0) ? {} : { thinking }) });
|
|
257
|
+
}
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
export function lastResponseOf(entries) {
|
|
261
|
+
for (const entry of entries) {
|
|
262
|
+
const message = entry.model?.[0];
|
|
263
|
+
// An errored reply carries zero usage; the status and the stat strip show the last good one.
|
|
264
|
+
if (message?.role !== "assistant" || message.stopReason === "error")
|
|
265
|
+
continue;
|
|
266
|
+
const usage = (message.usage ?? {});
|
|
267
|
+
return {
|
|
268
|
+
provider: String(message.provider ?? ""),
|
|
269
|
+
model: String(message.model ?? ""),
|
|
270
|
+
...(typeof message.responseModel === "string" ? { responseModel: message.responseModel } : {}),
|
|
271
|
+
cacheRead: usage.cacheRead ?? 0,
|
|
272
|
+
cacheWrite: usage.cacheWrite ?? 0,
|
|
273
|
+
input: usage.input ?? 0,
|
|
274
|
+
output: usage.output ?? 0,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
return undefined;
|
|
278
|
+
}
|
|
279
|
+
const IDLE_KEYS = "Enter sends, / commands, PgUp scrolls, Ctrl+T thinking, Ctrl+C exits";
|
|
280
|
+
const RUNNING_KEYS = "Esc or Ctrl+C stops the turn, PgUp scrolls";
|
|
281
|
+
const ASSISTANT_LABEL = "◆ piroboros";
|
|
282
|
+
const INDENT = " ";
|
|
283
|
+
const moreText = (n) => `(${n} more ${n === 1 ? "line" : "lines"})`;
|
|
284
|
+
/** A row moved right by the indent of a framed entry. */
|
|
285
|
+
const indented = (line) => ({ text: INDENT + line.text, spans: [{ text: INDENT }, ...spansOf(line)] });
|
|
286
|
+
/** Tool output: 3 rows at most. Each source line is cut to 6 widths, and the rest is counted. */
|
|
287
|
+
function capRows(source, width) {
|
|
288
|
+
const sourceLines = source.replace(/\s+$/u, "").split("\n");
|
|
289
|
+
const rows = [];
|
|
290
|
+
let whole = 0;
|
|
291
|
+
for (const text of sourceLines) {
|
|
292
|
+
const wrapped = wrap([...text].slice(0, 6 * width).join(""), width);
|
|
293
|
+
if (rows.length + wrapped.length > 3) {
|
|
294
|
+
rows.push(...wrapped.slice(0, 3 - rows.length));
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
rows.push(...wrapped);
|
|
298
|
+
whole += 1;
|
|
299
|
+
}
|
|
300
|
+
return { rows, more: whole < sourceLines.length ? sourceLines.length - whole : 0 };
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* The group a framed line belongs to, which decides its label row. You, piroboros (replies, tool calls, tool results and tool
|
|
304
|
+
* errors) and each report are groups. Errors, system lines and hints have none and never change the current group.
|
|
305
|
+
*/
|
|
306
|
+
export function groupOf(line) {
|
|
307
|
+
if (line.role === "user")
|
|
308
|
+
return "user";
|
|
309
|
+
if (line.role === "assistant" || line.role === "tool" || (line.role === "error" && line.bounded === true))
|
|
310
|
+
return "assistant";
|
|
311
|
+
return line.role === "report" ? `report:${line.key}` : undefined;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Which framed lines start a group (a label row), and which of those are user labels (a blank row before them), plus the group
|
|
315
|
+
* the chat ends in. A label row comes when the group differs from that of the last line that has one.
|
|
316
|
+
*/
|
|
317
|
+
export function labelPlan(lines) {
|
|
318
|
+
let group;
|
|
319
|
+
const marks = lines.map((line) => {
|
|
320
|
+
const next = groupOf(line);
|
|
321
|
+
const label = next !== undefined && next !== group;
|
|
322
|
+
if (next !== undefined)
|
|
323
|
+
group = next;
|
|
324
|
+
return { label, blank: label && line.role === "user" };
|
|
325
|
+
});
|
|
326
|
+
return { marks, group };
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* The rows of one entry in the framed layout: an optional divider row (a rule across the chat) and label row, the thinking rows (already indented), then the
|
|
330
|
+
* body indented by 2. `width` is the inner width of the chat box. The text of every row stays one span per piece the app chooses.
|
|
331
|
+
* A report's label ends with a pill (done or failed, or the `badge` state) and, when the app has one for it, the `(2m 14s)` duration: render only, never stored.
|
|
332
|
+
*/
|
|
333
|
+
export function framedRows(line, { label, blank, width, thinking = [], badge }) {
|
|
334
|
+
const rows = [];
|
|
335
|
+
if (blank)
|
|
336
|
+
rows.push(ruleLine(width));
|
|
337
|
+
const report = [{ text: `◆ ${line.member ?? "member"} report`, color: THEME.accentText, bold: true }, { text: " " }, pill(badge?.state ?? (line.failed === true ? "failed" : "done")), ...(badge?.duration === undefined ? [] : [{ text: ` (${badge.duration})`, color: THEME.muted }])];
|
|
338
|
+
if (label)
|
|
339
|
+
rows.push(spanLine(line.role === "user" ? [{ text: "● ", color: THEME.accent }, { text: "You", bold: true }] : line.role === "report" ? report : [{ text: ASSISTANT_LABEL, color: THEME.accentText, bold: true }], width));
|
|
340
|
+
const body = Math.max(1, width - 2);
|
|
341
|
+
const indent = (text, color) => wrap(text, body).map((row) => ({ text: INDENT + row, ...(color === undefined ? {} : { color }) }));
|
|
342
|
+
if (line.role === "error" && line.bounded !== true)
|
|
343
|
+
return [...rows, ...wrap(`✗ ${line.text}`, width).map((text) => ({ text, color: THEME.error }))];
|
|
344
|
+
if (line.role === "system")
|
|
345
|
+
return [...rows, ...wrap(`system: ${line.text}`, width).map((text) => ({ text }))];
|
|
346
|
+
if (line.role === "hint")
|
|
347
|
+
return [...rows, ...indent(line.text, THEME.muted)];
|
|
348
|
+
if (line.role === "tool") {
|
|
349
|
+
const capped = capRows(line.text, body);
|
|
350
|
+
return [...rows, ...capped.rows.map((row) => ({ text: INDENT + row, color: THEME.muted })), ...(capped.more > 0 ? [{ text: INDENT + moreText(capped.more), color: THEME.muted }] : [])];
|
|
351
|
+
}
|
|
352
|
+
if (line.role === "error") {
|
|
353
|
+
// A tool error: the cross and the tool in bold, then the error text, in at most 3 rows.
|
|
354
|
+
const head = `✗ ${line.toolName ?? "tool"} `;
|
|
355
|
+
const capped = capRows(head + (line.detail ?? line.text), body);
|
|
356
|
+
const errorRows = capped.rows.map((row, i) => (i === 0 && row.startsWith(head)
|
|
357
|
+
? spanLine([{ text: INDENT }, { text: "✗ ", color: THEME.error }, { text: line.toolName ?? "tool", color: THEME.error, bold: true }, { text: ` ${row.slice(head.length)}`, color: THEME.error }], width)
|
|
358
|
+
: { text: INDENT + row, color: THEME.error }));
|
|
359
|
+
return [...rows, ...errorRows, ...(capped.more > 0 ? [{ text: INDENT + moreText(capped.more), color: THEME.error }] : [])];
|
|
360
|
+
}
|
|
361
|
+
if (line.role === "assistant") {
|
|
362
|
+
rows.push(...thinking);
|
|
363
|
+
const text = line.body ?? line.text;
|
|
364
|
+
if (text !== "")
|
|
365
|
+
rows.push(...indent(text));
|
|
366
|
+
for (const call of line.calls ?? [])
|
|
367
|
+
rows.push(spanLine([{ text: INDENT }, { text: "▸ ", color: THEME.accent }, { text: call.name, bold: true }, ...(call.arg === undefined ? [] : [{ text: " " }, { text: call.arg, color: THEME.muted }])], width));
|
|
368
|
+
return rows;
|
|
369
|
+
}
|
|
370
|
+
return [...rows, ...indent(line.text)];
|
|
371
|
+
}
|
|
372
|
+
export { unknownCommand };
|
|
373
|
+
const MODE_WORDS = "collapsed, summary or expanded";
|
|
374
|
+
/** /thinking-steps [mode] sets the session mode; /thinking-steps global <mode|clear> writes settings.json and sets the session mode too. */
|
|
375
|
+
function thinkingStepsCommand(rt, args) {
|
|
376
|
+
if (args.length === 0)
|
|
377
|
+
return `thinking steps: ${rt.thinking.mode()}`;
|
|
378
|
+
if (args[0] === "global") {
|
|
379
|
+
const value = args[1]?.toLowerCase() === "clear" ? "clear" : args[1] === undefined ? undefined : parseThinkingMode(args[1]);
|
|
380
|
+
if (args.length !== 2 || value === undefined)
|
|
381
|
+
return "usage: /thinking-steps global <collapsed|summary|expanded|clear>";
|
|
382
|
+
try {
|
|
383
|
+
rt.thinking.setGlobal(value);
|
|
384
|
+
}
|
|
385
|
+
catch (error) {
|
|
386
|
+
return `thinking steps not saved: ${error instanceof Error ? error.message : String(error)}`;
|
|
387
|
+
}
|
|
388
|
+
return value === "clear" ? `global thinking steps cleared; this session shows ${rt.thinking.mode()}` : `global thinking steps set to ${value}`;
|
|
389
|
+
}
|
|
390
|
+
const mode = args.length === 1 ? parseThinkingMode(args[0]) : undefined;
|
|
391
|
+
if (mode === undefined)
|
|
392
|
+
return `unknown mode; use ${MODE_WORDS}`;
|
|
393
|
+
rt.thinking.set(mode);
|
|
394
|
+
return `thinking steps: ${mode} for this session`;
|
|
395
|
+
}
|
|
396
|
+
/** A flow's reply: a cancelled flow and a failed one both end as text, never as an unhandled rejection, and nothing secret-shaped is shown. */
|
|
397
|
+
const settled = (run, cancelled) => run.then(redactSensitive, (error) => (error instanceof SetupCancelled ? cancelled : redactSensitive(`failed: ${error instanceof Error ? error.message : String(error)}`)));
|
|
398
|
+
const NEEDS_CHAT = (name) => `/${name} needs the chat screen`;
|
|
399
|
+
/** Whether a search provider has no key, reading auth.json only when its mtime or the provider changed (a login rewrites it). */
|
|
400
|
+
export function missingKeyCheck(authPath, env = process.env) {
|
|
401
|
+
let stamp;
|
|
402
|
+
let missing = false;
|
|
403
|
+
return (provider) => {
|
|
404
|
+
let mtime = "none";
|
|
405
|
+
try {
|
|
406
|
+
mtime = String(statSync(authPath).mtimeMs);
|
|
407
|
+
}
|
|
408
|
+
catch { /* no auth.json yet */ }
|
|
409
|
+
const next = `${provider}:${mtime}`;
|
|
410
|
+
if (next !== stamp) {
|
|
411
|
+
stamp = next;
|
|
412
|
+
missing = searchKey(provider, authPath, env) === undefined;
|
|
413
|
+
}
|
|
414
|
+
return missing;
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
/** /conclave undo: list what it would do, ask, then restore the pre-images of the last Vesperia run. */
|
|
418
|
+
async function undoCommand(rt, ask) {
|
|
419
|
+
if (await rt.conclave.live())
|
|
420
|
+
return "undo not run: a pipeline is running; /conclave cancel stops it";
|
|
421
|
+
const home = rt.guard.config().home;
|
|
422
|
+
const folder = loadRun(home);
|
|
423
|
+
if (folder === undefined)
|
|
424
|
+
return "nothing to undo";
|
|
425
|
+
const allowed = (path, cwd) => checkPath(path, cwd, rt.guard.config()).allowed;
|
|
426
|
+
if (!(await ask(`${preview(plan(home, folder, allowed), folder.bash)}\nRestore these files?`)))
|
|
427
|
+
return "undo cancelled; nothing was changed";
|
|
428
|
+
const result = apply(home, folder, allowed);
|
|
429
|
+
if (result.restored)
|
|
430
|
+
await rt.conclave.markRestored(folder.run);
|
|
431
|
+
return result.text;
|
|
432
|
+
}
|
|
433
|
+
/** Slash commands handled in the UI. Returns the reply text, or undefined when the text is chat for the model. */
|
|
434
|
+
export function runCommand(rt, text, ask, flow) {
|
|
435
|
+
if (!text.startsWith("/"))
|
|
436
|
+
return undefined;
|
|
437
|
+
const unknown = unknownCommand(text, rt.skills.state().skills, rt.skills.state().declined.map((skill) => skill.name));
|
|
438
|
+
if (unknown !== undefined)
|
|
439
|
+
return unknown;
|
|
440
|
+
const [name = "", ...rest] = text.slice(1).split(/\s+/u);
|
|
441
|
+
if (name === "model") {
|
|
442
|
+
const ref = rest[0];
|
|
443
|
+
if (ref === undefined)
|
|
444
|
+
return `main model: ${rt.settings().main ?? "not set"}`;
|
|
445
|
+
const checked = rt.checkMain(ref);
|
|
446
|
+
if (!checked.ok)
|
|
447
|
+
return `model not changed: ${checked.error}`;
|
|
448
|
+
const write = () => {
|
|
449
|
+
const result = rt.setMain(ref);
|
|
450
|
+
return result.ok ? `main model set to ${ref}; it applies at the next turn` : `model not changed: ${result.error}`;
|
|
451
|
+
};
|
|
452
|
+
const lines = securityChanges(rt.stored(), { set: { main: ref } });
|
|
453
|
+
if (lines.length === 0)
|
|
454
|
+
return write();
|
|
455
|
+
if (ask === undefined)
|
|
456
|
+
return "model not changed: this change needs a confirmation, which only the chat screen can ask";
|
|
457
|
+
return ask(`${lines.join("\n")}\n${SECURITY_CONFIRM}`).then((yes) => (yes ? write() : "model not changed"));
|
|
458
|
+
}
|
|
459
|
+
if (name === "login") {
|
|
460
|
+
if (flow === undefined)
|
|
461
|
+
return NEEDS_CHAT(name);
|
|
462
|
+
const target = rest[0];
|
|
463
|
+
return settled(flow((io, signal) => runLogin(rt.setupEnv(), io, signal, target === undefined ? {} : { target })).then((result) => {
|
|
464
|
+
if (result.status === "signed-in")
|
|
465
|
+
rt.loop.wake();
|
|
466
|
+
return result.message;
|
|
467
|
+
}), "login cancelled");
|
|
468
|
+
}
|
|
469
|
+
if (name === "settings") {
|
|
470
|
+
if (flow === undefined)
|
|
471
|
+
return NEEDS_CHAT(name);
|
|
472
|
+
return settled(flow((io, signal) => runSettings(rt, io, signal, rest.filter((word) => word !== "").join(" "))), "settings not changed");
|
|
473
|
+
}
|
|
474
|
+
if (name === "reload") {
|
|
475
|
+
const question = (changes) => ask(`These files changed outside piroboros:\n${changes}\nAccept the changes and reload?`);
|
|
476
|
+
// Skills are rescanned whatever the settings reload said, with their own question for new or changed project skills.
|
|
477
|
+
const skillsNote = async () => {
|
|
478
|
+
rt.skills.rescan();
|
|
479
|
+
const asked = ask === undefined ? undefined : await rt.skills.review(ask);
|
|
480
|
+
const scan = rt.skills.state();
|
|
481
|
+
const counts = [scan.skills.length > 0 ? `${scan.skills.length} loaded` : "", scan.issues.length > 0 ? `${scan.issues.length} skipped` : "", scan.pending.length > 0 ? `${scan.pending.length} project skills not answered` : ""].filter((part) => part !== "").join(", ");
|
|
482
|
+
return [asked, counts === "" ? undefined : `skills: ${counts} (see /skills)`].filter((line) => line !== undefined).join("\n");
|
|
483
|
+
};
|
|
484
|
+
return rt.reload(ask === undefined ? undefined : question).then(async (result) => {
|
|
485
|
+
const reply = !result.ok ? (result.declined ? `settings not reloaded: ${result.error}` : `settings not reloaded, the previous configuration is kept: ${result.error}`) : result.warnings === undefined ? "settings reloaded" : `settings reloaded\n${result.warnings.map((warning) => `warning: ${warning}`).join("\n")}`;
|
|
486
|
+
const skills = await skillsNote();
|
|
487
|
+
return skills === "" ? reply : `${reply}\n${skills}`;
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
if (name === "status")
|
|
491
|
+
return statusText(rt.harness, rt.root, rt.compactor.state().label, rt.compactor);
|
|
492
|
+
if (name === "conclave") {
|
|
493
|
+
// cancel, approve, status and undo are whole-line subcommands; anything else is the task text.
|
|
494
|
+
const sub = rest.length === 1 ? rest[0] : undefined;
|
|
495
|
+
if (sub === "cancel")
|
|
496
|
+
return rt.conclave.cancel();
|
|
497
|
+
if (sub === "status")
|
|
498
|
+
return rt.conclave.status();
|
|
499
|
+
if (sub === "undo")
|
|
500
|
+
return ask === undefined ? "undo not run: this needs a confirmation, which only the chat screen can ask" : undoCommand(rt, ask);
|
|
501
|
+
const started = sub === "approve" ? rt.conclave.approve() : rt.conclave.start(text.slice("/conclave".length));
|
|
502
|
+
return started.then((result) => (result.ok ? result.message : `not started: ${result.error}`));
|
|
503
|
+
}
|
|
504
|
+
if (name === "skills")
|
|
505
|
+
return skillsReport(rt.skills.state(), COMMANDS.map((command) => command.name));
|
|
506
|
+
if (name === "akashic")
|
|
507
|
+
return rt.akashic(rest.join(" "));
|
|
508
|
+
if (name === "thinking-steps")
|
|
509
|
+
return thinkingStepsCommand(rt, rest);
|
|
510
|
+
return undefined;
|
|
511
|
+
}
|
|
512
|
+
export function createStatusBus() {
|
|
513
|
+
let current = { kind: "idle" };
|
|
514
|
+
let restored;
|
|
515
|
+
const listeners = new Set();
|
|
516
|
+
const notify = () => { for (const listener of listeners)
|
|
517
|
+
listener(); };
|
|
518
|
+
return {
|
|
519
|
+
get: () => current,
|
|
520
|
+
set: (status) => { current = status; notify(); },
|
|
521
|
+
restore: (text) => { restored = text; notify(); },
|
|
522
|
+
takeRestore: () => { const text = restored; restored = undefined; return text; },
|
|
523
|
+
subscribe: (listener) => { listeners.add(listener); return () => listeners.delete(listener); },
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
/** `overlay` is the question overlay the app owns; tests (and later flows) may pass their own to drive it. */
|
|
527
|
+
export function App({ rt, banners, bus, overlay }) {
|
|
528
|
+
const app = useApp();
|
|
529
|
+
const [entries, setEntries] = useState([]);
|
|
530
|
+
const [pending, setPending] = useState([]);
|
|
531
|
+
const [running, setRunning] = useState(false);
|
|
532
|
+
const [viewBytes, setViewBytes] = useState(0);
|
|
533
|
+
const [compactorNote, setCompactorNote] = useState(undefined);
|
|
534
|
+
const [memoryStatus, setMemoryStatus] = useState(undefined);
|
|
535
|
+
const [status, setStatus] = useState(bus.get());
|
|
536
|
+
// The response being written: its attempt and the committed partial message (D23 reads thinking from it).
|
|
537
|
+
const [live, setLive] = useState(undefined);
|
|
538
|
+
const [, setModeTick] = useState(0);
|
|
539
|
+
const busy = useRef(false);
|
|
540
|
+
const [notes, setNotes] = useState([]);
|
|
541
|
+
const [webKeyMissing, setWebKeyMissing] = useState(false);
|
|
542
|
+
const note = (reply) => setNotes((list) => [...list, reply].slice(-5));
|
|
543
|
+
const { stdout } = useStdout();
|
|
544
|
+
// Every render sets the real terminal cursor (a position, or undefined to hide it): Ink keeps only a position set since the last render.
|
|
545
|
+
const { setCursorPosition } = useCursor();
|
|
546
|
+
const sizeOf = () => ({ columns: stdout.columns ?? 80, rows: stdout.rows ?? 24 });
|
|
547
|
+
const [size, setSize] = useState(sizeOf());
|
|
548
|
+
const { columns, rows: screenRows } = size;
|
|
549
|
+
useEffect(() => {
|
|
550
|
+
const onResize = () => { setSize(sizeOf()); syncRef.current(); };
|
|
551
|
+
stdout.on("resize", onResize);
|
|
552
|
+
return () => { stdout.off("resize", onResize); };
|
|
553
|
+
}, [stdout]);
|
|
554
|
+
// One input handler for the whole app. ownerRef is set synchronously (when the overlay opens or closes and when the
|
|
555
|
+
// text changes), never through isActive, which switches one render late: a secret typed or pasted in that gap would reach the chat.
|
|
556
|
+
const [driver] = useState(() => overlay ?? createSetupDriver());
|
|
557
|
+
const flows = useRef(new Set());
|
|
558
|
+
const ownerRef = useRef("chat");
|
|
559
|
+
const valueRef = useRef("");
|
|
560
|
+
const restoredRef = useRef(undefined);
|
|
561
|
+
const dismissedRef = useRef(false);
|
|
562
|
+
const indexRef = useRef(0);
|
|
563
|
+
const offsetRef = useRef(0);
|
|
564
|
+
const lastCtrlC = useRef(0);
|
|
565
|
+
// Chat scroll: rows above the bottom, the chat height of the last render (a page is two rows less), and the width and
|
|
566
|
+
// row count of the render before, so a view that was scrolled keeps its place while new rows arrive.
|
|
567
|
+
const scrollRef = useRef(0);
|
|
568
|
+
const heightRef = useRef(3);
|
|
569
|
+
const seenRef = useRef({ width: 0, total: 0 });
|
|
570
|
+
/** The text in the input was typed or pasted since the last Ctrl+C or send; restored text is not a draft. */
|
|
571
|
+
const typedRef = useRef(false);
|
|
572
|
+
const rowCache = useRef(new Map());
|
|
573
|
+
const syncRef = useRef(() => { });
|
|
574
|
+
const [, repaint] = useState(0);
|
|
575
|
+
const modelOptions = () => rt.models.getProviders().flatMap((provider) => modelChoices(rt.models, provider.id, "main").map((choice) => ({ ref: choice.ref, ...(choice.check.ok ? {} : { disabled: choice.check.reason ?? "rejected" }) })));
|
|
576
|
+
const loginOptions = () => providerChoices(rt.models).map((provider) => ({ id: provider.id, name: provider.name }));
|
|
577
|
+
// Under 7 rows the frame has no room for the list (see allocate), so the chat keeps the keys.
|
|
578
|
+
const listNow = () => (dismissedRef.current || sizeOf().rows < 7 ? [] : suggest(valueRef.current, valueRef.current.startsWith("/model ") ? modelOptions() : [], valueRef.current.startsWith("/login ") ? loginOptions() : [], rt.skills.state().skills));
|
|
579
|
+
const sync = () => { ownerRef.current = driver.state().request !== undefined ? "overlay" : listNow().length > 0 ? "picker" : "chat"; };
|
|
580
|
+
syncRef.current = sync;
|
|
581
|
+
/** Any change of the text reopens a dismissed list and selects its first entry. */
|
|
582
|
+
const setValue = (text) => {
|
|
583
|
+
valueRef.current = text;
|
|
584
|
+
dismissedRef.current = false;
|
|
585
|
+
indexRef.current = 0;
|
|
586
|
+
offsetRef.current = 0;
|
|
587
|
+
sync();
|
|
588
|
+
repaint((n) => n + 1);
|
|
589
|
+
};
|
|
590
|
+
/** A flow is a sequence of overlay questions. It gets an AbortController that is aborted when it ends, is cancelled, or the app exits. */
|
|
591
|
+
const refreshRef = useRef(() => { });
|
|
592
|
+
// Every notice a flow shows goes through redactSensitive. The sign-in address is not text: it was checked by safeAuthUrl and is shown whole.
|
|
593
|
+
const flowIo = { ...driver.io, notify: (kind, message) => driver.io.notify(kind, redactSensitive(message)) };
|
|
594
|
+
const runFlow = async (flow) => {
|
|
595
|
+
const controller = new AbortController();
|
|
596
|
+
flows.current.add(controller);
|
|
597
|
+
try {
|
|
598
|
+
return await flow(flowIo, controller.signal);
|
|
599
|
+
}
|
|
600
|
+
finally {
|
|
601
|
+
flows.current.delete(controller);
|
|
602
|
+
controller.abort();
|
|
603
|
+
driver.reset();
|
|
604
|
+
refreshRef.current();
|
|
605
|
+
}
|
|
606
|
+
};
|
|
607
|
+
const cancelFlows = () => {
|
|
608
|
+
for (const controller of flows.current)
|
|
609
|
+
controller.abort();
|
|
610
|
+
driver.cancelAll();
|
|
611
|
+
};
|
|
612
|
+
// The /reload question: the changed files are notices (full text, scrollable), the last line is the confirm.
|
|
613
|
+
const ask = (question) => runFlow(async (io) => {
|
|
614
|
+
const lines = question.split("\n");
|
|
615
|
+
if (lines.length > 1)
|
|
616
|
+
io.notify("info", lines.slice(0, -1).join("\n"));
|
|
617
|
+
return io.confirm(lines[lines.length - 1], false);
|
|
618
|
+
}).catch((error) => {
|
|
619
|
+
if (error instanceof SetupCancelled)
|
|
620
|
+
return false;
|
|
621
|
+
throw error;
|
|
622
|
+
});
|
|
623
|
+
// A failed session is reported by runApp through rt.fatal; any other rejection becomes a notice instead of a crash.
|
|
624
|
+
const failure = (error) => { if (!(error instanceof SessionFailed))
|
|
625
|
+
note(error instanceof Error ? error.message : String(error)); };
|
|
626
|
+
const onSubmit = (text) => {
|
|
627
|
+
const reply = runCommand(rt, text, ask, runFlow);
|
|
628
|
+
if (reply === undefined) {
|
|
629
|
+
setNotes([]);
|
|
630
|
+
void rt.send(text).catch(failure);
|
|
631
|
+
}
|
|
632
|
+
else {
|
|
633
|
+
if (typeof reply === "string")
|
|
634
|
+
note(reply);
|
|
635
|
+
else
|
|
636
|
+
void reply.then(note, failure);
|
|
637
|
+
if (unknownCommand(text, rt.skills.state().skills, rt.skills.state().declined.map((skill) => skill.name)) !== undefined)
|
|
638
|
+
setValue(text);
|
|
639
|
+
}
|
|
640
|
+
};
|
|
641
|
+
const submit = (override) => {
|
|
642
|
+
const text = (override ?? valueRef.current).trim();
|
|
643
|
+
if (text.length === 0)
|
|
644
|
+
return;
|
|
645
|
+
scrollRef.current = 0;
|
|
646
|
+
typedRef.current = false;
|
|
647
|
+
setValue("");
|
|
648
|
+
onSubmit(text);
|
|
649
|
+
};
|
|
650
|
+
useInput((input, key) => {
|
|
651
|
+
const list = listNow();
|
|
652
|
+
const state = { busy: busy.current, now: Date.now(), lastCtrlC: lastCtrlC.current, draft: ownerRef.current !== "overlay" && valueRef.current !== "" && typedRef.current };
|
|
653
|
+
const routed = route(ownerRef.current, input, key, state, driver.state().request?.kind, valueRef.current, list[Math.min(indexRef.current, list.length - 1)]);
|
|
654
|
+
if (key.ctrl && input === "c") {
|
|
655
|
+
lastCtrlC.current = state.now;
|
|
656
|
+
typedRef.current = false;
|
|
657
|
+
}
|
|
658
|
+
if (routed.to === "overlay") {
|
|
659
|
+
applyOverlay(driver, routed.action, Math.max(1, sizeOf().rows - 8));
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
if (routed.to === "picker") {
|
|
663
|
+
const action = routed.action;
|
|
664
|
+
if (action.t === "move") {
|
|
665
|
+
indexRef.current = Math.min(Math.max(0, indexRef.current + action.delta), Math.max(0, list.length - 1));
|
|
666
|
+
repaint((n) => n + 1);
|
|
667
|
+
}
|
|
668
|
+
else if (action.t === "complete")
|
|
669
|
+
setValue(action.value);
|
|
670
|
+
else if (action.t === "dismiss") {
|
|
671
|
+
dismissedRef.current = true;
|
|
672
|
+
sync();
|
|
673
|
+
repaint((n) => n + 1);
|
|
674
|
+
}
|
|
675
|
+
else if (action.t === "submit")
|
|
676
|
+
submit(action.text);
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
const action = routed.action;
|
|
680
|
+
if (action.t === "exit") {
|
|
681
|
+
cancelFlows();
|
|
682
|
+
app.exit();
|
|
683
|
+
}
|
|
684
|
+
else if (action.t === "abort")
|
|
685
|
+
void rt.root.abort(ctx).catch(failure);
|
|
686
|
+
else if (action.t === "cycle")
|
|
687
|
+
note(`thinking steps: ${rt.thinking.cycle()}`);
|
|
688
|
+
else if (action.t === "level") {
|
|
689
|
+
const next = THINKING_LEVELS[(THINKING_LEVELS.indexOf((rt.settings().thinking ?? "medium")) + 1) % THINKING_LEVELS.length];
|
|
690
|
+
const result = rt.updateSettings({ set: { thinking: next } });
|
|
691
|
+
note(result.ok ? `thinking: ${next}; it applies at the next turn` : `thinking not changed: ${result.error}`);
|
|
692
|
+
}
|
|
693
|
+
else if (action.t === "submit")
|
|
694
|
+
submit();
|
|
695
|
+
else if (action.t === "clear")
|
|
696
|
+
setValue("");
|
|
697
|
+
else if (action.t === "scroll") {
|
|
698
|
+
scrollRef.current = action.to === "end" ? 0 : Math.max(0, scrollRef.current + (action.to === "up" ? 1 : -1) * Math.max(1, heightRef.current - 2));
|
|
699
|
+
repaint((n) => n + 1);
|
|
700
|
+
}
|
|
701
|
+
else if (action.t === "backspace") {
|
|
702
|
+
typedRef.current = true;
|
|
703
|
+
setValue(dropLast(valueRef.current));
|
|
704
|
+
}
|
|
705
|
+
else if (action.t === "insert") {
|
|
706
|
+
typedRef.current = true;
|
|
707
|
+
setValue(valueRef.current + action.text);
|
|
708
|
+
}
|
|
709
|
+
});
|
|
710
|
+
usePaste((text) => {
|
|
711
|
+
if (ownerRef.current === "overlay")
|
|
712
|
+
applyOverlay(driver, { t: "type", text: text.replace(/[\r\n]+/gu, "") }, 1);
|
|
713
|
+
else {
|
|
714
|
+
typedRef.current = true;
|
|
715
|
+
setValue(valueRef.current + text);
|
|
716
|
+
}
|
|
717
|
+
});
|
|
718
|
+
useEffect(() => driver.subscribe(() => { sync(); repaint((n) => n + 1); }), [driver]);
|
|
719
|
+
useEffect(() => () => cancelFlows(), []);
|
|
720
|
+
useEffect(() => rt.thinking.subscribe(() => setModeTick((n) => n + 1)), [rt]);
|
|
721
|
+
// Project skills seen for the first time (or changed): one question once the screen is up. Until it is answered the index holds user skills only.
|
|
722
|
+
useEffect(() => { void rt.skills.review(ask).then((reply) => { if (reply !== undefined)
|
|
723
|
+
note(reply); }, failure); }, [rt]);
|
|
724
|
+
useEffect(() => bus.subscribe(() => {
|
|
725
|
+
setStatus(bus.get());
|
|
726
|
+
const text = bus.takeRestore();
|
|
727
|
+
if (text === undefined)
|
|
728
|
+
return;
|
|
729
|
+
// A steer and its turn are restored one after the other, the later message first: put each new text before the one restored a moment ago, unless the user has typed since.
|
|
730
|
+
setValue(restoredRef.current !== undefined && valueRef.current === restoredRef.current ? `${text}\n${valueRef.current}` : text);
|
|
731
|
+
restoredRef.current = valueRef.current;
|
|
732
|
+
}), [bus]);
|
|
733
|
+
useEffect(() => {
|
|
734
|
+
let alive = true;
|
|
735
|
+
let scheduled = false;
|
|
736
|
+
const keyMissing = missingKeyCheck(rt.paths.auth);
|
|
737
|
+
const refresh = async () => {
|
|
738
|
+
scheduled = false;
|
|
739
|
+
if (!alive)
|
|
740
|
+
return;
|
|
741
|
+
try {
|
|
742
|
+
const list = await recentEntries(rt.root, 60);
|
|
743
|
+
const live = await rt.harness.snapshot(LiveDoc, ROOT, ctx);
|
|
744
|
+
const doc = await rt.harness.snapshot(PendingDoc, ctx);
|
|
745
|
+
const view = await rt.harness.snapshot(ViewDoc, ctx);
|
|
746
|
+
if (!alive)
|
|
747
|
+
return;
|
|
748
|
+
setViewBytes(view?.bytes ?? 0);
|
|
749
|
+
setCompactorNote(await rt.compactor.note());
|
|
750
|
+
setMemoryStatus(rt.memoryStatus());
|
|
751
|
+
const web = withDefaults(rt.settings()).web;
|
|
752
|
+
setWebKeyMissing(web.provider !== undefined && keyMissing(web.provider));
|
|
753
|
+
busy.current = live?.run !== undefined;
|
|
754
|
+
setRunning(busy.current);
|
|
755
|
+
setLive(live?.generation === undefined ? undefined : { attempt: live.generation.attempt, message: live.generation.message });
|
|
756
|
+
setEntries([...list]);
|
|
757
|
+
setPending((doc?.items ?? []).map((item) => ({ text: item.text, source: item.source, member: item.member })));
|
|
758
|
+
}
|
|
759
|
+
catch {
|
|
760
|
+
// the session closed while a refresh was in flight
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
const stop = rt.harness.subscribeCommits(() => { if (!scheduled) {
|
|
764
|
+
scheduled = true;
|
|
765
|
+
setTimeout(() => { void refresh(); }, 100);
|
|
766
|
+
} });
|
|
767
|
+
refreshRef.current = () => { void refresh(); };
|
|
768
|
+
void refresh();
|
|
769
|
+
return () => { alive = false; refreshRef.current = () => { }; stop(); };
|
|
770
|
+
}, [rt]);
|
|
771
|
+
const pane = usePane(rt);
|
|
772
|
+
const settings = rt.settings();
|
|
773
|
+
const label = rt.compactor.state().label;
|
|
774
|
+
const growing = viewBanner(label, viewBytes);
|
|
775
|
+
const frameWidth = Math.max(10, columns - 1);
|
|
776
|
+
// The framed layout (P18): a header row, a chat box, a right box and an input box. Under 60 columns or 16 rows the P17 layout is drawn.
|
|
777
|
+
const framed = screenRows >= 16 && columns >= 60;
|
|
778
|
+
// Tall: a rule under the header and the title row of the chat box (2 more rows of chrome).
|
|
779
|
+
const tall = framed && screenRows >= 24;
|
|
780
|
+
// Standing rows: one row each. Alerts: the row for the status kind, then what to do next (2 rows at most).
|
|
781
|
+
const standing = [...(growing === undefined ? [] : [growing]), ...(compactorNote === undefined ? [] : [compactorNote]), ...banners].map((text) => ({ text: clip(text, frameWidth), color: THEME.warn }));
|
|
782
|
+
const alerts = [];
|
|
783
|
+
const alert = (text, color) => { alerts.push({ text: clip(text, frameWidth), ...(color === undefined ? { dim: true } : { color }) }); };
|
|
784
|
+
if (status.kind === "login_required")
|
|
785
|
+
alert(`login required for ${status.provider}: use /login`, THEME.error);
|
|
786
|
+
if (status.kind === "unconfigured")
|
|
787
|
+
alert("no main model is set: use /model or /login", THEME.error);
|
|
788
|
+
if (status.kind === "stopped" && !running) {
|
|
789
|
+
alert(status.message, THEME.error);
|
|
790
|
+
alert("Send a new message to continue.");
|
|
791
|
+
}
|
|
792
|
+
if (status.kind === "compactor_degraded")
|
|
793
|
+
alert(status.message, THEME.warn);
|
|
794
|
+
if (status.kind === "notice")
|
|
795
|
+
alert(status.message, THEME.warn);
|
|
796
|
+
if (status.kind === "error")
|
|
797
|
+
alert(`error: ${status.message}`, THEME.error);
|
|
798
|
+
if (status.kind === "turn_failed" && !running && restoredRef.current !== undefined && valueRef.current === restoredRef.current)
|
|
799
|
+
alert("Your message is back in the input. Press Enter to send it again.");
|
|
800
|
+
// The thinking panel (D23): a level of off, or a model without reasoning, hides it. Only the visible lines are derived.
|
|
801
|
+
const mainModel = settings.main === undefined ? undefined : resolveModel(rt.models, settings.main);
|
|
802
|
+
const suppressed = (settings.thinking ?? "medium") === "off" || mainModel?.reasoning === false;
|
|
803
|
+
const mode = rt.thinking.mode();
|
|
804
|
+
const lastReply = lastResponseOf(entries);
|
|
805
|
+
const statusInput = { main: settings.main, last: lastReply, compactor: label, thinking: settings.thinking ?? "medium", busy: running, ...(memoryStatus === undefined ? {} : { memory: memoryStatus }), ...(status.kind === "turn_failed" ? { failed: status.message } : {}) };
|
|
806
|
+
const statusText = formatStatus(statusInput, frameWidth);
|
|
807
|
+
// An open overlay replaces the chat and the pane, and the input line is hidden. State keeps updating underneath.
|
|
808
|
+
// The frame plus the one-line status stays under the terminal height, and no line is wider than the terminal.
|
|
809
|
+
if (driver.state().request !== undefined) {
|
|
810
|
+
setCursorPosition(undefined);
|
|
811
|
+
const frame = buildFrame(driver.state(), columns, screenRows - 1);
|
|
812
|
+
return createElement(Box, { flexDirection: "column" }, ...rowsOf(frame, "o"), ...rowsOf([{ text: clip(statusText, frameWidth), dim: true }], "status"));
|
|
813
|
+
}
|
|
814
|
+
// Wide terminal: the right column is always there, with fixed widths, and shows the Conclave pane while a run is on
|
|
815
|
+
// screen and the session panel otherwise. Narrow terminal: the chat alone, and the pane under it while a pipeline exists.
|
|
816
|
+
// Framed, every outer width adds up to columns - 1; a box takes 4 columns for its borders and padding.
|
|
817
|
+
const sideBySide = columns >= SIDE_BY_SIDE_MIN_COLUMNS;
|
|
818
|
+
const leftWidth = Math.floor(columns * 0.7) - 1;
|
|
819
|
+
const rightWidth = columns - leftWidth;
|
|
820
|
+
const showPane = pane !== undefined && (!sideBySide || paneVisible(pane));
|
|
821
|
+
const innerWidth = frameWidth - 4;
|
|
822
|
+
const chatWidth = framed ? (sideBySide ? leftWidth - 4 : innerWidth) : sideBySide ? leftWidth : frameWidth;
|
|
823
|
+
const sideWidth = framed ? frameWidth - leftWidth - 4 : rightWidth - 2;
|
|
824
|
+
const paneThinking = pane?.thinking === undefined || pane.active === undefined ? undefined : { blocks: pane.thinking.blocks, steps: rt.thinking.memo.steps(pane.active.conv, pane.thinking.id, pane.thinking.blocks, pane.thinking.live), streaming: pane.thinking.live, mode };
|
|
825
|
+
// Chat rows: each entry wrapped to the chat width, cached by what decides its rows. The live partial is never cached.
|
|
826
|
+
const cache = new Map();
|
|
827
|
+
const thinkingOf = (id, blocks, streaming) => {
|
|
828
|
+
const rows = thinkingLines({ blocks, steps: rt.thinking.memo.steps(ROOT, id, blocks, streaming), streaming, mode, suppressed }, framed ? chatWidth - 2 : chatWidth);
|
|
829
|
+
return framed ? rows.map(indented) : rows;
|
|
830
|
+
};
|
|
831
|
+
const rowsOfLine = (line, label, blank, badge) => {
|
|
832
|
+
if (framed)
|
|
833
|
+
return framedRows(line, { label, blank, width: chatWidth, ...(badge === undefined ? {} : { badge }), ...(line.thinking === undefined || suppressed ? {} : { thinking: thinkingOf(line.key, line.thinking, false) }) });
|
|
834
|
+
if (line.role === "error" && line.bounded !== true)
|
|
835
|
+
return wrap(line.text, chatWidth).map((text) => ({ text, color: THEME.error }));
|
|
836
|
+
if (line.role === "hint")
|
|
837
|
+
return wrap(line.text, chatWidth).map((text) => ({ text, dim: true }));
|
|
838
|
+
const prefix = line.role === "user" ? "you" : line.role === "assistant" ? "piroboros" : line.role === "report" ? `${line.member ?? "member"} report` : line.role;
|
|
839
|
+
const source = line.role === "error" ? line.text : `${prefix}: ${line.text}`;
|
|
840
|
+
const style = line.role === "error" ? { color: THEME.error } : line.role === "user" ? { color: THEME.accentText } : {};
|
|
841
|
+
let body;
|
|
842
|
+
if (line.bounded === true) {
|
|
843
|
+
const capped = capRows(source, chatWidth);
|
|
844
|
+
body = capped.rows.map((row) => ({ text: row, ...style }));
|
|
845
|
+
if (capped.more > 0)
|
|
846
|
+
body.push({ text: moreText(capped.more), dim: true });
|
|
847
|
+
}
|
|
848
|
+
else
|
|
849
|
+
body = wrap(source, chatWidth).map((text) => ({ text, ...style }));
|
|
850
|
+
return line.thinking === undefined || suppressed ? body : [...thinkingOf(line.key, line.thinking, false), ...body];
|
|
851
|
+
};
|
|
852
|
+
const chatRows = entries.length >= 60 ? [{ text: "(older history not shown)", dim: true }] : [];
|
|
853
|
+
const lines = linesOf(entries);
|
|
854
|
+
const { marks, group } = framed ? labelPlan(lines) : { marks: lines.map(() => ({ label: false, blank: false })), group: undefined };
|
|
855
|
+
// Report labels end with a pill and, for the newest report of a member whose run has ended, its duration. Render only: no line or document stores them.
|
|
856
|
+
const newestReport = new Map();
|
|
857
|
+
lines.forEach((line, i) => { if (line.role === "report")
|
|
858
|
+
newestReport.set(line.member ?? "member", i); });
|
|
859
|
+
const paneSeats = pane === undefined ? [] : seatsOf(pane.rows);
|
|
860
|
+
const badgeOf = (line, i) => {
|
|
861
|
+
if (!framed || line.role !== "report" || newestReport.get(line.member ?? "member") !== i)
|
|
862
|
+
return undefined;
|
|
863
|
+
const k = pane?.rows.findIndex((row) => row.name === line.member) ?? -1;
|
|
864
|
+
const row = k < 0 ? undefined : pane.rows[k];
|
|
865
|
+
if (row?.end === undefined)
|
|
866
|
+
return undefined;
|
|
867
|
+
const waiting = pending.some((item) => item.source === "conclave" && item.member === line.member);
|
|
868
|
+
const ended = paneSeats[k] === "vesperia" && (row.state === "done" || row.state === "partial" || row.state === "blocked" || row.state === "failed");
|
|
869
|
+
return { ...(ended ? { state: row.state } : {}), ...(waiting || row.start === undefined ? {} : { duration: formatDuration(row.end - row.start) }) };
|
|
870
|
+
};
|
|
871
|
+
for (const [i, line] of lines.entries()) {
|
|
872
|
+
const { label: labeled } = marks[i];
|
|
873
|
+
// The first line of the chat has no rule above it, so what the cache holds never depends on the scroll.
|
|
874
|
+
const blank = marks[i].blank && i > 0;
|
|
875
|
+
const badge = badgeOf(line, i);
|
|
876
|
+
const key = `${line.key}|${line.text.length}|${chatWidth}|${mode}|${suppressed}|${framed}|${labeled}|${blank}|${badge?.state ?? ""}|${badge?.duration ?? ""}`;
|
|
877
|
+
const rows = rowCache.current.get(key) ?? rowsOfLine(line, labeled, blank, badge);
|
|
878
|
+
cache.set(key, rows);
|
|
879
|
+
chatRows.push(...rows);
|
|
880
|
+
}
|
|
881
|
+
rowCache.current = cache;
|
|
882
|
+
if (live !== undefined) {
|
|
883
|
+
const liveRows = [];
|
|
884
|
+
if (!suppressed)
|
|
885
|
+
liveRows.push(...thinkingOf(`live:${live.attempt}`, thinkingBlocksOf(live.message), true));
|
|
886
|
+
const writing = textOf(live.message?.content).replace(/\s+/gu, " ").trim();
|
|
887
|
+
if (framed) {
|
|
888
|
+
if (writing !== "")
|
|
889
|
+
liveRows.push(...wrap(`${writing} (writing)`, chatWidth - 2).map((text) => ({ text: ` ${text}`, color: THEME.muted })));
|
|
890
|
+
// No live rows, no live label; the label follows the last committed group, so committing the message adds none.
|
|
891
|
+
if (liveRows.length > 0 && group !== "assistant")
|
|
892
|
+
liveRows.unshift(spanLine([{ text: ASSISTANT_LABEL, color: THEME.accentText, bold: true }], chatWidth));
|
|
893
|
+
}
|
|
894
|
+
else if (writing !== "")
|
|
895
|
+
liveRows.push(...wrap(`piroboros: ${writing} (writing)`, chatWidth).map((text) => ({ text, dim: true })));
|
|
896
|
+
chatRows.push(...liveRows);
|
|
897
|
+
}
|
|
898
|
+
// Everything else the frame can show, then the split of the rows.
|
|
899
|
+
const list = listNow();
|
|
900
|
+
const queuedItems = pending.map((item) => ({ text: item.source === "conclave" ? `(queued) report from ${item.member ?? "member"}` : `(queued) ${item.text.split("\n")[0]}`, dim: true }));
|
|
901
|
+
const noteRows = notes.map((text) => wrap(text, framed ? frameWidth - 2 : frameWidth));
|
|
902
|
+
const paneStacked = !sideBySide && showPane;
|
|
903
|
+
const alloc = allocate(screenRows, {
|
|
904
|
+
picker: Math.min(list.length, PICKER_MAX_ROWS + 1),
|
|
905
|
+
alerts: alerts.length,
|
|
906
|
+
notes: noteRows.map((lines) => lines.length),
|
|
907
|
+
standing: standing.map(() => 1),
|
|
908
|
+
queued: queuedItems.length,
|
|
909
|
+
// Framed, the keys sit in the input box.
|
|
910
|
+
hint: !framed && valueRef.current === "" && ownerRef.current === "chat" ? 1 : 0,
|
|
911
|
+
pane: paneStacked ? paneLines(pane, framed ? innerWidth : frameWidth, 99, paneThinking, true, framed).length : 0,
|
|
912
|
+
stacked: paneStacked,
|
|
913
|
+
chrome: framed ? (tall ? 7 : 5) : 0,
|
|
914
|
+
live: framed && (running || pane?.live === true) ? 2 : 0,
|
|
915
|
+
});
|
|
916
|
+
// The chat view: which rows show, where the view sits (see chatWindow), and the indicator row.
|
|
917
|
+
let offset = scrollRef.current;
|
|
918
|
+
if (offset > 0 && seenRef.current.width === chatWidth)
|
|
919
|
+
offset += chatRows.length - seenRef.current.total;
|
|
920
|
+
const win = chatWindow(chatRows.length, alloc.chat, scrollRef.current > 0 ? Math.max(1, offset) : 0);
|
|
921
|
+
scrollRef.current = win.offset;
|
|
922
|
+
heightRef.current = alloc.chat;
|
|
923
|
+
seenRef.current = { width: chatWidth, total: chatRows.length };
|
|
924
|
+
const shown = [...(win.indicator ? [{ text: chatIndicator(win.earlier, win.newer), dim: true }] : []), ...chatRows.slice(win.start, win.end)];
|
|
925
|
+
const queued = alloc.queued < queuedItems.length && alloc.queued > 0 ? [...queuedItems.slice(0, alloc.queued - 1), { text: `(+${queuedItems.length - alloc.queued + 1} more queued)`, dim: true }] : queuedItems.slice(0, alloc.queued);
|
|
926
|
+
const web = withDefaults(settings).web;
|
|
927
|
+
const panelData = { main: settings.main, thinking: settings.thinking ?? "medium", viewBytes, compactor: label, memory: memoryStatus, web: { enabled: web.enabled, provider: web.provider, keyMissing: webKeyMissing }, outcome: pane !== undefined && !paneVisible(pane) ? pane.outcome : undefined };
|
|
928
|
+
// Framed, the chat box holds the title row (tall), the chat, the queued items, padding, and the live rows at its bottom.
|
|
929
|
+
const runningRow = pane?.live === true ? pane.rows.find((row) => row.state === "running") : undefined;
|
|
930
|
+
const waitingFor = runningRow === undefined ? "Waiting for the Conclave" : `Waiting for ${runningRow.name}${pane.active?.turns === undefined || pane.active.maxTurns === undefined ? "" : ` (turn ${Math.min(pane.active.turns + 1, pane.active.maxTurns)} of ${pane.active.maxTurns})`}`;
|
|
931
|
+
const liveRows = alloc.live === 0 ? [] : [ruleLine(chatWidth), spanLine([{ text: running ? "piroboros is working" : waitingFor, color: THEME.muted }], chatWidth)];
|
|
932
|
+
const titleRows = tall ? [spanLine([{ text: ASSISTANT_LABEL, color: THEME.accentText, bold: true }, { text: ` (${settings.main ?? "no model set"})`, color: THEME.muted }], chatWidth)] : [];
|
|
933
|
+
const padRows = liveRows.length === 0 ? [] : Array.from({ length: Math.max(0, alloc.chat + alloc.queued - shown.length - queued.length) }, () => ({ text: "" }));
|
|
934
|
+
const leftRows = [...rowsOf(titleRows, "T"), ...rowsOf(shown, "c"), ...rowsOf(queued, "q"), ...rowsOf(padRows, "g"), ...rowsOf(liveRows, "v")];
|
|
935
|
+
const box = { borderStyle: "round", paddingX: 1, overflow: "hidden", flexShrink: 0, flexDirection: "column" };
|
|
936
|
+
const boxHeight = alloc.chat + alloc.queued + (alloc.pane > 0 ? alloc.pane + 1 : 0) + alloc.live + (tall ? 1 : 0) + 2;
|
|
937
|
+
// The right box of the framed side-by-side layout: the same height as the chat box.
|
|
938
|
+
const contextWindow = lastReply === undefined ? undefined : resolveModel(rt.models, `${lastReply.provider}/${lastReply.model}`)?.contextWindow;
|
|
939
|
+
const panel = framed && sideBySide ? rightPanelLines({ ...(pane === undefined ? {} : { model: pane }), session: panelData, ...(lastReply === undefined ? {} : { usage: { ...lastReply, ...(contextWindow === undefined ? {} : { contextWindow }) } }), describe: pane?.descriptions ?? {}, ...(paneThinking === undefined ? {} : { thinking: paneThinking }), formatTime: clock }, sideWidth, boxHeight - 2) : undefined;
|
|
940
|
+
const body = framed
|
|
941
|
+
? sideBySide
|
|
942
|
+
? createElement(Box, { key: "panes", flexDirection: "row" }, createElement(Box, { key: "left", ...box, borderColor: THEME.border, width: leftWidth, height: boxHeight }, ...leftRows), createElement(Box, { key: "right", ...box, borderColor: THEME.border, width: frameWidth - leftWidth, height: boxHeight }, ...rowsOf(panel.lines, "r")))
|
|
943
|
+
: createElement(Box, { key: "panes", ...box, borderColor: THEME.border, width: frameWidth, height: boxHeight }, ...leftRows, ...(alloc.pane === 0 ? [] : [...rowsOf([{ text: "─".repeat(innerWidth), dim: true }], "m"), createElement(ConclavePane, { key: "pane", model: pane, width: innerWidth, maxRows: alloc.pane, stacked: true, framed: true, ...(paneThinking === undefined ? {} : { thinking: paneThinking }) })]))
|
|
944
|
+
: sideBySide
|
|
945
|
+
? createElement(Box, { key: "panes", flexDirection: "row" }, createElement(Box, { key: "left", flexDirection: "column", width: leftWidth, flexShrink: 0 }, ...leftRows), createElement(Box, { key: "right", flexDirection: "column", width: rightWidth, flexShrink: 0, paddingLeft: 1 }, showPane ? createElement(ConclavePane, { model: pane, width: rightWidth - 2, maxRows: alloc.chat + alloc.queued, stacked: false, ...(paneThinking === undefined ? {} : { thinking: paneThinking }) }) : createElement(SessionPanel, { data: panelData, width: rightWidth - 2, maxRows: alloc.chat + alloc.queued })))
|
|
946
|
+
: createElement(Box, { key: "panes", flexDirection: "column" }, ...leftRows, ...(alloc.pane === 0 ? [] : [...rowsOf([{ text: "" }], "m"), createElement(ConclavePane, { key: "pane", model: pane, width: frameWidth, maxRows: alloc.pane, stacked: true, ...(paneThinking === undefined ? {} : { thinking: paneThinking }) })]));
|
|
947
|
+
// Replies, newest last. A reply that does not fit ends with the count of the rows left out.
|
|
948
|
+
// A reply is green in the P17 layout; framed it sits behind an accent gutter in the default color.
|
|
949
|
+
const noteLine = (text) => (framed ? { text: `│ ${text}`, spans: [{ text: "│ ", color: THEME.accent }, { text }] } : { text, color: THEME.ok });
|
|
950
|
+
const noteFrame = noteRows.flatMap((lines, i) => {
|
|
951
|
+
const given = alloc.notes[i] ?? 0;
|
|
952
|
+
if (given >= lines.length)
|
|
953
|
+
return lines.map(noteLine);
|
|
954
|
+
if (given === 0)
|
|
955
|
+
return [];
|
|
956
|
+
const more = lines.length - (given - 1);
|
|
957
|
+
return [...lines.slice(0, given - 1).map(noteLine), { text: moreText(more), dim: true }];
|
|
958
|
+
});
|
|
959
|
+
const selected = Math.min(indexRef.current, Math.max(0, list.length - 1));
|
|
960
|
+
const picker = alloc.picker === 0 ? { lines: [], offset: 0 } : buildPicker(list, selected, offsetRef.current, columns, alloc.picker);
|
|
961
|
+
offsetRef.current = picker.offset;
|
|
962
|
+
const hint = alloc.hint === 0 ? [] : [{ text: clip(`keys: ${running ? RUNNING_KEYS : IDLE_KEYS}`, frameWidth), dim: true }];
|
|
963
|
+
const common = [
|
|
964
|
+
...rowsOf(standing.slice(0, alloc.standing.filter((n) => n > 0).length), "s"),
|
|
965
|
+
...rowsOf(noteFrame, "n"),
|
|
966
|
+
...rowsOf(alerts.slice(0, alloc.alerts), "a"),
|
|
967
|
+
];
|
|
968
|
+
const standingShown = alloc.standing.filter((n) => n > 0).length;
|
|
969
|
+
const alertsShown = alerts.slice(0, alloc.alerts).length;
|
|
970
|
+
const value = valueRef.current;
|
|
971
|
+
if (!framed) {
|
|
972
|
+
// The cursor row: every row built above the input. The body is as tall as its taller column, or the chat and the pane under it.
|
|
973
|
+
const maxRows = alloc.chat + alloc.queued;
|
|
974
|
+
const bodyRows = sideBySide
|
|
975
|
+
? Math.max(leftRows.length, showPane ? paneLines(pane, rightWidth - 2, maxRows, paneThinking, false).length : panelLines(panelData, rightWidth - 2).slice(0, Math.max(0, maxRows)).length)
|
|
976
|
+
: leftRows.length + (alloc.pane === 0 ? 0 : 1 + paneLines(pane, frameWidth, alloc.pane, paneThinking, true).length);
|
|
977
|
+
const shownTail = tail(value, columns - 3);
|
|
978
|
+
const y = inputRowIndex([bodyRows, Math.min(standingShown, standing.length), noteFrame.length, alertsShown, alloc.status === 0 ? 0 : 1, picker.lines.length, hint.length], false);
|
|
979
|
+
setCursorPosition(alloc.input === 0 ? undefined : { x: 2 + stringWidth(shownTail), y });
|
|
980
|
+
return createElement(Box, { flexDirection: "column" }, body, ...common, ...(alloc.status === 0 ? [] : rowsOf([{ text: statusText, dim: true }], "t")), ...rowsOf(picker.lines, "k"), ...rowsOf(hint, "h"), ...(alloc.input === 0 ? [] : rowsOf([{ text: `> ${shownTail}` }], "i")));
|
|
981
|
+
}
|
|
982
|
+
// The stat strip sits at the right of the input row. An empty input keeps its whole placeholder, so the strip needs room for both;
|
|
983
|
+
// typed text keeps 22 columns. The cache counts show in the status row exactly when the strip is hidden.
|
|
984
|
+
const stripSpans = statsOf(lastReply, contextWindow);
|
|
985
|
+
const stripWidth = stripSpans === undefined ? 0 : stringWidth(stripSpans.map((span) => span.text).join(""));
|
|
986
|
+
const placeholder = running ? RUNNING_KEYS : IDLE_KEYS;
|
|
987
|
+
// The strip gives way to the Input row of the right panel, when that row is on screen.
|
|
988
|
+
const showStrip = stripSpans !== undefined && panel?.usage.input !== true && (value === "" ? 2 + stringWidth(placeholder) + 2 + stripWidth <= innerWidth : innerWidth - 2 - stripWidth - 2 >= 22);
|
|
989
|
+
const room = innerWidth - 2 - (showStrip ? stripWidth + 2 : 0);
|
|
990
|
+
const left = [{ text: "> ", color: THEME.accent }, value === "" ? { text: clip(placeholder, room), color: THEME.muted } : { text: tail(value, room) }];
|
|
991
|
+
const used = 2 + stringWidth(left[1].text);
|
|
992
|
+
const inputRow = spanLine([...left, ...(showStrip ? [{ text: " ".repeat(innerWidth - used - stripWidth) }, ...stripSpans] : [])], innerWidth);
|
|
993
|
+
// The cache counts show in the status row unless the strip or the Read and Cache rows of the right panel show them.
|
|
994
|
+
const statusRow = spanLine(statusSpans({ ...statusInput, busy: false, failed: undefined }, frameWidth, !showStrip && panel?.usage.cache !== true), frameWidth);
|
|
995
|
+
// The cursor sits after the typed text, at the start of the placeholder when the input is empty: border, padding, "> ", then the text.
|
|
996
|
+
const y = inputRowIndex([1, tall ? 1 : 0, boxHeight, Math.min(standingShown, standing.length), noteFrame.length, alertsShown, alloc.status === 0 ? 0 : 1, picker.lines.length], true);
|
|
997
|
+
setCursorPosition({ x: 4 + (value === "" ? 0 : stringWidth(left[1].text)), y });
|
|
998
|
+
return createElement(Box, { flexDirection: "column" }, ...rowsOf([headerRow(running, status, pane?.live === true ? { done: pane.rows.filter((row) => row.state === "done").length, total: pane.rows.length } : undefined, frameWidth)], "H"), ...(tall ? rowsOf([ruleLine(frameWidth)], "R") : []), body, ...common, ...(alloc.status === 0 ? [] : rowsOf([statusRow], "t")), ...rowsOf(picker.lines, "k"), createElement(Box, { key: "input", borderStyle: "round", borderColor: THEME.accent, paddingX: 1, width: frameWidth, height: 3, overflow: "hidden", flexShrink: 0 }, ...rowsOf([inputRow], "i")));
|
|
999
|
+
}
|
|
1000
|
+
export async function runApp(rt, banners, bus, io = {}) {
|
|
1001
|
+
const app = render(createElement(App, { rt, banners, bus }), { exitOnCtrlC: false, stdout: io.stdout, stdin: io.stdin, patchConsole: false });
|
|
1002
|
+
// A failed durable session leaves nothing to type into: unmount and hand the storage error to the caller.
|
|
1003
|
+
const outcome = await Promise.race([app.waitUntilExit().then(() => undefined), rt.fatal.then((failed) => ({ failed }))]);
|
|
1004
|
+
if (outcome !== undefined) {
|
|
1005
|
+
app.unmount();
|
|
1006
|
+
await app.waitUntilExit().catch(() => { });
|
|
1007
|
+
}
|
|
1008
|
+
return outcome;
|
|
1009
|
+
}
|