@wheatley-ai/cli 0.2.0 → 0.4.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 (67) hide show
  1. package/README.md +37 -3
  2. package/dist/cli/ask.js +8 -4
  3. package/dist/cli/chat.js +8 -4
  4. package/dist/cli/daemon.js +45 -0
  5. package/dist/cli/io.js +1 -0
  6. package/dist/cli/main.js +145 -157
  7. package/dist/cli/session.js +59 -3
  8. package/dist/cli/status.js +4 -4
  9. package/dist/cli/tui/app.js +14 -2
  10. package/dist/cli/tui/controller.js +80 -19
  11. package/dist/cli/tui/markdown.js +229 -104
  12. package/dist/cli/tui/model-picker.js +76 -0
  13. package/dist/cli/tui/picker-panel.js +39 -0
  14. package/dist/core/agent/agent.js +23 -12
  15. package/dist/core/config/config-store.js +11 -6
  16. package/dist/core/config/diagnostics.js +116 -0
  17. package/dist/core/config/secret-store.js +13 -9
  18. package/dist/core/deployment.js +19 -1
  19. package/dist/core/markdown-tokens.js +60 -0
  20. package/dist/core/model-catalog.js +54 -0
  21. package/dist/core/rpc/deployment-handlers.js +2 -1
  22. package/dist/core/server/control-server.js +19 -21
  23. package/dist/core/server/http-server.js +17 -0
  24. package/dist/core/server/static-files.js +40 -66
  25. package/dist/dashboard/assets/index-DGa2Ps9u.js +12 -0
  26. package/dist/dashboard/assets/index-DeERxJOJ.css +2 -0
  27. package/dist/dashboard/assets/{sheet-presentation-DMljN0LW.js → sheet-presentation-CZ1dO2kr.js} +1 -1
  28. package/dist/dashboard/index.html +2 -2
  29. package/dist/frontends/discord/approvals.js +8 -43
  30. package/dist/frontends/discord/binding.js +81 -8
  31. package/dist/frontends/discord/json-file.js +57 -0
  32. package/dist/frontends/discord/model-picker.js +276 -0
  33. package/dist/frontends/slack/binding.js +33 -3
  34. package/dist/frontends/slack/inbound.js +21 -12
  35. package/dist/frontends/slack/model-picker-blocks.js +147 -0
  36. package/dist/frontends/slack/outbound.js +27 -2
  37. package/dist/frontends/slack/schemas.js +9 -2
  38. package/dist/frontends/telegram/approvals.js +13 -48
  39. package/dist/frontends/telegram/binding.js +5 -0
  40. package/dist/frontends/telegram/client.js +7 -0
  41. package/dist/frontends/telegram/delivery.js +19 -6
  42. package/dist/frontends/telegram/inbound.js +64 -8
  43. package/dist/frontends/telegram/markdown.js +120 -83
  44. package/dist/frontends/telegram/model-picker.js +160 -0
  45. package/dist/frontends/telegram/token-store.js +73 -0
  46. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +13 -0
  47. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +11 -0
  48. package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +1 -1
  49. package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +1 -1
  50. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +20 -0
  51. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +9 -1
  52. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +2 -2
  53. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +2 -2
  54. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +23 -0
  55. package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +1 -1
  56. package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
  57. package/dist/ops/cli.js +127 -114
  58. package/dist/ops/command-runner.js +1 -0
  59. package/dist/ops/install-method.js +189 -0
  60. package/dist/ops/registry.js +35 -0
  61. package/dist/ops/service.js +6 -1
  62. package/dist/ops/update.js +109 -88
  63. package/dist/triggers/delivery-codec.js +13 -0
  64. package/dist/triggers/webhook-ingress.js +89 -82
  65. package/package.json +11 -4
  66. package/dist/dashboard/assets/index-C9Rul5vE.css +0 -2
  67. package/dist/dashboard/assets/index-DXzGGAxQ.js +0 -11
@@ -4,7 +4,8 @@ import { errorMessage } from "../../core/error-message.js";
4
4
  import { ChatState, isCliChatRun, track } from "../chat-state.js";
5
5
  import { shuffledThinkingLines } from "../personality.js";
6
6
  import { LOCAL_COMMANDS, isCommandLine, matchCommands, suggestCommand, } from "./commands.js";
7
- import { createMarkdownRenderer, renderMarkdown } from "./markdown.js";
7
+ import { createMarkdownStream, renderMarkdown } from "./markdown.js";
8
+ import { openPicker, reducePicker } from "./model-picker.js";
8
9
  const MS_PER_SECOND = 1000;
9
10
  /** A Run that takes at least this long rings the bell when it ends. */
10
11
  const NOTIFY_AFTER_MS = 10_000;
@@ -38,9 +39,8 @@ export class ChatController {
38
39
  #now;
39
40
  #view;
40
41
  #nextId = 0;
41
- #buffer = "";
42
42
  #streamed = "";
43
- #renderLine = createMarkdownRenderer();
43
+ #markdown = createMarkdownStream();
44
44
  #replyStarted = false;
45
45
  #runStartedAt;
46
46
  #tools = 0;
@@ -57,6 +57,7 @@ export class ChatController {
57
57
  extensions: undefined,
58
58
  live: [],
59
59
  model: undefined,
60
+ picker: undefined,
60
61
  thinkingLines: shuffledThinkingLines(),
61
62
  usage: { costUsd: 0, inputTokens: 0, outputTokens: 0, runs: 0 },
62
63
  };
@@ -158,6 +159,56 @@ export class ChatController {
158
159
  });
159
160
  }
160
161
  };
162
+ /** Applies a key press to the open picker. */
163
+ editPicker = (action) => {
164
+ const { picker } = this.#view;
165
+ if (picker !== undefined) {
166
+ this.#update({ picker: reducePicker(picker, action) });
167
+ }
168
+ };
169
+ /**
170
+ * Closes the picker and switches to the selected model with `chat.command`. Does nothing if no model matches the
171
+ * query. The Agent's reply shows in the transcript.
172
+ *
173
+ * Errors: never rejects. A failed request becomes an error entry.
174
+ */
175
+ choosePicker = async () => {
176
+ const selected = this.#view.picker?.selected;
177
+ if (selected === undefined) {
178
+ return;
179
+ }
180
+ const model = `${selected.provider}/${selected.id}`;
181
+ this.#update({ picker: undefined });
182
+ try {
183
+ const { accepted } = await this.#options.client.request("chat.command", {
184
+ agent: this.#options.agent,
185
+ args: model,
186
+ name: "model",
187
+ });
188
+ if (accepted) {
189
+ this.#update({ model });
190
+ }
191
+ }
192
+ catch (error) {
193
+ this.#append({
194
+ kind: "notice",
195
+ text: `✗ ${errorMessage(error)}`,
196
+ tone: "error",
197
+ });
198
+ }
199
+ };
200
+ /** Closes the picker without a request. The model stays the same. */
201
+ cancelPicker = () => {
202
+ if (this.#view.picker === undefined) {
203
+ return;
204
+ }
205
+ this.#update({ picker: undefined });
206
+ this.#append({
207
+ kind: "notice",
208
+ text: "The model did not change.",
209
+ tone: "dim",
210
+ });
211
+ };
161
212
  /** Stops the shell command or the active Run. Returns false if nothing was running. */
162
213
  interrupt = () => {
163
214
  if (this.#shell !== undefined) {
@@ -189,6 +240,10 @@ export class ChatController {
189
240
  return;
190
241
  }
191
242
  const command = parseCommandText(line);
243
+ if (command?.name === "model" && command.args === undefined) {
244
+ await this.#openPicker();
245
+ return;
246
+ }
192
247
  if (command !== undefined) {
193
248
  await this.#options.client.request("chat.command", {
194
249
  agent: this.#options.agent,
@@ -224,6 +279,21 @@ export class ChatController {
224
279
  this.#state.sent(messageId);
225
280
  this.#refreshStatus();
226
281
  };
282
+ /**
283
+ * Opens the picker with the models of `models.list`. Without models, it sends `/model` to the Agent instead, so the
284
+ * transcript shows the Agent's own explanation.
285
+ */
286
+ #openPicker = async () => {
287
+ const { agent, client } = this.#options;
288
+ const { current, models } = await client.request("models.list", {
289
+ agent,
290
+ });
291
+ if (models.length === 0) {
292
+ await client.request("chat.command", { agent, name: "model" });
293
+ return;
294
+ }
295
+ this.#update({ picker: openPicker(models, current) });
296
+ };
227
297
  #runShell = (command) => {
228
298
  if (command === "") {
229
299
  this.#append({
@@ -397,20 +467,12 @@ export class ChatController {
397
467
  });
398
468
  };
399
469
  #stream = (delta) => {
400
- this.#buffer += delta;
401
470
  this.#streamed += delta;
402
- const end = this.#buffer.lastIndexOf("\n");
403
- if (end !== -1) {
404
- const lines = this.#buffer.slice(0, end).split("\n");
405
- this.#buffer = this.#buffer.slice(end + 1);
406
- this.#appendReply(lines.map((line) => this.#renderLine(line)));
471
+ const complete = this.#markdown.write(delta);
472
+ if (complete.length > 0) {
473
+ this.#appendReply(complete);
407
474
  }
408
- this.#update({ live: this.#buffer === "" ? [] : [this.#renderPreview()] });
409
- };
410
- /** Renders the unfinished line without changing the renderer's code-fence state. */
411
- #renderPreview = () => {
412
- const preview = createMarkdownRenderer();
413
- return preview(this.#buffer);
475
+ this.#update({ live: this.#markdown.live() });
414
476
  };
415
477
  #appendReply = (lines) => {
416
478
  this.#append({ first: !this.#replyStarted, kind: "reply", lines });
@@ -418,12 +480,11 @@ export class ChatController {
418
480
  };
419
481
  /** Ends the current streamed text block, for example before a Tool call or at the end of a reply. */
420
482
  #endSegment = () => {
421
- if (this.#buffer !== "") {
422
- this.#appendReply([this.#renderLine(this.#buffer)]);
483
+ const rest = this.#markdown.end();
484
+ if (rest.length > 0) {
485
+ this.#appendReply(rest);
423
486
  }
424
- this.#buffer = "";
425
487
  this.#streamed = "";
426
- this.#renderLine = createMarkdownRenderer();
427
488
  this.#replyStarted = false;
428
489
  this.#update({ live: [] });
429
490
  };
@@ -1,22 +1,16 @@
1
1
  import { styleText } from "node:util";
2
2
  import stringWidth from "string-width";
3
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;
4
+ import { blockTokens, inlineTokens, lexMarkdown, taskBox, walkInlineTokens, } from "../../core/markdown-tokens.js";
18
5
  const RULE_WIDTH = 40;
19
6
  const LEADING_SPACES = /^ */u;
7
+ /** Literal bracketed text, which a reference definition later in the reply can still turn into a link. */
8
+ const BRACKETED = /\[[^\]]*\]/u;
9
+ /** The source of a reference link or image, such as `[docs][1]` or `[docs]`. An inline link ends with `)` instead. */
10
+ const REFERENCE_LINK = /^!?\[[\s\S]*\]$/u;
11
+ const H1 = 1;
12
+ const H2 = 2;
13
+ const TASK_BOXES = { checked: "[x] ", unchecked: "[ ] " };
20
14
  const spaces = (text) => " ".repeat(stringWidth(text));
21
15
  const plainLine = (body) => ({
22
16
  body,
@@ -25,111 +19,242 @@ const plainLine = (body) => ({
25
19
  });
26
20
  /** The whole first row of a line, without wrapping. */
27
21
  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;
22
+ /** Styles each row on its own, so a style that spans a line break does not leak into the prefix of the next row. */
23
+ const style = (format, rows) => rows.map((row) => (row === "" ? row : styleText(format, row)));
24
+ const textRows = (text) => text.split("\n");
25
+ /** Joins inline parts. The last row of each part continues on the first row of the next part. */
26
+ const concatRows = (parts) => {
27
+ const rows = [""];
28
+ for (const part of parts) {
29
+ const [first = "", ...rest] = part;
30
+ rows[rows.length - 1] = `${rows.at(-1) ?? ""}${first}`;
31
+ for (const row of rest) {
32
+ rows.push(row);
33
+ }
37
34
  }
38
- return `${result}${text.slice(last)}`;
35
+ return rows;
39
36
  };
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)] ?? "");
37
+ const renderLink = (token) => {
38
+ const label = style("underline", renderInline(token.tokens));
39
+ const plainHref = token.href === token.text || token.href === `mailto:${token.text}`;
40
+ return plainHref
41
+ ? label
42
+ : concatRows([label, [` ${styleText("dim", `(${token.href})`)}`]]);
43
+ };
44
+ const renderInlineToken = (token) => {
45
+ switch (token.type) {
46
+ case "codespan": {
47
+ return [styleText("yellow", token.text.replaceAll("\n", " "))];
48
+ }
49
+ case "strong": {
50
+ return style("bold", renderInline(token.tokens));
51
+ }
52
+ case "em": {
53
+ return style("italic", renderInline(token.tokens));
54
+ }
55
+ case "del": {
56
+ return style("strikethrough", renderInline(token.tokens));
57
+ }
58
+ case "link":
59
+ case "image": {
60
+ return renderLink(token);
61
+ }
62
+ case "br": {
63
+ return ["", ""];
64
+ }
65
+ case "text": {
66
+ return token.tokens === undefined
67
+ ? textRows(token.text)
68
+ : renderInline(token.tokens);
69
+ }
70
+ case "escape": {
71
+ return textRows(token.text);
72
+ }
73
+ case "html": {
74
+ return textRows(token.raw);
75
+ }
76
+ default: {
77
+ return [];
78
+ }
79
+ }
53
80
  };
54
- const renderHeading = (level, text) => {
55
- const content = renderInline(text);
56
- if (level === H1) {
57
- return styleText(["bold", "cyan", "underline"], content);
81
+ /** Styles `code`, **bold**, *italic*, ~~strike~~, and [links](url). Code spans keep their content as is. */
82
+ const renderInline = (tokens) => concatRows(inlineTokens(tokens).map(renderInlineToken));
83
+ /** Puts `lead` before the first line and `hang` before every other line and every continuation row. */
84
+ const prefix = (lines, lead, hang) => lines.map((line, index) => ({
85
+ body: line.body,
86
+ hang: `${hang}${line.hang}`,
87
+ lead: `${index === 0 ? lead : hang}${line.lead}`,
88
+ }));
89
+ const renderHeading = (token) => {
90
+ const rows = renderInline(token.tokens);
91
+ if (token.depth === H1) {
92
+ return style(["bold", "cyan", "underline"], rows).map(plainLine);
58
93
  }
59
- return level === H2
60
- ? styleText(["bold", "cyan"], content)
61
- : styleText("bold", content);
94
+ return (token.depth === H2 ? style(["bold", "cyan"], rows) : style("bold", rows)).map(plainLine);
62
95
  };
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
- };
96
+ const renderCode = (token) => {
97
+ const language = token.lang?.split(" ")[0] ?? "";
98
+ const body = token.text === "" ? [] : token.text.split("\n");
99
+ const rows = body.map((line) => {
100
+ // The indentation goes into the gutter, so it stays on every row and the color codes do not hide it.
101
+ const indent = LEADING_SPACES.exec(line)?.[0] ?? "";
102
+ const gutter = `${styleText("dim", "│")} ${indent}`;
103
+ return {
104
+ body: styleText("green", line.slice(indent.length)),
105
+ hang: gutter,
106
+ lead: gutter,
107
+ };
108
+ });
109
+ return [
110
+ plainLine(styleText("dim", language === "" ? "╭─" : `╭─ ${language}`)),
111
+ ...rows,
112
+ plainLine(styleText("dim", "╰─")),
113
+ ];
70
114
  };
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)));
115
+ const alignCell = (text, width, align) => {
116
+ const gap = width - stringWidth(text);
117
+ if (align === "right") {
118
+ return `${" ".repeat(gap)}${text}`;
79
119
  }
80
- const bullet = BULLET.exec(line)?.groups;
81
- if (bullet !== undefined) {
82
- return renderListItem(bullet.indent ?? "", "•", bullet.text ?? "");
120
+ if (align === "center") {
121
+ const left = Math.floor(gap / 2);
122
+ return `${" ".repeat(left)}${text}${" ".repeat(gap - left)}`;
83
123
  }
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;
124
+ return `${text}${" ".repeat(gap)}`;
125
+ };
126
+ const cellText = (cell) => renderInline(cell.tokens).join(" ");
127
+ const renderTable = (token) => {
128
+ const header = token.header.map(cellText);
129
+ const rows = token.rows.map((row) => row.map(cellText));
130
+ const widths = header.map((text, column) => Math.max(stringWidth(text), ...rows.map((row) => stringWidth(row[column] ?? ""))));
131
+ const line = (cells) => widths
132
+ .map((width, column) => alignCell(cells[column] ?? "", width, token.align[column] ?? null))
133
+ .join(styleText("dim", " │ "));
134
+ const rule = widths.map((width) => "─".repeat(width)).join("─┼─");
135
+ return [
136
+ plainLine(styleText("bold", line(header))),
137
+ plainLine(styleText("dim", rule)),
138
+ ...rows.map((row) => plainLine(line(row))),
139
+ ];
140
+ };
141
+ const renderListItem = (item, marker) => {
142
+ const check = taskBox(item, TASK_BOXES);
143
+ const lead = `${styleText("cyan", marker)} ${check}`;
144
+ const lines = renderBlocks(item.tokens);
145
+ return prefix(lines.length === 0 ? [plainLine("")] : lines, lead, spaces(`${marker} ${check}`));
146
+ };
147
+ const renderList = (token) => {
148
+ const start = token.start === "" ? 1 : token.start;
149
+ return token.items.flatMap((item, index) => {
150
+ const marker = token.ordered ? `${start + index}.` : "•";
151
+ const gap = token.loose && index > 0 ? [plainLine("")] : [];
152
+ return [...gap, ...renderListItem(item, marker)];
153
+ });
154
+ };
155
+ const renderBlockquote = (token) => {
89
156
  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
- };
157
+ const inner = renderBlocks(token.tokens).map((line) => ({
158
+ ...line,
159
+ body: line.body === "" ? "" : styleText("italic", line.body),
160
+ }));
161
+ return prefix(inner, bar, bar);
162
+ };
163
+ const renderBlock = (token) => {
164
+ switch (token.type) {
165
+ case "heading": {
166
+ return renderHeading(token);
167
+ }
168
+ case "paragraph":
169
+ case "text": {
170
+ return (token.tokens === undefined
171
+ ? textRows(token.text)
172
+ : renderInline(token.tokens)).map(plainLine);
173
+ }
174
+ case "code": {
175
+ return renderCode(token);
176
+ }
177
+ case "table": {
178
+ return renderTable(token);
179
+ }
180
+ case "list": {
181
+ return renderList(token);
182
+ }
183
+ case "blockquote": {
184
+ return renderBlockquote(token);
185
+ }
186
+ case "hr": {
187
+ return [plainLine(styleText("dim", "─".repeat(RULE_WIDTH)))];
188
+ }
189
+ case "space": {
190
+ return [plainLine("")];
191
+ }
192
+ case "def":
193
+ case "checkbox":
194
+ case "list_item": {
195
+ return [];
196
+ }
197
+ case "html": {
198
+ return textRows(token.raw.trimEnd()).map(plainLine);
199
+ }
200
+ default: {
201
+ return [];
202
+ }
203
+ }
204
+ };
205
+ const renderBlocks = (tokens) => blockTokens(tokens).flatMap(renderBlock);
206
+ /** Renders a whole Markdown text for the terminal. */
207
+ export const renderMarkdown = (text) => renderBlocks(lexMarkdown(text));
208
+ const isSpace = (token) => token.type === "space";
209
+ /**
210
+ * True if a reference definition later in the reply, for example `[1]: url`, can still change `token`: it shows
211
+ * bracketed text that a definition can turn into a link, or a reference link whose definition can still grow.
212
+ */
213
+ const mayChangeWithDefinition = (token) => {
214
+ let found = false;
215
+ walkInlineTokens([token], (inline) => {
216
+ const isLiteral = inline.type === "text" && inline.tokens === undefined;
217
+ const isLink = inline.type === "link" || inline.type === "image";
218
+ found ||=
219
+ (isLiteral && BRACKETED.test(inline.text)) ||
220
+ (isLink && REFERENCE_LINK.test(inline.raw));
221
+ });
222
+ return found;
97
223
  };
98
224
  /**
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.
225
+ * Renders a streamed reply block by block, so tables, lists, quotes, and code fences render as whole blocks. Each
226
+ * render lexes the whole text, so reference links resolve against every definition so far. A block with bracketed text
227
+ * waits in the live lines until the end, because a later definition can still change it.
101
228
  */
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", "╰─"));
229
+ export const createMarkdownStream = () => {
230
+ let text = "";
231
+ /** The number of top-level tokens of `text` that `write` returned. */
232
+ let printed = 0;
233
+ const unprinted = () => lexMarkdown(text).slice(printed).flatMap(renderBlock);
234
+ return {
235
+ end: () => {
236
+ const lines = unprinted();
237
+ text = "";
238
+ printed = 0;
239
+ return lines;
240
+ },
241
+ live: unprinted,
242
+ write: (delta) => {
243
+ text += delta;
244
+ const tokens = lexMarkdown(text);
245
+ // Blank lines after the last block do not complete it. More list items or quote lines can still follow them.
246
+ const last = tokens.findLastIndex((token) => !isSpace(token));
247
+ const held = tokens.findIndex((token, index) => index >= printed && mayChangeWithDefinition(token));
248
+ const complete = held === -1 ? last : Math.min(last, held);
249
+ if (complete <= printed) {
250
+ return [];
110
251
  }
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));
252
+ const lines = tokens.slice(printed, complete).flatMap(renderBlock);
253
+ printed = complete;
254
+ return lines;
255
+ },
126
256
  };
127
257
  };
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
258
  /** Wraps one line. Leading spaces of the body, for example code indentation, stay on every row. */
134
259
  const wrapLine = (line, width) => {
135
260
  const indent = LEADING_SPACES.exec(line.body)?.[0] ?? "";
@@ -0,0 +1,76 @@
1
+ const WORD_SPLIT = /\s+/u;
2
+ const GRAPHEMES = new Intl.Segmenter();
3
+ const isSameModel = (left, right) => left !== undefined &&
4
+ right !== undefined &&
5
+ left.provider === right.provider &&
6
+ left.id === right.id;
7
+ /** The models that contain every word of the query in their provider, ID, or name, ignoring case. */
8
+ export const pickerMatches = (picker) => {
9
+ const words = picker.query.toLowerCase().split(WORD_SPLIT).filter(Boolean);
10
+ return picker.models.filter((model) => {
11
+ const text = `${model.provider} ${model.id} ${model.name}`.toLowerCase();
12
+ return words.every((word) => text.includes(word));
13
+ });
14
+ };
15
+ /** Opens the picker with the current model selected, or the first model if the current model is not in the list. */
16
+ export const openPicker = (models, current) => ({
17
+ current,
18
+ models,
19
+ query: "",
20
+ selected: models.find((model) => isSameModel(model, current)) ?? models[0],
21
+ });
22
+ const withQuery = (picker, query) => {
23
+ const next = { ...picker, query };
24
+ const matches = pickerMatches(next);
25
+ // The selection stays on its model while the model still matches.
26
+ const kept = matches.find((model) => isSameModel(model, picker.selected));
27
+ return { ...next, selected: kept ?? matches[0] };
28
+ };
29
+ export const reducePicker = (picker, action) => {
30
+ if (action.kind === "type") {
31
+ return withQuery(picker, `${picker.query}${action.text}`);
32
+ }
33
+ if (action.kind === "erase") {
34
+ const last = [...GRAPHEMES.segment(picker.query)].at(-1);
35
+ return withQuery(picker, picker.query.slice(0, picker.query.length - (last?.segment.length ?? 0)));
36
+ }
37
+ const matches = pickerMatches(picker);
38
+ if (matches.length === 0) {
39
+ return picker;
40
+ }
41
+ const index = matches.findIndex((model) => isSameModel(model, picker.selected));
42
+ const next = (index + action.step + matches.length) % matches.length;
43
+ return { ...picker, selected: matches[next] };
44
+ };
45
+ /** The matching models, each provider group under its heading. */
46
+ export const pickerRows = (picker) => {
47
+ const rows = [];
48
+ let provider;
49
+ for (const model of pickerMatches(picker)) {
50
+ if (model.provider !== provider) {
51
+ ({ provider } = model);
52
+ rows.push({ kind: "provider", provider: model.provider });
53
+ }
54
+ rows.push({
55
+ current: isSameModel(model, picker.current),
56
+ kind: "model",
57
+ model,
58
+ selected: isSameModel(model, picker.selected),
59
+ });
60
+ }
61
+ return rows;
62
+ };
63
+ /** At most `height` rows around the selected model, so the selection always shows. */
64
+ export const pickerWindow = (rows, height) => {
65
+ const size = Math.max(1, height);
66
+ if (rows.length <= size) {
67
+ return { above: 0, below: 0, rows };
68
+ }
69
+ const selected = Math.max(0, rows.findIndex((row) => row.kind === "model" && row.selected));
70
+ const start = Math.min(Math.max(0, selected - Math.floor(size / 2)), rows.length - size);
71
+ return {
72
+ above: start,
73
+ below: rows.length - start - size,
74
+ rows: rows.slice(start, start + size),
75
+ };
76
+ };
@@ -0,0 +1,39 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text, useInput } from "ink";
3
+ import { pickerMatches, pickerRows, pickerWindow } from "./model-picker.js";
4
+ /** The lines of the panel and the chat around it that are not list rows: borders, title, query, footer, status bar. */
5
+ const RESERVED_LINES = 8;
6
+ const MIN_LIST_ROWS = 3;
7
+ const RowView = ({ row }) => {
8
+ if (row.kind === "provider") {
9
+ return (_jsx(Text, { bold: true, dimColor: true, wrap: "truncate-end", children: row.provider }));
10
+ }
11
+ const { model, selected, current } = row;
12
+ return (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", children: selected ? "› " : " " }), _jsx(Text, { bold: selected, color: selected ? "cyan" : undefined, children: model.id }), model.name === model.id ? undefined : (_jsxs(Text, { dimColor: true, children: [" ", model.name] })), current ? _jsx(Text, { color: "green", children: " (current)" }) : undefined] }));
13
+ };
14
+ /** The `/model` picker. Typing filters, arrows move, Enter chooses, Esc cancels. */
15
+ export const PickerPanel = ({ picker, columns, rows, onEdit, onChoose, onCancel, }) => {
16
+ useInput((input, key) => {
17
+ if (key.escape || (key.ctrl && input === "c")) {
18
+ onCancel();
19
+ }
20
+ else if (key.return) {
21
+ onChoose();
22
+ }
23
+ else if (key.upArrow || key.downArrow) {
24
+ onEdit({ kind: "move", step: key.upArrow ? -1 : 1 });
25
+ }
26
+ else if (key.backspace || key.delete) {
27
+ onEdit({ kind: "erase" });
28
+ }
29
+ else if (!key.ctrl && !key.meta && input !== "") {
30
+ onEdit({ kind: "type", text: input });
31
+ }
32
+ });
33
+ const matches = pickerMatches(picker);
34
+ const view = pickerWindow(pickerRows(picker), Math.max(MIN_LIST_ROWS, rows - RESERVED_LINES));
35
+ const position = picker.selected === undefined ? 0 : matches.indexOf(picker.selected) + 1;
36
+ return (_jsxs(Box, { borderColor: "cyan", borderStyle: "round", flexDirection: "column", paddingX: 1, width: columns, children: [_jsxs(Text, { children: [_jsx(Text, { bold: true, children: "Choose a model " }), _jsx(Text, { children: picker.query }), _jsx(Text, { inverse: true, children: " " })] }), view.above > 0 ? _jsxs(Text, { dimColor: true, children: ["\u2191 ", view.above, " more"] }) : undefined, matches.length === 0 ? (_jsxs(Text, { dimColor: true, children: ["No model matches \u201C", picker.query, "\u201D."] })) : (view.rows.map((row) => (_jsx(RowView, { row: row }, row.kind === "provider"
37
+ ? `provider:${row.provider}`
38
+ : `model:${row.model.provider}/${row.model.id}`)))), view.below > 0 ? _jsxs(Text, { dimColor: true, children: ["\u2193 ", view.below, " more"] }) : undefined, _jsxs(Text, { dimColor: true, children: [position, "/", matches.length, " \u00B7 type to filter \u00B7 \u2191\u2193 move \u00B7 Enter selects \u00B7 Esc cancels"] })] }));
39
+ };