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,121 @@
1
+ // The slash commands: the single table, the parser, the "did you mean" check and the suggestion list for the
2
+ // picker above the input. All pure; the Ink layer and runCommand call them.
3
+ import { CONCLAVE_MEMBERS, SETTING_FIELDS } from "../config.js";
4
+ export const COMMANDS = [
5
+ { name: "model", description: "show or set the main model", args: "[provider/model]" },
6
+ { name: "reload", description: "reload settings.json and models.json" },
7
+ { name: "login", description: "sign in to a provider", args: "[provider]" },
8
+ { name: "settings", description: "show or change a setting", args: "[key]" },
9
+ { name: "status", description: "show the chat and compactor status" },
10
+ { name: "conclave", description: "run the review pipeline on a task", args: "<task> | approve | cancel | status | undo" },
11
+ { name: "akashic", description: "memory status, accept and vault", args: "[status | accept | vault ...]" },
12
+ { name: "thinking-steps", description: "choose how thinking steps are shown", args: "[mode | global <mode | clear>]" },
13
+ { name: "skills", description: "list the skills the chat can use" },
14
+ { name: "telemetry", description: "model requests, latency and cost of the last 24 hours" },
15
+ ];
16
+ /** The skills that are commands: a name that starts with a letter, and no built-in command of the same name (that one wins). */
17
+ const commandSkills = (skills) => skills.filter((skill) => /^[a-z]/u.test(skill.name) && !COMMANDS.some((command) => command.name === skill.name));
18
+ /**
19
+ * A message is a command when it is a slash followed by lowercase letters or hyphens and then the end of the text
20
+ * or whitespace: "/model", "/model x/y". A name with a digit counts only when it is a loaded skill ("/v2" and
21
+ * "/42 is the answer" are chat). Anything else that starts with a slash, such as "/srv/data/file", "/ " or
22
+ * "/Model", is chat. The name may be one that does not exist (a typo).
23
+ */
24
+ export function parseSlash(text, skills = []) {
25
+ const match = /^\/([a-z0-9-]+)(?:\s+([\s\S]*))?$/u.exec(text);
26
+ if (match === null)
27
+ return undefined;
28
+ if (/[0-9]/u.test(match[1]) && !commandSkills(skills).some((skill) => skill.name === match[1]))
29
+ return undefined;
30
+ return { name: match[1], rest: match[2] ?? "" };
31
+ }
32
+ function distance(a, b) {
33
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
34
+ for (let i = 1; i <= a.length; i++) {
35
+ const next = [i];
36
+ for (let j = 1; j <= b.length; j++)
37
+ next.push(Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)));
38
+ row = next;
39
+ }
40
+ return row[b.length];
41
+ }
42
+ /**
43
+ * The message for a command name that does not exist, with the closest known name when one is near. Loaded skills are
44
+ * commands; a name in `declined` (a project skill the user said no to) gets its own reply.
45
+ */
46
+ export function unknownCommand(text, skills = [], declined = []) {
47
+ const name = parseSlash(text, skills)?.name;
48
+ if (name === undefined)
49
+ return undefined;
50
+ const known = [...COMMANDS.map((command) => command.name), ...commandSkills(skills).map((skill) => skill.name)];
51
+ if (known.includes(name))
52
+ return undefined;
53
+ if (declined.includes(name))
54
+ return "project skill declined; /reload asks again after it changes";
55
+ const near = known.map((candidate) => ({ known: candidate, d: distance(name, candidate) })).sort((a, b) => a.d - b.d)[0];
56
+ return `unknown command /${name}${near.d <= 2 && near.d < name.length ? `; did you mean /${near.known}?` : ""}`;
57
+ }
58
+ const WEB_LOGINS = [{ id: "web-tinyfish", name: "TinyFish web search key" }, { id: "web-exa", name: "Exa web search key" }];
59
+ const MODES = ["collapsed", "summary", "expanded"];
60
+ const VAULT = ["status", "init", "sync", "commit", "push", "import", "accept"];
61
+ /** Prefix-matching choices for the last word of the input; `more` names the choices that open another level. */
62
+ function words(lead, typed, choices, more = []) {
63
+ const needle = typed.toLowerCase();
64
+ return choices.filter((choice) => choice.startsWith(needle)).map((choice) => ({ complete: `${lead}${choice}${more.includes(choice) ? " " : ""}`, label: choice }));
65
+ }
66
+ /**
67
+ * The suggestions for the current input, a pure function of the text. The first word is matched by prefix. Models
68
+ * are matched by substring. `models` is the list the caller got from the model registry.
69
+ */
70
+ export function suggest(value, models = [], logins = [], skills = []) {
71
+ if (!value.startsWith("/"))
72
+ return [];
73
+ if (!/\s/u.test(value)) {
74
+ const prefix = value.slice(1);
75
+ if (!/^[a-z0-9-]*$/u.test(prefix))
76
+ return [];
77
+ const commands = COMMANDS.filter((command) => command.name.startsWith(prefix)).map((command) => ({ complete: `/${command.name} `, label: `/${command.name}`, detail: `${command.description}${command.args === undefined ? "" : ` ${command.args}`}` }));
78
+ // Skills follow the built-ins, each with its description and a request hint.
79
+ return [...commands, ...commandSkills(skills).filter((skill) => skill.name.startsWith(prefix)).map((skill) => ({ complete: `/${skill.name} `, label: `/${skill.name}`, detail: `${skill.description} [request]`, args: true }))];
80
+ }
81
+ const match = /^\/([a-z-]+)\s+([\s\S]*)$/u.exec(value);
82
+ if (match === null)
83
+ return [];
84
+ const name = match[1];
85
+ const arg = match[2];
86
+ const tokens = arg.split(/\s+/u);
87
+ const lead = `/${name} ${tokens.slice(0, -1).join(" ")}${tokens.length > 1 ? " " : ""}`;
88
+ const last = tokens[tokens.length - 1];
89
+ if (name === "model") {
90
+ if (tokens.length > 1)
91
+ return [];
92
+ const needle = arg.toLowerCase();
93
+ return models.filter((model) => model.ref.toLowerCase().includes(needle)).map((model) => ({ complete: `/model ${model.ref}`, label: model.ref, ...(model.disabled === undefined ? {} : { disabled: model.disabled }) }));
94
+ }
95
+ if (name === "conclave")
96
+ return tokens.length > 1 ? [] : words(lead, last, ["approve", "cancel", "status", "undo"]);
97
+ if (name === "thinking-steps") {
98
+ if (tokens.length === 1)
99
+ return words(lead, last, [...MODES, "global"], ["global"]);
100
+ return tokens.length === 2 && tokens[0] === "global" ? words(lead, last, [...MODES, "clear"]) : [];
101
+ }
102
+ if (name === "akashic") {
103
+ if (tokens.length === 1)
104
+ return words(lead, last, ["status", "accept", "vault"], ["vault"]);
105
+ return tokens.length === 2 && tokens[0] === "vault" ? words(lead, last, VAULT) : [];
106
+ }
107
+ if (tokens.length > 1)
108
+ return [];
109
+ const needle = arg.toLowerCase();
110
+ // Providers and keys are matched by substring, like models.
111
+ if (name === "login")
112
+ return [...logins, ...WEB_LOGINS].filter((login) => login.id.toLowerCase().includes(needle) || login.name.toLowerCase().includes(needle)).map((login) => ({ complete: `/login ${login.id}`, label: login.id, detail: login.name }));
113
+ if (name === "settings") {
114
+ // Member keys are listed only once the text names a member and goes on past its dot.
115
+ const deep = /^conclave\.members\.[a-z]+\./u.test(needle);
116
+ const keys = deep ? SETTING_FIELDS : SETTING_FIELDS.filter((f) => !f.path.startsWith("conclave.members."));
117
+ const members = deep ? [] : CONCLAVE_MEMBERS.map((member) => ({ path: `conclave.members.${member}`, detail: "model and limits of this member" }));
118
+ return [...keys.map((f) => ({ path: f.path, detail: `${f.type}${f.security ? ", asks first" : ""}` })), ...members].filter((key) => key.path.toLowerCase().includes(needle)).map((key) => ({ complete: `/settings ${key.path}`, label: key.path, detail: key.detail }));
119
+ }
120
+ return [];
121
+ }
@@ -0,0 +1,83 @@
1
+ import { COMMANDS } from "./commands.js";
2
+ import { overlayKey } from "./setup.js";
3
+ export const DOUBLE_CTRL_C_MS = 2_000;
4
+ /**
5
+ * While a turn runs, Ctrl+C stops it, and a second press within two seconds exits. When idle it clears a typed draft,
6
+ * and exits when there is none.
7
+ */
8
+ export function ctrlC(state) {
9
+ if (state.busy)
10
+ return state.now - state.lastCtrlC < DOUBLE_CTRL_C_MS ? "exit" : "abort";
11
+ return state.draft ? "clear" : "exit";
12
+ }
13
+ export function chatKey(input, key, state) {
14
+ if (key.ctrl && input === "c")
15
+ return { t: ctrlC(state) };
16
+ if (key.escape)
17
+ return { t: "abort" };
18
+ if (key.pageUp)
19
+ return { t: "scroll", to: "up" };
20
+ if (key.pageDown)
21
+ return { t: "scroll", to: "down" };
22
+ if (key.end)
23
+ return { t: "scroll", to: "end" };
24
+ if (key.meta && input.toLowerCase() === "t")
25
+ return { t: "cycle" };
26
+ if (key.ctrl && input === "t")
27
+ return { t: "level" };
28
+ if (key.return)
29
+ return { t: "submit" };
30
+ if (key.backspace || key.delete)
31
+ return { t: "backspace" };
32
+ if (input.length > 0 && !key.ctrl && !key.meta && !key.tab)
33
+ return { t: "insert", text: input };
34
+ return { t: "none" };
35
+ }
36
+ /**
37
+ * What Enter does with the highlighted entry. A command with no argument hint runs. A typed prefix of a longer name
38
+ * completes to "/name ". An exact name runs. At the second level only enumerated choices complete, and an entry that
39
+ * equals the text, or any /conclave text, is submitted as typed so a task is never turned into "approve".
40
+ */
41
+ export function enterAction(value, entry) {
42
+ if (entry === undefined || entry.hint === true || entry.disabled !== undefined)
43
+ return { t: "submit" };
44
+ if (!/\s/u.test(value)) {
45
+ const info = COMMANDS.find((command) => `/${command.name}` === entry.label);
46
+ if (COMMANDS.some((command) => value === `/${command.name}`) || (entry.args === true && value === entry.label))
47
+ return { t: "submit" };
48
+ return info?.args === undefined && entry.args !== true ? { t: "submit", text: entry.label } : { t: "complete", value: entry.complete };
49
+ }
50
+ if (/^\/conclave\s/u.test(value) || entry.complete === value)
51
+ return { t: "submit" };
52
+ return { t: "complete", value: entry.complete };
53
+ }
54
+ /** Keys of the command list. Returns "none" for a key the list does not use, which then goes to the chat rules. */
55
+ export function pickerKey(value, entry, key) {
56
+ if (key.upArrow)
57
+ return { t: "move", delta: -1 };
58
+ if (key.downArrow)
59
+ return { t: "move", delta: 1 };
60
+ if (key.escape)
61
+ return { t: "dismiss" };
62
+ if (key.tab)
63
+ return entry === undefined || entry.hint === true || entry.disabled !== undefined ? { t: "none" } : { t: "complete", value: entry.complete };
64
+ if (key.return)
65
+ return enterAction(value, entry);
66
+ return { t: "none" };
67
+ }
68
+ /**
69
+ * The single entry point for a key. Ctrl+C always has its chat meaning. Otherwise the owner decides: the overlay
70
+ * takes every key, the command list takes the keys it uses and passes the rest to the chat.
71
+ */
72
+ export function route(owner, input, key, state, requestKind, value, entry) {
73
+ if (key.ctrl && input === "c")
74
+ return { to: "chat", action: chatKey(input, key, state) };
75
+ if (owner === "overlay")
76
+ return { to: "overlay", action: overlayKey(requestKind, input, key) };
77
+ if (owner === "picker") {
78
+ const action = pickerKey(value, entry, key);
79
+ if (action.t !== "none" || key.tab)
80
+ return { to: "picker", action };
81
+ }
82
+ return { to: "chat", action: chatKey(input, key, state) };
83
+ }
@@ -0,0 +1,387 @@
1
+ import { createElement, useEffect, useState } from "react";
2
+ import { Box } from "ink";
3
+ import { ctx, LiveDoc, recentEntries } from "../durable.js";
4
+ import { redactSensitive } from "../redact.js";
5
+ import { rowsOf } from "./sanitize.js";
6
+ import { tailOf, thinkingBlocksOf } from "./thinking/state.js";
7
+ import { thinkingLines } from "./thinking/view.js";
8
+ import stringWidth from "string-width";
9
+ import { CONCLAVE_MEMBERS } from "../config.js";
10
+ import { panelFrame } from "./panel.js";
11
+ import { THEME } from "./theme.js";
12
+ import { clip, spanLine, wrap } from "./viewport.js";
13
+ // The Conclave pane (P5b). It is built from committed state: Conclave.progress() for the members, the running member's
14
+ // last entries and the committed partial of its current answer for the stream. Nothing here runs unless a pipeline
15
+ // exists, and the child text is bounded: at most CHILD_ENTRIES entries are read, at most CHILD_LINES lines are shown,
16
+ // and each line is cut to CLIP characters.
17
+ /** From this many columns the pane sits to the right of the chat. Below it the pane goes under the chat at full width. */
18
+ export const SIDE_BY_SIDE_MIN_COLUMNS = 100;
19
+ export const CHILD_ENTRIES = 12;
20
+ export const CHILD_LINES = { side: 10, stacked: 4 };
21
+ const CLIP = 200;
22
+ const THROTTLE_MS = 250;
23
+ const oneLine = (text) => {
24
+ const flat = text.replace(/\s+/gu, " ").trim();
25
+ return flat.slice(0, CLIP);
26
+ };
27
+ const ARGUMENT_KEYS = ["command", "path", "file_path", "pattern", "query", "url", "name"];
28
+ /** A tool call as its name and one short argument. The argument is the first string among the usual keys, else the first string value, redacted and cut to 60. */
29
+ export function toolCallParts(block) {
30
+ const name = block.name ?? "?";
31
+ const args = block.arguments;
32
+ if (args === null || typeof args !== "object" || Array.isArray(args))
33
+ return { name };
34
+ const record = args;
35
+ const value = ARGUMENT_KEYS.map((key) => record[key]).find((v) => typeof v === "string") ?? Object.values(record).find((v) => typeof v === "string");
36
+ const flat = typeof value === "string" ? redactSensitive(value.replace(/\s+/gu, " ").trim()) : "";
37
+ return flat === "" ? { name } : { name, arg: [...flat].slice(0, 60).join("") };
38
+ }
39
+ /** A tool call as one short phrase: `[tool bash: npm run build]`. */
40
+ export function toolCallText(block) {
41
+ const { name, arg } = toolCallParts(block);
42
+ return arg === undefined ? `[tool ${name}]` : `[tool ${name}: ${arg}]`;
43
+ }
44
+ export const textOf = (content) => {
45
+ if (typeof content === "string")
46
+ return content;
47
+ return Array.isArray(content) ? content.map((block) => (block?.type === "text" ? block.text ?? "" : block?.type === "toolCall" ? ` ${toolCallText(block)} ` : "")).join("") : "";
48
+ };
49
+ const capped = (blocks) => blocks.map((block) => ({ ...block, text: tailOf(block.text) }));
50
+ /** Lines of the member's recent entries, oldest first, the committed partial of the answer being written, and its newest thinking. */
51
+ async function childView(rt, conv) {
52
+ const child = await rt.harness.conversation(conv, ctx);
53
+ if (child === undefined)
54
+ return { lines: [] };
55
+ const lines = [];
56
+ let thinking;
57
+ for (const entry of (await recentEntries(child, CHILD_ENTRIES)).slice().reverse()) {
58
+ const message = entry.model?.[0];
59
+ if (message === undefined || message.role === "user")
60
+ continue;
61
+ const text = oneLine(textOf(message.content));
62
+ if (text !== "")
63
+ lines.push(message.role === "toolResult" ? `${message.toolName ?? "tool"} result: ${text}` : text);
64
+ if (message.role === "assistant") {
65
+ const blocks = thinkingBlocksOf(message);
66
+ thinking = blocks.length === 0 ? undefined : { id: String(entry.id), live: false, blocks: capped(blocks) };
67
+ }
68
+ }
69
+ const generation = (await rt.harness.snapshot(LiveDoc, conv, ctx))?.generation;
70
+ const partial = generation?.message;
71
+ const live = oneLine(textOf(partial?.content));
72
+ if (live !== "")
73
+ lines.push(`${live} (writing)`);
74
+ const liveBlocks = thinkingBlocksOf(partial);
75
+ // The live text is not cut here: StepMemo keys on the whole length and parses only its own tail, so the steps keep moving past the cap.
76
+ if (generation !== undefined && liveBlocks.length > 0)
77
+ thinking = { id: `live:${generation.attempt}`, live: true, blocks: liveBlocks };
78
+ return { lines, ...(thinking === undefined ? {} : { thinking }) };
79
+ }
80
+ export async function readPane(rt) {
81
+ const progress = await rt.conclave.progress();
82
+ if (progress === undefined)
83
+ return undefined;
84
+ if (progress.active === undefined)
85
+ return { ...progress, child: [] };
86
+ const view = await childView(rt, progress.active.conv);
87
+ return { ...progress, child: view.lines, ...(view.thinking === undefined ? {} : { thinking: view.thinking }) };
88
+ }
89
+ /**
90
+ * Follows the pipeline. The task graph watch reports when a pipeline task starts or ends; while one is live, commits
91
+ * also refresh the pane so the child stream moves. With no pipeline the commit listener does nothing.
92
+ */
93
+ export function usePane(rt) {
94
+ const [model, setModel] = useState(undefined);
95
+ useEffect(() => {
96
+ let alive = true;
97
+ let scheduled = false;
98
+ let active = false;
99
+ let last = "";
100
+ const refresh = async () => {
101
+ scheduled = false;
102
+ if (!alive)
103
+ return;
104
+ try {
105
+ const next = await readPane(rt);
106
+ if (!alive)
107
+ return;
108
+ active = next?.live === true;
109
+ const key = JSON.stringify(next ?? null);
110
+ if (key !== last) {
111
+ last = key;
112
+ setModel(next);
113
+ }
114
+ }
115
+ catch {
116
+ // the session closed while a refresh was in flight
117
+ }
118
+ };
119
+ const schedule = () => { if (!scheduled) {
120
+ scheduled = true;
121
+ setTimeout(() => { void refresh(); }, THROTTLE_MS).unref();
122
+ } };
123
+ const stopCommits = rt.harness.subscribeCommits(() => { if (active)
124
+ schedule(); });
125
+ let watch;
126
+ void rt.harness.watchTaskGraph(ctx).then((handle) => {
127
+ if (!alive) {
128
+ void handle.stop();
129
+ return;
130
+ }
131
+ watch = handle;
132
+ handle.start(async () => { schedule(); });
133
+ }).catch(() => { });
134
+ void refresh();
135
+ return () => { alive = false; stopCommits(); void watch?.stop(); };
136
+ }, [rt]);
137
+ return model;
138
+ }
139
+ const COLORS = { waiting: undefined, running: THEME.warn, done: THEME.ok, partial: THEME.warn, blocked: THEME.error, failed: THEME.error, "awaiting approve": THEME.accentText, "not run": undefined };
140
+ /** The framed pane colors every state, waiting and not run included. */
141
+ const STATE_COLORS = { waiting: THEME.muted, running: THEME.accentText, done: THEME.ok, partial: THEME.warn, blocked: THEME.error, failed: THEME.error, "awaiting approve": THEME.accentText, "not run": THEME.muted };
142
+ /** A pipeline is shown in full while it is live, waiting for approval, or stopped with a failed member. Otherwise it collapses to its outcome. */
143
+ export const paneVisible = (model) => model.live || model.rows.some((row) => row.state === "awaiting approve" || row.state === "failed" || row.state === "partial" || row.state === "blocked");
144
+ /** The pane. `stacked` is the narrow layout: the same rows, fewer stream lines. A pipeline that ended without a failure collapses to its outcome. */
145
+ export function ConclavePane({ model, width, maxRows, stacked, thinking, framed }) {
146
+ return createElement(Box, { flexDirection: "column" }, ...rowsOf(paneLines(model, width, maxRows, thinking, stacked, framed), "p"));
147
+ }
148
+ /** What the user can do next, by the state of the pipeline. */
149
+ function paneHint(model) {
150
+ if (model.live)
151
+ return "/conclave cancel stops it";
152
+ if (model.rows.some((row) => row.state === "awaiting approve"))
153
+ return "/conclave approve runs Vesperia";
154
+ return model.mode === "execute" ? "/conclave approve runs Vesperia again" : "/conclave <task> starts a new review";
155
+ }
156
+ /** The progress bar of the framed pane: filled cells for the members that are done, and the count. */
157
+ function progressRow(model, w) {
158
+ const done = model.rows.filter((row) => row.state === "done").length;
159
+ const cells = Math.max(4, w - 6);
160
+ const filled = model.rows.length === 0 ? 0 : Math.round((done / model.rows.length) * cells);
161
+ return spanLine([{ text: "━".repeat(filled), color: THEME.accent }, { text: "─".repeat(cells - filled), color: THEME.border }, { text: ` ${done}/${model.rows.length}`, color: THEME.muted }], w);
162
+ }
163
+ /** Rows leave in this order when the pane has too few. Inside a part: stream and done rows leave oldest first, hints last first, thinking and the rest from the bottom. */
164
+ const DROP_ORDER = ["stream", "thinking", "header", "progress", "idle", "done", "hint", "other", "running", "title"];
165
+ const FROM_TOP = new Set(["stream", "done"]);
166
+ /**
167
+ * The pane as rows of at most `width` columns, in at most `maxRows` rows. A pipeline that ended without a failure
168
+ * collapses to its title and outcome (the outcome stays when there is room for one row). Otherwise it is the title, the
169
+ * members, the running member's thinking and stream, and a hint; rows leave in DROP_ORDER until the rest fits.
170
+ * Framed (P18): the title has a diamond, a progress bar follows it, and each member row is a colored dot, the name and a right-aligned state word.
171
+ */
172
+ export function paneLines(model, width, maxRows, thinking, stacked = false, framed = false) {
173
+ if (maxRows <= 0)
174
+ return [];
175
+ const w = Math.max(1, width);
176
+ const titleText = `Conclave ${model.mode === "review" ? "review" : "execution"}`;
177
+ const title = { text: clip(framed ? `◆ ${titleText}` : titleText, w), bold: true };
178
+ if (!paneVisible(model)) {
179
+ const outcome = { text: clip(model.outcome === "" ? "ended" : model.outcome, w), dim: true };
180
+ return maxRows >= 2 ? [title, outcome] : [outcome];
181
+ }
182
+ const limit = stacked ? CHILD_LINES.stacked : CHILD_LINES.side;
183
+ const items = [{ part: "title", line: title }];
184
+ if (framed)
185
+ items.push({ part: "progress", line: progressRow(model, w) });
186
+ for (const row of model.rows) {
187
+ const part = row.state === "running" ? "running" : row.state === "done" ? "done" : row.state === "waiting" || row.state === "not run" ? "idle" : "other";
188
+ if (framed) {
189
+ const color = STATE_COLORS[row.state];
190
+ const left = `● ${row.name}${row.detail === undefined ? "" : ` (${row.detail})`}`;
191
+ const gap = Math.max(1, w - stringWidth(left) - stringWidth(row.state));
192
+ items.push({ part, line: spanLine([{ text: "● ", color }, { text: row.name }, ...(row.detail === undefined ? [] : [{ text: ` (${row.detail})`, color: THEME.muted }]), { text: " ".repeat(gap) }, { text: row.state, color }], w) });
193
+ continue;
194
+ }
195
+ items.push({ part, line: { text: clip(`${row.name}: ${row.state}${row.detail === undefined ? "" : ` (${row.detail})`}`, w), ...(COLORS[row.state] === undefined ? {} : { color: COLORS[row.state] }), ...(part === "idle" ? { dim: true } : {}) } });
196
+ }
197
+ const stream = model.child.slice(-limit);
198
+ if (model.active !== undefined && (stream.length > 0 || thinking !== undefined)) {
199
+ items.push({ part: "header", line: framed ? { text: clip(`▸ ${model.active.name}`, w), bold: true, color: THEME.accentText } : { text: clip(`${model.active.name}:`, w), bold: true } });
200
+ if (thinking !== undefined)
201
+ for (const line of thinkingLines(thinking, w, { truncate: true, maxRows: limit }))
202
+ items.push({ part: "thinking", line });
203
+ for (const text of stream)
204
+ items.push({ part: "stream", line: { text: clip(text, w), dim: true } });
205
+ }
206
+ for (const text of wrap(paneHint(model), w))
207
+ items.push({ part: "hint", line: { text, dim: true } });
208
+ while (items.length > maxRows) {
209
+ const part = DROP_ORDER.find((p) => items.some((item) => item.part === p));
210
+ const at = FROM_TOP.has(part) ? items.findIndex((item) => item.part === part) : items.map((item) => item.part).lastIndexOf(part);
211
+ items.splice(at, 1);
212
+ }
213
+ return items.map((item) => item.line);
214
+ }
215
+ const LIGHT = "#FFFFFF";
216
+ const DARK = "#1A1A1A";
217
+ /** Background and text color of a pill, by state. */
218
+ const PILL_COLORS = {
219
+ running: { bg: THEME.accent, color: LIGHT }, "awaiting approve": { bg: THEME.accent, color: LIGHT },
220
+ done: { bg: THEME.ok, color: DARK }, failed: { bg: THEME.error, color: DARK }, blocked: { bg: THEME.error, color: DARK }, partial: { bg: THEME.warn, color: DARK },
221
+ waiting: { bg: THEME.border, color: LIGHT }, "not run": { bg: THEME.border, color: LIGHT }, idle: { bg: THEME.border, color: LIGHT },
222
+ };
223
+ /** A state as a badge: its word with a space on each side. `short` swaps the two long words (`awaiting approve` is `approve`, `not run` is `idle`). */
224
+ export function pill(state, short = false) {
225
+ const word = short ? (state === "awaiting approve" ? "approve" : state === "not run" ? "idle" : state) : state;
226
+ return { text: ` ${word} `, ...PILL_COLORS[state] };
227
+ }
228
+ /** `45s`, `2m 14s`, `1h 03m`. */
229
+ export function formatDuration(ms) {
230
+ const seconds = Math.max(0, Math.round(ms / 1000));
231
+ if (seconds < 60)
232
+ return `${seconds}s`;
233
+ const minutes = Math.floor(seconds / 60);
234
+ return minutes < 60 ? `${minutes}m ${seconds % 60}s` : `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`;
235
+ }
236
+ /** The seat of each progress row: the seats in CONCLAVE_MEMBERS order, and the final-plan row is Samaela's second run. */
237
+ export function seatsOf(rows) {
238
+ let next = 0;
239
+ return rows.map((row) => (row.name.endsWith(" (final plan)") ? "samaela" : CONCLAVE_MEMBERS[next++] ?? row.name));
240
+ }
241
+ /** Rows leave in this order when the panel has too few. A step takes one row at a time, from the bottom unless `top`. */
242
+ const R_STEPS = [
243
+ { match: (i) => i.part === "desc" && i.running !== true },
244
+ { match: (i) => i.part === "actDetail" },
245
+ { match: (i) => i.part === "actEvent" },
246
+ { match: (i) => i.part === "stream", top: true },
247
+ { match: (i) => i.part === "thinking" },
248
+ { match: (i) => i.part === "rule" },
249
+ { match: (i) => i.part === "row2" && i.running !== true },
250
+ { match: (i) => i.part === "hint" },
251
+ { match: (i) => i.part === "desc" },
252
+ { match: (i) => i.part === "row2" },
253
+ { match: (i) => i.part === "useRow" },
254
+ { match: (i) => i.part === "useContext" },
255
+ { match: (i) => i.part === "useTitle" },
256
+ { match: (i) => i.part === "session" },
257
+ { match: (i) => i.part === "progress" },
258
+ { match: (i) => i.part === "header" },
259
+ { match: (i) => i.part === "member" && i.kind === "idle" },
260
+ { match: (i) => i.part === "member" && i.kind === "done", top: true },
261
+ { match: (i) => i.part === "member" && i.kind === "other" },
262
+ { match: (i) => i.part === "member" && i.kind === "running" },
263
+ { match: (i) => i.part === "title" },
264
+ ];
265
+ /** A title leaves with its last event, and a rule stays only between two rows that are not rules: never first, last or doubled. */
266
+ function tidy(items) {
267
+ const live = items.some((item) => item.part === "actEvent") ? items : items.filter((item) => item.part !== "actTitle");
268
+ const out = [];
269
+ live.forEach((item, k) => {
270
+ if (item.part !== "rule" || (out.length > 0 && out.at(-1).part !== "rule" && live[k + 1] !== undefined && live[k + 1].part !== "rule"))
271
+ out.push(item);
272
+ });
273
+ return out;
274
+ }
275
+ const NUMBER = new Intl.NumberFormat("en-US");
276
+ /**
277
+ * The right box of the framed side-by-side layout, in at most `maxRows` rows of at most `width` columns: the title, the progress row (or the
278
+ * session rows), a block per member (name and pill, a muted row of duration, turn and detail, the description), the running member's thinking
279
+ * and stream, the hint, Recent Activity and Resource Usage. Rows leave in R_STEPS order. `usage` says whether the Input row and the Read row
280
+ * (with the Cache row) survived: the input strip and the cache counts of the status row give way to them.
281
+ */
282
+ export function rightPanelLines(input, width, maxRows) {
283
+ const none = { lines: [], usage: { input: false, cache: false } };
284
+ if (maxRows <= 0)
285
+ return none;
286
+ const w = Math.max(1, width);
287
+ const { model } = input;
288
+ const visible = model !== undefined && paneVisible(model);
289
+ let items = [];
290
+ const add = (part, line, extra = {}) => { items.push({ part, line, ...extra }); };
291
+ const rule = () => { add("rule", spanLine([{ text: "─".repeat(w), color: THEME.border }], w)); };
292
+ const title = (text) => spanLine([{ text, bold: true }], w);
293
+ add("title", title(visible ? `◆ Conclave ${model.mode === "review" ? "review" : "execution"}` : "◆ Session"));
294
+ if (visible)
295
+ add("progress", progressRow(model, w));
296
+ else
297
+ for (const line of panelFrame(input.session, w).slice(1))
298
+ add("session", line);
299
+ // Members: one block per seat. Without a visible pipeline every seat is idle.
300
+ const seats = visible ? seatsOf(model.rows) : [...CONCLAVE_MEMBERS];
301
+ const members = visible ? model.rows : CONCLAVE_MEMBERS.map((seat) => ({ name: seat[0].toUpperCase() + seat.slice(1), state: "waiting" }));
302
+ rule();
303
+ members.forEach((row, k) => {
304
+ const state = visible ? row.state : "idle";
305
+ const running = state === "running";
306
+ const kind = running ? "running" : state === "done" ? "done" : state === "waiting" || state === "not run" || state === "idle" ? "idle" : "other";
307
+ let badge = pill(state);
308
+ if (2 + stringWidth(row.name) + 1 + stringWidth(badge.text) > w)
309
+ badge = pill(state, true);
310
+ const room = Math.max(1, w - 2 - 1 - stringWidth(badge.text));
311
+ const name = stringWidth(row.name) > room ? clip(row.name, room) : row.name;
312
+ const gap = Math.max(1, w - 2 - stringWidth(name) - stringWidth(badge.text));
313
+ add("member", spanLine([{ text: "● ", color: STATE_COLORS[row.state] }, { text: name }, { text: " ".repeat(gap) }, badge], w), { running, kind });
314
+ const turn = running && model?.active?.name === row.name && model.active.turns !== undefined && model.active.maxTurns !== undefined ? `turn ${Math.min(model.active.turns + 1, model.active.maxTurns)} of ${model.active.maxTurns}` : undefined;
315
+ const parts = [
316
+ ...(turn === undefined ? [] : [turn]),
317
+ ...(running && row.start !== undefined ? [`since ${input.formatTime(row.start)}`] : []),
318
+ ...(!running && row.start !== undefined && row.end !== undefined ? [formatDuration(row.end - row.start)] : []),
319
+ ...(visible && row.detail !== undefined ? [row.detail] : []),
320
+ ];
321
+ if (parts.length > 0)
322
+ add("row2", spanLine([{ text: ` ${parts.join(" · ")}`, color: THEME.muted }], w), { running });
323
+ const description = input.describe[seats[k] ?? ""];
324
+ if (description !== undefined && description !== "")
325
+ add("desc", spanLine([{ text: ` ${clip(description, Math.max(1, w - 2))}`, color: THEME.muted }], w), { running });
326
+ });
327
+ // The running member's thinking and stream, then the hint.
328
+ if (visible) {
329
+ if (model.active !== undefined && (model.child.length > 0 || input.thinking !== undefined)) {
330
+ add("header", { text: clip(`▸ ${model.active.name}`, w), bold: true, color: THEME.accentText });
331
+ if (input.thinking !== undefined)
332
+ for (const line of thinkingLines(input.thinking, w, { truncate: true, maxRows: CHILD_LINES.side }))
333
+ add("thinking", line);
334
+ for (const text of model.child.slice(-CHILD_LINES.side))
335
+ add("stream", { text: clip(text, w), dim: true });
336
+ }
337
+ for (const text of wrap(paneHint(model), w))
338
+ add("hint", { text, dim: true });
339
+ }
340
+ // Recent Activity: starts and ends, newest first (an end before a start at the same time, then seat order), two rows each.
341
+ // Without a timed run the section still shows, with one muted row that leaves like an event.
342
+ {
343
+ const events = (model?.rows ?? [])
344
+ .flatMap((row, k) => [...(row.start === undefined ? [] : [{ ms: row.start, end: false, k, row }]), ...(row.end === undefined ? [] : [{ ms: row.end, end: true, k, row }])])
345
+ .sort((a, b) => b.ms - a.ms || (a.end === b.end ? a.k - b.k : a.end ? -1 : 1))
346
+ .slice(0, 8);
347
+ rule();
348
+ add("actTitle", title("◆ Recent Activity"));
349
+ if (events.length === 0)
350
+ add("actEvent", spanLine([{ text: "no conclave run yet", color: THEME.muted }], w));
351
+ for (const { ms, end, row } of events) {
352
+ const state = end ? row.state : "running";
353
+ add("actEvent", spanLine([{ text: input.formatTime(ms), color: THEME.muted }, { text: " " }, { text: row.name }, { text: " → ", color: THEME.muted }, { text: state, color: STATE_COLORS[state] }], w));
354
+ const detail = !end ? "started" : state === "done" ? row.verdict : row.detail ?? row.verdict;
355
+ if (detail !== undefined && detail !== "")
356
+ add("actDetail", spanLine([{ text: ` ${detail}`, color: THEME.muted }], w));
357
+ }
358
+ }
359
+ // Resource Usage: the last reply of the main chat.
360
+ const { usage } = input;
361
+ if (usage !== undefined) {
362
+ const prompt = (usage.input ?? 0) + usage.cacheRead + usage.cacheWrite;
363
+ const row = (label, value, tag) => add("useRow", spanLine([{ text: label.padEnd(8), color: THEME.muted }, { text: value }], w), { tag });
364
+ rule();
365
+ add("useTitle", title("◆ Resource Usage"));
366
+ if (usage.input !== undefined)
367
+ row("Input", `${NUMBER.format(usage.input)} tokens`, "input");
368
+ if (usage.output !== undefined)
369
+ row("Output", `${NUMBER.format(usage.output)} tokens`, "output");
370
+ row("Read", `${NUMBER.format(usage.cacheRead)} tokens`, "read");
371
+ if (prompt > 0)
372
+ row("Cache", `${Math.round((usage.cacheRead / prompt) * 100)}%`, "cache");
373
+ if (usage.contextWindow !== undefined && usage.contextWindow > 0) {
374
+ const percent = Math.round(((prompt + (usage.output ?? 0)) / usage.contextWindow) * 100);
375
+ const filled = Math.min(10, Math.max(0, percent > 0 ? Math.max(1, Math.round(percent / 10)) : 0));
376
+ add("useContext", spanLine([{ text: "Context ", color: THEME.muted }, { text: `${percent}%` }, { text: " " }, { text: "━".repeat(filled), color: THEME.accent }, { text: "─".repeat(10 - filled), color: THEME.border }], w));
377
+ }
378
+ }
379
+ items = tidy(items);
380
+ while (items.length > maxRows) {
381
+ const step = R_STEPS.find((s) => items.some(s.match));
382
+ const at = step === undefined ? items.length - 1 : step.top === true ? items.findIndex(step.match) : items.map(step.match).lastIndexOf(true);
383
+ items.splice(at, 1);
384
+ items = tidy(items);
385
+ }
386
+ return { lines: items.map((item) => item.line), usage: { input: items.some((item) => item.tag === "input"), cache: items.some((item) => item.tag === "read") } };
387
+ }
@@ -0,0 +1,60 @@
1
+ import { createElement } from "react";
2
+ import { Box } from "ink";
3
+ import { VIEW_MAX } from "../chat/view.js";
4
+ import { safe } from "./sanitize.js";
5
+ import { THEME } from "./theme.js";
6
+ import { clip, spanLine } from "./viewport.js";
7
+ // The session panel: what the right column shows while no Conclave run is on screen. It is a fixed block of
8
+ // PANEL_ROWS single-line rows, so the layout does not move while text streams. It reads only data that App
9
+ // already refreshes; nothing here reads a file or starts a timer.
10
+ export const PANEL_ROWS = 8;
11
+ export const PANEL_HINT = "/conclave <task>";
12
+ export function memoryText(memory) {
13
+ if (memory === undefined)
14
+ return "not read yet";
15
+ const parts = [...(memory.pendingSync ? ["vault sync pending"] : []), ...(memory.quarantined > 0 ? [`${memory.quarantined} quarantined`] : []), ...(memory.proposed > 0 ? [`${memory.proposed} proposed`] : [])];
16
+ return parts.length === 0 ? "ok" : parts.join(", ");
17
+ }
18
+ export function webText(web) {
19
+ if (!web.enabled)
20
+ return "off";
21
+ if (web.provider === undefined)
22
+ return "fetch only";
23
+ return `search ${web.provider}${web.keyMissing ? ", key missing" : ""}`;
24
+ }
25
+ /** Exactly PANEL_ROWS lines, each at most `width` columns, a blank line where a row has nothing to say. */
26
+ export function panelLines(data, width) {
27
+ const rows = [
28
+ "Session",
29
+ `main ${data.main ?? "not set"}`,
30
+ `thinking ${data.thinking}`,
31
+ `view ${Math.round(data.viewBytes / 1000)} KB / ${VIEW_MAX / 1000} KB`,
32
+ `compactor ${data.compactor}`,
33
+ `memory ${memoryText(data.memory)}`,
34
+ `web ${webText(data.web)}`,
35
+ data.outcome === undefined || data.outcome === "" ? PANEL_HINT : `last run: ${data.outcome}`,
36
+ ];
37
+ return rows.map((row) => clip(row, Math.max(1, width)) || " ");
38
+ }
39
+ /** The framed panel (P18): the title, then uppercase muted labels padded to 10 with their values, then the hint or the last run. Still PANEL_ROWS rows. */
40
+ export function panelFrame(data, width) {
41
+ const w = Math.max(1, width);
42
+ const warn = THEME.warn;
43
+ const row = (label, value, color) => spanLine([{ text: label.padEnd(10), color: THEME.muted }, { text: value, ...(color === undefined ? {} : { color }) }], w);
44
+ const memory = memoryText(data.memory);
45
+ return [
46
+ spanLine([{ text: "◆ Session", bold: true }], w),
47
+ row("MAIN", data.main ?? "not set"),
48
+ row("THINKING", data.thinking),
49
+ row("VIEW", `${Math.round(data.viewBytes / 1000)} KB / ${VIEW_MAX / 1000} KB`),
50
+ row("COMPACTOR", data.compactor),
51
+ row("MEMORY", memory, data.memory === undefined || memory === "ok" ? undefined : warn),
52
+ row("WEB", webText(data.web), data.web.keyMissing ? warn : undefined),
53
+ spanLine([{ text: data.outcome === undefined || data.outcome === "" ? PANEL_HINT : `last run: ${data.outcome}`, color: THEME.muted }], w),
54
+ ];
55
+ }
56
+ /** The panel in at most `maxRows` rows: the first rows stay, the rest are cut. */
57
+ export function SessionPanel({ data, width, maxRows = PANEL_ROWS }) {
58
+ const lines = panelLines(data, width).slice(0, Math.max(0, maxRows));
59
+ return createElement(Box, { flexDirection: "column" }, ...lines.map((line, i) => safe(line, { key: `r${i}`, wrap: "truncate-end", ...(i === 0 ? { bold: true } : {}), ...(i === PANEL_ROWS - 1 && line === PANEL_HINT ? { color: THEME.muted } : {}) })));
60
+ }