@pmndre/pine 0.34.0 → 0.35.1
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/changes.json +12 -12
- package/docs/SKILL.md +1 -1
- package/docs/references/agents.md +6 -0
- package/docs/references/tui.md +65 -2
- package/package.json +1 -1
- package/src/agents.js +2 -0
- package/src/manual.js +1 -1
- package/src/sources/telegram.js +5 -3
- package/src/tui/app.d.ts +2 -0
- package/src/tui/app.js +62 -15
- package/src/tui/theme.d.ts +41 -5
- package/src/tui/theme.js +156 -4
- package/src/util.d.ts +27 -0
- package/src/util.js +129 -0
package/changes.json
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.35.1",
|
|
4
|
+
"changes": [
|
|
5
|
+
"fix: when pine asks you for several values at once (the two tokens of a Slack app), each is a block of its own in the dialog"
|
|
6
|
+
]
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
"version": "0.35.0",
|
|
10
|
+
"changes": [
|
|
11
|
+
"feat: an agent can fold away part of an answer, and you open it with a click"
|
|
12
|
+
]
|
|
13
|
+
},
|
|
2
14
|
{
|
|
3
15
|
"version": "0.34.0",
|
|
4
16
|
"changes": [
|
|
@@ -249,17 +261,5 @@
|
|
|
249
261
|
"feat: steering, undo, plan mode, goals, background commands, questions and a list of steps",
|
|
250
262
|
"feat: an agent operates the apps on a Mac, by outline or by picture, and asks once per app"
|
|
251
263
|
]
|
|
252
|
-
},
|
|
253
|
-
{
|
|
254
|
-
"version": "0.9.1",
|
|
255
|
-
"changes": [
|
|
256
|
-
"fix: an agent does not act on a browser page its owner opened unseen, and esc spares the message typed meanwhile"
|
|
257
|
-
]
|
|
258
|
-
},
|
|
259
|
-
{
|
|
260
|
-
"version": "0.9.0",
|
|
261
|
-
"changes": [
|
|
262
|
-
"feat: pine init sets up Linux itself, and the README says how to run pine in Docker"
|
|
263
|
-
]
|
|
264
264
|
}
|
|
265
265
|
]
|
package/docs/SKILL.md
CHANGED
|
@@ -165,7 +165,7 @@ hand work to the agents listed in your prompt, and write shared state under your
|
|
|
165
165
|
| You want to | Read |
|
|
166
166
|
|---|---|
|
|
167
167
|
| See what an agent is given (events, schedules, MCP servers, skills) and how events, tasks and sessions fit together | [references/overview.md](references/overview.md) |
|
|
168
|
-
| Chat with agents in the terminal: tabs, slash commands (`/goal`, `/compact`, `/copy`, `/export`, `/undo`), keys, the five modes (auto, safe, manual, bypass, plan), approvals, an agent's questions and its list of steps, what a model thinks, pictures, switching models | [references/tui.md](references/tui.md) |
|
|
168
|
+
| Chat with agents in the terminal: tabs, slash commands (`/goal`, `/compact`, `/copy`, `/export`, `/undo`), keys, the five modes (auto, safe, manual, bypass, plan), approvals, an agent's questions and its list of steps, what a model thinks, pictures, parts of an answer that are folded away, switching models | [references/tui.md](references/tui.md) |
|
|
169
169
|
| Work on a project: `pine .`, a folder for a conversation, the code pane with git changes, files and tool output, what an agent left running, what it runs in the background, and taking a message back with `/undo` and `/redo` | [references/coding.md](references/coding.md) |
|
|
170
170
|
| Install it, start it, update it, use the CLI (every `pine` command), the control API for scripts, run it at login or in a container, find out why something did not happen | [references/operations.md](references/operations.md) |
|
|
171
171
|
| Look up a key in `pine.json`, `agent.json`, `models.json` or `.env` | [references/configuration.md](references/configuration.md) |
|
|
@@ -176,6 +176,12 @@ not to play a sound with a command of its own (`afplay`), which you could neithe
|
|
|
176
176
|
screenshot, an image an MCP server made) is drawn where the tool ran, and the agent is told not
|
|
177
177
|
to show it a second time.
|
|
178
178
|
|
|
179
|
+
To fold away something long that goes with an answer (a full message, a log, a long list), an
|
|
180
|
+
agent writes `<details><summary>what it is</summary>` in front of it and `</details>` after it.
|
|
181
|
+
The terminal UI shows one line for it, which you open with a click (see "Folded parts of an
|
|
182
|
+
answer" in [tui.md](tui.md)); a Telegram message carries the summary as a line and the text
|
|
183
|
+
under it. pine's base prompt tells every agent this too.
|
|
184
|
+
|
|
179
185
|
Nothing in the system prompt changes from one turn to the next. That is deliberate: a model
|
|
180
186
|
server keeps what it has already read (the prompt cache) only as long as the beginning of the
|
|
181
187
|
prompt is identical, and on a local model a miss means reading the whole conversation again
|
package/docs/references/tui.md
CHANGED
|
@@ -58,6 +58,7 @@ Everything in the two bars reacts to a click.
|
|
|
58
58
|
| Anywhere beside an open list | It closes. The click does nothing else |
|
|
59
59
|
| Anywhere beside an approval dialog or a question | Nothing: it stays open until you answer it or put it off with `esc` |
|
|
60
60
|
| A `▸ 12 tool calls` line | Everything the agent did in that turn opens: every tool call, thought and sub-task, and what it wrote in between. A click on the line, or on `▴ close` at the end, closes it again. See [The tool calls of a turn](#the-tool-calls-of-a-turn) |
|
|
61
|
+
| A `▸` line inside an answer (`▸ Full message · click to open`) | The part of the answer that was folded away opens under the line. A click on the line, or on `▴ close` at its end, folds it again. See [Folded parts of an answer](#folded-parts-of-an-answer) |
|
|
61
62
|
| A `▸ thinking` or `▸ thought for` line, or the lines under it | What the model thought opens in full. A click anywhere on the open text closes it again. See [What a model thinks](#what-a-model-thinks) |
|
|
62
63
|
| A web address in the conversation | It opens in your browser |
|
|
63
64
|
| A picture | It is enlarged; a second click shrinks it again |
|
|
@@ -368,10 +369,12 @@ answer the one before it or put it off.
|
|
|
368
369
|
| `esc` | Later: the request stays open until `security.approvalTimeout` (5 minutes) has passed and then counts as denied. Until then the status line keeps reminding you, `enter` on an empty line opens the dialog again, and `/approve` or `/deny` answer it A question in a tab that is not in front opens no dialog there: that tab gets a `!` in the tab bar, and the status line of the tab you are in says which tab waits (`alt+<n>` goes there) |
|
|
369
370
|
|
|
370
371
|
When the action needs something only you have (a bot's token, a device's password), the dialog
|
|
371
|
-
has a field for it
|
|
372
|
+
has a field for it: the value's name, under it what it is, and a bar to type into. When it needs
|
|
373
|
+
several (the two tokens of a Slack app), each is a block of its own, numbered "1 of 2", and the
|
|
374
|
+
name of the one you are typing into is in colour. Type or paste it: a secret is shown as dots, goes into pine's `.env` and is
|
|
372
375
|
never seen by the agent or its model. (Pairing a Telegram account uses the same dialog for the
|
|
373
376
|
six-digit code the bot sent to your phone; the code is shown as you type and is not stored.)
|
|
374
|
-
`enter` saves and allows, `tab` and `shift+tab
|
|
377
|
+
`enter` saves and allows, `tab` and `shift+tab`, the arrow keys or a click on a field move between fields, `ctrl+u`
|
|
375
378
|
empties one, `esc` leaves it for later, and `/approve` opens the dialog again. The letter keys
|
|
376
379
|
are part of what you type there, so `a` and `d` are not shortcuts in this dialog; Deny is a
|
|
377
380
|
button to click.
|
|
@@ -414,12 +417,72 @@ An answer is markdown, and it is drawn, not shown as written:
|
|
|
414
417
|
| A table | A grid. Columns follow the alignment of the table's second line (`---:` right, `:---:` centred); a `<br>` in a cell is a line break; cells wrap when the table is wider than the terminal |
|
|
415
418
|
| Headings | Bold and in colour, without their `#`; the first level is underlined |
|
|
416
419
|
| Lists, task lists, quotes, rules, links, bold, italic, strikethrough, inline code | As such |
|
|
420
|
+
| A `<details>` block | One line with its summary, which a click opens. See [Folded parts of an answer](#folded-parts-of-an-answer) |
|
|
417
421
|
|
|
418
422
|
Shown as written: other HTML tags and footnotes. A table too wide to fit even with one
|
|
419
423
|
character per column is shown as written too. Code is coloured with the terminal's own sixteen
|
|
420
424
|
colours; the accent and the background of your own messages come from the 256-colour palette.
|
|
421
425
|
`NO_COLOR` turns colours off.
|
|
422
426
|
|
|
427
|
+
## Folded parts of an answer
|
|
428
|
+
|
|
429
|
+
An answer can carry something long that belongs with it and need not be read at once: the
|
|
430
|
+
whole of a message it summed up, a log, a long list. The agent folds it away, and the
|
|
431
|
+
conversation shows one line for it:
|
|
432
|
+
|
|
433
|
+
```
|
|
434
|
+
▸ Full message · click to open
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
A click on the line opens it. What was folded away stands under the line, drawn as markdown
|
|
438
|
+
like the rest of the answer and set in by two columns:
|
|
439
|
+
|
|
440
|
+
```
|
|
441
|
+
▾ Full message · click here to close
|
|
442
|
+
Dear Ms Okapi,
|
|
443
|
+
|
|
444
|
+
the keys are with the caretaker until Friday.
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
A second click on the line folds it again, and so does `▴ close` at the end of a part of more
|
|
448
|
+
than six lines; the line that is left is brought into view. There is no key for it. What you
|
|
449
|
+
opened stays open for as long as the tab is: a new message, scrolling or a resize do not fold
|
|
450
|
+
it. After the UI is opened again every part is as the answer wrote it.
|
|
451
|
+
|
|
452
|
+
What an agent writes for it (every agent is told so in its prompt):
|
|
453
|
+
|
|
454
|
+
```markdown
|
|
455
|
+
The landlord agrees to the date. The keys are with the caretaker.
|
|
456
|
+
|
|
457
|
+
<details><summary>Full message</summary>
|
|
458
|
+
|
|
459
|
+
Dear Ms Okapi,
|
|
460
|
+
|
|
461
|
+
the keys are with the caretaker until Friday.
|
|
462
|
+
|
|
463
|
+
</details>
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
| In the answer | What it does |
|
|
467
|
+
|---|---|
|
|
468
|
+
| `<details>` ... `</details>` | Folds away what stands between them. Capitals do not matter and attributes are ignored. Without the closing tag the part runs to the end of the answer |
|
|
469
|
+
| `<summary>` ... `</summary>` | Right after `<details>`: the one line that is shown. Bold and inline code in it are drawn, a line break is a space, and a long one is cut to the width. Without it the line reads `Details` |
|
|
470
|
+
| `<details open>` | The part starts open |
|
|
471
|
+
|
|
472
|
+
- A part inside a part is folded the same way: it has its own line inside the outer one, and
|
|
473
|
+
opens and closes by itself.
|
|
474
|
+
- The tags inside a code block or inline code are text and are printed, so an agent can show
|
|
475
|
+
how it is written.
|
|
476
|
+
- While an answer is still arriving, a part that is not finished is one line already (`▸ …`
|
|
477
|
+
until its summary is whole). The tags themselves never show.
|
|
478
|
+
- A link inside a folded part has its address printed next to it, as everywhere.
|
|
479
|
+
- A picture that a folded part points at with `` is drawn under the answer,
|
|
480
|
+
not inside the part.
|
|
481
|
+
- `/copy` and `/export` give the answer as the agent wrote it, with the tags, so that it folds
|
|
482
|
+
again in a markdown viewer.
|
|
483
|
+
- On Telegram nothing folds: the part arrives as its summary on a line of its own
|
|
484
|
+
(`▾ Full message`) with the text under it.
|
|
485
|
+
|
|
423
486
|
## Pictures
|
|
424
487
|
|
|
425
488
|
Pictures are drawn in the conversation:
|
package/package.json
CHANGED
package/src/agents.js
CHANGED
|
@@ -98,6 +98,7 @@ const BASE_PROMPT = `You are an agent in pine, a system that runs several AI age
|
|
|
98
98
|
- MEMORY.md: your memory. When you learn something that matters beyond this conversation (a decision, a fact, a preference, an open end), write it there right away, briefly. It is read with every message, so keep it short: when it has grown long, tidy it. Merge what belongs together, drop what no longer holds, move details into other files in your workspace and leave a pointer.
|
|
99
99
|
- {{OWNER}}
|
|
100
100
|
- To show your owner a picture, write  in your answer, with a file in your workspace (png, jpg, gif or webp; a video as mp4, mov or webm is shown the same way). A sound is played to your owner the same way, with the file in your workspace (wav, mp3, m4a, ogg or flac): , once, and no other link to it. pine plays it and gives your owner play and pause: never play a sound yourself with a command such as afplay. A web address works too, but your owner has to click to load it; for a picture from the web, download it first and show the file. A picture that came with a tool's answer is already on your owner's screen, above your reply: do not write  for it, and do not copy or download it unless your owner asks for it as a file.
|
|
101
|
+
- To fold away something long that goes with your answer (a full message, a log, a long list), write <details><summary>what it is</summary>, then the text, then </details>: your owner sees one line and opens it with a click.
|
|
101
102
|
</working>
|
|
102
103
|
|
|
103
104
|
<limits>
|
|
@@ -127,6 +128,7 @@ const SHORT_PROMPT = `You are an agent in pine, a system that runs several AI ag
|
|
|
127
128
|
- MEMORY.md: your memory. When you learn something that matters beyond this conversation (a decision, a fact, a preference, an open end), write it there right away, briefly. It is part of every conversation, so keep it short: merge what belongs together, drop what no longer holds, move details into other files and leave a pointer.
|
|
128
129
|
- {{OWNER}}
|
|
129
130
|
- To show your owner a picture, a video or a sound, write  in your answer, with a file in your workspace. pine shows or plays it: never play a sound yourself with a command. A picture from the web: download it first and show the file. A picture that came with a tool's answer is already on your owner's screen: do not show it again.
|
|
131
|
+
- To fold away something long that goes with your answer (a full message, a log, a long list), write <details><summary>what it is</summary>, then the text, then </details>: your owner sees one line and opens it with a click.
|
|
130
132
|
</working>
|
|
131
133
|
|
|
132
134
|
<limits>
|
package/src/manual.js
CHANGED
|
@@ -67,7 +67,7 @@ const SYNONYMS = [
|
|
|
67
67
|
["bars", "waveform", "spectrum", "equalizer", "equaliser", "visualizer", "visualiser", "animation", "animated"],
|
|
68
68
|
["dictate", "dictating", "dictation", "microphone", "talk", "talking", "speak", "speaking"],
|
|
69
69
|
["browser", "web", "playwright", "page", "search"],
|
|
70
|
-
["fold", "collapse", "collapsed", "expand", "unfold", "clutter", "cluttered", "noise"],
|
|
70
|
+
["fold", "collapse", "collapsed", "collapsible", "expand", "expandable", "unfold", "accordion", "spoiler", "details", "disclosure", "clutter", "cluttered", "noise"],
|
|
71
71
|
["show", "visible", "headed", "headless", "window", "watch", "see"],
|
|
72
72
|
["plan", "propose", "proposal", "outline", "preview", "dry"],
|
|
73
73
|
["todo", "step", "checklist", "track", "progress", "tasklist"],
|
package/src/sources/telegram.js
CHANGED
|
@@ -2,7 +2,7 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { Type } from "typebox";
|
|
5
|
-
import { errText, sleep, truncate } from "../util.js";
|
|
5
|
+
import { errText, sleep, truncate, unfolded } from "../util.js";
|
|
6
6
|
/**
|
|
7
7
|
* A Telegram bot: the owner writes to it from wherever they are, and the agent answers there.
|
|
8
8
|
*
|
|
@@ -140,11 +140,13 @@ export default async function telegram(source) {
|
|
|
140
140
|
if (!Number.isFinite(chatId))
|
|
141
141
|
throw new Error("nobody is connected yet: your owner has to write to the bot once, and confirm it in pine");
|
|
142
142
|
const file = message.file;
|
|
143
|
+
// Sent as plain text, which folds nothing: a block the terminal UI would fold is its summary and what it holds.
|
|
144
|
+
const text = unfolded(String(message.text ?? ""));
|
|
143
145
|
if (file && Buffer.isBuffer(file.bytes)) {
|
|
144
|
-
await sendFile(chatId, file,
|
|
146
|
+
await sendFile(chatId, file, text);
|
|
145
147
|
return `sent to your owner on Telegram, with ${file.name}`;
|
|
146
148
|
}
|
|
147
|
-
await send(chatId,
|
|
149
|
+
await send(chatId, text);
|
|
148
150
|
return "sent to your owner on Telegram";
|
|
149
151
|
});
|
|
150
152
|
// "typing…" while an agent works on something that will be answered here.
|
package/src/tui/app.d.ts
CHANGED
|
@@ -200,6 +200,8 @@ export declare class PineTui {
|
|
|
200
200
|
private foldWords;
|
|
201
201
|
/** The turn is over: its work becomes one line, unless somebody opened it. */
|
|
202
202
|
private endWork;
|
|
203
|
+
/** A task's message is whole: it is drawn as it was written, with nothing held back for a tag that might still come. */
|
|
204
|
+
private endBlock;
|
|
203
205
|
/** A task's model stopped thinking: what it thought is closed, or stays open if somebody opened it. */
|
|
204
206
|
private endThought;
|
|
205
207
|
/** Ask what the commands of the conversation in front left running. Quietly: a daemon that does not answer changes nothing. */
|
package/src/tui/app.js
CHANGED
|
@@ -3,7 +3,7 @@ import fs from "node:fs";
|
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { CombinedAutocompleteProvider, Container, Editor, isKeyRelease, isKeyRepeat, matchesKey, fuzzyFilter, getCapabilities, HStack, hyperlink, ScrollView, setCapabilities, sliceByColumn, SelectList, Spacer, stripTerminalSequences, Text, truncateToWidth, TuiAltScreen, visibleWidth, VStack, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
|
|
6
|
-
import { errText, expandHome, openInSystem, safeName, speedOf, speedText } from "../util.js";
|
|
6
|
+
import { errText, expandHome, openInSystem, safeName, speedOf, speedText, unfolded } from "../util.js";
|
|
7
7
|
import { Listening, voiceTools } from "./voice.js";
|
|
8
8
|
import { CodePane, PANE_VIEWS } from "./code-pane.js";
|
|
9
9
|
import { redoText, undoText } from "./undo.js";
|
|
@@ -544,7 +544,19 @@ class Work {
|
|
|
544
544
|
rowOf(inner, width) {
|
|
545
545
|
this.render(width);
|
|
546
546
|
const at = this.rows.findIndex((r) => r && r !== "toggle" && (r.part.component === inner || (r.part.component instanceof Linked && r.part.component.inner === inner)));
|
|
547
|
-
|
|
547
|
+
if (at >= 0)
|
|
548
|
+
return at;
|
|
549
|
+
// A folded block in words the agent wrote on the way.
|
|
550
|
+
for (let y = 0; y < this.rows.length; y++) {
|
|
551
|
+
const r = this.rows[y];
|
|
552
|
+
if (!r || r === "toggle" || r.y !== 0)
|
|
553
|
+
continue;
|
|
554
|
+
const words = r.part.component instanceof Linked ? r.part.component.inner : r.part.component;
|
|
555
|
+
const within = words instanceof Answer ? words.rowOf(inner, width) : undefined;
|
|
556
|
+
if (within !== undefined)
|
|
557
|
+
return y + within;
|
|
558
|
+
}
|
|
559
|
+
return undefined;
|
|
548
560
|
}
|
|
549
561
|
handleMouse(e) {
|
|
550
562
|
const row = this.rows[e.y];
|
|
@@ -806,6 +818,8 @@ class ApprovalDialog {
|
|
|
806
818
|
*/
|
|
807
819
|
fields;
|
|
808
820
|
field = 0;
|
|
821
|
+
/** The rows each value's block takes in the dialog, for a click on one. */
|
|
822
|
+
areas = [];
|
|
809
823
|
constructor(req, done) {
|
|
810
824
|
this.req = req;
|
|
811
825
|
this.done = done;
|
|
@@ -839,6 +853,10 @@ class ApprovalDialog {
|
|
|
839
853
|
const b = this.buttons.find((x) => e.y === x.row && e.x >= x.from && e.x < x.to);
|
|
840
854
|
if (b && e.type === "click" && e.button === "left")
|
|
841
855
|
this.answer(b.answer);
|
|
856
|
+
// A click on a value's block is where the typing goes next.
|
|
857
|
+
const area = this.areas.find((x) => e.y >= x.from && e.y < x.to);
|
|
858
|
+
if (area && e.type === "click" && e.button === "left")
|
|
859
|
+
this.field = area.field;
|
|
842
860
|
return { handled: true, render: true };
|
|
843
861
|
}
|
|
844
862
|
handleInput(data) {
|
|
@@ -883,11 +901,6 @@ class ApprovalDialog {
|
|
|
883
901
|
}
|
|
884
902
|
render(width) {
|
|
885
903
|
const inner = Math.max(20, width - 4);
|
|
886
|
-
const inputs = this.fields.flatMap((f, i) => [
|
|
887
|
-
...wrapTextWithAnsi(c.bold(f.label), inner),
|
|
888
|
-
// A secret is never shown: a dot for each character, so that you see it arrive.
|
|
889
|
-
`${i === this.field ? c.accent(">") : " "} ${c.yellow(f.secret ? "•".repeat(Math.min(f.value.length, inner - 6)) : f.value.slice(-(inner - 6)))}${i === this.field ? c.inverse(" ") : ""}`,
|
|
890
|
-
]);
|
|
891
904
|
const body = [
|
|
892
905
|
c.bold(c.yellow(this.fields.length ? "Approval needed, and something only you have" : "Approval needed")),
|
|
893
906
|
"",
|
|
@@ -899,9 +912,33 @@ class ApprovalDialog {
|
|
|
899
912
|
...(this.req.holds ? wrapTextWithAnsi(c.gray(`"Allow" holds for ${this.req.holds}: you are not asked about it again there.`), inner) : []),
|
|
900
913
|
...(this.req.remember ? wrapTextWithAnsi(c.gray(`"Always here" stops asking about ${this.req.remember} in this conversation.`), inner) : []),
|
|
901
914
|
...(!this.req.remember && !this.req.holds && !this.fields.length ? wrapTextWithAnsi(c.gray("This one is asked every time: there is no \"always\" for it."), inner) : []),
|
|
902
|
-
...(inputs.length ? ["", ...inputs, ...wrapTextWithAnsi(c.gray(this.fields.some((f) => f.secret) ? "Type or paste it here. It is not shown, goes into pine's .env file, and never reaches the agent or its model." : "Type it here and press enter. Without it, this cannot be allowed."), inner)] : []),
|
|
903
|
-
"",
|
|
904
915
|
];
|
|
916
|
+
// Each value is a block of its own: its name, what it is, and a bar to type into, with an empty
|
|
917
|
+
// line before it. Run together, two tokens read as one paragraph.
|
|
918
|
+
const bar = inner - 2;
|
|
919
|
+
this.areas = [];
|
|
920
|
+
this.fields.forEach((f, i) => {
|
|
921
|
+
const active = i === this.field;
|
|
922
|
+
// A label that reads "name: what it is" or "NAME (what it is)" is its name and, under it, the rest.
|
|
923
|
+
const [, name, about] = f.label.match(/^([\w.-]+): ([\s\S]+)$/) ?? f.label.match(/^([\w.-]+) \(([\s\S]+)\)$/) ?? [null, f.label, ""];
|
|
924
|
+
const count = this.fields.length > 1 ? `${i + 1} of ${this.fields.length}` : "";
|
|
925
|
+
// A secret is never shown: a dot for each character, so that you see it arrive.
|
|
926
|
+
const shown = f.secret ? "•".repeat(Math.min(f.value.length, bar - 2)) : f.value.slice(-(bar - 2));
|
|
927
|
+
const typed = shown || active ? `${c.yellow(shown)}${active ? c.inverse(" ") : ""}` : c.gray("empty");
|
|
928
|
+
body.push("");
|
|
929
|
+
const from = 1 + body.length;
|
|
930
|
+
body.push(...wrapTextWithAnsi(active ? c.bold(c.accent(name)) : c.bold(name), inner - count.length - 2).map((l, n) => (n || !count ? l : `${l}${" ".repeat(Math.max(2, inner - visibleWidth(l) - count.length))}${c.gray(count)}`)), ...(about ? wrapTextWithAnsi(about, inner) : []), `${active ? c.accent(">") : " "} ${c.bgPanel(`${typed}${" ".repeat(Math.max(0, bar - visibleWidth(typed)))}`)}`);
|
|
931
|
+
this.areas.push({ from, to: 1 + body.length, field: i });
|
|
932
|
+
});
|
|
933
|
+
if (this.fields.length) {
|
|
934
|
+
const hint = !this.fields.some((f) => f.secret)
|
|
935
|
+
? "Type it here and press enter. Without it, this cannot be allowed."
|
|
936
|
+
: this.fields.length > 1
|
|
937
|
+
? "Type or paste each one into its bar; tab goes to the next. They are not shown, go into pine's .env file, and never reach the agent or its model."
|
|
938
|
+
: "Type or paste it here. It is not shown, goes into pine's .env file, and never reaches the agent or its model.";
|
|
939
|
+
body.push("", ...wrapTextWithAnsi(c.gray(hint), inner));
|
|
940
|
+
}
|
|
941
|
+
body.push("");
|
|
905
942
|
// The buttons, wrapped onto a second line in a narrow window. Their places are kept for clicks:
|
|
906
943
|
// two columns of border and padding, then the labels.
|
|
907
944
|
const rows = [""];
|
|
@@ -1488,6 +1525,9 @@ export class PineTui {
|
|
|
1488
1525
|
add(tab, component, gap = true) {
|
|
1489
1526
|
if (gap && tab.doc.children.length)
|
|
1490
1527
|
tab.doc.addChild(new Spacer(1));
|
|
1528
|
+
// A block of the answer that a click opens or closes stays in the window, like the work of a turn.
|
|
1529
|
+
if (component instanceof Answer)
|
|
1530
|
+
component.toggled = (block, open) => this.keepInView(tab, block, open);
|
|
1491
1531
|
tab.doc.addChild(new Linked(component));
|
|
1492
1532
|
if (tab !== this.active)
|
|
1493
1533
|
tab.unread = true;
|
|
@@ -1529,7 +1569,7 @@ export class PineTui {
|
|
|
1529
1569
|
if (inner) {
|
|
1530
1570
|
if (child === inner || (child instanceof Linked && child.inner === inner))
|
|
1531
1571
|
return row;
|
|
1532
|
-
const at = child instanceof Work ? child.rowOf(inner, width) : undefined;
|
|
1572
|
+
const at = child instanceof Work ? child.rowOf(inner, width) : child instanceof Linked && child.inner instanceof Answer ? child.inner.rowOf(inner, width) : undefined;
|
|
1533
1573
|
if (at !== undefined)
|
|
1534
1574
|
return row + at;
|
|
1535
1575
|
}
|
|
@@ -1578,7 +1618,7 @@ export class PineTui {
|
|
|
1578
1618
|
if (shown.at(-1) instanceof Spacer)
|
|
1579
1619
|
shown.pop();
|
|
1580
1620
|
// A model's text on one line: nothing in it may move the cursor or colour the screen.
|
|
1581
|
-
this.work(tab).add({ component: last, brief: () => short(oneLine(stripTerminalSequences(said.block.text).replace(/[\x00-\x1f\x7f]/g, " ")), 160) });
|
|
1621
|
+
this.work(tab).add({ component: last, brief: () => short(oneLine(stripTerminalSequences(unfolded(said.block.text)).replace(/[\x00-\x1f\x7f]/g, " ")), 160) });
|
|
1582
1622
|
}
|
|
1583
1623
|
/** The turn is over: its work becomes one line, unless somebody opened it. */
|
|
1584
1624
|
endWork(tab) {
|
|
@@ -1586,6 +1626,13 @@ export class PineTui {
|
|
|
1586
1626
|
tab.work = undefined;
|
|
1587
1627
|
tab.said = undefined;
|
|
1588
1628
|
}
|
|
1629
|
+
/** A task's message is whole: it is drawn as it was written, with nothing held back for a tag that might still come. */
|
|
1630
|
+
endBlock(tab, task) {
|
|
1631
|
+
const block = tab.blocks.get(task);
|
|
1632
|
+
if (block)
|
|
1633
|
+
block.md.setText(block.text);
|
|
1634
|
+
tab.blocks.delete(task);
|
|
1635
|
+
}
|
|
1589
1636
|
/** A task's model stopped thinking: what it thought is closed, or stays open if somebody opened it. */
|
|
1590
1637
|
endThought(tab, task, ms) {
|
|
1591
1638
|
const block = tab.thoughts.get(task);
|
|
@@ -3145,7 +3192,7 @@ export class PineTui {
|
|
|
3145
3192
|
tab.said = { task: p.task, block };
|
|
3146
3193
|
}
|
|
3147
3194
|
block.text += p.text;
|
|
3148
|
-
block.md.setText(block.text);
|
|
3195
|
+
block.md.setText(block.text, true);
|
|
3149
3196
|
break;
|
|
3150
3197
|
}
|
|
3151
3198
|
case "message":
|
|
@@ -3156,7 +3203,7 @@ export class PineTui {
|
|
|
3156
3203
|
tab.streamed.set(p.task, tab.blocks.get(p.task).text);
|
|
3157
3204
|
this.answerPictures(tab, p.agent, tab.blocks.get(p.task).text);
|
|
3158
3205
|
}
|
|
3159
|
-
|
|
3206
|
+
this.endBlock(tab, p.task);
|
|
3160
3207
|
if (depth === 0) {
|
|
3161
3208
|
tab.tokens = { input: p.input ?? 0, output: p.output ?? 0, cached: p.cached ?? 0 };
|
|
3162
3209
|
if (p.context?.percent !== undefined)
|
|
@@ -3175,7 +3222,7 @@ export class PineTui {
|
|
|
3175
3222
|
case "tool": {
|
|
3176
3223
|
tab.thinking = false;
|
|
3177
3224
|
this.endThought(tab, p.task);
|
|
3178
|
-
|
|
3225
|
+
this.endBlock(tab, p.task);
|
|
3179
3226
|
tab.streamed.delete(p.task);
|
|
3180
3227
|
const key = `${p.task}:${p.call}`;
|
|
3181
3228
|
const label = `${c.bold(p.tool)}${p.subject ? ` ${c.gray(short(oneLine(p.subject), 100))}` : ""}`;
|
|
@@ -3207,7 +3254,7 @@ export class PineTui {
|
|
|
3207
3254
|
case "done":
|
|
3208
3255
|
case "failed": {
|
|
3209
3256
|
const block = tab.blocks.get(p.task);
|
|
3210
|
-
|
|
3257
|
+
this.endBlock(tab, p.task);
|
|
3211
3258
|
this.endThought(tab, p.task);
|
|
3212
3259
|
if (depth > 0) {
|
|
3213
3260
|
const child = tab.children.get(p.task);
|
package/src/tui/theme.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type Component, type EditorTheme, type MarkdownTheme, type SelectListTheme } from "@earendil-works/pi-tui";
|
|
2
2
|
/** Plain 16/256-colour styling, so the UI follows the terminal's own palette. */
|
|
3
3
|
export declare const c: {
|
|
4
4
|
bold: (s: string) => string;
|
|
@@ -23,10 +23,46 @@ export declare const selectTheme: SelectListTheme;
|
|
|
23
23
|
export declare const editorTheme: EditorTheme;
|
|
24
24
|
export declare const markdownTheme: MarkdownTheme;
|
|
25
25
|
export declare const SPINNER: string[];
|
|
26
|
-
/**
|
|
27
|
-
export
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
/** A part of an answer that is folded into one line (`<details>`), and opens on a click. */
|
|
27
|
+
export interface Block {
|
|
28
|
+
/** What stands for it: its summary as written, and drawn. */
|
|
29
|
+
summary: string;
|
|
30
|
+
label: string;
|
|
31
|
+
/** `<details open>`: how it is until somebody clicks it. */
|
|
32
|
+
written: boolean;
|
|
33
|
+
/** What a click made of it. Kept while the answer is on screen, also while more of it arrives. */
|
|
34
|
+
chosen?: boolean;
|
|
35
|
+
body: Answer;
|
|
36
|
+
/** The line of the answer it begins at, as it was last drawn. */
|
|
37
|
+
row: number;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Markdown from an agent or a tool, drawn. A part that the answer folds away
|
|
41
|
+
* (`<details><summary>what it is</summary> ... </details>`) is one line, and a click on that line
|
|
42
|
+
* opens and closes it. What it holds is an answer again, set in under its line, so a block
|
|
43
|
+
* inside a block works the same way.
|
|
44
|
+
*/
|
|
45
|
+
export declare class Answer implements Component {
|
|
46
|
+
/** A click opened or closed a block: whoever shows the answer keeps the block's line in view. */
|
|
47
|
+
toggled?: (block: Block, open: boolean) => void;
|
|
48
|
+
private parts;
|
|
49
|
+
private proses;
|
|
50
|
+
private blocks;
|
|
51
|
+
private rows;
|
|
52
|
+
private drawn?;
|
|
30
53
|
constructor(text: string);
|
|
54
|
+
/**
|
|
55
|
+
* `live`: the answer is still being written. Then the beginning of a tag at its end is held
|
|
56
|
+
* back until it is known what it becomes, and a block whose summary is not whole yet is "…".
|
|
57
|
+
*/
|
|
58
|
+
setText(text: string, live?: boolean): void;
|
|
59
|
+
private block;
|
|
60
|
+
invalidate(): void;
|
|
31
61
|
render(width: number): string[];
|
|
62
|
+
/** The line at which a block begins, as the answer is drawn at this width. Nothing if it is not in it, or inside a block that is closed. */
|
|
63
|
+
rowOf(block: object, width: number): number | undefined;
|
|
64
|
+
handleMouse(e: any): {
|
|
65
|
+
handled: boolean;
|
|
66
|
+
render: boolean;
|
|
67
|
+
} | undefined;
|
|
32
68
|
}
|
package/src/tui/theme.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { Markdown, visibleWidth } from "@earendil-works/pi-tui";
|
|
1
|
+
import { Markdown, stripTerminalSequences, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
2
|
+
import { foldsIn, summaryOf } from "../util.js";
|
|
2
3
|
import { highlightCode } from "./highlight.js";
|
|
3
4
|
const on = !process.env.NO_COLOR;
|
|
4
5
|
const sgr = (open, close) => (s) => (on ? `\x1b[${open}m${s}\x1b[${close}m` : s);
|
|
@@ -58,12 +59,21 @@ export const markdownTheme = {
|
|
|
58
59
|
underline: c.underline,
|
|
59
60
|
};
|
|
60
61
|
export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
61
|
-
/** Markdown
|
|
62
|
-
|
|
62
|
+
/** Markdown drawn: headings, lists, tables, quotes, and code in colour. */
|
|
63
|
+
class Prose extends Markdown {
|
|
63
64
|
from;
|
|
64
65
|
drawn = [];
|
|
66
|
+
written;
|
|
65
67
|
constructor(text) {
|
|
66
68
|
super(text, 1, 0, markdownTheme);
|
|
69
|
+
this.written = text;
|
|
70
|
+
}
|
|
71
|
+
/** The same text again costs nothing: an answer that streams in sets all its parts with every piece. */
|
|
72
|
+
setText(text) {
|
|
73
|
+
if (text === this.written)
|
|
74
|
+
return;
|
|
75
|
+
this.written = text;
|
|
76
|
+
super.setText(text);
|
|
67
77
|
}
|
|
68
78
|
render(width) {
|
|
69
79
|
const lines = super.render(width);
|
|
@@ -74,6 +84,148 @@ export class Answer extends Markdown {
|
|
|
74
84
|
return this.drawn;
|
|
75
85
|
}
|
|
76
86
|
}
|
|
87
|
+
/** An open block of more lines than this has a line at its end that closes it. */
|
|
88
|
+
const LONG = 6;
|
|
89
|
+
/** The beginning of a tag that folds, at the end of a text that is still being written. */
|
|
90
|
+
const HALF_TAG = /<\/?(?:d(?:e(?:t(?:a(?:i(?:l(?:s(?:\s[^<>]*)?)?)?)?)?)?)?)?$/i;
|
|
91
|
+
/** Blank lines in front of a text. Not the spaces that begin its first line: they can mean something. */
|
|
92
|
+
const BLANK_LINES = /^(?:[ \t]*\n)+/;
|
|
93
|
+
/** A summary as one line, with the bold and code in it drawn. Nothing in it may move the cursor or colour the screen. */
|
|
94
|
+
function drawLabel(summary) {
|
|
95
|
+
// Inside a tag, models write tags for what markdown has marks for.
|
|
96
|
+
const text = stripTerminalSequences(summary).replace(/[\x00-\x1f\x7f]+/g, " ").replace(/<\/?(?:b|strong)>/gi, "**").replace(/<\/?(?:i|em)>/gi, "*").replace(/<\/?code>/gi, "`");
|
|
97
|
+
const lines = new Markdown(text, 0, 0, markdownTheme).render(2000).map((l) => l.trimEnd()).filter(Boolean);
|
|
98
|
+
return lines.join(" ") || text;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Markdown from an agent or a tool, drawn. A part that the answer folds away
|
|
102
|
+
* (`<details><summary>what it is</summary> ... </details>`) is one line, and a click on that line
|
|
103
|
+
* opens and closes it. What it holds is an answer again, set in under its line, so a block
|
|
104
|
+
* inside a block works the same way.
|
|
105
|
+
*/
|
|
106
|
+
export class Answer {
|
|
107
|
+
/** A click opened or closed a block: whoever shows the answer keeps the block's line in view. */
|
|
108
|
+
toggled;
|
|
109
|
+
parts = [];
|
|
110
|
+
proses = [];
|
|
111
|
+
blocks = [];
|
|
112
|
+
rows = [];
|
|
113
|
+
drawn;
|
|
114
|
+
constructor(text) {
|
|
115
|
+
this.setText(text);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* `live`: the answer is still being written. Then the beginning of a tag at its end is held
|
|
119
|
+
* back until it is known what it becomes, and a block whose summary is not whole yet is "…".
|
|
120
|
+
*/
|
|
121
|
+
setText(text, live = false) {
|
|
122
|
+
const shown = live ? text.replace(HALF_TAG, "") : text;
|
|
123
|
+
const folds = foldsIn(shown, live);
|
|
124
|
+
const parts = [];
|
|
125
|
+
let proses = 0;
|
|
126
|
+
const words = (piece) => {
|
|
127
|
+
// Without a block the text is drawn as it is, empty too. Between blocks, nothing is nothing.
|
|
128
|
+
if (folds.length && !piece.trim())
|
|
129
|
+
return;
|
|
130
|
+
const prose = (this.proses[proses++] ??= new Prose(piece));
|
|
131
|
+
prose.setText(piece);
|
|
132
|
+
parts.push(prose);
|
|
133
|
+
};
|
|
134
|
+
let at = 0;
|
|
135
|
+
folds.forEach((fold, i) => {
|
|
136
|
+
words(shown.slice(at, fold.from).replace(BLANK_LINES, "").trimEnd());
|
|
137
|
+
// The n-th block stays the n-th block while the answer grows, and with it what a click made of it.
|
|
138
|
+
const block = (this.blocks[i] ??= this.block());
|
|
139
|
+
block.written = fold.open;
|
|
140
|
+
const summary = live && fold.pending ? "…" : summaryOf(fold);
|
|
141
|
+
if (summary !== block.summary)
|
|
142
|
+
block.label = drawLabel((block.summary = summary));
|
|
143
|
+
block.body.setText(fold.body.replace(BLANK_LINES, "").trimEnd(), live);
|
|
144
|
+
parts.push(block);
|
|
145
|
+
at = fold.to;
|
|
146
|
+
});
|
|
147
|
+
words(at ? shown.slice(at).replace(BLANK_LINES, "").trimEnd() : shown);
|
|
148
|
+
this.proses.length = proses;
|
|
149
|
+
this.blocks.length = folds.length;
|
|
150
|
+
this.parts = parts;
|
|
151
|
+
this.rows = [];
|
|
152
|
+
this.drawn = undefined;
|
|
153
|
+
}
|
|
154
|
+
block() {
|
|
155
|
+
const body = new Answer("");
|
|
156
|
+
body.toggled = (block, open) => {
|
|
157
|
+
this.drawn = undefined;
|
|
158
|
+
this.toggled?.(block, open);
|
|
159
|
+
};
|
|
160
|
+
return { summary: "", label: "", written: false, body, row: 0 };
|
|
161
|
+
}
|
|
162
|
+
invalidate() {
|
|
163
|
+
for (const p of this.proses)
|
|
164
|
+
p.invalidate();
|
|
165
|
+
for (const b of this.blocks)
|
|
166
|
+
b.body.invalidate();
|
|
167
|
+
this.drawn = undefined;
|
|
168
|
+
}
|
|
169
|
+
render(width) {
|
|
170
|
+
// An answer that folds nothing is its markdown, as it always was.
|
|
171
|
+
if (!this.blocks.length)
|
|
172
|
+
return this.proses[0]?.render(width) ?? [];
|
|
173
|
+
if (this.drawn?.width === width)
|
|
174
|
+
return this.drawn.lines;
|
|
175
|
+
const lines = [];
|
|
176
|
+
const rows = [];
|
|
177
|
+
const put = (line, row) => (lines.push(line), rows.push(row));
|
|
178
|
+
this.parts.forEach((part, i) => {
|
|
179
|
+
if (i)
|
|
180
|
+
put("", undefined);
|
|
181
|
+
if (part instanceof Prose) {
|
|
182
|
+
for (const l of part.render(width))
|
|
183
|
+
put(l, undefined);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const open = part.chosen ?? part.written;
|
|
187
|
+
const hint = ` · ${open ? "click here to close" : "click to open"}`;
|
|
188
|
+
part.row = lines.length;
|
|
189
|
+
put(truncateToWidth(` ${c.gray(open ? "▾" : "▸")} ${truncateToWidth(part.label, Math.max(8, width - 4 - hint.length), "…")}${c.gray(hint)}`, width), { block: part });
|
|
190
|
+
if (!open)
|
|
191
|
+
return;
|
|
192
|
+
const body = part.body.render(Math.max(1, width - 2));
|
|
193
|
+
body.forEach((l, y) => put(` ${l}`, { block: part, y }));
|
|
194
|
+
if (body.length > LONG)
|
|
195
|
+
put(` ${c.gray("▴ close")}`, { block: part });
|
|
196
|
+
});
|
|
197
|
+
this.rows = rows;
|
|
198
|
+
this.drawn = { width, lines };
|
|
199
|
+
return lines;
|
|
200
|
+
}
|
|
201
|
+
/** The line at which a block begins, as the answer is drawn at this width. Nothing if it is not in it, or inside a block that is closed. */
|
|
202
|
+
rowOf(block, width) {
|
|
203
|
+
this.render(width);
|
|
204
|
+
for (const b of this.blocks) {
|
|
205
|
+
if (b === block)
|
|
206
|
+
return b.row;
|
|
207
|
+
const at = (b.chosen ?? b.written) ? b.body.rowOf(block, Math.max(1, width - 2)) : undefined;
|
|
208
|
+
if (at !== undefined)
|
|
209
|
+
return b.row + 1 + at;
|
|
210
|
+
}
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
handleMouse(e) {
|
|
214
|
+
const row = this.rows[e.y];
|
|
215
|
+
if (!row)
|
|
216
|
+
return undefined; // text: left to selection
|
|
217
|
+
if (row.y !== undefined)
|
|
218
|
+
return row.block.body.handleMouse({ ...e, x: e.x - 2, y: row.y });
|
|
219
|
+
if (e.button !== "left" || (e.type !== "press" && e.type !== "click" && e.type !== "release"))
|
|
220
|
+
return undefined;
|
|
221
|
+
if (e.type === "click") {
|
|
222
|
+
row.block.chosen = !(row.block.chosen ?? row.block.written);
|
|
223
|
+
this.drawn = undefined;
|
|
224
|
+
this.toggled?.(row.block, row.block.chosen);
|
|
225
|
+
}
|
|
226
|
+
return { handled: true, render: true };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
77
229
|
// Two things the library's tables leave out, added where it wraps a cell's text to its column:
|
|
78
230
|
// a <br>, which models write for a line break inside a cell, becomes that break; and a column
|
|
79
231
|
// that the table's second line aligns to the right ("---:") or centres (":---:") is set that way.
|
|
@@ -83,7 +235,7 @@ const drawTable = proto.renderTable;
|
|
|
83
235
|
const inline = proto.renderInlineTokens;
|
|
84
236
|
const BR = /\s*<br\s*\/?>\s*/i;
|
|
85
237
|
if (wrapCell && drawTable && inline) {
|
|
86
|
-
const own =
|
|
238
|
+
const own = Prose.prototype;
|
|
87
239
|
own.renderTable = function (token, ...rest) {
|
|
88
240
|
// The library first reads every cell once to size the columns, then once more, cell after
|
|
89
241
|
// cell and row by row, to draw them. Counting says which of the two it is doing, and which
|
package/src/util.d.ts
CHANGED
|
@@ -63,3 +63,30 @@ export declare function callTiming(input: number, output: number, startedAt: num
|
|
|
63
63
|
export declare function speedOf(t: CallTiming | undefined): Speed;
|
|
64
64
|
/** "↑ 1.4k t/s ↓ 42 t/s": up is what the model read, down is what it wrote, as with the token counts. Empty when neither is known. */
|
|
65
65
|
export declare function speedText(s: Speed | undefined): string;
|
|
66
|
+
/** A part of an answer that its writer folded away: `<details><summary>what it is</summary> ... </details>`. */
|
|
67
|
+
export interface Fold {
|
|
68
|
+
/** Where it lies in the text: from its opening tag to the end of its closing tag, or to the end of the text. */
|
|
69
|
+
from: number;
|
|
70
|
+
to: number;
|
|
71
|
+
/** What stands for it while it is folded, as written. None when it has no `<summary>`. */
|
|
72
|
+
summary?: string;
|
|
73
|
+
/** `<details open>`: it starts open. */
|
|
74
|
+
open: boolean;
|
|
75
|
+
/** What it folds away, as written. Another block inside it is part of this text. */
|
|
76
|
+
body: string;
|
|
77
|
+
/** The text ends before its summary does: all that can be said of it yet is that it is there. */
|
|
78
|
+
pending: boolean;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The folded blocks of a markdown text, the outermost ones: what is inside one, another block
|
|
82
|
+
* too, is its body. Tags are read whatever their capitals and attributes; one inside code is not
|
|
83
|
+
* a tag. A block whose closing tag is missing runs to the end of the text.
|
|
84
|
+
*/
|
|
85
|
+
export declare function foldsIn(markdown: string, live?: boolean): Fold[];
|
|
86
|
+
/** A block's summary on one line; "Details" for a block that has none, as a browser calls it. */
|
|
87
|
+
export declare const summaryOf: (fold: Fold) => string;
|
|
88
|
+
/**
|
|
89
|
+
* A text with folded blocks for a place that folds nothing (a chat message): each block becomes
|
|
90
|
+
* its summary on a line of its own with what it held under it, so that no tags are left to read.
|
|
91
|
+
*/
|
|
92
|
+
export declare function unfolded(markdown: string): string;
|
package/src/util.js
CHANGED
|
@@ -169,3 +169,132 @@ export function speedText(s) {
|
|
|
169
169
|
return "";
|
|
170
170
|
return [s.read ? `↑ ${rate(s.read)} t/s` : "", s.write ? `↓ ${rate(s.write)} t/s` : ""].filter(Boolean).join(" ");
|
|
171
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* The stretches of a markdown text that are code: fenced blocks and inline code. A tag written
|
|
174
|
+
* there is text. `live`: the text is still being written, so code that is not closed yet runs to
|
|
175
|
+
* the end of it.
|
|
176
|
+
*/
|
|
177
|
+
function codeIn(text, live) {
|
|
178
|
+
const out = [];
|
|
179
|
+
const inline = (from, to) => {
|
|
180
|
+
for (let i = from; i < to;) {
|
|
181
|
+
if (text[i] === "\\")
|
|
182
|
+
i += 2;
|
|
183
|
+
else if (text[i] !== "`")
|
|
184
|
+
i++;
|
|
185
|
+
else {
|
|
186
|
+
let n = 1;
|
|
187
|
+
while (text[i + n] === "`")
|
|
188
|
+
n++;
|
|
189
|
+
// Closed by as many backticks as opened it, in the same paragraph.
|
|
190
|
+
let close = -1;
|
|
191
|
+
for (let j = i + n; j < to && close < 0;) {
|
|
192
|
+
if (text[j] !== "`") {
|
|
193
|
+
j++;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
let m = 1;
|
|
197
|
+
while (text[j + m] === "`")
|
|
198
|
+
m++;
|
|
199
|
+
if (m === n)
|
|
200
|
+
close = j;
|
|
201
|
+
j += m;
|
|
202
|
+
}
|
|
203
|
+
if (close < 0 && live && to === text.length)
|
|
204
|
+
close = to;
|
|
205
|
+
if (close >= 0)
|
|
206
|
+
out.push([i, close + n]);
|
|
207
|
+
i = close < 0 ? i + n : close + n;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
let fence;
|
|
212
|
+
let paragraph = -1;
|
|
213
|
+
let at = 0;
|
|
214
|
+
for (const line of text.split("\n")) {
|
|
215
|
+
const end = at + line.length;
|
|
216
|
+
const mark = /^[ \t>]*(`{3,}|~{3,})(.*)$/.exec(line);
|
|
217
|
+
if (fence) {
|
|
218
|
+
if (mark && mark[1][0] === fence.mark[0] && mark[1].length >= fence.mark.length && !mark[2].trim()) {
|
|
219
|
+
out.push([fence.from, end]);
|
|
220
|
+
fence = undefined;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
else if (mark && !(mark[1][0] === "`" && mark[2].includes("`"))) {
|
|
224
|
+
if (paragraph >= 0)
|
|
225
|
+
inline(paragraph, at);
|
|
226
|
+
paragraph = -1;
|
|
227
|
+
fence = { mark: mark[1], from: at };
|
|
228
|
+
}
|
|
229
|
+
else if (!line.trim()) {
|
|
230
|
+
if (paragraph >= 0)
|
|
231
|
+
inline(paragraph, at);
|
|
232
|
+
paragraph = -1;
|
|
233
|
+
}
|
|
234
|
+
else if (paragraph < 0)
|
|
235
|
+
paragraph = at;
|
|
236
|
+
at = end + 1;
|
|
237
|
+
}
|
|
238
|
+
if (fence)
|
|
239
|
+
out.push([fence.from, text.length]);
|
|
240
|
+
else if (paragraph >= 0)
|
|
241
|
+
inline(paragraph, text.length);
|
|
242
|
+
return out;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* The folded blocks of a markdown text, the outermost ones: what is inside one, another block
|
|
246
|
+
* too, is its body. Tags are read whatever their capitals and attributes; one inside code is not
|
|
247
|
+
* a tag. A block whose closing tag is missing runs to the end of the text.
|
|
248
|
+
*/
|
|
249
|
+
export function foldsIn(markdown, live = false) {
|
|
250
|
+
if (!/<details/i.test(markdown))
|
|
251
|
+
return [];
|
|
252
|
+
const code = codeIn(markdown, live);
|
|
253
|
+
const out = [];
|
|
254
|
+
const fold = (tag, end, to) => {
|
|
255
|
+
const closed = end < to;
|
|
256
|
+
const inner = markdown.slice(tag.index + tag[0].length, end).trimStart();
|
|
257
|
+
const opens = /^<summary(?:\s[^<>]*)?>/i.exec(inner);
|
|
258
|
+
const closes = opens ? /<\/summary\s*>/i.exec(inner) : null;
|
|
259
|
+
const line = inner.indexOf("\n") < 0 ? inner.length : inner.indexOf("\n");
|
|
260
|
+
// A summary that was never closed is its first line: the rest is what the block holds.
|
|
261
|
+
const summary = opens ? inner.slice(opens[0].length, closes ? closes.index : line) : undefined;
|
|
262
|
+
const waits = !opens && !closed && (/^<summary\s[^<>]*$/i.test(inner) || "<summary".startsWith(inner.toLowerCase()));
|
|
263
|
+
const body = waits ? "" : !opens ? inner : inner.slice(closes ? closes.index + closes[0].length : line);
|
|
264
|
+
out.push({ from: tag.index, to, summary, open: /\sopen(?:[\s=]|$)/i.test(tag[2]), body, pending: waits || (!!opens && !closes && !closed) });
|
|
265
|
+
};
|
|
266
|
+
let depth = 0;
|
|
267
|
+
let first;
|
|
268
|
+
for (const tag of markdown.matchAll(/<(\/?)details((?:\s[^<>]*)?)>/gi)) {
|
|
269
|
+
if (code.some(([a, z]) => tag.index >= a && tag.index < z))
|
|
270
|
+
continue;
|
|
271
|
+
if (!tag[1]) {
|
|
272
|
+
if (depth++ === 0)
|
|
273
|
+
first = tag;
|
|
274
|
+
}
|
|
275
|
+
else if (depth > 0 && --depth === 0)
|
|
276
|
+
fold(first, tag.index, tag.index + tag[0].length);
|
|
277
|
+
}
|
|
278
|
+
if (depth > 0)
|
|
279
|
+
fold(first, markdown.length, markdown.length);
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
/** A block's summary on one line; "Details" for a block that has none, as a browser calls it. */
|
|
283
|
+
export const summaryOf = (fold) => (fold.summary ?? "").replace(/\s+/g, " ").trim() || "Details";
|
|
284
|
+
/**
|
|
285
|
+
* A text with folded blocks for a place that folds nothing (a chat message): each block becomes
|
|
286
|
+
* its summary on a line of its own with what it held under it, so that no tags are left to read.
|
|
287
|
+
*/
|
|
288
|
+
export function unfolded(markdown) {
|
|
289
|
+
const folds = foldsIn(markdown);
|
|
290
|
+
if (!folds.length)
|
|
291
|
+
return markdown;
|
|
292
|
+
const parts = [];
|
|
293
|
+
let at = 0;
|
|
294
|
+
for (const f of folds) {
|
|
295
|
+
parts.push(markdown.slice(at, f.from).trim(), `▾ ${summaryOf(f)}\n${unfolded(f.body).trim()}`.trim());
|
|
296
|
+
at = f.to;
|
|
297
|
+
}
|
|
298
|
+
parts.push(markdown.slice(at).trim());
|
|
299
|
+
return parts.filter(Boolean).join("\n\n");
|
|
300
|
+
}
|