@wheatley-ai/cli 0.1.1 → 0.3.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/README.md +37 -3
- package/dist/cli/chat-state.js +95 -0
- package/dist/cli/chat.js +32 -95
- package/dist/cli/io.js +22 -2
- package/dist/cli/main.js +8 -2
- package/dist/cli/personality.js +81 -0
- package/dist/cli/tui/app.js +159 -0
- package/dist/cli/tui/commands.js +98 -0
- package/dist/cli/tui/controller.js +504 -0
- package/dist/cli/tui/editor.js +125 -0
- package/dist/cli/tui/format.js +32 -0
- package/dist/cli/tui/markdown.js +147 -0
- package/dist/cli/tui/prompt.js +275 -0
- package/dist/cli/tui/run.js +63 -0
- package/dist/cli/tui/transcript.js +89 -0
- package/dist/dashboard/assets/{index-DXzGGAxQ.js → index-DThc2x_d.js} +2 -2
- package/dist/dashboard/assets/{sheet-presentation-DMljN0LW.js → sheet-presentation-CkgiDsTg.js} +1 -1
- package/dist/dashboard/index.html +1 -1
- package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
- package/dist/ops/cli.js +41 -22
- package/dist/ops/command-runner.js +1 -0
- package/dist/ops/install-method.js +189 -0
- package/dist/ops/registry.js +35 -0
- package/dist/ops/update.js +95 -61
- package/package.json +8 -2
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
export const EMPTY_DRAFT = { cursor: 0, text: "" };
|
|
2
|
+
export const draftOf = (text) => ({ cursor: text.length, text });
|
|
3
|
+
export const insert = (draft, value) => ({
|
|
4
|
+
cursor: draft.cursor + value.length,
|
|
5
|
+
text: `${draft.text.slice(0, draft.cursor)}${value}${draft.text.slice(draft.cursor)}`,
|
|
6
|
+
});
|
|
7
|
+
export const deleteBackward = (draft) => draft.cursor === 0
|
|
8
|
+
? draft
|
|
9
|
+
: {
|
|
10
|
+
cursor: draft.cursor - 1,
|
|
11
|
+
text: `${draft.text.slice(0, draft.cursor - 1)}${draft.text.slice(draft.cursor)}`,
|
|
12
|
+
};
|
|
13
|
+
export const deleteForward = (draft) => ({
|
|
14
|
+
cursor: draft.cursor,
|
|
15
|
+
text: `${draft.text.slice(0, draft.cursor)}${draft.text.slice(draft.cursor + 1)}`,
|
|
16
|
+
});
|
|
17
|
+
export const moveLeft = (draft) => ({
|
|
18
|
+
...draft,
|
|
19
|
+
cursor: Math.max(0, draft.cursor - 1),
|
|
20
|
+
});
|
|
21
|
+
export const moveRight = (draft) => ({
|
|
22
|
+
...draft,
|
|
23
|
+
cursor: Math.min(draft.text.length, draft.cursor + 1),
|
|
24
|
+
});
|
|
25
|
+
const lineStart = (draft) => draft.text.lastIndexOf("\n", draft.cursor - 1) + 1;
|
|
26
|
+
const lineEnd = (draft) => {
|
|
27
|
+
const end = draft.text.indexOf("\n", draft.cursor);
|
|
28
|
+
return end === -1 ? draft.text.length : end;
|
|
29
|
+
};
|
|
30
|
+
export const moveHome = (draft) => ({
|
|
31
|
+
...draft,
|
|
32
|
+
cursor: lineStart(draft),
|
|
33
|
+
});
|
|
34
|
+
export const moveEnd = (draft) => ({
|
|
35
|
+
...draft,
|
|
36
|
+
cursor: lineEnd(draft),
|
|
37
|
+
});
|
|
38
|
+
const WORD_CHARACTER = /\w/u;
|
|
39
|
+
const isWordCharacter = (character) => character !== undefined && WORD_CHARACTER.test(character);
|
|
40
|
+
/** The index of the start of the word before the cursor. Skips spaces and punctuation before the word first. */
|
|
41
|
+
const previousWordStart = (draft) => {
|
|
42
|
+
let index = draft.cursor;
|
|
43
|
+
while (index > 0 && !isWordCharacter(draft.text[index - 1])) {
|
|
44
|
+
index -= 1;
|
|
45
|
+
}
|
|
46
|
+
while (index > 0 && isWordCharacter(draft.text[index - 1])) {
|
|
47
|
+
index -= 1;
|
|
48
|
+
}
|
|
49
|
+
return index;
|
|
50
|
+
};
|
|
51
|
+
const nextWordEnd = (draft) => {
|
|
52
|
+
let index = draft.cursor;
|
|
53
|
+
while (index < draft.text.length && !isWordCharacter(draft.text[index])) {
|
|
54
|
+
index += 1;
|
|
55
|
+
}
|
|
56
|
+
while (index < draft.text.length && isWordCharacter(draft.text[index])) {
|
|
57
|
+
index += 1;
|
|
58
|
+
}
|
|
59
|
+
return index;
|
|
60
|
+
};
|
|
61
|
+
export const moveWordLeft = (draft) => ({
|
|
62
|
+
...draft,
|
|
63
|
+
cursor: previousWordStart(draft),
|
|
64
|
+
});
|
|
65
|
+
export const moveWordRight = (draft) => ({
|
|
66
|
+
...draft,
|
|
67
|
+
cursor: nextWordEnd(draft),
|
|
68
|
+
});
|
|
69
|
+
/** Ctrl+W: deletes the word before the cursor. */
|
|
70
|
+
export const deleteWordBackward = (draft) => {
|
|
71
|
+
const start = previousWordStart(draft);
|
|
72
|
+
return {
|
|
73
|
+
cursor: start,
|
|
74
|
+
text: `${draft.text.slice(0, start)}${draft.text.slice(draft.cursor)}`,
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
/** Ctrl+U: deletes from the start of the current line to the cursor. */
|
|
78
|
+
export const deleteToLineStart = (draft) => {
|
|
79
|
+
const start = lineStart(draft);
|
|
80
|
+
return {
|
|
81
|
+
cursor: start,
|
|
82
|
+
text: `${draft.text.slice(0, start)}${draft.text.slice(draft.cursor)}`,
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
/** Ctrl+K: deletes from the cursor to the end of the current line. */
|
|
86
|
+
export const deleteToLineEnd = (draft) => ({
|
|
87
|
+
cursor: draft.cursor,
|
|
88
|
+
text: `${draft.text.slice(0, draft.cursor)}${draft.text.slice(lineEnd(draft))}`,
|
|
89
|
+
});
|
|
90
|
+
/** True if the cursor is on the first line of the draft. Up then recalls history instead of moving between lines. */
|
|
91
|
+
export const onFirstLine = (draft) => !draft.text.slice(0, draft.cursor).includes("\n");
|
|
92
|
+
/** True if the cursor is on the last line of the draft. */
|
|
93
|
+
export const onLastLine = (draft) => !draft.text.slice(draft.cursor).includes("\n");
|
|
94
|
+
/** Moves the cursor one line up or down, and keeps its column where the line is long enough. */
|
|
95
|
+
export const moveVertical = (draft, step) => {
|
|
96
|
+
const start = lineStart(draft);
|
|
97
|
+
const column = draft.cursor - start;
|
|
98
|
+
if (step === -1) {
|
|
99
|
+
const previousEnd = start - 1;
|
|
100
|
+
const previousStart = draft.text.lastIndexOf("\n", previousEnd - 1) + 1;
|
|
101
|
+
return {
|
|
102
|
+
...draft,
|
|
103
|
+
cursor: Math.min(previousStart + column, previousEnd),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
const end = lineEnd(draft);
|
|
107
|
+
const nextStart = end + 1;
|
|
108
|
+
const nextEnd = lineEnd({ ...draft, cursor: nextStart });
|
|
109
|
+
return { ...draft, cursor: Math.min(nextStart + column, nextEnd) };
|
|
110
|
+
};
|
|
111
|
+
export const HISTORY_START = { index: -1, saved: EMPTY_DRAFT };
|
|
112
|
+
/** Moves one step back (older) or forward (newer) in `history`. Returns `undefined` at either end. */
|
|
113
|
+
export const stepHistory = (history, cursor, current, step) => {
|
|
114
|
+
// Step 1 is older. The newest entry is at index 0.
|
|
115
|
+
const index = cursor.index + step;
|
|
116
|
+
if (index < -1 || index >= history.length) {
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
const saved = cursor.index === -1 ? current : cursor.saved;
|
|
120
|
+
const entry = history[index];
|
|
121
|
+
return {
|
|
122
|
+
cursor: { index, saved },
|
|
123
|
+
draft: index === -1 || entry === undefined ? saved : draftOf(entry),
|
|
124
|
+
};
|
|
125
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const THOUSAND = 1000;
|
|
2
|
+
const MILLION = 1_000_000;
|
|
3
|
+
const SECONDS_PER_MINUTE = 60;
|
|
4
|
+
const SECONDS_PER_HOUR = 3600;
|
|
5
|
+
const SHORT_SECONDS = 10;
|
|
6
|
+
const CENT = 0.01;
|
|
7
|
+
/** A token count for the status bar, for example `842`, `12.3k`, or `1.2M`. */
|
|
8
|
+
export const formatCount = (count) => {
|
|
9
|
+
if (count >= MILLION) {
|
|
10
|
+
return `${(count / MILLION).toFixed(1)}M`;
|
|
11
|
+
}
|
|
12
|
+
return count >= THOUSAND ? `${(count / THOUSAND).toFixed(1)}k` : `${count}`;
|
|
13
|
+
};
|
|
14
|
+
/** A cost in US dollars, with more digits below one cent. */
|
|
15
|
+
export const formatCost = (usd) => usd > 0 && usd < CENT ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`;
|
|
16
|
+
/** A duration, for example `0.4s`, `12s`, `3m 05s`, or `1h 02m`. */
|
|
17
|
+
export const formatSeconds = (seconds) => {
|
|
18
|
+
if (seconds < SHORT_SECONDS) {
|
|
19
|
+
return `${seconds.toFixed(1)}s`;
|
|
20
|
+
}
|
|
21
|
+
const whole = Math.round(seconds);
|
|
22
|
+
if (whole < SECONDS_PER_MINUTE) {
|
|
23
|
+
return `${whole}s`;
|
|
24
|
+
}
|
|
25
|
+
if (whole < SECONDS_PER_HOUR) {
|
|
26
|
+
const minutes = Math.floor(whole / SECONDS_PER_MINUTE);
|
|
27
|
+
return `${minutes}m ${String(whole % SECONDS_PER_MINUTE).padStart(2, "0")}s`;
|
|
28
|
+
}
|
|
29
|
+
const hours = Math.floor(whole / SECONDS_PER_HOUR);
|
|
30
|
+
const minutes = Math.floor((whole % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
|
|
31
|
+
return `${hours}h ${String(minutes).padStart(2, "0")}m`;
|
|
32
|
+
};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { styleText } from "node:util";
|
|
2
|
+
import stringWidth from "string-width";
|
|
3
|
+
import wrapAnsi from "wrap-ansi";
|
|
4
|
+
const FENCE = /^\s*(?<marker>```|~~~)\s*(?<language>[\w+-]*)\s*$/u;
|
|
5
|
+
const HEADING = /^(?<hashes>#{1,6})\s+(?<text>.*)$/u;
|
|
6
|
+
const BULLET = /^(?<indent>\s*)[-*+]\s+(?<text>.*)$/u;
|
|
7
|
+
const NUMBERED = /^(?<indent>\s*)(?<number>\d+)[.)]\s+(?<text>.*)$/u;
|
|
8
|
+
const QUOTE = /^\s*>\s?(?<text>.*)$/u;
|
|
9
|
+
const RULE = /^\s*(?<mark>[-*_])(?:\s*\k<mark>){2,}\s*$/u;
|
|
10
|
+
const INLINE_CODE = /`(?<code>[^`]+)`/gu;
|
|
11
|
+
const BOLD = /\*\*(?<star>[^*]+)\*\*|__(?<under>[^_]+)__/gu;
|
|
12
|
+
const ITALIC = /(?<![\w*])\*(?<star>[^*\s][^*]*)\*(?!\*)|(?<![\w_])_(?<under>[^_\s][^_]*)_(?!\w)/gu;
|
|
13
|
+
const STRIKE = /~~(?<text>[^~]+)~~/gu;
|
|
14
|
+
const LINK = /\[(?<label>[^\]]+)\]\((?<url>[^)\s]+)\)/gu;
|
|
15
|
+
/** Marks a code span while the emphasis rules run. U+E000 is a private-use character that real text does not use. */
|
|
16
|
+
const CODE_MARK = "";
|
|
17
|
+
const CODE_PLACEHOLDER = /(?<index>\d+)/gu;
|
|
18
|
+
const RULE_WIDTH = 40;
|
|
19
|
+
const LEADING_SPACES = /^ */u;
|
|
20
|
+
const spaces = (text) => " ".repeat(stringWidth(text));
|
|
21
|
+
const plainLine = (body) => ({
|
|
22
|
+
body,
|
|
23
|
+
hang: "",
|
|
24
|
+
lead: "",
|
|
25
|
+
});
|
|
26
|
+
/** The whole first row of a line, without wrapping. */
|
|
27
|
+
export const lineText = (line) => `${line.lead}${line.body}`;
|
|
28
|
+
const H1 = 1;
|
|
29
|
+
const H2 = 2;
|
|
30
|
+
/** Replaces every match of `pattern` in `text` with `render` of its named groups. */
|
|
31
|
+
const replaceMatches = (text, pattern, render) => {
|
|
32
|
+
let result = "";
|
|
33
|
+
let last = 0;
|
|
34
|
+
for (const match of text.matchAll(pattern)) {
|
|
35
|
+
result += `${text.slice(last, match.index)}${render(match.groups ?? {})}`;
|
|
36
|
+
last = match.index + match[0].length;
|
|
37
|
+
}
|
|
38
|
+
return `${result}${text.slice(last)}`;
|
|
39
|
+
};
|
|
40
|
+
/** Styles `code`, **bold**, *italic*, ~~strike~~, and [links](url) in one line. Code spans keep their content as is. */
|
|
41
|
+
export const renderInline = (text) => {
|
|
42
|
+
const codeSpans = [];
|
|
43
|
+
// Code spans go out first and come back last, so emphasis rules do not touch their content.
|
|
44
|
+
const withoutCode = replaceMatches(text, INLINE_CODE, ({ code }) => {
|
|
45
|
+
codeSpans.push(styleText("yellow", code ?? ""));
|
|
46
|
+
return `${CODE_MARK}${codeSpans.length - 1}${CODE_MARK}`;
|
|
47
|
+
});
|
|
48
|
+
const linked = replaceMatches(withoutCode, LINK, ({ label, url }) => `${styleText("underline", label ?? "")} ${styleText("dim", `(${url ?? ""})`)}`);
|
|
49
|
+
const bold = replaceMatches(linked, BOLD, ({ star, under }) => styleText("bold", star ?? under ?? ""));
|
|
50
|
+
const italic = replaceMatches(bold, ITALIC, ({ star, under }) => styleText("italic", star ?? under ?? ""));
|
|
51
|
+
const struck = replaceMatches(italic, STRIKE, ({ text: inner }) => styleText("strikethrough", inner ?? ""));
|
|
52
|
+
return replaceMatches(struck, CODE_PLACEHOLDER, ({ index }) => codeSpans[Number(index)] ?? "");
|
|
53
|
+
};
|
|
54
|
+
const renderHeading = (level, text) => {
|
|
55
|
+
const content = renderInline(text);
|
|
56
|
+
if (level === H1) {
|
|
57
|
+
return styleText(["bold", "cyan", "underline"], content);
|
|
58
|
+
}
|
|
59
|
+
return level === H2
|
|
60
|
+
? styleText(["bold", "cyan"], content)
|
|
61
|
+
: styleText("bold", content);
|
|
62
|
+
};
|
|
63
|
+
const renderListItem = (indent, marker, text) => {
|
|
64
|
+
const lead = `${indent}${styleText("cyan", marker)} `;
|
|
65
|
+
return {
|
|
66
|
+
body: renderInline(text),
|
|
67
|
+
hang: spaces(`${indent}${marker} `),
|
|
68
|
+
lead,
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
/** Renders one line outside a code block, or returns `undefined` if the line is plain text. */
|
|
72
|
+
const renderBlock = (line) => {
|
|
73
|
+
const heading = HEADING.exec(line)?.groups;
|
|
74
|
+
if (heading !== undefined) {
|
|
75
|
+
return plainLine(renderHeading(heading.hashes?.length ?? 1, heading.text ?? ""));
|
|
76
|
+
}
|
|
77
|
+
if (RULE.test(line)) {
|
|
78
|
+
return plainLine(styleText("dim", "─".repeat(RULE_WIDTH)));
|
|
79
|
+
}
|
|
80
|
+
const bullet = BULLET.exec(line)?.groups;
|
|
81
|
+
if (bullet !== undefined) {
|
|
82
|
+
return renderListItem(bullet.indent ?? "", "•", bullet.text ?? "");
|
|
83
|
+
}
|
|
84
|
+
const numbered = NUMBERED.exec(line)?.groups;
|
|
85
|
+
if (numbered !== undefined) {
|
|
86
|
+
return renderListItem(numbered.indent ?? "", `${numbered.number ?? ""}.`, numbered.text ?? "");
|
|
87
|
+
}
|
|
88
|
+
const quote = QUOTE.exec(line)?.groups;
|
|
89
|
+
const bar = `${styleText("dim", "▎")} `;
|
|
90
|
+
return quote === undefined
|
|
91
|
+
? undefined
|
|
92
|
+
: {
|
|
93
|
+
body: styleText("italic", renderInline(quote.text ?? "")),
|
|
94
|
+
hang: bar,
|
|
95
|
+
lead: bar,
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Renders Markdown one line at a time, as a streamed reply arrives. The renderer keeps the code-fence state between
|
|
100
|
+
* lines, so a code block that arrives over many deltas renders as one block.
|
|
101
|
+
*/
|
|
102
|
+
export const createMarkdownRenderer = () => {
|
|
103
|
+
let fence;
|
|
104
|
+
return (line) => {
|
|
105
|
+
const opening = FENCE.exec(line)?.groups;
|
|
106
|
+
if (fence !== undefined) {
|
|
107
|
+
if (opening?.marker === fence) {
|
|
108
|
+
fence = undefined;
|
|
109
|
+
return plainLine(styleText("dim", "╰─"));
|
|
110
|
+
}
|
|
111
|
+
// The indentation goes into the gutter, so it stays on every row and the color codes do not hide it.
|
|
112
|
+
const indent = LEADING_SPACES.exec(line)?.[0] ?? "";
|
|
113
|
+
const gutter = `${styleText("dim", "│")} ${indent}`;
|
|
114
|
+
return {
|
|
115
|
+
body: styleText("green", line.slice(indent.length)),
|
|
116
|
+
hang: gutter,
|
|
117
|
+
lead: gutter,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
if (opening !== undefined) {
|
|
121
|
+
fence = opening.marker;
|
|
122
|
+
const language = opening.language ?? "";
|
|
123
|
+
return plainLine(styleText("dim", language === "" ? "╭─" : `╭─ ${language}`));
|
|
124
|
+
}
|
|
125
|
+
return renderBlock(line) ?? plainLine(renderInline(line));
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
/** Renders a whole Markdown text for the terminal. */
|
|
129
|
+
export const renderMarkdown = (text) => {
|
|
130
|
+
const render = createMarkdownRenderer();
|
|
131
|
+
return text.split("\n").map((line) => render(line));
|
|
132
|
+
};
|
|
133
|
+
/** Wraps one line. Leading spaces of the body, for example code indentation, stay on every row. */
|
|
134
|
+
const wrapLine = (line, width) => {
|
|
135
|
+
const indent = LEADING_SPACES.exec(line.body)?.[0] ?? "";
|
|
136
|
+
const lead = `${line.lead}${indent}`;
|
|
137
|
+
const hang = `${line.hang}${indent}`;
|
|
138
|
+
const prefixWidth = Math.max(stringWidth(lead), stringWidth(hang));
|
|
139
|
+
const rows = wrapAnsi(line.body.slice(indent.length), Math.max(1, width - prefixWidth), { hard: true, trim: true }).split("\n");
|
|
140
|
+
return rows
|
|
141
|
+
.map((row, index) => `${index === 0 ? lead : hang}${row}`)
|
|
142
|
+
.join("\n");
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* Wraps rendered lines to `width` columns at word boundaries. A word breaks only when it is longer than the line.
|
|
146
|
+
*/
|
|
147
|
+
export const wrapLines = (lines, width) => lines.map((line) => wrapLine(line, width)).join("\n");
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { Box, Text, useInput, usePaste } from "ink";
|
|
3
|
+
import { useRef, useState } from "react";
|
|
4
|
+
import { commandLabel, matchCommands } from "./commands.js";
|
|
5
|
+
import { deleteBackward, deleteForward, deleteToLineEnd, deleteToLineStart, deleteWordBackward, draftOf, EMPTY_DRAFT, HISTORY_START, insert, moveEnd, moveHome, moveLeft, moveRight, moveVertical, moveWordLeft, moveWordRight, onFirstLine, onLastLine, stepHistory, } from "./editor.js";
|
|
6
|
+
const MENU_ROWS = 10;
|
|
7
|
+
/** A second Ctrl+C or Esc within this time exits or clears the line. */
|
|
8
|
+
const DOUBLE_PRESS_MS = 2000;
|
|
9
|
+
/** A paste with more lines or characters than this shows as one placeholder in the input box. */
|
|
10
|
+
const PASTE_LINES = 8;
|
|
11
|
+
const PASTE_CHARACTERS = 2000;
|
|
12
|
+
const HISTORY_LIMIT = 500;
|
|
13
|
+
const PASTE_TOKEN = /\[Pasted text #(?<number>\d+) · \d+ lines\]/gu;
|
|
14
|
+
const FIRST_PRINTABLE = 0x20;
|
|
15
|
+
const DELETE_CHARACTER = 0x7f;
|
|
16
|
+
/** Removes control characters from typed input, for example the bytes of an unknown escape sequence. */
|
|
17
|
+
const printable = (text) => {
|
|
18
|
+
let result = "";
|
|
19
|
+
for (const character of text) {
|
|
20
|
+
const code = character.codePointAt(0) ?? 0;
|
|
21
|
+
if (code >= FIRST_PRINTABLE && code !== DELETE_CHARACTER) {
|
|
22
|
+
result += character;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
};
|
|
27
|
+
const Menu = ({ matches, selected }) => {
|
|
28
|
+
const width = Math.max(...matches.map((command) => commandLabel(command).length));
|
|
29
|
+
return (_jsx(Box, { flexDirection: "column", marginLeft: 2, children: matches.map((command, index) => {
|
|
30
|
+
const isSelected = index === selected;
|
|
31
|
+
return (_jsxs(Text, { children: [_jsx(Text, { color: "cyan", children: isSelected ? "› " : " " }), _jsx(Text, { bold: isSelected, color: isSelected ? "cyan" : undefined, children: commandLabel(command).padEnd(width) }), _jsxs(Text, { dimColor: true, children: [" ", command.description] }), command.local ? _jsx(Text, { dimColor: true, children: " \u00B7 local" }) : undefined] }, command.word));
|
|
32
|
+
}) }));
|
|
33
|
+
};
|
|
34
|
+
/** The draft with a block cursor. The ghost text shows the rest of the selected command after the cursor. */
|
|
35
|
+
const InputLines = ({ draft, ghost, busy }) => {
|
|
36
|
+
if (draft.text === "") {
|
|
37
|
+
return (_jsxs(Text, { children: [_jsx(Text, { inverse: true, children: " " }), _jsx(Text, { dimColor: true, children: busy
|
|
38
|
+
? " Type the next message, or press Esc to interrupt"
|
|
39
|
+
: " Ask anything · / for commands · ! for shell" })] }));
|
|
40
|
+
}
|
|
41
|
+
const before = draft.text.slice(0, draft.cursor);
|
|
42
|
+
const atCursor = draft.text[draft.cursor];
|
|
43
|
+
const after = draft.text.slice(draft.cursor + 1);
|
|
44
|
+
// A newline under the cursor shows as a space, so the cursor stays visible at a line end.
|
|
45
|
+
const cursorCharacter = atCursor === undefined || atCursor === "\n" ? " " : atCursor;
|
|
46
|
+
const restAfterCursor = atCursor === "\n" ? `\n${after}` : after;
|
|
47
|
+
return (_jsxs(Text, { children: [before, _jsx(Text, { inverse: true, children: cursorCharacter }), restAfterCursor, ghost === "" ? undefined : _jsx(Text, { dimColor: true, children: ghost })] }));
|
|
48
|
+
};
|
|
49
|
+
/** The input box with the command menu and the key bindings. */
|
|
50
|
+
export const Prompt = ({ busy, columns, history, onHistory, onSubmit, onInterrupt, onExit, }) => {
|
|
51
|
+
const [draft, setDraft] = useState(EMPTY_DRAFT);
|
|
52
|
+
const [selected, setSelected] = useState(0);
|
|
53
|
+
const [menuDismissed, setMenuDismissed] = useState(false);
|
|
54
|
+
const [hint, setHint] = useState();
|
|
55
|
+
const historyRef = useRef([...history]);
|
|
56
|
+
const historyCursor = useRef(HISTORY_START);
|
|
57
|
+
const pastes = useRef(new Map());
|
|
58
|
+
const lastCtrlC = useRef(0);
|
|
59
|
+
const lastEscape = useRef(0);
|
|
60
|
+
const matches = menuDismissed
|
|
61
|
+
? []
|
|
62
|
+
: matchCommands(draft.text).slice(0, MENU_ROWS);
|
|
63
|
+
const choice = matches[Math.min(selected, matches.length - 1)];
|
|
64
|
+
const ghost = choice !== undefined &&
|
|
65
|
+
choice.word.startsWith(draft.text) &&
|
|
66
|
+
draft.cursor === draft.text.length
|
|
67
|
+
? choice.word.slice(draft.text.length)
|
|
68
|
+
: "";
|
|
69
|
+
const edit = (next) => {
|
|
70
|
+
setDraft(next);
|
|
71
|
+
setSelected(0);
|
|
72
|
+
setMenuDismissed(false);
|
|
73
|
+
setHint(undefined);
|
|
74
|
+
historyCursor.current = HISTORY_START;
|
|
75
|
+
};
|
|
76
|
+
const submit = (text) => {
|
|
77
|
+
let expanded = text;
|
|
78
|
+
for (const match of text.matchAll(PASTE_TOKEN)) {
|
|
79
|
+
const pasted = pastes.current.get(Number(match.groups?.number));
|
|
80
|
+
if (pasted !== undefined) {
|
|
81
|
+
expanded = expanded.replace(match[0], pasted);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (expanded.trim() !== "") {
|
|
85
|
+
const next = [
|
|
86
|
+
expanded,
|
|
87
|
+
...historyRef.current.filter((entry) => entry !== expanded),
|
|
88
|
+
].slice(0, HISTORY_LIMIT);
|
|
89
|
+
historyRef.current = next;
|
|
90
|
+
onHistory(next);
|
|
91
|
+
}
|
|
92
|
+
pastes.current.clear();
|
|
93
|
+
edit(EMPTY_DRAFT);
|
|
94
|
+
onSubmit(expanded);
|
|
95
|
+
};
|
|
96
|
+
const onReturn = (key) => {
|
|
97
|
+
if (key.meta || key.shift) {
|
|
98
|
+
edit(insert(draft, "\n"));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (draft.text.endsWith("\\") && draft.cursor === draft.text.length) {
|
|
102
|
+
edit(insert(deleteBackward(draft), "\n"));
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
submit(choice === undefined ? draft.text : choice.word);
|
|
106
|
+
};
|
|
107
|
+
const onCtrlC = () => {
|
|
108
|
+
if (draft.text !== "") {
|
|
109
|
+
edit(EMPTY_DRAFT);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (onInterrupt()) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const now = Date.now();
|
|
116
|
+
if (now - lastCtrlC.current < DOUBLE_PRESS_MS) {
|
|
117
|
+
onExit();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
lastCtrlC.current = now;
|
|
121
|
+
setHint("Press Ctrl+C again to exit");
|
|
122
|
+
};
|
|
123
|
+
const onEscape = () => {
|
|
124
|
+
if (matches.length > 0) {
|
|
125
|
+
setMenuDismissed(true);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (onInterrupt()) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const now = Date.now();
|
|
132
|
+
if (draft.text !== "" && now - lastEscape.current < DOUBLE_PRESS_MS) {
|
|
133
|
+
edit(EMPTY_DRAFT);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
lastEscape.current = now;
|
|
137
|
+
if (draft.text !== "") {
|
|
138
|
+
setHint("Press Esc again to clear the line");
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
const onVertical = (step) => {
|
|
142
|
+
if (matches.length > 0) {
|
|
143
|
+
setSelected((selected + step + matches.length) % matches.length);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const atEdge = step === -1 ? onFirstLine(draft) : onLastLine(draft);
|
|
147
|
+
if (!atEdge) {
|
|
148
|
+
setDraft(moveVertical(draft, step));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
// Up goes to older entries, which have higher indexes.
|
|
152
|
+
const moved = stepHistory(historyRef.current, historyCursor.current, draft, step === -1 ? 1 : -1);
|
|
153
|
+
if (moved !== undefined) {
|
|
154
|
+
historyCursor.current = moved.cursor;
|
|
155
|
+
setDraft(moved.draft);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
/** Ctrl plus a letter. Returns false for a letter without a binding. */
|
|
159
|
+
const ctrlLetter = (letter) => {
|
|
160
|
+
switch (letter) {
|
|
161
|
+
case "a": {
|
|
162
|
+
setDraft(moveHome(draft));
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
case "c": {
|
|
166
|
+
onCtrlC();
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
case "d": {
|
|
170
|
+
if (draft.text === "") {
|
|
171
|
+
onExit();
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
edit(deleteForward(draft));
|
|
175
|
+
}
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
case "e": {
|
|
179
|
+
setDraft(moveEnd(draft));
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
case "j": {
|
|
183
|
+
edit(insert(draft, "\n"));
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
case "k": {
|
|
187
|
+
edit(deleteToLineEnd(draft));
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
case "u": {
|
|
191
|
+
edit(deleteToLineStart(draft));
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
case "w": {
|
|
195
|
+
edit(deleteWordBackward(draft));
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
default: {
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return true;
|
|
203
|
+
};
|
|
204
|
+
const ctrlKeys = (input, key) => {
|
|
205
|
+
if (!key.ctrl) {
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
if (key.leftArrow || key.rightArrow) {
|
|
209
|
+
setDraft(key.leftArrow ? moveWordLeft(draft) : moveWordRight(draft));
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
return ctrlLetter(input);
|
|
213
|
+
};
|
|
214
|
+
const navigationKeys = (_input, key) => {
|
|
215
|
+
if (key.upArrow || key.downArrow) {
|
|
216
|
+
onVertical(key.upArrow ? -1 : 1);
|
|
217
|
+
}
|
|
218
|
+
else if (key.leftArrow) {
|
|
219
|
+
setDraft(key.meta ? moveWordLeft(draft) : moveLeft(draft));
|
|
220
|
+
}
|
|
221
|
+
else if (key.rightArrow) {
|
|
222
|
+
// Right at the end of the line takes the ghost text, as in a shell.
|
|
223
|
+
if (ghost !== "" && draft.cursor === draft.text.length) {
|
|
224
|
+
setDraft(draftOf(`${draft.text}${ghost}`));
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
setDraft(key.meta ? moveWordRight(draft) : moveRight(draft));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
else if (key.home || key.end) {
|
|
231
|
+
setDraft(key.home ? moveHome(draft) : moveEnd(draft));
|
|
232
|
+
}
|
|
233
|
+
else {
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
return true;
|
|
237
|
+
};
|
|
238
|
+
useInput((input, key) => {
|
|
239
|
+
if (ctrlKeys(input, key) || navigationKeys(input, key)) {
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (key.return) {
|
|
243
|
+
onReturn(key);
|
|
244
|
+
}
|
|
245
|
+
else if (key.escape) {
|
|
246
|
+
onEscape();
|
|
247
|
+
}
|
|
248
|
+
else if (key.tab) {
|
|
249
|
+
if (choice !== undefined) {
|
|
250
|
+
edit(draftOf(choice.argument === undefined ? choice.word : `${choice.word} `));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
else if (key.backspace || key.delete) {
|
|
254
|
+
edit(key.meta ? deleteWordBackward(draft) : deleteBackward(draft));
|
|
255
|
+
}
|
|
256
|
+
else if (input !== "") {
|
|
257
|
+
const text = printable(input);
|
|
258
|
+
if (text !== "") {
|
|
259
|
+
edit(insert(draft, text));
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
usePaste((pasted) => {
|
|
264
|
+
const text = pasted.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
|
265
|
+
const lines = text.split("\n").length;
|
|
266
|
+
if (lines <= PASTE_LINES && text.length <= PASTE_CHARACTERS) {
|
|
267
|
+
edit(insert(draft, text));
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const number = pastes.current.size + 1;
|
|
271
|
+
pastes.current.set(number, text);
|
|
272
|
+
edit(insert(draft, `[Pasted text #${number} · ${lines} lines]`));
|
|
273
|
+
});
|
|
274
|
+
return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { borderColor: busy ? "gray" : "cyan", borderStyle: "round", paddingX: 1, width: columns, children: [_jsx(Box, { width: 2, children: _jsx(Text, { bold: true, color: "cyan", children: "\u203A" }) }), _jsx(Box, { flexGrow: 1, flexShrink: 1, children: _jsx(InputLines, { busy: busy, draft: draft, ghost: ghost }) })] }), matches.length > 0 ? (_jsx(Menu, { matches: matches, selected: Math.min(selected, matches.length - 1) })) : undefined, hint === undefined ? undefined : (_jsx(Box, { marginLeft: 2, children: _jsx(Text, { color: "yellow", children: hint }) }))] }));
|
|
275
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { styleText } from "node:util";
|
|
5
|
+
import { render } from "ink";
|
|
6
|
+
import { GOODBYES, pick } from "../personality.js";
|
|
7
|
+
import { ChatApp } from "./app.js";
|
|
8
|
+
import { ChatController } from "./controller.js";
|
|
9
|
+
import { formatCost, formatCount, formatSeconds } from "./format.js";
|
|
10
|
+
/** The file in the Deployment home that keeps the input history of the interactive chat. */
|
|
11
|
+
const HISTORY_FILE = "chat_history";
|
|
12
|
+
/** Each history entry takes one line, with its newlines escaped. */
|
|
13
|
+
const NEWLINE = /\n/gu;
|
|
14
|
+
const ESCAPED_NEWLINE = /\\n/gu;
|
|
15
|
+
const MS_PER_SECOND = 1000;
|
|
16
|
+
const readHistory = async (file) => {
|
|
17
|
+
try {
|
|
18
|
+
const text = await readFile(file, "utf-8");
|
|
19
|
+
return text
|
|
20
|
+
.split("\n")
|
|
21
|
+
.filter(Boolean)
|
|
22
|
+
.map((line) => line.replaceAll(ESCAPED_NEWLINE, "\n"));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
const writeHistory = async (file, history) => {
|
|
29
|
+
try {
|
|
30
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
31
|
+
await writeFile(file, `${history.map((entry) => entry.replaceAll(NEWLINE, "\\n")).join("\n")}\n`, { mode: 0o600 });
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// The history is a convenience. A chat without it still works.
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** Runs the interactive terminal chat until the user exits. Resolves with the exit code. */
|
|
38
|
+
export const runInteractiveChat = async ({ agent, client, home, version, streams, }) => {
|
|
39
|
+
const controller = new ChatController({
|
|
40
|
+
agent,
|
|
41
|
+
client,
|
|
42
|
+
control: (sequence) => {
|
|
43
|
+
streams.output.write(sequence);
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
await controller.start();
|
|
47
|
+
const historyFile = path.join(home, HISTORY_FILE);
|
|
48
|
+
const history = await readHistory(historyFile);
|
|
49
|
+
const startedAt = Date.now();
|
|
50
|
+
const instance = render(_jsx(ChatApp, { controller: controller, history: history, onHistory: (next) => {
|
|
51
|
+
void writeHistory(historyFile, next);
|
|
52
|
+
}, version: version }), { exitOnCtrlC: false, stdin: streams.input, stdout: streams.output });
|
|
53
|
+
await instance.waitUntilExit();
|
|
54
|
+
const { usage } = controller.view();
|
|
55
|
+
const summary = [
|
|
56
|
+
formatSeconds((Date.now() - startedAt) / MS_PER_SECOND),
|
|
57
|
+
usage.runs === 1 ? "1 run" : `${usage.runs} runs`,
|
|
58
|
+
`↑${formatCount(usage.inputTokens)} ↓${formatCount(usage.outputTokens)} tokens`,
|
|
59
|
+
formatCost(usage.costUsd),
|
|
60
|
+
].join(" · ");
|
|
61
|
+
streams.output.write(`\n${styleText("cyan", "◉")} ${styleText("italic", pick(GOODBYES) ?? "")}\n${styleText("dim", ` ${summary}`)}\n`);
|
|
62
|
+
return 0;
|
|
63
|
+
};
|