@pmndre/pine 0.0.0-stage → 0.22.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.
Files changed (151) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +226 -2
  3. package/bin/pine.js +27 -0
  4. package/docs/SKILL.md +234 -0
  5. package/docs/references/agents.md +454 -0
  6. package/docs/references/coding.md +311 -0
  7. package/docs/references/computer.md +212 -0
  8. package/docs/references/configuration.md +310 -0
  9. package/docs/references/events.md +267 -0
  10. package/docs/references/mcp.md +420 -0
  11. package/docs/references/operations.md +394 -0
  12. package/docs/references/overview.md +195 -0
  13. package/docs/references/security.md +896 -0
  14. package/docs/references/setup.md +385 -0
  15. package/docs/references/sources.md +772 -0
  16. package/docs/references/stack.md +121 -0
  17. package/docs/references/tui.md +575 -0
  18. package/examples/home/.env.example +7 -0
  19. package/examples/home/USER.md +4 -0
  20. package/examples/home/agents/main/agent.json +4 -0
  21. package/examples/home/agents/main/workspace/AGENTS.md +14 -0
  22. package/examples/home/agents/main/workspace/MEMORY.md +4 -0
  23. package/examples/home/agents/main/workspace/SOUL.md +4 -0
  24. package/examples/home/models.json +62 -0
  25. package/examples/home/pine.json +34 -0
  26. package/examples/home/skills/README.txt +7 -0
  27. package/examples/launchd/com.pine.daemon.plist +32 -0
  28. package/examples/systemd/pine.service +22 -0
  29. package/mcp/browser.d.ts +99 -0
  30. package/mcp/browser.js +496 -0
  31. package/mcp/commands.d.ts +20 -0
  32. package/mcp/commands.js +88 -0
  33. package/mcp/computer.d.ts +139 -0
  34. package/mcp/computer.js +698 -0
  35. package/mcp/computer.swift +989 -0
  36. package/mcp/lib.d.ts +23 -0
  37. package/mcp/lib.js +52 -0
  38. package/mcp/web.d.ts +6 -0
  39. package/mcp/web.js +140 -0
  40. package/package.json +32 -4
  41. package/src/access.d.ts +112 -0
  42. package/src/access.js +438 -0
  43. package/src/actions.d.ts +75 -0
  44. package/src/actions.js +167 -0
  45. package/src/admin.d.ts +167 -0
  46. package/src/admin.js +625 -0
  47. package/src/agent-admin.d.ts +24 -0
  48. package/src/agent-admin.js +55 -0
  49. package/src/agents.d.ts +540 -0
  50. package/src/agents.js +2776 -0
  51. package/src/background.d.ts +29 -0
  52. package/src/background.js +100 -0
  53. package/src/cli.d.ts +2 -0
  54. package/src/cli.js +777 -0
  55. package/src/computer.d.ts +30 -0
  56. package/src/computer.js +32 -0
  57. package/src/config.d.ts +396 -0
  58. package/src/config.js +549 -0
  59. package/src/dev/claude-model.d.ts +37 -0
  60. package/src/dev/claude-model.js +204 -0
  61. package/src/env-file.d.ts +4 -0
  62. package/src/env-file.js +40 -0
  63. package/src/goals.d.ts +133 -0
  64. package/src/goals.js +316 -0
  65. package/src/http.d.ts +46 -0
  66. package/src/http.js +509 -0
  67. package/src/limiter.d.ts +32 -0
  68. package/src/limiter.js +84 -0
  69. package/src/login.d.ts +23 -0
  70. package/src/login.js +130 -0
  71. package/src/manual.d.ts +61 -0
  72. package/src/manual.js +443 -0
  73. package/src/mcp-config.d.ts +49 -0
  74. package/src/mcp-config.js +182 -0
  75. package/src/models.d.ts +90 -0
  76. package/src/models.js +274 -0
  77. package/src/net.d.ts +50 -0
  78. package/src/net.js +150 -0
  79. package/src/pine.d.ts +32 -0
  80. package/src/pine.js +134 -0
  81. package/src/programs.d.ts +123 -0
  82. package/src/programs.js +412 -0
  83. package/src/router.d.ts +56 -0
  84. package/src/router.js +164 -0
  85. package/src/sandbox-fs.d.ts +34 -0
  86. package/src/sandbox-fs.js +186 -0
  87. package/src/sandbox-linux.d.ts +96 -0
  88. package/src/sandbox-linux.js +297 -0
  89. package/src/sandbox-setup.d.ts +70 -0
  90. package/src/sandbox-setup.js +216 -0
  91. package/src/security.d.ts +238 -0
  92. package/src/security.js +660 -0
  93. package/src/skills.d.ts +67 -0
  94. package/src/skills.js +163 -0
  95. package/src/snapshots.d.ts +68 -0
  96. package/src/snapshots.js +306 -0
  97. package/src/source-types.d.ts +61 -0
  98. package/src/source-types.js +1 -0
  99. package/src/sources/command.d.ts +4 -0
  100. package/src/sources/command.js +77 -0
  101. package/src/sources/folder.d.ts +6 -0
  102. package/src/sources/folder.js +116 -0
  103. package/src/sources/ftp.d.ts +4 -0
  104. package/src/sources/ftp.js +307 -0
  105. package/src/sources/http.d.ts +4 -0
  106. package/src/sources/http.js +201 -0
  107. package/src/sources/mqtt.d.ts +18 -0
  108. package/src/sources/mqtt.js +97 -0
  109. package/src/sources/telegram.d.ts +22 -0
  110. package/src/sources/telegram.js +283 -0
  111. package/src/sources/webhook.d.ts +4 -0
  112. package/src/sources/webhook.js +52 -0
  113. package/src/sources.d.ts +344 -0
  114. package/src/sources.js +966 -0
  115. package/src/store.d.ts +99 -0
  116. package/src/store.js +277 -0
  117. package/src/timers.d.ts +83 -0
  118. package/src/timers.js +318 -0
  119. package/src/tools.d.ts +11 -0
  120. package/src/tools.js +1297 -0
  121. package/src/tui/app.d.ts +305 -0
  122. package/src/tui/app.js +3195 -0
  123. package/src/tui/client.d.ts +236 -0
  124. package/src/tui/client.js +131 -0
  125. package/src/tui/code-pane.d.ts +68 -0
  126. package/src/tui/code-pane.js +535 -0
  127. package/src/tui/highlight.d.ts +8 -0
  128. package/src/tui/highlight.js +86 -0
  129. package/src/tui/picture.d.ts +206 -0
  130. package/src/tui/picture.js +801 -0
  131. package/src/tui/run.d.ts +8 -0
  132. package/src/tui/run.js +97 -0
  133. package/src/tui/theme.d.ts +32 -0
  134. package/src/tui/theme.js +128 -0
  135. package/src/tui/undo.d.ts +5 -0
  136. package/src/tui/undo.js +50 -0
  137. package/src/tui/voice.d.ts +49 -0
  138. package/src/tui/voice.js +155 -0
  139. package/src/tui/voice.swift +223 -0
  140. package/src/types.d.ts +139 -0
  141. package/src/types.js +1 -0
  142. package/src/undo.d.ts +224 -0
  143. package/src/undo.js +465 -0
  144. package/src/update.d.ts +35 -0
  145. package/src/update.js +130 -0
  146. package/src/util.d.ts +65 -0
  147. package/src/util.js +171 -0
  148. package/src/watching.d.ts +20 -0
  149. package/src/watching.js +68 -0
  150. package/src/workspace-view.d.ts +72 -0
  151. package/src/workspace-view.js +221 -0
package/src/tui/app.js ADDED
@@ -0,0 +1,3195 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
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, speedOf, speedText } from "../util.js";
7
+ import { Listening, voiceTools } from "./voice.js";
8
+ import { CodePane, PANE_VIEWS } from "./code-pane.js";
9
+ import { redoText, undoText } from "./undo.js";
10
+ import { isAudioFile, isImageFile, isVideoFile, mimeOf, Picture, picturesAsText, picturesIn, prepare, prepareSound, prepareVideo, Slot, Sound, soundPlayer, stopSounds, stopVideos, Video } from "./picture.js";
11
+ import { Answer, c, editorTheme, selectTheme, SPINNER } from "./theme.js";
12
+ /** Below this many columns the code pane takes the whole width instead of half of it. */
13
+ const SIDE_BY_SIDE = 100;
14
+ const RULE = Array.from({ length: 400 }, () => c.gray("│"));
15
+ const tilde = (p) => (p === os.homedir() ? "~" : p.startsWith(`${os.homedir()}/`) ? `~${p.slice(os.homedir().length)}` : p);
16
+ /** The library's name for "this component lays out children". */
17
+ const LAYOUT = Symbol.for("@earendil-works/pi-tui/layout-node");
18
+ /**
19
+ * A conversation with the code pane beside it. The pane gets half the width (the library's own
20
+ * sharing of free room is not an even split), or all of it where two halves would be too narrow.
21
+ */
22
+ class Split extends HStack {
23
+ side;
24
+ columns;
25
+ constructor(main, rule, side, open, columns) {
26
+ super([
27
+ { component: main, basis: 0, grow: 1, shrink: 1, minSize: 1, visible: (v) => !(open() && v.width < SIDE_BY_SIDE) },
28
+ { component: rule, basis: 1, grow: 0, shrink: 0, visible: (v) => open() && v.width >= SIDE_BY_SIDE },
29
+ { component: side, basis: 0, grow: 1, shrink: 1, minSize: 1, visible: () => open() },
30
+ ]);
31
+ this.side = side;
32
+ this.columns = columns;
33
+ }
34
+ [LAYOUT]() {
35
+ const node = HStack.prototype[LAYOUT].call(this);
36
+ const width = this.columns();
37
+ if (width < SIDE_BY_SIDE)
38
+ return node;
39
+ const side = Math.max(44, Math.min(96, Math.floor(width / 2)));
40
+ return { ...node, entries: node.entries.map((e) => (e.component === this.side ? { ...e, basis: side, grow: 0, shrink: 0 } : e)) };
41
+ }
42
+ }
43
+ /**
44
+ * What a conversation shows. A real picture can only be drawn at the left edge of a full line;
45
+ * with a pane beside the conversation it would lie across that pane, so pictures are drawn as
46
+ * text for as long as the pane is there.
47
+ */
48
+ class Doc extends Container {
49
+ asText = () => false;
50
+ render(width) {
51
+ const lines = super.render(width);
52
+ return this.asText() ? picturesAsText(lines, () => true) : lines;
53
+ }
54
+ }
55
+ /** A one-line (or few-line) piece of chrome whose first line has clickable stretches. */
56
+ function clickable(render, hits, row = 0) {
57
+ return {
58
+ invalidate() { },
59
+ render,
60
+ handleMouse(e) {
61
+ if (e.y !== row || e.button !== "left" || (e.type !== "press" && e.type !== "click" && e.type !== "release"))
62
+ return undefined;
63
+ const hit = hits().find((h) => e.x >= h.from && e.x < h.to);
64
+ if (!hit)
65
+ return undefined; // leave everything else to text selection
66
+ if (e.type === "click")
67
+ hit.run();
68
+ return { handled: true, render: true };
69
+ },
70
+ };
71
+ }
72
+ /** Builds a line from pieces and remembers where the clickable ones ended up. */
73
+ class Line {
74
+ text = "";
75
+ width = 0;
76
+ hits = [];
77
+ add(styled, run) {
78
+ const w = visibleWidth(styled);
79
+ if (run)
80
+ this.hits.push({ from: this.width, to: this.width + w, run });
81
+ this.text += styled;
82
+ this.width += w;
83
+ return this;
84
+ }
85
+ }
86
+ const MAX_ATTACHMENT = 20 * 1024 * 1024;
87
+ /** The ending a sound file gets when its name has none: a player tells the kind by it. */
88
+ const SOUND_EXT = { "audio/wav": ".wav", "audio/mpeg": ".mp3", "audio/mp4": ".m4a", "audio/ogg": ".ogg", "audio/flac": ".flac", "audio/aiff": ".aiff" };
89
+ const URL_CHARS = /[A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;
90
+ /**
91
+ * Web addresses in a block of plain screen lines, with the cells each one covers. A long address
92
+ * is wrapped over several lines; a line that runs to the right edge is read together with the next,
93
+ * and every piece of the address points to the whole of it.
94
+ */
95
+ export function findLinks(lines, width) {
96
+ const full = (l) => visibleWidth(l.replace(/\s+$/, "")) >= width - 2;
97
+ const out = [];
98
+ for (let first = 0; first < lines.length;) {
99
+ // One logical run: `first` and the lines it wraps into.
100
+ const parts = [];
101
+ let text = "";
102
+ let i = first;
103
+ for (; i < lines.length; i++) {
104
+ const line = lines[i].replace(/\s+$/, "");
105
+ const pad = i === first ? 0 : line.length - line.replace(/^ +/, "").length;
106
+ parts.push({ line: i, start: text.length, pad, text: line.slice(pad) });
107
+ text += line.slice(pad);
108
+ if (!full(lines[i]))
109
+ break;
110
+ }
111
+ for (const m of text.matchAll(/https?:\/\/[^\s<>"`]+/g)) {
112
+ let url = m[0];
113
+ while (url.length && (!URL_CHARS.test(url.at(-1)) || /[.,;:!?'")\]]/.test(url.at(-1)))) {
114
+ // Closing punctuation belongs to the sentence, unless the address itself opened the bracket.
115
+ if (url.at(-1) === ")" && url.split("(").length > url.split(")").length - 1)
116
+ break;
117
+ url = url.slice(0, -1);
118
+ }
119
+ if (url.length < 10)
120
+ continue;
121
+ const end = m.index + url.length;
122
+ for (const part of parts) {
123
+ const a = Math.max(m.index, part.start);
124
+ const z = Math.min(end, part.start + part.text.length);
125
+ if (a >= z)
126
+ continue;
127
+ const before = " ".repeat(part.pad) + part.text.slice(0, a - part.start);
128
+ out.push({ line: part.line, from: visibleWidth(before), to: visibleWidth(before) + visibleWidth(part.text.slice(a - part.start, z - part.start)), url });
129
+ }
130
+ }
131
+ first = Math.min(i, lines.length - 1) + 1;
132
+ }
133
+ return out;
134
+ }
135
+ /** The address under a cell, if any. */
136
+ export function urlAt(lines, y, x, width) {
137
+ return findLinks(lines, width).find((l) => l.line === y && x >= l.from && x < l.to)?.url;
138
+ }
139
+ /**
140
+ * Makes the web addresses in a component clickable. The text is not changed: an address is
141
+ * always shown in full, and what is shown is what a click opens.
142
+ */
143
+ class Linked {
144
+ inner;
145
+ constructor(inner) {
146
+ this.inner = inner;
147
+ }
148
+ invalidate() {
149
+ this.inner.invalidate();
150
+ }
151
+ handleMouse(e) {
152
+ return this.inner.handleMouse?.(e);
153
+ }
154
+ render(width) {
155
+ const lines = this.inner.render(width);
156
+ const spans = findLinks(lines.map((l) => stripTerminalSequences(l)), width);
157
+ if (!spans.length)
158
+ return lines;
159
+ const out = [...lines];
160
+ // Right to left, so earlier columns stay valid while a line is being rebuilt.
161
+ for (const sp of spans.sort((p, q) => q.line - p.line || q.from - p.from)) {
162
+ const line = out[sp.line];
163
+ const total = visibleWidth(line);
164
+ out[sp.line] = `${sliceByColumn(line, 0, sp.from)}${hyperlink(sliceByColumn(line, sp.from, sp.to - sp.from), sp.url)}${sliceByColumn(line, sp.to, Math.max(0, total - sp.to))}`;
165
+ }
166
+ return out;
167
+ }
168
+ }
169
+ /**
170
+ * Text that a terminal pastes when files are dropped on it: one or more paths, with spaces
171
+ * escaped or the path in quotes, sometimes as file:// URLs. Returns the files (with `folders`: the folders) only when every
172
+ * piece of the text is an existing one; otherwise the text is ordinary input.
173
+ */
174
+ export function droppedFiles(text, folders = false) {
175
+ const tokens = [];
176
+ let cur = "";
177
+ let quote = "";
178
+ for (let i = 0; i < text.length; i++) {
179
+ const ch = text[i];
180
+ if (quote) {
181
+ if (ch === quote)
182
+ quote = "";
183
+ else
184
+ cur += ch;
185
+ }
186
+ else if (ch === "'" || ch === '"')
187
+ quote = ch;
188
+ else if (ch === "\\" && i + 1 < text.length)
189
+ cur += text[++i];
190
+ else if (/\s/.test(ch)) {
191
+ if (cur)
192
+ tokens.push(cur);
193
+ cur = "";
194
+ }
195
+ else
196
+ cur += ch;
197
+ }
198
+ if (cur)
199
+ tokens.push(cur);
200
+ if (!tokens.length)
201
+ return null;
202
+ const files = [];
203
+ for (const t of tokens) {
204
+ let file = t;
205
+ try {
206
+ if (t.startsWith("file://"))
207
+ file = decodeURIComponent(new URL(t).pathname);
208
+ }
209
+ catch {
210
+ return null;
211
+ }
212
+ file = expandHome(file);
213
+ try {
214
+ const stat = path.isAbsolute(file) ? fs.statSync(file) : undefined;
215
+ if (!stat || !(folders ? stat.isDirectory() : stat.isFile()))
216
+ return null;
217
+ }
218
+ catch {
219
+ return null;
220
+ }
221
+ files.push(file);
222
+ }
223
+ return files;
224
+ }
225
+ /**
226
+ * Entries that match what was typed: every word must occur somewhere in the name or description,
227
+ * in any position ("dee" finds opencode-go/deepseek-v4.1-flash). If nothing matches that way,
228
+ * fall back to loose matching so a typo still finds something.
229
+ */
230
+ export function searchItems(items, query) {
231
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
232
+ if (!words.length)
233
+ return items;
234
+ const text = (x) => `${x.label} ${x.description ?? ""}`.toLowerCase();
235
+ const hits = items.filter((x) => words.every((w) => text(x).includes(w)));
236
+ if (!hits.length)
237
+ return fuzzyFilter(items, query, (x) => x.label);
238
+ // Names that start with the query, or have it right after a separator, come first.
239
+ const rank = (x) => (x.label.toLowerCase().startsWith(words[0]) ? 0 : new RegExp(`[/._ -]${words[0].replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(x.label.toLowerCase()) ? 1 : 2);
240
+ return hits.map((x, i) => ({ x, i })).sort((p, q) => rank(p.x) - rank(q.x) || p.i - q.i).map((p) => p.x);
241
+ }
242
+ /** A line of the conversation that does something when it is clicked. */
243
+ class Button {
244
+ text;
245
+ run;
246
+ constructor(text, run) {
247
+ this.text = text;
248
+ this.run = run;
249
+ }
250
+ setText(text) {
251
+ this.text.setText(text);
252
+ }
253
+ invalidate() {
254
+ this.text.invalidate();
255
+ }
256
+ render(width) {
257
+ return this.text.render(width);
258
+ }
259
+ handleMouse(e) {
260
+ if (e.button !== "left" || (e.type !== "press" && e.type !== "click" && e.type !== "release"))
261
+ return undefined;
262
+ if (e.type === "click")
263
+ this.run();
264
+ return { handled: true, render: true };
265
+ }
266
+ }
267
+ /**
268
+ * "@" in the input offers the files of the folder the conversation works in, found by a few
269
+ * letters of their name; everything else is the library's own completion (commands and their
270
+ * arguments). The files are the daemon's to list: the UI is only a client.
271
+ */
272
+ class Mentions {
273
+ triggerCharacters = ["@"];
274
+ inner;
275
+ find;
276
+ constructor(inner, find) {
277
+ this.inner = inner;
278
+ this.find = find;
279
+ }
280
+ /** What was typed after an "@" that begins a word, up to the cursor. */
281
+ typed(lines, line, col) {
282
+ return (lines[line] ?? "").slice(0, col).match(/(?:^|\s)@([^\s@#]*)$/)?.[1];
283
+ }
284
+ async getSuggestions(lines, line, col, options) {
285
+ const typed = this.typed(lines, line, col);
286
+ if (typed === undefined)
287
+ return this.inner.getSuggestions(lines, line, col, options);
288
+ const files = await this.find(typed).catch(() => []);
289
+ if (options.signal.aborted || !files.length)
290
+ return null;
291
+ return { items: files.map((f) => ({ value: `@${f}`, label: f.slice(f.lastIndexOf("/") + 1), description: f.includes("/") ? f.slice(0, f.lastIndexOf("/")) : undefined })), prefix: `@${typed}` };
292
+ }
293
+ applyCompletion(lines, line, col, item, prefix) {
294
+ if (!item.value.startsWith("@") || this.typed(lines, line, col) === undefined)
295
+ return this.inner.applyCompletion(lines, line, col, item, prefix);
296
+ const text = lines[line] ?? "";
297
+ const start = col - prefix.length;
298
+ const next = [...lines];
299
+ next[line] = `${text.slice(0, start)}${item.value} ${text.slice(col).replace(/^ /, "")}`;
300
+ return { lines: next, cursorLine: line, cursorCol: start + item.value.length + 1 };
301
+ }
302
+ shouldTriggerFileCompletion(lines, line, col) {
303
+ return this.typed(lines, line, col) !== undefined || (this.inner.shouldTriggerFileCompletion?.(lines, line, col) ?? false);
304
+ }
305
+ }
306
+ /** The files a message points at: every "@path" in it, with the lines after a "#" if any ("src/a.ts#20-45"). */
307
+ export function mentionsIn(text) {
308
+ return [...new Set([...text.matchAll(/(?:^|\s)@([^\s@#]+(?:#\d+(?:-\d+)?)?)/g)].map((m) => m[1].replace(/[.,;:!?)]+$/, "")))];
309
+ }
310
+ /** For this long after esc stopped something, esc does not stop what started since. */
311
+ const STOP_GRACE = 3000;
312
+ /** A round of a goal: pine calling the agent again (src/goals.ts). Only pine makes a task of this kind. */
313
+ const isGoalRound = (kind, label) => kind === "notify" && typeof label === "string" && label.startsWith("goal: ");
314
+ /** The microphone and the room around it, in cells. */
315
+ const MIC = " 🎤 ";
316
+ const MIC_WIDTH = 4;
317
+ /**
318
+ * The input with a microphone at the right end of its first line, where this system can listen.
319
+ * A click on it starts dictating, and ends it. Where it cannot listen there is no microphone,
320
+ * and the input is as wide as it always was.
321
+ */
322
+ class WithMicrophone {
323
+ inner;
324
+ shown;
325
+ listening;
326
+ click;
327
+ /** Where the microphone begins in the line, when it is drawn. */
328
+ at = 0;
329
+ constructor(inner, shown, listening, click) {
330
+ this.inner = inner;
331
+ this.shown = shown;
332
+ this.listening = listening;
333
+ this.click = click;
334
+ }
335
+ invalidate() {
336
+ this.inner.invalidate();
337
+ }
338
+ render(width) {
339
+ if (!this.shown() || width < 24) {
340
+ this.at = 0;
341
+ return this.inner.render(width);
342
+ }
343
+ this.at = width - MIC_WIDTH;
344
+ return this.inner.render(this.at).map((line, i) => {
345
+ // The lines above and below the text run on under the microphone.
346
+ if (/^─+$/.test(stripTerminalSequences(line)))
347
+ return line + c.gray("─".repeat(MIC_WIDTH));
348
+ const padded = line + " ".repeat(Math.max(0, this.at - visibleWidth(line)));
349
+ return padded + (i === 1 ? (this.listening() ? c.bgAccent(MIC) : MIC) : " ".repeat(MIC_WIDTH));
350
+ });
351
+ }
352
+ handleMouse(e) {
353
+ if (this.at && e.y === 1 && e.x >= this.at) {
354
+ if (e.button !== "left" || (e.type !== "press" && e.type !== "click" && e.type !== "release"))
355
+ return undefined;
356
+ if (e.type === "click")
357
+ this.click();
358
+ return { handled: true, render: true };
359
+ }
360
+ return this.inner.handleMouse?.(e);
361
+ }
362
+ }
363
+ /** How many lines of a thought are shown while it is being thought. */
364
+ const PEEK = 4;
365
+ /**
366
+ * What a model thought before it answered. While it thinks, its last few lines are shown. A click
367
+ * opens all of it, and a click anywhere on it closes it again, so there is nothing small to find
368
+ * after scrolling. A thought that was not opened becomes one line when the thinking ends.
369
+ */
370
+ class Thought {
371
+ open = false;
372
+ done = false;
373
+ /** The width it was last drawn at, for working out where it lies in the conversation. */
374
+ width = 80;
375
+ text = "";
376
+ started = Date.now();
377
+ ms;
378
+ /** How fast the model call it belongs to went, once that call has ended ("↑ 1.4k t/s ↓ 42 t/s"). */
379
+ speed = "";
380
+ toggled;
381
+ wrapped;
382
+ constructor(toggled) {
383
+ this.toggled = toggled;
384
+ }
385
+ append(text) {
386
+ this.text += text;
387
+ this.wrapped = undefined;
388
+ }
389
+ /** The thinking is over. `ms` is how long it took; `null` when nobody knows (a thought read back from a session). */
390
+ finish(ms) {
391
+ if (this.done)
392
+ return;
393
+ this.done = true;
394
+ this.ms = ms === null ? undefined : (ms ?? Date.now() - this.started);
395
+ }
396
+ invalidate() {
397
+ this.wrapped = undefined;
398
+ }
399
+ lines(width) {
400
+ if (this.wrapped?.width !== width) {
401
+ // A model's text, shown as it is: nothing in it may move the cursor or colour the screen.
402
+ const clean = stripTerminalSequences(this.text).replace(/\t/g, " ").replace(/[\x00-\x09\x0b-\x1f\x7f]/g, "").replace(/\n{3,}/g, "\n\n").trim();
403
+ this.wrapped = { width, lines: clean ? wrapTextWithAnsi(clean, Math.max(10, width - 4)) : [] };
404
+ }
405
+ return this.wrapped.lines;
406
+ }
407
+ render(width) {
408
+ this.width = width;
409
+ const all = this.lines(width);
410
+ const secs = Math.max(1, Math.round((this.done ? (this.ms ?? 0) : Date.now() - this.started) / 1000));
411
+ const took = secs < 60 ? `${secs}s` : `${Math.floor(secs / 60)}m ${secs % 60}s`;
412
+ const what = `${this.done ? (this.ms === undefined ? "thought" : `thought for ${took}`) : `thinking ${took}`}${this.speed ? ` · ${this.speed}` : ""}`;
413
+ const body = (lines) => lines.map((l) => ` ${c.gray(`│ ${l}`)}`);
414
+ if (this.open)
415
+ return [` ${c.gray(`▾ ${what} · click anywhere on it to close`)}`, ...body(all), ...(all.length > PEEK ? [` ${c.gray("▴ close")}`] : [])];
416
+ const head = ` ${c.gray(`▸ ${what}${all.length ? " · click to read" : ""}`)}`;
417
+ return this.done ? [head] : [head, ...body(all.slice(-PEEK))];
418
+ }
419
+ handleMouse(e) {
420
+ if (e.button !== "left" || (e.type !== "press" && e.type !== "click" && e.type !== "release"))
421
+ return undefined;
422
+ if (e.type === "click") {
423
+ this.open = !this.open;
424
+ this.toggled(this);
425
+ }
426
+ return { handled: true, render: true };
427
+ }
428
+ }
429
+ const SCOPES = ["local", "agent", "global"];
430
+ const SCOPE_HELP = { local: "only this conversation, until it is closed", agent: "the agent, in its main conversation", global: "every agent" };
431
+ const PANE_HELP = { changes: "what git says changed in the folder, with the diff of each file", files: "the files of the folder", output: "what the agent's tool calls printed", running: "servers and other programs the agent left running, each with a way to stop it", turn: "what your last message changed in the folder (what /undo would restore)", off: "close the pane" };
432
+ const childKind = (kind) => (kind === "subagent" ? "sub-agent" : kind === "delegate" ? "delegated task" : kind);
433
+ /** A list to choose from, opened over the conversation. Type to narrow it down. */
434
+ class Picker {
435
+ title;
436
+ items;
437
+ list;
438
+ filter = "";
439
+ done;
440
+ constructor(title, items, done, current) {
441
+ this.title = title;
442
+ this.items = items;
443
+ this.done = done;
444
+ this.build(current);
445
+ }
446
+ /** The list component only matches from the start of a value, so the narrowing is done here. */
447
+ build(current) {
448
+ const shown = searchItems(this.items, this.filter);
449
+ // Give the names the room they need, so descriptions are not cut short by an empty column.
450
+ const primary = Math.min(44, Math.max(10, ...this.items.map((x) => visibleWidth(x.label))) + 2);
451
+ this.list = new SelectList(shown, 12, selectTheme, { minPrimaryColumnWidth: primary, maxPrimaryColumnWidth: primary });
452
+ const i = shown.findIndex((x) => x.value === current);
453
+ if (i >= 0)
454
+ this.list.setSelectedIndex(i);
455
+ this.list.onSelect = (item) => this.done(item.value);
456
+ this.list.onCancel = () => this.done(undefined);
457
+ }
458
+ invalidate() {
459
+ this.list.invalidate();
460
+ }
461
+ handleInput(data) {
462
+ if (matchesKey(data, "escape"))
463
+ return this.done(undefined);
464
+ if (matchesKey(data, "backspace"))
465
+ this.filter = this.filter.slice(0, -1);
466
+ else if (data.length === 1 && data >= " " && data !== "\x7f")
467
+ this.filter += data;
468
+ else
469
+ return this.list.handleInput(data);
470
+ this.build();
471
+ }
472
+ handleMouse(e) {
473
+ // The list starts below the top border, the title and the filter line, one column in.
474
+ const r = this.list.handleMouse({ ...e, x: e.x - 2, y: e.y - 3 });
475
+ return r ?? { handled: true };
476
+ }
477
+ render(width) {
478
+ const inner = Math.max(20, width - 4);
479
+ const pad = (l) => `${c.gray("│")} ${truncateToWidth(l, inner)}${" ".repeat(Math.max(0, inner - visibleWidth(truncateToWidth(l, inner))))} ${c.gray("│")}`;
480
+ return [
481
+ c.gray(`╭${"─".repeat(inner + 2)}╮`),
482
+ pad(c.bold(this.title)),
483
+ pad(`${c.accent(">")} ${this.filter}${c.gray(this.filter ? "" : "type to search · enter picks · esc closes")}`),
484
+ ...this.list.render(inner).map(pad),
485
+ c.gray(`╰${"─".repeat(inner + 2)}╯`),
486
+ ];
487
+ }
488
+ }
489
+ /** How long something has been going on, from seconds: "40 s", "3 min", "2 h 5 min". */
490
+ const elapsed = (secs) => (secs < 60 ? `${secs} s` : secs < 3600 ? `${Math.floor(secs / 60)} min` : `${Math.floor(secs / 3600)} h ${Math.floor((secs % 3600) / 60)} min`);
491
+ const since = (ms) => {
492
+ const min = Math.max(0, Math.round((Date.now() - ms) / 60_000));
493
+ return min < 1 ? "just now" : min < 60 ? `${min} min ago` : min < 48 * 60 ? `${Math.round(min / 60)} h ago` : `${Math.round(min / 1440)} days ago`;
494
+ };
495
+ const until = (ms) => {
496
+ const hours = Math.round((ms - Date.now()) / 3_600_000);
497
+ return hours < 1 ? "goes soon" : hours < 48 ? `goes in ${hours} h` : `goes in ${Math.round(hours / 24)} days`;
498
+ };
499
+ /**
500
+ * An agent's conversations, opened over the screen: open one, pin it so that it stays, or remove
501
+ * it with the × at its end (asked twice, because it cannot be undone). Type to narrow the list.
502
+ */
503
+ class ConversationList {
504
+ title;
505
+ items;
506
+ act;
507
+ filter = "";
508
+ /** 0 is "+ new conversation", the conversations follow. */
509
+ selected = 0;
510
+ top = 0;
511
+ /** The conversation whose × was clicked once. */
512
+ asked;
513
+ /** Where the words "pin" and "×" of each row on screen are: columns from, to (inclusive). */
514
+ hits = new Map();
515
+ static ROWS = 12;
516
+ constructor(title, items, current, act) {
517
+ this.title = title;
518
+ this.items = items;
519
+ this.act = act;
520
+ this.selected = Math.max(0, items.findIndex((x) => x.session === current) + 1);
521
+ }
522
+ invalidate() { }
523
+ shown() {
524
+ const f = this.filter.toLowerCase();
525
+ return f ? this.items.filter((x) => x.session.toLowerCase().includes(f)) : this.items;
526
+ }
527
+ get conv() {
528
+ return this.shown()[this.selected - 1];
529
+ }
530
+ async pin(conv) {
531
+ if (conv.session === "main")
532
+ return;
533
+ conv.pinned = await this.act.pin(conv);
534
+ this.act.redraw();
535
+ }
536
+ async remove(conv) {
537
+ if (this.asked !== conv.session) {
538
+ this.asked = conv.session;
539
+ return this.act.redraw();
540
+ }
541
+ this.asked = undefined;
542
+ // The agent's own conversation stays: what can be taken away is what was said in it.
543
+ if (conv.session === "main") {
544
+ if (await this.act.reset(conv))
545
+ conv.tasks = 0;
546
+ }
547
+ else if (await this.act.remove(conv)) {
548
+ this.items = this.items.filter((x) => x !== conv);
549
+ this.selected = Math.min(this.selected, this.shown().length);
550
+ }
551
+ this.act.redraw();
552
+ }
553
+ handleInput(data) {
554
+ const count = this.shown().length + 1;
555
+ if (matchesKey(data, "escape"))
556
+ return this.act.close();
557
+ if (matchesKey(data, "up"))
558
+ this.selected = (this.selected - 1 + count) % count;
559
+ else if (matchesKey(data, "down"))
560
+ this.selected = (this.selected + 1) % count;
561
+ else if (matchesKey(data, "enter"))
562
+ return this.selected === 0 ? this.act.fresh() : this.conv && this.act.open(this.conv.session);
563
+ else if (matchesKey(data, "ctrl+p"))
564
+ return void (this.conv && this.pin(this.conv));
565
+ else if (matchesKey(data, "ctrl+x"))
566
+ return void (this.conv && this.remove(this.conv));
567
+ else if (matchesKey(data, "backspace"))
568
+ (this.filter = this.filter.slice(0, -1)), (this.selected = 0);
569
+ else if (data.length === 1 && data >= " " && data !== "\x7f")
570
+ (this.filter += data), (this.selected = this.shown().length ? 1 : 0);
571
+ else
572
+ return;
573
+ this.asked = undefined;
574
+ this.act.redraw();
575
+ }
576
+ handleMouse(e) {
577
+ const count = this.shown().length + 1;
578
+ if (e.type === "wheel" && e.wheelDelta) {
579
+ this.selected = Math.max(0, Math.min(count - 1, this.selected + (e.wheelDelta < 0 ? -1 : 1)));
580
+ return { handled: true, render: true };
581
+ }
582
+ if (e.button !== "left" || e.type !== "click")
583
+ return { handled: true };
584
+ // Rows start below the border, the title and the filter line; their text starts two columns in.
585
+ const index = this.top + e.y - 3;
586
+ if (e.y < 3 || index < 0 || index >= count || e.y - 3 >= ConversationList.ROWS)
587
+ return { handled: true };
588
+ this.selected = index;
589
+ const conv = this.conv;
590
+ const hit = this.hits.get(index);
591
+ const within = (zone) => zone !== undefined && e.x >= zone[0] && e.x <= zone[1];
592
+ if (!conv)
593
+ this.act.fresh();
594
+ else if (within(hit?.x))
595
+ void this.remove(conv);
596
+ else if (within(hit?.pin))
597
+ void this.pin(conv);
598
+ else
599
+ this.act.open(conv.session);
600
+ return { handled: true, render: true };
601
+ }
602
+ render(width) {
603
+ const inner = Math.max(20, width - 4);
604
+ this.hits.clear();
605
+ const pad = (l) => `${c.gray("│")} ${truncateToWidth(l, inner)}${" ".repeat(Math.max(0, inner - visibleWidth(truncateToWidth(l, inner))))} ${c.gray("│")}`;
606
+ const shown = this.shown();
607
+ const rows = ConversationList.ROWS;
608
+ this.top = Math.max(0, Math.min(this.selected - Math.floor(rows / 2), shown.length + 1 - rows));
609
+ const name = Math.min(28, Math.max(10, ...shown.map((x) => visibleWidth(x.session)))) + 1;
610
+ const lines = [];
611
+ for (let i = this.top; i < Math.min(shown.length + 1, this.top + rows); i++) {
612
+ const on = i === this.selected;
613
+ if (i === 0) {
614
+ lines.push(pad(on ? c.accent(" + new conversation") : " + new conversation"));
615
+ continue;
616
+ }
617
+ const conv = shown[i - 1];
618
+ const main = conv.session === "main";
619
+ const state = main ? "the agent's own, always kept" : conv.pinned ? "pinned" : conv.open ? "open in a tab" : conv.expires ? until(conv.expires) : "kept";
620
+ // The agent's own conversation is kept without a pin: it has the mark of one.
621
+ const mark = conv.pinned || main ? c.accent("★") : " ";
622
+ const label = short(conv.session, name - 1).padEnd(name);
623
+ const left = `${mark} ${on ? c.accent(label) : label} ${c.gray(`${conv.tasks} message${conv.tasks === 1 ? "" : "s"} · ${since(conv.last)} · ${state}`)}`;
624
+ // At the end of the row, the two things that can be done to it, as words to click.
625
+ const pin = main ? "" : conv.pinned ? "unpin" : "pin";
626
+ const x = main ? (this.asked === conv.session ? "reset? ×" : "reset") : this.asked === conv.session ? "remove? ×" : "×";
627
+ const right = main ? (this.asked === conv.session ? c.red(x) : c.gray(x)) : `${c.accent(pin)} ${this.asked === conv.session ? c.red(x) : c.gray(x)}`;
628
+ const room = inner - visibleWidth(right) - 2;
629
+ const cut = truncateToWidth(left, room);
630
+ lines.push(pad(`${cut}${" ".repeat(Math.max(0, room - visibleWidth(cut)))} ${right}`));
631
+ // Columns as a click reports them: the border and a space come first. A click just beside a word counts too.
632
+ const end = 2 + inner - 1;
633
+ this.hits.set(i, { x: [end - x.length, end], pin: main ? [-1, -1] : [end - x.length - 3 - pin.length, end - x.length - 2] });
634
+ }
635
+ return [
636
+ c.gray(`╭${"─".repeat(inner + 2)}╮`),
637
+ pad(c.bold(this.title)),
638
+ pad(`${c.accent(">")} ${this.filter}${c.gray(this.filter ? "" : "type to search · enter opens · ctrl+p pins · ctrl+x removes · esc closes")}`),
639
+ ...lines,
640
+ pad(c.gray(`pin keeps a conversation for good · × removes it now · reset empties the agent's own${shown.length + 1 > rows ? ` · ${shown.length} in all` : ""}`)),
641
+ c.gray(`╰${"─".repeat(inner + 2)}╯`),
642
+ ];
643
+ }
644
+ }
645
+ const REASONING_ITEMS = [
646
+ { value: "off", label: "off", description: "answer straight away" },
647
+ { value: "minimal", label: "minimal" },
648
+ { value: "low", label: "low" },
649
+ { value: "medium", label: "medium" },
650
+ { value: "high", label: "high", description: "think longer before answering" },
651
+ { value: "xhigh", label: "xhigh" },
652
+ { value: "max", label: "max", description: "as much as the model allows" },
653
+ ];
654
+ const MODE_ITEMS = [
655
+ { value: "auto", label: "auto", description: "no sandbox: your whole account and the network; critical actions are checked" },
656
+ { value: "safe", label: "safe", description: "works inside its sandbox, asks for the rest" },
657
+ { value: "manual", label: "manual", description: "inside its sandbox, and asks before every action" },
658
+ { value: "bypass", label: "bypass", description: "no sandbox, and never asks" },
659
+ { value: "plan", label: "plan", description: "looks, reads and asks, changes nothing: you get a plan first" },
660
+ ];
661
+ const short = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
662
+ const oneLine = (s) => s.replace(/\s+/g, " ").trim();
663
+ /** Modal question for one approval request. */
664
+ class ApprovalDialog {
665
+ req;
666
+ done;
667
+ choice = 0;
668
+ options;
669
+ buttons = [];
670
+ /**
671
+ * Values the request needs from the owner and that no model may see: a password, a token. They
672
+ * are typed here without being shown, and go from this dialog straight to the daemon.
673
+ */
674
+ fields;
675
+ field = 0;
676
+ constructor(req, done) {
677
+ this.req = req;
678
+ this.done = done;
679
+ this.fields = (Array.isArray(req.inputs) ? req.inputs : []).map((i) => ({ name: String(i.name), label: String(i.label ?? i.name), value: "", secret: i.secret !== false }));
680
+ this.options = this.fields.length
681
+ ? [
682
+ { answer: "allow", label: "Save and allow (enter)" },
683
+ { answer: "deny", label: "Deny" },
684
+ { answer: "later", label: "Later (esc)" },
685
+ ]
686
+ : [
687
+ // A yes that already holds for more than this call is not called "once".
688
+ { answer: "allow", label: req.holds ? "Allow (a)" : "Allow once (a)" },
689
+ // Only where the daemon offers it: not for actions that are configured to ask every time.
690
+ ...(req.remember ? [{ answer: "always", label: "Always here (s)" }] : []),
691
+ { answer: "deny", label: "Deny (d)" },
692
+ { answer: "later", label: "Later (esc)" },
693
+ ];
694
+ }
695
+ answer(answer) {
696
+ if (answer !== "allow" || !this.fields.length)
697
+ return this.done(answer);
698
+ // A yes needs every value: go to the first one that is still empty.
699
+ const empty = this.fields.findIndex((f) => !f.value.trim());
700
+ if (empty >= 0)
701
+ return void (this.field = empty);
702
+ this.done("allow", Object.fromEntries(this.fields.map((f) => [f.name, f.value.trim()])));
703
+ }
704
+ invalidate() { }
705
+ handleMouse(e) {
706
+ const b = this.buttons.find((x) => e.y === x.row && e.x >= x.from && e.x < x.to);
707
+ if (b && e.type === "click" && e.button === "left")
708
+ this.answer(b.answer);
709
+ return { handled: true, render: true };
710
+ }
711
+ handleInput(data) {
712
+ if (this.fields.length)
713
+ return this.typed(data);
714
+ const n = this.options.length;
715
+ if (data === "a" || data === "y")
716
+ return this.done("allow");
717
+ if (data === "s" && this.req.remember)
718
+ return this.done("always");
719
+ if (data === "d" || data === "n")
720
+ return this.done("deny");
721
+ if (matchesKey(data, "escape"))
722
+ return this.done("later");
723
+ if (matchesKey(data, "left") || matchesKey(data, "up") || matchesKey(data, "shift+tab"))
724
+ this.choice = (this.choice + n - 1) % n;
725
+ else if (matchesKey(data, "right") || matchesKey(data, "down") || matchesKey(data, "tab"))
726
+ this.choice = (this.choice + 1) % n;
727
+ else if (matchesKey(data, "enter"))
728
+ return this.done(this.options[this.choice].answer);
729
+ }
730
+ /** Keys while a value is being typed: every printable key is part of the value, so there are no letter shortcuts. */
731
+ typed(data) {
732
+ const f = this.fields[this.field];
733
+ const paste = data.match(/\x1b\[200~([\s\S]*?)\x1b\[201~/);
734
+ if (paste)
735
+ return void (f.value += paste[1].replace(/[\r\n\t]/g, "").trim());
736
+ if (matchesKey(data, "escape"))
737
+ return this.done("later");
738
+ if (matchesKey(data, "enter"))
739
+ return this.answer("allow");
740
+ if (matchesKey(data, "tab") || matchesKey(data, "down"))
741
+ this.field = (this.field + 1) % this.fields.length;
742
+ else if (matchesKey(data, "shift+tab") || matchesKey(data, "up"))
743
+ this.field = (this.field + this.fields.length - 1) % this.fields.length;
744
+ else if (matchesKey(data, "backspace"))
745
+ f.value = f.value.slice(0, -1);
746
+ else if (matchesKey(data, "ctrl+u"))
747
+ f.value = "";
748
+ else if (data.length === 1 && data >= " " && data !== "\x7f")
749
+ f.value += data;
750
+ }
751
+ render(width) {
752
+ const inner = Math.max(20, width - 4);
753
+ const inputs = this.fields.flatMap((f, i) => [
754
+ ...wrapTextWithAnsi(c.bold(f.label), inner),
755
+ // A secret is never shown: a dot for each character, so that you see it arrive.
756
+ `${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(" ") : ""}`,
757
+ ]);
758
+ const body = [
759
+ c.bold(c.yellow(this.fields.length ? "Approval needed, and something only you have" : "Approval needed")),
760
+ "",
761
+ `${c.gray("agent ")} ${this.req.agent}${this.req.task ? ` ${c.gray(`(task #${this.req.task})`)}` : ""}`,
762
+ `${c.gray("action")} ${c.bold(String(this.req.tool))}`,
763
+ ...String(this.req.summary ?? "").split("\n").slice(0, 8).flatMap((l) => wrapTextWithAnsi(` ${l}`, inner)).slice(0, 12),
764
+ "",
765
+ ...wrapTextWithAnsi(c.gray(`Why you are asked: ${this.req.why}`), inner),
766
+ ...(this.req.holds ? wrapTextWithAnsi(c.gray(`"Allow" holds for ${this.req.holds}: you are not asked about it again there.`), inner) : []),
767
+ ...(this.req.remember ? wrapTextWithAnsi(c.gray(`"Always here" stops asking about ${this.req.remember} in this conversation.`), inner) : []),
768
+ ...(!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) : []),
769
+ ...(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)] : []),
770
+ "",
771
+ ];
772
+ // The buttons, wrapped onto a second line in a narrow window. Their places are kept for clicks:
773
+ // two columns of border and padding, then the labels.
774
+ const rows = [""];
775
+ this.buttons = [];
776
+ let col = 0;
777
+ this.options.forEach((o, i) => {
778
+ const w = o.label.length + 2;
779
+ if (col > 0 && col + w > inner) {
780
+ rows.push("");
781
+ col = 0;
782
+ }
783
+ rows[rows.length - 1] += `${i === this.choice ? c.bgAccent(` ${o.label} `) : ` ${o.label} `} `;
784
+ this.buttons.push({ row: 1 + body.length + rows.length - 1, from: 2 + col, to: 2 + col + w, answer: o.answer });
785
+ col += w + 2;
786
+ });
787
+ body.push(...rows);
788
+ const pad = (l) => `${c.yellow("│")} ${l}${" ".repeat(Math.max(0, inner - visibleWidth(l)))} ${c.yellow("│")}`;
789
+ return [c.yellow(`╭${"─".repeat(inner + 2)}╮`), ...body.map((l) => pad(truncateToWidth(l, inner))), c.yellow(`╰${"─".repeat(inner + 2)}╯`)];
790
+ }
791
+ }
792
+ /**
793
+ * A question of the agent's (its `question` tool): the answers it offers, one to a line, and a
794
+ * line for the owner's own words. Arrows and enter or a click pick an answer, a digit picks by
795
+ * number; anything typed is an answer of the owner's own.
796
+ */
797
+ class QuestionDialog {
798
+ req;
799
+ done;
800
+ choices;
801
+ at = 0;
802
+ own = "";
803
+ rows = [];
804
+ constructor(req, done) {
805
+ this.req = req;
806
+ this.done = done;
807
+ this.choices = (Array.isArray(req.choices) ? req.choices : []).map((x) => String(x));
808
+ }
809
+ invalidate() { }
810
+ handleMouse(e) {
811
+ const hit = this.rows.find((r) => r.row === e.y);
812
+ if (hit && e.type === "click" && e.button === "left")
813
+ this.done(this.choices[hit.index]);
814
+ return { handled: true, render: true };
815
+ }
816
+ handleInput(data) {
817
+ const paste = data.match(/\x1b\[200~([\s\S]*?)\x1b\[201~/);
818
+ if (paste)
819
+ return void (this.own += paste[1].replace(/[\r\n\t]+/g, " ").trim());
820
+ if (matchesKey(data, "escape"))
821
+ return this.done(undefined);
822
+ if (matchesKey(data, "enter")) {
823
+ if (this.own.trim())
824
+ return this.done(this.own.trim());
825
+ return this.choices.length ? this.done(this.choices[this.at]) : undefined;
826
+ }
827
+ if (matchesKey(data, "up") || matchesKey(data, "shift+tab"))
828
+ this.at = (this.at + Math.max(1, this.choices.length) - 1) % Math.max(1, this.choices.length);
829
+ else if (matchesKey(data, "down") || matchesKey(data, "tab"))
830
+ this.at = (this.at + 1) % Math.max(1, this.choices.length);
831
+ else if (matchesKey(data, "backspace"))
832
+ this.own = this.own.slice(0, -1);
833
+ else if (matchesKey(data, "ctrl+u"))
834
+ this.own = "";
835
+ else if (!this.own && /^[1-9]$/.test(data) && Number(data) <= this.choices.length)
836
+ return this.done(this.choices[Number(data) - 1]);
837
+ else if (data.length === 1 && data >= " " && data !== "\x7f")
838
+ this.own += data;
839
+ }
840
+ render(width) {
841
+ const inner = Math.max(20, width - 4);
842
+ const body = [c.bold(c.accent(`${this.req.agent} asks`)), "", ...String(this.req.summary ?? "").split("\n").flatMap((l) => wrapTextWithAnsi(l, inner)).slice(0, 14), ""];
843
+ this.rows = [];
844
+ this.choices.forEach((choice, i) => {
845
+ this.rows.push({ row: 1 + body.length, index: i });
846
+ const label = truncateToWidth(`${i + 1} ${choice}`, inner - 2);
847
+ body.push(i === this.at && !this.own ? c.bgAccent(` ${label} `) : ` ${label}`);
848
+ });
849
+ body.push("", `${c.gray(this.choices.length ? "or in your own words:" : "your answer:")} ${c.yellow(this.own.slice(-(inner - 26)))}${c.inverse(" ")}`, "", c.gray(this.choices.length ? "enter or a click answers · 1-9 picks by number · esc: later" : "enter answers · esc: later"));
850
+ const pad = (l) => `${c.accent("│")} ${l}${" ".repeat(Math.max(0, inner - visibleWidth(l)))} ${c.accent("│")}`;
851
+ return [c.accent(`╭${"─".repeat(inner + 2)}╮`), ...body.map((l) => pad(truncateToWidth(l, inner))), c.accent(`╰${"─".repeat(inner + 2)}╯`)];
852
+ }
853
+ }
854
+ /**
855
+ * The screen, with one addition: while a menu or question is open, a click next to it goes to the
856
+ * app (which closes the menu) instead of to whatever lies underneath.
857
+ */
858
+ class Screen extends TuiAltScreen {
859
+ onOutside;
860
+ /** The terminal said that its window came to the front, or went from it. */
861
+ onFocus;
862
+ constructor(...args) {
863
+ super(...args);
864
+ // The library takes these two reports for itself before anything else sees them; it is asked first here.
865
+ const own = this.handleViewportInput;
866
+ if (typeof own === "function") {
867
+ this.handleViewportInput = (data) => {
868
+ if (data === "\x1b[I" || data === "\x1b[O")
869
+ this.onFocus?.(data === "\x1b[I");
870
+ return own.call(this, data);
871
+ };
872
+ }
873
+ }
874
+ dispatchMouseToOverlay(event) {
875
+ const r = super.dispatchMouseToOverlay(event);
876
+ return !r.hit && this.onOutside?.(event) ? { hit: true } : r;
877
+ }
878
+ /**
879
+ * A real picture is drawn above all text, so it would lie across a menu opened over it. Pictures
880
+ * that a menu or dialog covers are drawn as text for as long as it is there.
881
+ */
882
+ compositeOverlays(lines, width, height) {
883
+ const out = super.compositeOverlays(lines, width, height);
884
+ const boxes = this.renderedOverlayLayouts ?? [];
885
+ if (!boxes.length)
886
+ return out;
887
+ // Overlays are placed from the top of the visible screen; `lines` may be longer than that.
888
+ const top = Math.max(0, out.length - height);
889
+ const asText = picturesAsText(lines, (row, col, w, h) => boxes.some((b) => row < top + b.row + b.height && top + b.row < row + h && col < b.col + b.width && b.col < col + w));
890
+ return asText === lines ? out : super.compositeOverlays(asText, width, height);
891
+ }
892
+ }
893
+ /** The terminal UI: one tab per conversation, a live event tab, slash commands, approval prompts. */
894
+ export class PineTui {
895
+ client;
896
+ tui;
897
+ editor;
898
+ header;
899
+ status;
900
+ footer;
901
+ dock;
902
+ tabs = [];
903
+ active;
904
+ nextTabId = 1;
905
+ agents = [];
906
+ commands = [];
907
+ connected = false;
908
+ notice = "";
909
+ noticeTimer;
910
+ /** Dictating a message: what listens, what stood in the input before, and how far it is. */
911
+ voice;
912
+ voiceTools;
913
+ /** The language to listen for, when the owner named one (/voice de-DE). Default: the system's. */
914
+ voiceLanguage;
915
+ spinner;
916
+ watching;
917
+ frame = 0;
918
+ unsubscribe;
919
+ /** `waits`: a question to the owner that is still open on the daemon's side. A click beside it does not close it. */
920
+ dialog;
921
+ /** When a menu or question last closed. A key that closed it is not also a key for what lies under it. */
922
+ dialogClosedAt = 0;
923
+ /** Videos fetched from the daemon, as files for ffmpeg and the player. Removed when the UI closes. */
924
+ mediaDir;
925
+ mediaCount = 0;
926
+ headerHits = [];
927
+ footerHits = [];
928
+ attachHits = [];
929
+ attach;
930
+ sessionModes = new Map();
931
+ lastCtrlC = 0;
932
+ taints = new Map();
933
+ /** The pinned conversations of the agents that have a tab ("agent:session"): a tab of one shows the mark of a kept conversation. */
934
+ pins = new Set();
935
+ bypassWhenTainted = false;
936
+ opts;
937
+ stopped = false;
938
+ /** While the tabs of last time are being opened again. */
939
+ restoring = false;
940
+ /** The pane beside a conversation: changes, files, tool output. */
941
+ code;
942
+ codeOpen = false;
943
+ codeRule = { invalidate() { }, render: () => RULE };
944
+ /** Whether the terminal's window is in front (terminals that do not say are taken to be). */
945
+ focused = true;
946
+ /** Whether to call for attention when something ends or waits while the window is not in front. */
947
+ notify = true;
948
+ constructor(opts) {
949
+ this.opts = opts;
950
+ this.client = opts.client;
951
+ this.tui = new Screen(opts.terminal, false, undefined, {
952
+ mouse: true,
953
+ openUrl: (url) => this.open(url),
954
+ // With the mouse in use by the UI, selecting text is the UI's job too: what you drag over is copied.
955
+ copyOnSelect: true,
956
+ copySelection: (text) => this.copyText(text),
957
+ });
958
+ this.editor = new Editor(this.tui, editorTheme, { paddingX: 1, autocompleteMaxVisible: 8 });
959
+ this.editor.onSubmit = (text) => void this.submit(text);
960
+ this.header = clickable((w) => this.renderHeader(w), () => this.headerHits);
961
+ this.status = { invalidate: () => { }, render: (w) => this.renderStatus(w) };
962
+ this.attach = clickable((w) => this.renderAttachments(w), () => this.attachHits);
963
+ this.footer = clickable((w) => this.renderFooter(w), () => this.footerHits);
964
+ this.dock = new VStack([
965
+ { component: this.status, shrink: 1, minSize: 0 },
966
+ { component: this.attach, shrink: 1, minSize: 0 },
967
+ { component: new WithMicrophone(this.editor, () => this.active?.kind === "chat" && this.canListen(), () => this.voice !== undefined, () => void this.dictate()), shrink: 1, minSize: 3 },
968
+ { component: this.footer, shrink: 1, minSize: 0 },
969
+ ]);
970
+ this.code = new CodePane({
971
+ client: this.client,
972
+ redraw: () => this.tui.requestRender(),
973
+ close: () => this.showCode(false),
974
+ target: () => (this.active?.kind === "chat" ? { agent: this.active.agent, session: this.active.session } : undefined),
975
+ steps: () => (this.active?.kind === "chat" ? this.active.todo?.items : undefined),
976
+ });
977
+ this.defineCommands();
978
+ this.editor.setAutocompleteProvider(new Mentions(new CombinedAutocompleteProvider(this.commands, process.cwd(), null), async (query) => {
979
+ const t = this.active;
980
+ if (t?.kind !== "chat")
981
+ return [];
982
+ const files = (await this.client.find(t.agent, t.session, query)).files;
983
+ for (const f of files)
984
+ t.files.add(f);
985
+ return files;
986
+ }));
987
+ this.tui.addInputListener((data) => (this.onKey(data) ? { consume: true } : undefined));
988
+ // A menu or question is modal: a click beside it does not reach the tabs and the bar
989
+ // underneath. It closes a menu. It does not close a question that waits for the owner's
990
+ // answer: a click into the window must not make it vanish, and an unanswered question
991
+ // counts as a no when its time is up. The wheel still scrolls.
992
+ this.tui.onFocus = (focused) => void (this.focused = focused);
993
+ this.tui.onOutside = (e) => {
994
+ if (!this.dialog || e.type === "wheel")
995
+ return false;
996
+ if (e.type === "click" && e.button === "left" && !this.dialog.waits)
997
+ this.dialog.dismiss();
998
+ return true;
999
+ };
1000
+ // Addresses are always printed in full, so what is clicked is what is opened; a link whose text
1001
+ // hides its target would be an easy trick for a web page to play through an agent's answer.
1002
+ setCapabilities({ ...getCapabilities(), hyperlinks: false });
1003
+ }
1004
+ async start() {
1005
+ this.agents = await this.client.agents();
1006
+ if (!this.agents.length)
1007
+ throw new Error("the daemon has no agents");
1008
+ const first = this.agents.find((a) => a.main) ?? this.agents[0];
1009
+ this.unsubscribe = this.client.subscribe((e) => this.onEvent(e), (up) => {
1010
+ const back = up && !this.connected;
1011
+ this.connected = up;
1012
+ // What was asked while the line was down, or by a daemon that has since been restarted,
1013
+ // is no longer open: a question nobody can answer must not stay on screen.
1014
+ if (back)
1015
+ void this.dropAnswered();
1016
+ this.tui.requestRender();
1017
+ });
1018
+ this.tui.start();
1019
+ this.spinner = setInterval(() => {
1020
+ if (!this.tabs.some((t) => t.running.size))
1021
+ return;
1022
+ this.frame++;
1023
+ this.tui.requestRender();
1024
+ }, 120);
1025
+ this.spinner.unref?.();
1026
+ // What a conversation's commands left running is not an event: it is asked for now and then,
1027
+ // so that the status line can say that something is still going on after the agent's turn.
1028
+ this.watching = setInterval(() => void this.pollPrograms(), 3000);
1029
+ this.watching.unref?.();
1030
+ // The same tabs as last time, in the same order.
1031
+ const saved = await this.client.tabs().catch(() => ({ tabs: [], active: 0, code: false, notify: true }));
1032
+ this.notify = saved.notify !== false;
1033
+ const again = saved.tabs.filter((t) => this.agents.some((a) => a.id === t.agent));
1034
+ this.restoring = true;
1035
+ try {
1036
+ if (!again.length)
1037
+ await this.openTab(first.id, "main");
1038
+ for (const t of again)
1039
+ await this.openTab(t.agent, t.session);
1040
+ const chats = this.tabs.filter((t) => t.kind === "chat");
1041
+ if (again.length && chats[saved.active])
1042
+ this.activate(chats[saved.active]);
1043
+ }
1044
+ finally {
1045
+ this.restoring = false;
1046
+ }
1047
+ if (saved.code)
1048
+ this.showCode(true);
1049
+ this.saveTabs();
1050
+ void this.refreshTaints();
1051
+ void this.refreshPins();
1052
+ }
1053
+ /** Remember which conversations are open, so that the next start opens the same tabs. */
1054
+ saveTabs() {
1055
+ if (this.restoring || this.stopped)
1056
+ return;
1057
+ const chats = this.tabs.filter((t) => t.kind === "chat");
1058
+ void this.client.saveTabs(chats.map((t) => ({ agent: t.agent, session: t.session })), Math.max(0, chats.indexOf(this.active)), this.codeOpen, this.notify).catch(() => { });
1059
+ }
1060
+ async stop() {
1061
+ if (this.stopped)
1062
+ return;
1063
+ this.stopped = true;
1064
+ clearInterval(this.spinner);
1065
+ clearInterval(this.watching);
1066
+ clearTimeout(this.noticeTimer);
1067
+ // Leaving keeps every conversation as it is: the same tabs open again next time.
1068
+ this.unsubscribe?.();
1069
+ this.code.stop();
1070
+ stopVideos();
1071
+ stopSounds();
1072
+ this.voice?.listening?.cancel();
1073
+ if (this.mediaDir)
1074
+ fs.rmSync(this.mediaDir, { recursive: true, force: true });
1075
+ this.tui.stop();
1076
+ await this.opts.onQuit?.();
1077
+ }
1078
+ /** What is on screen, without colours. For tests and debugging. */
1079
+ screen() {
1080
+ this.tui.renderNow(true);
1081
+ return this.tui.getScreenLines().map((l) => stripTerminalSequences(l).replace(/\s+$/, ""));
1082
+ }
1083
+ // ---- tabs ------------------------------------------------------------------------------------
1084
+ newTab(kind, agent, session) {
1085
+ const doc = new Doc();
1086
+ const scroll = new ScrollView(doc, { follow: "end", primary: true, overscroll: "chain", scrollbar: "auto" });
1087
+ // A conversation can have the code pane beside it: half the width each, or the pane alone where that is too narrow.
1088
+ const beside = kind === "chat";
1089
+ doc.asText = () => beside && this.codeOpen;
1090
+ const body = beside ? new Split(scroll, this.codeRule, this.code.component, () => this.codeOpen, () => this.opts.terminal.columns) : scroll;
1091
+ const tab = {
1092
+ id: this.nextTabId++, kind, agent, session, doc, scroll,
1093
+ layout: new VStack([
1094
+ { component: this.header, basis: "auto", grow: 0, shrink: 0 },
1095
+ { component: body, basis: 0, grow: 1, shrink: 1, minSize: 1 },
1096
+ { component: this.dock, basis: "auto", grow: 0, shrink: 1, minSize: 1 },
1097
+ ]),
1098
+ roots: new Set(), running: new Set(), awaiting: [], blocks: new Map(), thoughts: new Map(), tools: new Map(), streamed: new Map(), approvals: new Map(), baseDepth: 0, children: new Map(),
1099
+ unread: false, startedAt: 0, toolCalls: 0, tokens: { input: 0, output: 0, cached: 0 }, thinking: false, lines: [], attachments: [], pauseNoted: false, files: new Set(),
1100
+ };
1101
+ this.tabs.push(tab);
1102
+ return tab;
1103
+ }
1104
+ async openTab(agent, session) {
1105
+ const existing = this.tabs.find((t) => t.kind === "chat" && t.agent === agent && t.session === session);
1106
+ if (existing)
1107
+ return this.activate(existing);
1108
+ if (!this.agents.some((a) => a.id === agent))
1109
+ this.agents = await this.client.agents().catch(() => this.agents);
1110
+ if (!this.agents.some((a) => a.id === agent))
1111
+ return this.flash(`there is no agent called ${agent}`);
1112
+ const tab = this.newTab("chat", agent, session);
1113
+ this.activate(tab);
1114
+ this.saveTabs();
1115
+ void this.refreshPins();
1116
+ const info = this.agents.find((a) => a.id === agent);
1117
+ tab.folder = (await this.client.folder(agent, session).catch(() => undefined))?.folder;
1118
+ tab.goal = (await this.client.goal(agent, session).catch(() => undefined))?.goal;
1119
+ this.say(tab, c.gray(`${c.bold(agent)}${info?.description ? ` · ${info.description}` : ""}\nsession ${session} · model ${info?.model ?? "?"}${tab.folder ? ` · works in ${tilde(tab.folder)}` : ""} · type a message, / for commands, or click the bar below`));
1120
+ try {
1121
+ const history = (await this.client.history(agent, session)).filter((t) => t.depth === 0).reverse();
1122
+ if (history.length)
1123
+ this.say(tab, c.gray(`── earlier in this session (${history.length}) ──`));
1124
+ for (const t of history)
1125
+ this.renderPast(tab, t);
1126
+ this.takeStats(tab, history.at(-1)?.meta?.stats);
1127
+ // What the agent listed for itself and has not finished is still its plan.
1128
+ const steps = await this.client.todos(agent, session).catch(() => []);
1129
+ if (steps.some((t) => t.status !== "done"))
1130
+ this.showSteps(tab, -1, steps);
1131
+ if (history.length)
1132
+ this.say(tab, c.gray("── now ──"));
1133
+ if (tab.goal)
1134
+ this.say(tab, this.goalLine(tab.goal, true));
1135
+ }
1136
+ catch (e) {
1137
+ this.say(tab, c.red(`could not load history: ${errText(e)}`));
1138
+ }
1139
+ this.tui.requestRender();
1140
+ }
1141
+ /**
1142
+ * Open a tab on one task, typically a sub-agent: what it was given, what it thought and wrote,
1143
+ * every tool call with the start of its result. A running task is followed live.
1144
+ */
1145
+ async openTask(id) {
1146
+ const existing = this.tabs.find((t) => t.kind === "task" && t.task === id);
1147
+ if (existing)
1148
+ return this.activate(existing);
1149
+ let data;
1150
+ try {
1151
+ data = await this.client.transcript(id);
1152
+ }
1153
+ catch (e) {
1154
+ return this.flash(`task #${id}: ${errText(e)}`);
1155
+ }
1156
+ const { task, entries } = data;
1157
+ const tab = this.newTab("task", task.agent, task.session);
1158
+ tab.task = id;
1159
+ tab.baseDepth = task.depth;
1160
+ tab.roots.add(id);
1161
+ this.activate(tab);
1162
+ const who = task.kind === "subagent" ? `sub-agent of ${task.agent}` : task.kind === "delegate" ? `${task.agent}, on a task from ${task.meta.chain?.at(-1) ?? "another agent"}` : task.agent;
1163
+ const live = task.status === "running" || task.status === "pending";
1164
+ this.say(tab, c.gray(`${c.bold(who)} · task #${id}${task.parent !== undefined ? ` · started by task #${task.parent}` : ""} · ${task.status}\nsession ${task.session} · this tab shows the work and takes no messages${live ? " · esc stops this task" : ""}`));
1165
+ if (entries.length)
1166
+ for (const e of entries)
1167
+ this.renderEntry(tab, e);
1168
+ else {
1169
+ // No session file (not started yet, or cleared): what the task list knows.
1170
+ this.user(tab, task.prompt, "task");
1171
+ if (task.result)
1172
+ this.add(tab, new Answer(task.result));
1173
+ }
1174
+ if (live) {
1175
+ tab.running.add(id);
1176
+ tab.startedAt = task.started ?? Date.now();
1177
+ }
1178
+ else
1179
+ this.say(tab, c.gray(this.taskSummary(task.status, task.meta.stats, task.error)));
1180
+ tab.scroll.scrollToEnd();
1181
+ this.tui.requestRender();
1182
+ }
1183
+ taskSummary(status, stats, error) {
1184
+ const parts = [status, ...(stats ? [`${Math.round(stats.ms / 100) / 10} s`, `${stats.tools.length} tool call${stats.tools.length === 1 ? "" : "s"}`, `${stats.input + (stats.cached ?? 0)}↑ ${stats.output}↓`, ...(speedText(speedOf(stats.timing)) ? [speedText(speedOf(stats.timing))] : [])] : []), ...(error ? [error] : [])];
1185
+ return `── ${parts.join(" · ")} ──`;
1186
+ }
1187
+ renderEntry(tab, e) {
1188
+ if (e.kind === "user")
1189
+ return this.user(tab, e.text ?? "", "task");
1190
+ if (e.kind === "text") {
1191
+ this.add(tab, new Answer(e.text ?? ""));
1192
+ return this.answerPictures(tab, tab.agent, e.text, false);
1193
+ }
1194
+ if (e.kind === "thinking") {
1195
+ const thought = this.thought(tab);
1196
+ thought.append(e.text ?? "");
1197
+ return thought.finish(null);
1198
+ }
1199
+ const mark = e.ok === undefined ? c.yellow("●") : e.ok ? c.green("✓") : c.red("✗");
1200
+ const took = e.ms !== undefined ? c.gray(` ${e.ms < 1000 ? `${Math.round(e.ms)} ms` : `${(e.ms / 1000).toFixed(1)} s`}`) : "";
1201
+ const result = e.result ? `\n ${(e.ok === false ? c.red : c.gray)(short(oneLine(e.result), 240))}` : "";
1202
+ this.say(tab, `${mark} ${c.bold(e.tool ?? "")}${e.subject ? ` ${c.gray(short(oneLine(e.subject), 100))}` : ""}${took}${result}`, false);
1203
+ for (const id of e.images ?? [])
1204
+ this.picture(tab, `from ${e.tool}`, () => this.client.toolImage(id));
1205
+ }
1206
+ openEvents() {
1207
+ let tab = this.tabs.find((t) => t.kind === "events");
1208
+ if (!tab) {
1209
+ tab = this.newTab("events", "events", "");
1210
+ tab.log = new Text(c.gray("Live events. Agent text deltas are left out."), 1, 0);
1211
+ tab.doc.addChild(tab.log);
1212
+ }
1213
+ this.activate(tab);
1214
+ }
1215
+ activate(tab) {
1216
+ this.active = tab;
1217
+ tab.unread = false;
1218
+ this.tui.setLayoutRoot(tab.layout);
1219
+ this.tui.setFocus(this.editor);
1220
+ tab.scroll.scrollToEnd();
1221
+ if (this.codeOpen)
1222
+ this.code.show();
1223
+ this.tui.requestRender();
1224
+ this.saveTabs();
1225
+ const waiting = [...tab.approvals.values()][0];
1226
+ if (waiting && !this.dialog)
1227
+ this.ask(tab, waiting.req);
1228
+ }
1229
+ cycle(by) {
1230
+ const i = this.tabs.indexOf(this.active);
1231
+ this.activate(this.tabs[(i + by + this.tabs.length) % this.tabs.length]);
1232
+ }
1233
+ /**
1234
+ * The tab of a conversation other than an agent's main one is closed: what it was subscribed to
1235
+ * on its own ends, the conversation itself stays in the agent's list. (The main conversation is
1236
+ * the agent; its subscriptions stay.)
1237
+ */
1238
+ async endLocal(tab, say = true) {
1239
+ if (tab.kind !== "chat" || tab.session === "main" || this.tabs.some((t) => t !== tab && t.kind === "chat" && t.agent === tab.agent && t.session === tab.session))
1240
+ return;
1241
+ const ended = (await this.client.closeSession(tab.agent, tab.session).catch(() => ({ unsubscribed: [] }))).unsubscribed;
1242
+ if (ended.length && say)
1243
+ this.flash(`closed ${tab.agent}·${tab.session}: its subscription${ended.length === 1 ? "" : "s"} to ${ended.join(", ")} ended with it`, 6000);
1244
+ }
1245
+ closeTab(tab) {
1246
+ if (this.tabs.length === 1)
1247
+ return this.flash("the last tab stays open; /quit leaves");
1248
+ const i = this.tabs.indexOf(tab);
1249
+ this.tabs.splice(i, 1);
1250
+ void this.endLocal(tab);
1251
+ if (this.active === tab)
1252
+ this.activate(this.tabs[Math.max(0, i - 1)]);
1253
+ else
1254
+ this.tui.requestRender();
1255
+ this.saveTabs();
1256
+ }
1257
+ // ---- the code pane and the folder of a conversation -------------------------------------------
1258
+ /** Open or close the pane beside the conversation, optionally on one of its views. */
1259
+ showCode(open, view) {
1260
+ this.codeOpen = open;
1261
+ if (open)
1262
+ this.code.show(view);
1263
+ // Pictures change between real ones and text with the pane; what was drawn is drawn anew.
1264
+ for (const t of this.tabs)
1265
+ t.doc.invalidate();
1266
+ this.tui.requestRender(true);
1267
+ this.saveTabs();
1268
+ }
1269
+ /** Give a conversation a folder to work in, or with `null` take it back to the agent's own workspace. */
1270
+ async setFolder(tab, folder) {
1271
+ if (tab.kind !== "chat")
1272
+ return;
1273
+ let now;
1274
+ try {
1275
+ now = (await this.client.setFolder(tab.agent, tab.session, folder ? path.resolve(expandHome(folder)) : null)).folder;
1276
+ }
1277
+ catch (e) {
1278
+ return void this.say(tab, c.red(`the folder was not changed: ${errText(e)}`));
1279
+ }
1280
+ for (const t of this.tabs)
1281
+ if (t.kind === "chat" && t.agent === tab.agent && t.session === tab.session)
1282
+ t.folder = now;
1283
+ this.say(tab, now
1284
+ ? `${c.gray("this conversation now works in")} ${c.bold(tilde(now))}${c.gray(`: ${tab.agent}'s tools start there and may read and change what is in it, from your next message on.`)}`
1285
+ : c.gray(`this conversation works in ${tab.agent}'s own workspace again; the folder is closed to it from your next message on.`));
1286
+ this.code.forget({ agent: tab.agent, session: tab.session });
1287
+ this.tui.requestRender();
1288
+ }
1289
+ async pickFolder() {
1290
+ const t = this.active;
1291
+ if (t.kind !== "chat")
1292
+ return;
1293
+ const here = path.resolve(this.opts.cwd ?? process.cwd());
1294
+ const used = await this.client.folders(t.agent).catch(() => []);
1295
+ const items = [{ value: "none", label: "No folder", description: `${t.agent}'s own workspace` }];
1296
+ if (t.folder)
1297
+ items.push({ value: t.folder, label: tilde(t.folder), description: "this conversation's folder" });
1298
+ // A home folder holds pine's own files and is refused anyway, so it is not offered.
1299
+ if (here !== t.folder && here !== os.homedir() && here !== "/")
1300
+ items.push({ value: here, label: tilde(here), description: "where pine was started" });
1301
+ for (const u of used)
1302
+ if (!items.some((i) => i.value === u.folder) && items.length < 9)
1303
+ items.push({ value: u.folder, label: tilde(u.folder), description: `also open in ${u.session}` });
1304
+ items.push({ value: "pick", label: "Pick a folder …", description: "choose one, or type /folder <path>" });
1305
+ const chosen = await this.pick(`Folder for ${t.agent}·${t.session}`, items, t.folder ?? "none");
1306
+ if (!chosen || chosen === (t.folder ?? "none"))
1307
+ return;
1308
+ if (chosen !== "pick")
1309
+ return this.setFolder(t, chosen === "none" ? null : chosen);
1310
+ const picked = await (this.opts.chooseFolder ?? chooseFolder)();
1311
+ // The window of the chooser took the keyboard; the screen is drawn anew when it is back.
1312
+ this.tui.requestRender(true);
1313
+ if (picked)
1314
+ await this.setFolder(t, picked);
1315
+ else if (process.platform !== "darwin" && !this.opts.chooseFolder)
1316
+ this.flash("type /folder <path> to open a folder", 6000);
1317
+ }
1318
+ /**
1319
+ * `pine <folder>`: a tab on the conversation that works in that folder. The one that already
1320
+ * does is opened again; otherwise the main agent gets a new conversation named after the folder.
1321
+ */
1322
+ async openFolder(dir) {
1323
+ const agent = (this.agents.find((a) => a.main) ?? this.agents[0]).id;
1324
+ let full = path.resolve(expandHome(dir));
1325
+ try {
1326
+ full = fs.realpathSync(full);
1327
+ }
1328
+ catch {
1329
+ return void this.say(this.active, c.red(`${dir} is not a folder`));
1330
+ }
1331
+ const used = await this.client.folders(agent).catch(() => []);
1332
+ const have = used.find((u) => u.folder === full);
1333
+ if (have)
1334
+ return this.openTab(agent, have.session);
1335
+ const taken = new Set(["main", ...used.map((u) => u.session), ...(await this.client.sessions(agent).catch(() => [])).map((x) => x.session)]);
1336
+ const base = (path.basename(full).replace(/[^A-Za-z0-9.-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "") || "folder").slice(0, 24);
1337
+ let name = base;
1338
+ for (let n = 2; taken.has(name); n++)
1339
+ name = `${base}-${n}`;
1340
+ try {
1341
+ await this.client.setFolder(agent, name, full);
1342
+ }
1343
+ catch (e) {
1344
+ return void this.say(this.active, c.red(`${tilde(full)} was not opened: ${errText(e)}`));
1345
+ }
1346
+ await this.openTab(agent, name);
1347
+ }
1348
+ // ---- transcript ------------------------------------------------------------------------------
1349
+ add(tab, component, gap = true) {
1350
+ if (gap && tab.doc.children.length)
1351
+ tab.doc.addChild(new Spacer(1));
1352
+ tab.doc.addChild(new Linked(component));
1353
+ if (tab !== this.active)
1354
+ tab.unread = true;
1355
+ this.tui.requestRender();
1356
+ }
1357
+ say(tab, text, gap = true) {
1358
+ const t = new Text(text, 1, 0);
1359
+ this.add(tab, t, gap);
1360
+ return t;
1361
+ }
1362
+ /** A place for what a model thinks. Opening and closing it keeps it in the window. */
1363
+ thought(tab) {
1364
+ const thought = new Thought((t) => {
1365
+ const scroll = tab.scroll;
1366
+ if (t.open) {
1367
+ // It grows downwards from its first line. A window that follows the end would run after
1368
+ // the end and take that line out of sight, so it stays where it is.
1369
+ if (scroll.isFollowingEnd && this.rowOf(tab) - scroll.viewportHeight > this.rowOf(tab, t))
1370
+ scroll.scrollTo(scroll.scrollTop, { disableFollow: true });
1371
+ }
1372
+ else {
1373
+ // Closed from far down in it: the one line that is left must not end up above the window.
1374
+ const top = this.rowOf(tab, t);
1375
+ if (top < scroll.scrollTop)
1376
+ scroll.scrollTo(top);
1377
+ }
1378
+ this.tui.requestRender();
1379
+ });
1380
+ this.add(tab, thought);
1381
+ return thought;
1382
+ }
1383
+ /** The row of the conversation at which a component begins; without one, how many rows there are. */
1384
+ rowOf(tab, inner) {
1385
+ let width = inner?.width;
1386
+ if (width === undefined)
1387
+ for (const child of tab.doc.children)
1388
+ if (child instanceof Linked && child.inner instanceof Thought)
1389
+ width = child.inner.width;
1390
+ let row = 0;
1391
+ for (const child of tab.doc.children) {
1392
+ if (inner && child instanceof Linked && child.inner === inner)
1393
+ return row;
1394
+ row += child.render(width ?? 80).length;
1395
+ }
1396
+ return row;
1397
+ }
1398
+ /** A task's model stopped thinking: what it thought is closed, or stays open if somebody opened it. */
1399
+ endThought(tab, task, ms) {
1400
+ const block = tab.thoughts.get(task);
1401
+ if (!block)
1402
+ return;
1403
+ block.finish(ms);
1404
+ tab.thought = { task, block };
1405
+ tab.thoughts.delete(task);
1406
+ }
1407
+ /** Ask what the commands of the conversation in front left running. Quietly: a daemon that does not answer changes nothing. */
1408
+ async pollPrograms() {
1409
+ const t = this.active;
1410
+ if (this.stopped || !t || t.kind !== "chat")
1411
+ return;
1412
+ const list = await this.client.programs(t.agent, t.session).catch(() => undefined);
1413
+ if (!list)
1414
+ return;
1415
+ const had = t.left?.list.length ?? 0;
1416
+ t.left = { at: Date.now(), list };
1417
+ if (list.length || had)
1418
+ this.tui.requestRender();
1419
+ }
1420
+ /** The agent's list of steps (its `todo` tool), drawn: done, in work, still to do. */
1421
+ stepsText(items) {
1422
+ const done = items.filter((t) => t.status === "done").length;
1423
+ const lines = items.map((t) => (t.status === "done" ? `${c.green("✓")} ${c.gray(t.text)}` : t.status === "in_progress" ? `${c.yellow("◐")} ${c.bold(t.text)}` : `${c.gray("☐")} ${t.text}`));
1424
+ return [c.gray(`steps · ${done} of ${items.length} done`), ...lines].join("\n");
1425
+ }
1426
+ /** Show the list where the conversation is: the same block while one task keeps changing it, a new one for the next task. */
1427
+ showSteps(tab, task, items) {
1428
+ if (!items.length)
1429
+ return void (tab.todo = undefined);
1430
+ if (tab.todo?.task === task)
1431
+ tab.todo.block.setText(this.stepsText(items));
1432
+ else
1433
+ tab.todo = { block: this.say(tab, this.stepsText(items)), task, items };
1434
+ tab.todo.items = items;
1435
+ }
1436
+ /** A line that opens something on a click. */
1437
+ button(tab, text, run, gap = false) {
1438
+ const b = new Button(new Text(text, 1, 0), run);
1439
+ this.add(tab, b, gap);
1440
+ return b;
1441
+ }
1442
+ /**
1443
+ * Reserve a place for a picture and fill it once the picture is fetched and prepared, so it lands
1444
+ * where it belongs however long that takes. Display only: nothing here reaches a model.
1445
+ */
1446
+ picture(tab, name, load, missing, live = true) {
1447
+ const slot = new Slot();
1448
+ // Not through add(): picture lines are not text, and are not searched for web addresses.
1449
+ tab.doc.addChild(slot);
1450
+ // A video that arrives while you are looking starts by itself; one from earlier in the conversation waits for a click.
1451
+ void this.fill(slot, name, load, missing, () => live && this.active === tab);
1452
+ return slot;
1453
+ }
1454
+ async fill(slot, name, load, missing, autoplay = () => true) {
1455
+ try {
1456
+ const got = await load();
1457
+ if (got?.mime.startsWith("video/")) {
1458
+ const video = await this.video(this.keepVideo(got.bytes, got.mime, name), name);
1459
+ slot.inner = video;
1460
+ if (autoplay())
1461
+ video.play();
1462
+ }
1463
+ else if (got?.mime.startsWith("audio/")) {
1464
+ // A sound that arrives while you are looking is played, like a video; one from earlier waits for a click.
1465
+ const sound = new Sound(await prepareSound(this.keepVideo(got.bytes, got.mime, name), name), this.opts.soundPlayer ?? soundPlayer(), () => this.tui.requestRender(), (f) => (this.opts.openFile ?? openInSystem)(f));
1466
+ slot.inner = sound;
1467
+ if (autoplay())
1468
+ sound.play();
1469
+ }
1470
+ else if (got)
1471
+ slot.inner = new Picture(await prepare(got.bytes, got.mime, name));
1472
+ else
1473
+ slot.inner = missing ? new Text(c.gray(missing), 1, 0) : undefined;
1474
+ }
1475
+ catch (e) {
1476
+ slot.inner = new Text(c.gray(`(picture ${name}: ${errText(e)})`), 1, 0);
1477
+ }
1478
+ this.tui.requestRender();
1479
+ }
1480
+ /** A video or sound that came over the API needs to be a file for ffmpeg and for the player. Kept until the UI closes. */
1481
+ keepVideo(bytes, mime, name) {
1482
+ this.mediaDir ??= fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), "pine-media-"));
1483
+ const ext = SOUND_EXT[mime] ?? (mime === "video/webm" ? ".webm" : mime === "video/quicktime" ? ".mov" : ".mp4");
1484
+ const file = path.join(this.mediaDir, `${this.mediaCount++}-${name.replace(/[^A-Za-z0-9._-]+/g, "_").slice(-60) || "video"}${/\.\w{2,5}$/.test(name) ? "" : ext}`);
1485
+ fs.writeFileSync(file, bytes, { mode: 0o600 });
1486
+ return file;
1487
+ }
1488
+ async video(file, name) {
1489
+ return new Video(await prepareVideo(file, name), () => this.tui.requestRender(), (f) => (this.opts.openFile ?? openInSystem)(f));
1490
+ }
1491
+ /**
1492
+ * The pictures an answer points at with ![caption](target). A file in the agent's workspace is
1493
+ * shown at once. A web address is not fetched until it is clicked: an address can carry
1494
+ * information out, and an answer may repeat what a web page told the agent to write.
1495
+ */
1496
+ answerPictures(tab, agent, text, live = true) {
1497
+ for (const ref of picturesIn(text ?? "")) {
1498
+ const name = ref.caption || path.basename(ref.target.split("?")[0]) || "picture";
1499
+ if (!ref.remote) {
1500
+ this.picture(tab, name, () => this.client.workspaceImage(agent, ref.target, tab.kind === "chat" ? tab.session : undefined), `(no ${isAudioFile(ref.target) ? "sound file" : "picture"} at ${ref.target} in the ${tab.folder ? "folder or the " : ""}workspace)`, live);
1501
+ continue;
1502
+ }
1503
+ let slot;
1504
+ const sound = isAudioFile(ref.target.split("?")[0]);
1505
+ this.button(tab, `${c.accent(sound ? "▸ load sound" : "▸ load picture")} ${c.gray(ref.target)}`, () => {
1506
+ if (!slot)
1507
+ return;
1508
+ slot.inner = new Text(c.gray("loading …"), 1, 0);
1509
+ this.tui.requestRender();
1510
+ void this.fill(slot, name, () => this.client.fetchImage(ref.target), sound ? "(that address is not a sound file)" : "(that address is not a picture)");
1511
+ });
1512
+ slot = new Slot();
1513
+ tab.doc.addChild(slot);
1514
+ }
1515
+ }
1516
+ /** An event that woke the agent, shown as what it is and not as something you typed: the source, and the start of what it reported. */
1517
+ eventLine(tab, label, prompt) {
1518
+ const body = prompt.replace(/^\[(?:You are subscribed to|Your owner wrote|Somebody wrote|It is time for your schedule)[\s\S]*?\]\n\n/, "").replace(/^\[event on [^\n]*\]\n/, "").replace(/^Event [^\n]*:\n/, "");
1519
+ // Paths under the user's home are shown the short way, as one would type them.
1520
+ this.say(tab, `${c.yellow("⚡")} ${c.bold(label)}\n${c.gray(` ${short(oneLine(body).replaceAll(os.homedir(), "~"), 300)}`)}`);
1521
+ }
1522
+ user(tab, text, from) {
1523
+ this.add(tab, new Text(`${from ? c.gray(`[${from}] `) : ""}${text}`, 1, 0, c.bgUser));
1524
+ }
1525
+ /** Context and cache figures of a finished task, for the bottom bar. */
1526
+ takeStats(tab, stats) {
1527
+ if (!stats)
1528
+ return;
1529
+ if (stats.context?.percent !== undefined)
1530
+ tab.context = stats.context.percent;
1531
+ const total = stats.input + (stats.cached ?? 0);
1532
+ // Shown once the server has reported cached input at least once; many servers report nothing,
1533
+ // and a permanent "0%" would say something that is not known.
1534
+ if (total > 0 && (stats.cached || tab.cacheShare !== undefined))
1535
+ tab.cacheShare = Math.round((100 * (stats.cached ?? 0)) / total);
1536
+ // The task as a whole, over all its calls. A task that was too short to time leaves the last figures.
1537
+ const speed = speedOf(stats.timing);
1538
+ if (speed.read || speed.write)
1539
+ tab.speed = speed;
1540
+ }
1541
+ /**
1542
+ * /undo and /redo. The daemon does it; here the conversation is shown anew, since the lines on
1543
+ * screen are not its history any more, with what happened said below it. After an undo the
1544
+ * message's text is in the input again, to be changed and sent.
1545
+ */
1546
+ async undo(redo) {
1547
+ const tab = this.active;
1548
+ if (tab.kind !== "chat")
1549
+ return this.flash("switch to a conversation tab first");
1550
+ const r = redo ? await this.client.redo(tab.agent, tab.session) : await this.client.undo(tab.agent, tab.session);
1551
+ tab.doc.clear();
1552
+ for (const live of [tab.roots, tab.running, tab.blocks, tab.thoughts, tab.tools, tab.streamed, tab.children])
1553
+ live.clear();
1554
+ tab.awaiting = [];
1555
+ tab.thinking = false;
1556
+ const history = (await this.client.history(tab.agent, tab.session).catch(() => [])).filter((t) => t.depth === 0).reverse();
1557
+ if (history.length)
1558
+ this.say(tab, c.gray(`── earlier in this session (${history.length}) ──`));
1559
+ for (const t of history)
1560
+ this.renderPast(tab, t);
1561
+ this.say(tab, redo ? redoText(r) : undoText(r));
1562
+ if (!redo && tab === this.active)
1563
+ this.editor.setText(r.prompt);
1564
+ tab.scroll.scrollToEnd();
1565
+ if (this.codeOpen && tab === this.active)
1566
+ this.code.touch();
1567
+ void this.refreshTaints();
1568
+ this.tui.requestRender();
1569
+ }
1570
+ renderPast(tab, t) {
1571
+ if (t.meta?.compact)
1572
+ return void this.say(tab, c.gray(`⟲ ${t.status === "done" ? t.result : `shortening the conversation: ${t.status}${t.error ? ` (${t.error})` : ""}`}`));
1573
+ if (t.kind === "event" && t.meta?.label)
1574
+ this.eventLine(tab, t.meta.label, t.prompt);
1575
+ else if (isGoalRound(t.kind, t.meta?.label))
1576
+ this.say(tab, c.gray(`↻ ${t.meta.label}`));
1577
+ else
1578
+ this.user(tab, t.prompt, t.kind === "prompt" ? undefined : t.kind);
1579
+ (t.meta?.images ?? []).forEach((_, i) => this.picture(tab, `attached picture ${i + 1}`, () => this.client.taskImage(t.id, i)));
1580
+ // It was read by work that was already running; the answer is that work's.
1581
+ if (t.meta?.steered !== undefined)
1582
+ return;
1583
+ if (t.status === "done") {
1584
+ if (t.result)
1585
+ tab.lastAnswer = t.result;
1586
+ this.add(tab, new Answer(t.result || "(no answer)"));
1587
+ this.answerPictures(tab, t.agent, t.result, false);
1588
+ }
1589
+ else if (t.status === "failed" || t.status === "cancelled")
1590
+ this.say(tab, c.red(`✗ ${t.status}${t.error ? `: ${t.error}` : ""}`));
1591
+ else
1592
+ this.say(tab, c.gray(`… ${t.status}`));
1593
+ }
1594
+ flash(text, ms = 4000) {
1595
+ this.notice = text;
1596
+ clearTimeout(this.noticeTimer);
1597
+ this.noticeTimer = setTimeout(() => {
1598
+ this.notice = "";
1599
+ this.tui.requestRender();
1600
+ }, ms);
1601
+ this.noticeTimer.unref?.();
1602
+ this.tui.requestRender();
1603
+ }
1604
+ // ---- input -----------------------------------------------------------------------------------
1605
+ /** Whether this system has voice input. Where it has none, nothing offers it. */
1606
+ canListen() {
1607
+ return (this.opts.voice ?? (this.voiceTools ??= voiceTools())).unavailable === undefined;
1608
+ }
1609
+ /**
1610
+ * Dictate the message, or end dictating. What is heard is put into the input, after what was
1611
+ * typed there, as it is heard. It is text like typed text: the owner reads it, changes it, and
1612
+ * sends it with enter. Nothing that was heard is ever sent by itself.
1613
+ */
1614
+ async dictate(language) {
1615
+ if (this.voice) {
1616
+ if (this.voice.state === "listening") {
1617
+ this.voice.state = "finishing";
1618
+ this.voice.listening?.stop();
1619
+ this.tui.requestRender();
1620
+ }
1621
+ else if (this.voice.state === "starting") {
1622
+ // Not listening yet, and asked to end: there is nothing to wait for. Without this a
1623
+ // helper that never gets ready would take every enter from then on.
1624
+ this.endDictating();
1625
+ }
1626
+ return;
1627
+ }
1628
+ const tools = this.opts.voice ?? (this.voiceTools ??= voiceTools());
1629
+ // Not on this system: said in a sentence, and nothing is started.
1630
+ if (tools.unavailable)
1631
+ return this.flash(tools.unavailable, 9000);
1632
+ if (language)
1633
+ this.voiceLanguage = language;
1634
+ const before = this.editor.getText();
1635
+ const lead = before && !/\s$/.test(before) ? `${before} ` : before;
1636
+ const mine = { before, state: "starting" };
1637
+ this.voice = mine;
1638
+ this.tui.requestRender();
1639
+ let command;
1640
+ try {
1641
+ command = await tools.program();
1642
+ }
1643
+ catch (e) {
1644
+ if (this.voice === mine)
1645
+ this.voice = undefined;
1646
+ return this.flash(errText(e), 15_000);
1647
+ }
1648
+ // Given up (esc) while the helper was being built.
1649
+ if (this.voice !== mine)
1650
+ return;
1651
+ // A helper that never says it listens (the system waits for an answer about the microphone,
1652
+ // say) must not hold the input for good.
1653
+ const patience = setTimeout(() => {
1654
+ if (this.voice !== mine || mine.state !== "starting")
1655
+ return;
1656
+ if (mine.fetching)
1657
+ return void patience.refresh();
1658
+ this.endDictating();
1659
+ this.flash("voice input did not start. If the system asked whether this terminal may use the microphone or speech recognition, answer that and try again (System Settings › Privacy & Security)", 15_000);
1660
+ }, 20_000);
1661
+ patience.unref?.();
1662
+ mine.listening = new Listening(command, this.voiceLanguage, {
1663
+ ready: () => {
1664
+ if (mine.state === "starting")
1665
+ mine.state = "listening";
1666
+ mine.fetching = false;
1667
+ this.tui.requestRender();
1668
+ },
1669
+ model: (state) => {
1670
+ mine.fetching = state === "downloading";
1671
+ this.tui.requestRender();
1672
+ },
1673
+ partial: (text) => {
1674
+ if (this.voice !== mine)
1675
+ return;
1676
+ this.editor.setText(lead + text);
1677
+ this.tui.requestRender();
1678
+ },
1679
+ done: (text, error) => {
1680
+ if (this.voice !== mine)
1681
+ return;
1682
+ this.voice = undefined;
1683
+ this.editor.setText(text ? lead + text : before);
1684
+ if (error)
1685
+ this.flash(error, 15_000);
1686
+ this.tui.requestRender();
1687
+ },
1688
+ });
1689
+ }
1690
+ /** End dictating where it stands: what is in the input stays, nothing more is put into it. */
1691
+ endDictating() {
1692
+ const v = this.voice;
1693
+ if (!v)
1694
+ return;
1695
+ this.voice = undefined;
1696
+ v.listening?.cancel();
1697
+ this.tui.requestRender();
1698
+ }
1699
+ /** Keys the app handles before the editor sees them. Returns true when the key is used up. */
1700
+ onKey(data) {
1701
+ if (this.dialog)
1702
+ return false;
1703
+ // While dictating: enter says "that was all" and leaves the text to be read, esc throws it away. Neither sends.
1704
+ if (this.voice && !isKeyRelease(data)) {
1705
+ if (matchesKey(data, "escape")) {
1706
+ const v = this.voice;
1707
+ this.voice = undefined;
1708
+ v.listening?.cancel();
1709
+ this.editor.setText(v.before);
1710
+ this.tui.requestRender();
1711
+ return true;
1712
+ }
1713
+ if (matchesKey(data, "enter") || matchesKey(data, "ctrl+r"))
1714
+ return void this.dictate(), true;
1715
+ // A key that types: the owner has gone on by hand. What is heard would overwrite it with
1716
+ // every word, and the input would seem frozen. Dictating ends, and the key is typed.
1717
+ if ((data.length === 1 && data >= " ") || matchesKey(data, "backspace") || data.startsWith("\x1b[200~"))
1718
+ this.endDictating();
1719
+ }
1720
+ if (matchesKey(data, "ctrl+r") && this.active.kind === "chat" && !isKeyRelease(data))
1721
+ return void this.dictate(), true;
1722
+ // Terminals that report key releases send one for the key that just closed a menu, and repeats
1723
+ // while it is held. Neither is a new key press: esc that closes a menu must not also stop the task.
1724
+ if (isKeyRelease(data))
1725
+ return false;
1726
+ if (matchesKey(data, "escape") && (isKeyRepeat(data) || Date.now() - this.dialogClosedAt < 250))
1727
+ return true;
1728
+ // Files dropped on the terminal arrive as pasted paths. Take them as attachments.
1729
+ const paste = data.match(/\x1b\[200~([\s\S]*?)\x1b\[201~/);
1730
+ if (paste && this.active.kind === "chat") {
1731
+ // One folder dropped on the terminal: that is the folder this conversation is to work in.
1732
+ const folder = droppedFiles(paste[1], true);
1733
+ if (folder?.length === 1)
1734
+ return void this.setFolder(this.active, folder[0]), true;
1735
+ const files = droppedFiles(paste[1]);
1736
+ if (files)
1737
+ return files.forEach((f) => this.attachFile(f)), true;
1738
+ }
1739
+ const empty = this.editor.getText().length === 0;
1740
+ // A question that was put off ("Later") is still waiting, and counts as a no when its time
1741
+ // is up: enter on an empty line opens it again.
1742
+ if (matchesKey(data, "enter") && empty && !isKeyRepeat(data)) {
1743
+ const waiting = [...this.active.approvals.values()][0];
1744
+ if (waiting)
1745
+ return void this.ask(this.active, waiting.req), true;
1746
+ }
1747
+ // A terminal pastes text only. Where it passes ctrl+v on, a picture on the clipboard is attached; text is pasted as ever.
1748
+ if (matchesKey(data, "ctrl+v") && this.active.kind === "chat")
1749
+ void this.clipboardImage().then((file) => file && this.attachFile(file));
1750
+ // Enter gives a message to the work that is running; alt+enter makes it wait until that work is done.
1751
+ if (matchesKey(data, "alt+enter") && !empty && !this.editor.isShowingAutocomplete())
1752
+ return void this.submit(this.editor.getText(), "queue"), true;
1753
+ if (matchesKey(data, "ctrl+c")) {
1754
+ if (!empty) {
1755
+ this.editor.setText("");
1756
+ this.tui.requestRender();
1757
+ return true;
1758
+ }
1759
+ if (Date.now() - this.lastCtrlC < 1500)
1760
+ return void this.stop(), true;
1761
+ this.lastCtrlC = Date.now();
1762
+ this.flash("press ctrl+c again to quit", 1500);
1763
+ return true;
1764
+ }
1765
+ if (matchesKey(data, "ctrl+d") && empty)
1766
+ return void this.stop(), true;
1767
+ if (this.editor.isShowingAutocomplete()) {
1768
+ // A command typed in full and without arguments runs on enter, even if the suggestion list
1769
+ // has not caught up with fast typing. With arguments, enter belongs to the list: it picks
1770
+ // the highlighted suggestion.
1771
+ const text = this.editor.getText();
1772
+ if (matchesKey(data, "enter") && /^\/\S+$/.test(text) && this.commands.some((x) => x.name === text.slice(1)))
1773
+ return void this.submit(text), true;
1774
+ // Picking an argument (a model, an agent, a session) also runs the command: one enter, not two.
1775
+ if (matchesKey(data, "enter") && /^\/\S+\s/.test(text)) {
1776
+ setImmediate(() => {
1777
+ const picked = this.editor.getText();
1778
+ // If the editor already sent the line, it is empty by now and nothing happens here.
1779
+ if (!this.editor.isShowingAutocomplete() && picked.startsWith("/"))
1780
+ void this.submit(picked);
1781
+ });
1782
+ }
1783
+ return false;
1784
+ }
1785
+ if (matchesKey(data, "escape") && this.active.running.size)
1786
+ return void this.stopRunning(this.active), true;
1787
+ // Between two rounds of a goal nothing runs, but the next round is about to start: esc holds it back.
1788
+ if (matchesKey(data, "escape") && this.active.goal?.status === "active")
1789
+ return void this.goal("pause").catch((e) => this.flash(errText(e))), true;
1790
+ if (matchesKey(data, "tab") && empty)
1791
+ return this.cycle(1), true;
1792
+ // As in Claude Code and opencode: shift+tab steps through the modes.
1793
+ if (matchesKey(data, "shift+tab") && empty && this.active.kind === "chat") {
1794
+ const info = this.agents.find((a) => a.id === this.active.agent);
1795
+ const order = ["auto", "plan", "safe", "manual", "bypass"];
1796
+ return void this.setMode(this.active, order[(order.indexOf(info?.mode ?? "auto") + 1) % order.length]).catch((e) => this.flash(errText(e))), true;
1797
+ }
1798
+ if (matchesKey(data, "ctrl+t"))
1799
+ return void this.run("new"), true;
1800
+ if (matchesKey(data, "ctrl+g"))
1801
+ return this.showCode(!this.codeOpen), true;
1802
+ if (matchesKey(data, "ctrl+w"))
1803
+ return this.closeTab(this.active), true;
1804
+ for (let n = 1; n <= 9; n++) {
1805
+ if (matchesKey(data, `alt+${n}`) && this.tabs[n - 1])
1806
+ return this.activate(this.tabs[n - 1]), true;
1807
+ }
1808
+ if (matchesKey(data, "pageUp"))
1809
+ return void this.active.scroll.scrollBy(-Math.max(1, this.active.scroll.viewportHeight - 2)), this.tui.requestRender(), true;
1810
+ if (matchesKey(data, "pageDown"))
1811
+ return void this.active.scroll.scrollBy(Math.max(1, this.active.scroll.viewportHeight - 2)), this.tui.requestRender(), true;
1812
+ return false;
1813
+ }
1814
+ /** A click on a web address. Only the web: nothing an answer contains may launch a program or open a file. */
1815
+ open(url) {
1816
+ if (!/^https?:\/\//i.test(url))
1817
+ return;
1818
+ (this.opts.openUrl ?? openInSystem)(url);
1819
+ this.flash(`opened ${short(url, 90)}`, 2500);
1820
+ }
1821
+ /**
1822
+ * Send what was typed. While the agent works, a message goes into that work at its next step
1823
+ * ("steer"), so a correction lands without stopping anything; "queue" keeps it for afterwards.
1824
+ */
1825
+ async submit(raw, whenBusy = "steer") {
1826
+ const text = raw.trim();
1827
+ if (!text)
1828
+ return;
1829
+ this.editor.addToHistory(text);
1830
+ this.editor.setText("");
1831
+ if (text.startsWith("/"))
1832
+ return this.run(text.slice(1));
1833
+ const tab = this.active;
1834
+ if (tab.kind !== "chat")
1835
+ return this.flash(tab.kind === "task" ? "this tab shows one task's work and takes no messages; write in the conversation tab" : "this tab only shows events; switch to a conversation tab to write");
1836
+ const files = tab.attachments.splice(0);
1837
+ this.user(tab, files.length ? `${text}\n${c.gray(`attached: ${files.map((f) => f.name).join(", ")}`)}` : text);
1838
+ for (const f of files.filter((x) => isImageFile(x.name)))
1839
+ this.picture(tab, f.name, async () => ({ mime: mimeOf(f.name), bytes: await fs.promises.readFile(f.path) }));
1840
+ for (const f of files.filter((x) => isVideoFile(x.name))) {
1841
+ // Played from where it lies; nothing is copied.
1842
+ const slot = new Slot();
1843
+ tab.doc.addChild(slot);
1844
+ void this.video(f.path, f.name).then((v) => ((slot.inner = v), this.active === tab && v.play(), this.tui.requestRender())).catch(() => { });
1845
+ }
1846
+ tab.awaiting.push(text);
1847
+ tab.scroll.scrollToEnd();
1848
+ try {
1849
+ const attachments = files.map((f) => ({ name: f.name, data: fs.readFileSync(f.path).toString("base64") }));
1850
+ const busy = tab.running.size > 0;
1851
+ // Only what the list offered counts as a file: "@somebody" in a sentence is not one.
1852
+ const mentions = mentionsIn(text).filter((m) => tab.files.has(m.split("#")[0]));
1853
+ const { task, steered } = await this.client.prompt(tab.agent, text, tab.session, attachments.length ? attachments : undefined, whenBusy, mentions.length ? mentions : undefined);
1854
+ this.adopt(tab, task);
1855
+ if (steered !== undefined) {
1856
+ tab.awaiting = tab.awaiting.filter((p) => p !== text);
1857
+ this.flash("given to the agent while it works (alt+enter makes a message wait its turn instead)", 2500);
1858
+ }
1859
+ else if (busy)
1860
+ this.flash("waits its turn: it is answered when the work that is running is done", 2500);
1861
+ }
1862
+ catch (e) {
1863
+ tab.awaiting = tab.awaiting.filter((p) => p !== text);
1864
+ tab.attachments.unshift(...files);
1865
+ this.say(tab, c.red(`✗ not sent: ${errText(e)}`));
1866
+ }
1867
+ }
1868
+ attachFile(file) {
1869
+ const tab = this.active;
1870
+ if (tab.kind !== "chat")
1871
+ return this.flash("switch to a conversation tab to attach files");
1872
+ try {
1873
+ const full = path.resolve(expandHome(file));
1874
+ const stat = fs.statSync(full);
1875
+ if (!stat.isFile())
1876
+ return this.flash(`${file} is not a file`);
1877
+ if (stat.size > MAX_ATTACHMENT)
1878
+ return this.flash(`${path.basename(full)} is larger than 20 MB`);
1879
+ if (tab.attachments.length >= 10)
1880
+ return this.flash("at most 10 files per message");
1881
+ if (!tab.attachments.some((a) => a.path === full))
1882
+ tab.attachments.push({ path: full, name: path.basename(full), size: stat.size });
1883
+ this.tui.requestRender();
1884
+ }
1885
+ catch {
1886
+ this.flash(`cannot read ${file}`);
1887
+ }
1888
+ }
1889
+ /** Open a list over the conversation and resolve with what was chosen. */
1890
+ pick(title, items, current) {
1891
+ if (this.dialog)
1892
+ return Promise.resolve(undefined);
1893
+ return new Promise((resolve) => {
1894
+ const picker = new Picker(title, items, (value) => {
1895
+ this.closeDialog();
1896
+ resolve(value);
1897
+ }, current);
1898
+ const handle = this.tui.showOverlay(picker, { anchor: "center", width: "64%", minWidth: 44, maxHeight: "80%" });
1899
+ handle.focus();
1900
+ this.dialog = { id: `pick:${title}`, handle, dismiss: () => (this.closeDialog(), resolve(undefined)) };
1901
+ this.tui.requestRender();
1902
+ });
1903
+ }
1904
+ async pickAgent() {
1905
+ // Below the agents: what this conversation has started, so a sub-agent can be found and looked at.
1906
+ const helpers = [...this.active.children].reverse().slice(0, 8).map(([id, x]) => ({ value: `task:${id}`, label: `↳ #${id} ${childKind(x.kind)}`, description: `${x.running ? "running" : "finished"} · ${x.agent} · ${x.label}` }));
1907
+ // Asked anew each time: the main agent can create agents while pine runs.
1908
+ this.agents = await this.client.agents().catch(() => this.agents);
1909
+ const id = await this.pick("Agent", [...this.agents.map((a) => ({ value: a.id, label: a.id, description: a.description || a.model })), ...helpers], this.active.agent);
1910
+ if (id?.startsWith("task:"))
1911
+ await this.openTask(Number(id.slice(5)));
1912
+ else if (id)
1913
+ await this.openTab(id, "main");
1914
+ }
1915
+ /** What a tab shows after its conversation was reset: nothing of what was said. */
1916
+ freshen(t) {
1917
+ t.doc.clear();
1918
+ t.roots.clear();
1919
+ t.context = undefined;
1920
+ t.cacheShare = undefined;
1921
+ this.taints.delete(`${t.agent}:${t.session}`);
1922
+ this.say(t, c.gray("fresh conversation"));
1923
+ }
1924
+ async pickSession() {
1925
+ const t = this.active;
1926
+ if (t.kind !== "chat")
1927
+ return;
1928
+ if (this.dialog)
1929
+ return;
1930
+ const agent = t.agent;
1931
+ const isOpen = (session) => this.tabs.some((x) => x.kind === "chat" && x.agent === agent && x.session === session);
1932
+ const list = (await this.client.sessions(agent).catch(() => [])).map((s) => ({ ...s, open: isOpen(s.session) }));
1933
+ const close = () => this.closeDialog();
1934
+ const view = new ConversationList(`Conversations of ${agent}`, list, t.session, {
1935
+ open: (session) => (close(), void this.openTab(agent, session)),
1936
+ fresh: () => (close(), void this.run("new")),
1937
+ pin: async (conv) => {
1938
+ try {
1939
+ const pinned = (await this.client.pinSession(agent, conv.session, !conv.pinned)).pinned;
1940
+ if (pinned)
1941
+ this.pins.add(`${agent}:${conv.session}`);
1942
+ else
1943
+ this.pins.delete(`${agent}:${conv.session}`);
1944
+ return pinned;
1945
+ }
1946
+ catch (e) {
1947
+ this.flash(errText(e));
1948
+ return conv.pinned;
1949
+ }
1950
+ },
1951
+ remove: async (conv) => {
1952
+ let gone;
1953
+ try {
1954
+ gone = await this.client.removeSession(agent, conv.session);
1955
+ }
1956
+ catch (e) {
1957
+ this.flash(errText(e), 6000);
1958
+ return false;
1959
+ }
1960
+ // A tab that showed it has nothing left to show.
1961
+ const showing = this.tabs.filter((x) => x.kind === "chat" && x.agent === agent && x.session === conv.session);
1962
+ for (const tab of showing)
1963
+ this.tabs.splice(this.tabs.indexOf(tab), 1);
1964
+ if (showing.includes(this.active)) {
1965
+ close();
1966
+ if (this.tabs.length)
1967
+ this.activate(this.tabs[0]);
1968
+ else
1969
+ await this.openTab(agent, "main");
1970
+ }
1971
+ this.saveTabs();
1972
+ // What was set up for it alone went with it; say so, since it is gone for good.
1973
+ const with_ = [...(gone.sources.length ? [`its event source${gone.sources.length === 1 ? "" : "s"} ${gone.sources.join(", ")}`] : gone.unsubscribed.length ? [`its subscription${gone.unsubscribed.length === 1 ? "" : "s"} to ${gone.unsubscribed.join(", ")}`] : []), ...(gone.servers.length ? [`its MCP server${gone.servers.length === 1 ? "" : "s"} ${gone.servers.join(", ")}`] : [])];
1974
+ this.flash(`removed the conversation ${conv.session} of ${agent}${with_.length ? `, with ${with_.join(" and ")}` : ""}`, with_.length ? 7000 : 4000);
1975
+ return true;
1976
+ },
1977
+ reset: async (conv) => {
1978
+ try {
1979
+ await this.client.reset(agent, conv.session);
1980
+ }
1981
+ catch (e) {
1982
+ this.flash(errText(e), 6000);
1983
+ return false;
1984
+ }
1985
+ for (const tab of this.tabs)
1986
+ if (tab.kind === "chat" && tab.agent === agent && tab.session === conv.session)
1987
+ this.freshen(tab);
1988
+ this.flash(`the ${conv.session} conversation of ${agent} starts fresh`);
1989
+ return true;
1990
+ },
1991
+ close,
1992
+ redraw: () => this.tui.requestRender(),
1993
+ });
1994
+ const handle = this.tui.showOverlay(view, { anchor: "center", width: "72%", minWidth: 50, maxHeight: "80%" });
1995
+ handle.focus();
1996
+ this.dialog = { id: "conversations", handle, dismiss: close };
1997
+ this.tui.requestRender();
1998
+ }
1999
+ async pickModel() {
2000
+ const t = this.active;
2001
+ if (t.kind !== "chat")
2002
+ return;
2003
+ const info = this.agents.find((a) => a.id === t.agent);
2004
+ const models = await this.client.models();
2005
+ const model = await this.pick(`Model for ${t.agent}`, models.map((m) => ({ value: m, label: m })), info.model);
2006
+ if (model)
2007
+ await this.run(`model ${model}`);
2008
+ }
2009
+ async pickReasoning() {
2010
+ const t = this.active;
2011
+ if (t.kind !== "chat")
2012
+ return;
2013
+ const info = this.agents.find((a) => a.id === t.agent);
2014
+ const level = await this.pick(`Reasoning for ${t.agent}`, REASONING_ITEMS, info.thinking);
2015
+ if (level)
2016
+ await this.run(`reasoning ${level}`);
2017
+ }
2018
+ async pickMode() {
2019
+ const t = this.active;
2020
+ if (t.kind !== "chat")
2021
+ return;
2022
+ const info = this.agents.find((a) => a.id === t.agent);
2023
+ const mode = await this.pick(`Mode for ${t.agent}`, MODE_ITEMS, info.mode);
2024
+ if (mode)
2025
+ await this.setMode(t, mode);
2026
+ }
2027
+ isTainted(t) {
2028
+ return this.taints.has(`${t.agent}:${t.session}`);
2029
+ }
2030
+ async setMode(t, mode) {
2031
+ const info = this.agents.find((a) => a.id === t.agent);
2032
+ if (!MODE_ITEMS.some((m) => m.value === mode))
2033
+ return this.flash("modes: auto, plan, manual, bypass");
2034
+ let anyway;
2035
+ await this.refreshTaints();
2036
+ if (mode === "bypass" && this.isTainted(t) && !this.bypassWhenTainted) {
2037
+ // Bypass normally stops applying once a conversation has read outside content. Make that a choice, not a surprise.
2038
+ const choice = await this.pick("This conversation has read outside content", [
2039
+ { value: "new", label: "Bypass in a new, clean conversation", description: "recommended" },
2040
+ { value: "anyway", label: "Bypass here anyway", description: "what it read could steer an agent with your whole account" },
2041
+ { value: "cancel", label: "Cancel" },
2042
+ ]);
2043
+ if (!choice || choice === "cancel")
2044
+ return;
2045
+ if (choice === "anyway")
2046
+ anyway = t.session;
2047
+ else {
2048
+ await this.client.setMode(t.agent, mode);
2049
+ info.mode = "bypass";
2050
+ await this.openTab(t.agent, `s${Date.now().toString(36)}`);
2051
+ return void this.say(this.active, `${c.gray(`${t.agent} is in`)} ${c.bold("bypass")} ${c.gray("mode in this new conversation.")}${c.yellow(" Nothing waits for approval, and its shell and file tools reach your whole account and the network.")}`);
2052
+ }
2053
+ }
2054
+ await this.client.setMode(t.agent, mode, anyway);
2055
+ info.mode = mode;
2056
+ t.pauseNoted = false;
2057
+ const note = mode === "bypass" ? c.yellow(" Nothing waits for approval now, and its shell and file tools reach your whole account and the network.") : mode === "plan" ? c.gray(" It looks, reads and asks, and changes nothing: ask for what you want, read its plan, then switch the mode back to have it carried out.") : mode === "auto" ? c.gray(" Its shell and file tools work without a sandbox: your whole account and the network. What is critical is still checked.") : mode === "safe" ? c.gray(" Its shell and file tools work inside its sandbox: its own folders, and what you allow it.") : "";
2058
+ this.say(t, `${c.gray(`${t.agent} is now in`)} ${c.bold(mode)} ${c.gray(mode === "bypass" || mode === "plan" ? "mode (until pine restarts)." : "mode. It is saved, and holds after a restart too.")}${note}`);
2059
+ await this.refreshTaints();
2060
+ }
2061
+ adopt(tab, task) {
2062
+ if (tab.roots.has(task))
2063
+ return;
2064
+ tab.roots.add(task);
2065
+ }
2066
+ /**
2067
+ * Call for the owner's attention while they are looking at something else: the terminal's bell
2068
+ * and a notification through the terminal (OSC 9, which Ghostty, iTerm and others show as a
2069
+ * system notification). The text is pine's own; nothing an agent or a page wrote goes into it.
2070
+ */
2071
+ attention(text) {
2072
+ if (!this.notify || this.focused || this.stopped)
2073
+ return;
2074
+ this.opts.terminal.write(`\x07\x1b]9;${text.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 120)}\x1b\\`);
2075
+ }
2076
+ /**
2077
+ * The picture on the clipboard (a screenshot, say), saved as a file to attach. A terminal pastes
2078
+ * text only, so the clipboard is asked directly, on the machine the UI runs on.
2079
+ */
2080
+ clipboardImage() {
2081
+ if (this.opts.clipboardImage)
2082
+ return this.opts.clipboardImage();
2083
+ const file = path.join(os.tmpdir(), `pine-paste-${Date.now().toString(36)}.png`);
2084
+ const kept = () => {
2085
+ try {
2086
+ return fs.statSync(file).size > 0 ? file : (fs.rmSync(file, { force: true }), undefined);
2087
+ }
2088
+ catch {
2089
+ return undefined;
2090
+ }
2091
+ };
2092
+ return new Promise((resolve) => {
2093
+ if (process.platform === "darwin") {
2094
+ // The path is pine's own, made above; nothing typed or received goes into the script.
2095
+ const script = ["set png to (the clipboard as «class PNGf»)", `set f to open for access POSIX file "${file}" with write permission`, "write png to f", "close access f"];
2096
+ const child = spawn("/usr/bin/osascript", script.flatMap((line) => ["-e", line]), { stdio: "ignore" });
2097
+ child.on("error", () => resolve(undefined));
2098
+ child.on("close", () => resolve(kept()));
2099
+ return;
2100
+ }
2101
+ const [cmd, ...args] = process.env.WAYLAND_DISPLAY ? ["wl-paste", "-t", "image/png"] : ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"];
2102
+ const child = spawn(cmd, args, { stdio: ["ignore", fs.openSync(file, "w"), "ignore"] });
2103
+ child.on("error", () => resolve(kept()));
2104
+ child.on("close", () => resolve(kept()));
2105
+ });
2106
+ }
2107
+ copyText(text) {
2108
+ if (this.opts.copy)
2109
+ return this.opts.copy(text);
2110
+ return new Promise((resolve) => {
2111
+ const [copy, ...args] = process.platform === "darwin" ? ["pbcopy"] : process.env.WAYLAND_DISPLAY ? ["wl-copy"] : ["xclip", "-selection", "clipboard"];
2112
+ const child = spawn(copy, args, { stdio: ["pipe", "ignore", "ignore"] });
2113
+ child.on("error", (e) => resolve(e.message));
2114
+ child.on("close", (code) => resolve(code === 0 ? true : `copy failed (${code})`));
2115
+ child.stdin.end(text);
2116
+ });
2117
+ }
2118
+ /**
2119
+ * The conversation as Markdown: what was said, in order. With `full`, also what the agent thought
2120
+ * and which tools it called, read from each task's record.
2121
+ */
2122
+ async markdownOf(tab, full) {
2123
+ const tasks = (await this.client.history(tab.agent, tab.session, 500)).filter((t) => t.depth === 0).reverse();
2124
+ const out = [`# ${tab.agent} · ${tab.session}`, "", `Exported from pine on ${new Date().toLocaleString("sv-SE")}.`];
2125
+ for (const t of tasks) {
2126
+ if (t.meta?.compact) {
2127
+ out.push("", "---", "", `*${t.result || "The earlier part of the conversation was summarised here."}*`);
2128
+ continue;
2129
+ }
2130
+ out.push("", t.kind === "prompt" ? (t.meta?.steered !== undefined ? "## You, while the agent worked" : "## You") : `## ${t.kind === "event" ? `Event${t.meta?.label ? `: ${t.meta.label}` : ""}` : `pine (${t.kind})`}`, "", t.prompt.trim());
2131
+ if (t.meta?.steered !== undefined)
2132
+ continue;
2133
+ if (full) {
2134
+ const steps = (await this.client.transcript(t.id).catch(() => undefined))?.entries ?? [];
2135
+ for (const e of steps) {
2136
+ if (e.kind === "thinking" && e.text?.trim())
2137
+ out.push("", "<details><summary>Thinking</summary>", "", e.text.trim(), "", "</details>");
2138
+ else if (e.kind === "tool")
2139
+ out.push("", `- ${e.ok === false ? "✗" : "✓"} \`${e.tool}\`${e.subject ? ` ${oneLine(e.subject)}` : ""}${e.ok === false && e.result ? `: ${short(oneLine(e.result), 300)}` : ""}`);
2140
+ }
2141
+ }
2142
+ out.push("", `## ${t.agent}`, "", t.status === "done" ? t.result?.trim() || "(no answer)" : `*${t.status}${t.error && t.error !== t.status ? `: ${t.error}` : ""}*`);
2143
+ }
2144
+ return `${out.join("\n")}\n`;
2145
+ }
2146
+ /**
2147
+ * esc stops what is running. A message typed while the agent worked starts the moment that
2148
+ * work stops, and the status line says "working" again: a second esc, pressed because nothing
2149
+ * seemed to happen, would stop that message too. So for a few seconds after a stop, esc leaves
2150
+ * alone a message that was waiting when it was pressed.
2151
+ */
2152
+ async stopRunning(tab) {
2153
+ const recent = tab.stopped && Date.now() - tab.stopped.at < STOP_GRACE ? tab.stopped : undefined;
2154
+ const ids = [...tab.running].filter((id) => !recent?.spared.has(id));
2155
+ if (!ids.length)
2156
+ return this.flash("stopped. This is your next message being answered; esc again in a moment stops it too", 4000);
2157
+ tab.stopped = { at: Date.now(), waiting: tab.awaiting.length, spared: recent?.spared ?? new Set() };
2158
+ for (const id of ids)
2159
+ await this.client.cancel(id).catch(() => { });
2160
+ this.flash("stopping…", 1500);
2161
+ }
2162
+ // ---- commands --------------------------------------------------------------------------------
2163
+ defineCommands() {
2164
+ const agentIds = (prefix) => this.agents.filter((a) => a.id.startsWith(prefix)).map((a) => ({ value: a.id, label: a.id, description: a.description }));
2165
+ const chat = () => (this.active.kind === "chat" ? this.active : (this.flash("switch to a conversation tab first"), undefined));
2166
+ this.commands = [
2167
+ { name: "help", description: "Commands and keys", run: () => this.help() },
2168
+ {
2169
+ name: "new", description: "New conversation with this agent in a new tab", argumentHint: "[name]",
2170
+ run: (args) => this.openTab(this.active.kind === "chat" ? this.active.agent : this.agents[0].id, args.trim() || `s${Date.now().toString(36)}`),
2171
+ },
2172
+ {
2173
+ name: "agent", description: "Open a tab with another agent", argumentHint: "<id> [session]", getArgumentCompletions: agentIds,
2174
+ run: (args) => {
2175
+ const [id, session] = args.trim().split(/\s+/);
2176
+ if (!id)
2177
+ return this.pickAgent();
2178
+ if (!this.agents.some((a) => a.id === id))
2179
+ return this.flash(`no agent "${id}"`);
2180
+ return this.openTab(id, session || "main");
2181
+ },
2182
+ },
2183
+ {
2184
+ name: "sessions", description: "List this agent's conversations, or open one", argumentHint: "[name]",
2185
+ getArgumentCompletions: async (prefix) => {
2186
+ const t = this.active;
2187
+ if (t.kind !== "chat")
2188
+ return null;
2189
+ return (await this.client.sessions(t.agent).catch(() => [])).filter((s) => s.session.startsWith(prefix)).map((s) => ({ value: s.session, label: s.session, description: `${s.tasks} messages` }));
2190
+ },
2191
+ run: async (args) => {
2192
+ const t = chat();
2193
+ if (!t)
2194
+ return;
2195
+ if (args.trim())
2196
+ return this.openTab(t.agent, args.trim());
2197
+ return this.pickSession();
2198
+ },
2199
+ },
2200
+ { name: "tab", description: "Go to tab number", argumentHint: "<n>", run: (args) => (this.tabs[Number(args) - 1] ? this.activate(this.tabs[Number(args) - 1]) : this.flash("no such tab")) },
2201
+ { name: "close", description: "Close this tab (the conversation stays in the list)", run: () => this.closeTab(this.active) },
2202
+ {
2203
+ name: "rename", description: "Give this conversation, and its tab, another name", argumentHint: "<name>",
2204
+ run: async (args) => {
2205
+ const t = chat();
2206
+ if (!t)
2207
+ return;
2208
+ if (!args.trim())
2209
+ return this.flash("usage: /rename <name>");
2210
+ const was = t.session;
2211
+ const now = (await this.client.renameSession(t.agent, was, args.trim())).session;
2212
+ for (const tab of this.tabs)
2213
+ if (tab.kind === "chat" && tab.agent === t.agent && tab.session === was)
2214
+ tab.session = now;
2215
+ this.saveTabs();
2216
+ await this.refreshTaints();
2217
+ this.say(t, c.gray(`this conversation is now called ${c.bold(now)}`));
2218
+ },
2219
+ },
2220
+ {
2221
+ name: "pin", description: "Keep this conversation however long it is not used; /unpin takes that back",
2222
+ run: async () => {
2223
+ const t = chat();
2224
+ if (!t)
2225
+ return;
2226
+ if (t.session === "main")
2227
+ return this.flash("the main conversation always stays");
2228
+ await this.client.pinSession(t.agent, t.session, true);
2229
+ this.pins.add(`${t.agent}:${t.session}`);
2230
+ this.say(t, c.gray("pinned: this conversation stays until you remove it"));
2231
+ },
2232
+ },
2233
+ {
2234
+ name: "unpin", description: "Let this conversation go when it has not been used for a while",
2235
+ run: async () => {
2236
+ const t = chat();
2237
+ if (!t)
2238
+ return;
2239
+ await this.client.pinSession(t.agent, t.session, false);
2240
+ this.pins.delete(`${t.agent}:${t.session}`);
2241
+ this.say(t, c.gray("not pinned any more: it is removed by itself once it is neither open nor used for some days"));
2242
+ },
2243
+ },
2244
+ {
2245
+ name: "reset", description: "Forget this conversation and start fresh",
2246
+ run: async () => {
2247
+ const t = chat();
2248
+ if (!t)
2249
+ return;
2250
+ await this.client.reset(t.agent, t.session);
2251
+ this.freshen(t);
2252
+ },
2253
+ },
2254
+ { name: "undo", description: "Take back your last message: its files are restored, the conversation forgets it, its text returns to the input", run: () => this.undo(false) },
2255
+ { name: "redo", description: "Bring back what the last /undo took, until you send a new message", run: () => this.undo(true) },
2256
+ {
2257
+ name: "folder", description: "The folder this conversation works in: open one, or none", argumentHint: "[path|none]",
2258
+ run: async (args) => {
2259
+ const t = chat();
2260
+ if (!t)
2261
+ return;
2262
+ const wanted = args.trim();
2263
+ if (!wanted)
2264
+ return this.pickFolder();
2265
+ return this.setFolder(t, /^(none|off|-)$/i.test(wanted) ? null : (droppedFiles(wanted, true)?.[0] ?? wanted));
2266
+ },
2267
+ },
2268
+ {
2269
+ name: "code", description: "The pane beside the conversation: changes (git), files, tool output", argumentHint: "[changes|files|output|running|turn|off]",
2270
+ getArgumentCompletions: (prefix) => [...PANE_VIEWS, "turn", "off"].filter((v) => v.startsWith(prefix.trim())).map((v) => ({ value: v, label: v, description: PANE_HELP[v] })),
2271
+ run: (args) => {
2272
+ const word = args.trim().toLowerCase();
2273
+ if (word && word !== "off" && word !== "turn" && !PANE_VIEWS.includes(word))
2274
+ return this.flash("usage: /code [changes|turn|files|output|running|off]");
2275
+ if (this.active.kind !== "chat")
2276
+ return this.flash("switch to a conversation tab first");
2277
+ // What the last message changed: the changes view, counted from before that message.
2278
+ if (word === "turn")
2279
+ return this.showCode(true), this.code.showTurn();
2280
+ // Without a word it opens and closes, like the button and ctrl+g.
2281
+ this.showCode(word ? word !== "off" : !this.codeOpen, word && word !== "off" ? word : undefined);
2282
+ },
2283
+ },
2284
+ {
2285
+ name: "goal", description: "Keep the agent working until something is reached; /goal alone shows where it stands", argumentHint: "[objective|pause|resume|clear]",
2286
+ getArgumentCompletions: (prefix) => [
2287
+ { value: "pause", label: "pause", description: "no further rounds until /goal resume" },
2288
+ { value: "resume", label: "resume", description: "go on with a goal that stopped" },
2289
+ { value: "clear", label: "clear", description: "take the goal off this conversation" },
2290
+ ].filter((w) => prefix.trim() !== "" && w.value.startsWith(prefix.trim().toLowerCase())),
2291
+ run: (args) => this.goal(args.trim()),
2292
+ },
2293
+ { name: "stop", description: "Stop what the agent is doing (also: esc)", run: () => (this.active.running.size ? this.stopRunning(this.active) : this.flash("nothing is running")) },
2294
+ {
2295
+ name: "model", description: "Show or switch this agent's model", argumentHint: "[provider/id]",
2296
+ getArgumentCompletions: async (prefix) => (await this.client.models().catch(() => [])).filter((m) => m.includes(prefix)).slice(0, 50).map((m) => ({ value: m, label: m })),
2297
+ run: async (args) => {
2298
+ const t = chat();
2299
+ if (!t)
2300
+ return;
2301
+ const info = this.agents.find((a) => a.id === t.agent);
2302
+ if (!args.trim())
2303
+ return this.pickModel();
2304
+ await this.client.setModel(t.agent, args.trim());
2305
+ info.model = args.trim();
2306
+ this.say(t, c.gray(`${t.agent} now uses ${c.bold(info.model)} (saved as its model)`));
2307
+ },
2308
+ },
2309
+ {
2310
+ name: "voice", description: "Dictate the message instead of typing it (on a Mac; ctrl+r does the same)", argumentHint: "[language, for example de-DE]",
2311
+ run: async (args) => {
2312
+ if (!chat())
2313
+ return;
2314
+ await this.dictate(args.trim() || undefined);
2315
+ },
2316
+ },
2317
+ {
2318
+ name: "reasoning", description: "How much this agent's model thinks before it answers", argumentHint: "[off|minimal|low|medium|high|xhigh|max]",
2319
+ getArgumentCompletions: (prefix) => REASONING_ITEMS.filter((x) => x.value.startsWith(prefix.trim())),
2320
+ run: async (args) => {
2321
+ const t = chat();
2322
+ if (!t)
2323
+ return;
2324
+ const level = args.trim();
2325
+ if (!level)
2326
+ return this.pickReasoning();
2327
+ await this.client.setThinking(t.agent, level);
2328
+ this.agents.find((a) => a.id === t.agent).thinking = level;
2329
+ this.say(t, c.gray(`${t.agent} now reasons at level ${c.bold(level)} (saved; a model that cannot reason ignores it)`));
2330
+ },
2331
+ },
2332
+ {
2333
+ name: "mode", description: "How much this agent may do without asking", argumentHint: "[auto|safe|manual|bypass|plan]",
2334
+ getArgumentCompletions: (prefix) => [
2335
+ { value: "auto", label: "auto", description: "no sandbox: shell and files reach your whole account; critical actions are checked" },
2336
+ { value: "safe", label: "safe", description: "work freely inside the sandbox, ask for the rest" },
2337
+ { value: "manual", label: "manual", description: "inside the sandbox, and ask before every action" },
2338
+ { value: "bypass", label: "bypass", description: "no sandbox, and never ask" },
2339
+ { value: "plan", label: "plan", description: "look and plan only; nothing is changed or sent" },
2340
+ ].filter((m) => m.value.startsWith(prefix.trim())),
2341
+ run: async (args) => {
2342
+ const t = chat();
2343
+ if (!t)
2344
+ return;
2345
+ return args.trim() ? this.setMode(t, args.trim()) : this.pickMode();
2346
+ },
2347
+ },
2348
+ {
2349
+ name: "attach", description: "Attach a file to your next message (or drop it on the terminal)", argumentHint: "<path>",
2350
+ run: (args) => (args.trim() ? (droppedFiles(args.trim()) ?? [args.trim()]).forEach((f) => this.attachFile(f)) : this.flash("usage: /attach <path>, or drag a file onto the terminal")),
2351
+ },
2352
+ {
2353
+ name: "detach", description: "Remove attached files", argumentHint: "[n]",
2354
+ run: (args) => {
2355
+ const t = this.active;
2356
+ if (args.trim())
2357
+ t.attachments.splice(Number(args) - 1, 1);
2358
+ else
2359
+ t.attachments = [];
2360
+ this.tui.requestRender();
2361
+ },
2362
+ },
2363
+ {
2364
+ name: "status", description: "Running tasks and live sessions",
2365
+ run: async () => {
2366
+ const s = await this.client.status();
2367
+ const lines = [
2368
+ `${c.gray("model slots")} ${s.limiter.active}/${s.limiter.max} busy, ${s.limiter.waiting} waiting`,
2369
+ ...s.running.map((r) => `${c.yellow("●")} task #${r.task} ${r.agent}/${r.session} ${c.gray(r.kind)}`),
2370
+ ...s.sessions.map((x) => `${c.gray("session")} ${x.agent}/${x.session}${x.busy ? c.yellow(" busy") : ""}${x.tainted ? c.yellow(` tainted: ${x.tainted}`) : ""}`),
2371
+ ];
2372
+ this.say(this.active, lines.join("\n"));
2373
+ },
2374
+ },
2375
+ {
2376
+ name: "sources", description: "Event sources: what can wake an agent, and who is subscribed",
2377
+ run: async () => {
2378
+ const list = await this.client.sources();
2379
+ const t = this.active;
2380
+ if (!list.length)
2381
+ return void this.say(t, c.gray(`no event sources configured. They go into "sources" in pine.json (for every agent) or an agent.json; docs/references/sources.md has the types.`));
2382
+ this.say(t, list.map((x) => `${c.bold(x.name)}${x.scope === "global" ? "" : c.gray(` (of ${x.scope})`)} ${c.gray(x.type)} ${x.error ? c.red(`not running: ${x.error}`) : x.running ? c.green("running") : c.gray("idle")}${x.description ? c.gray(` · ${x.description}`) : ""}${x.status ? `\n ${x.status}` : ""}\n${c.gray(` subscribers: ${x.subscribers.join(", ") || "none"} · ${x.last ? `last event ${new Date(x.last.ts).toLocaleTimeString("sv-SE")}, ${x.events} since start` : "no events since start"}`)}`).join("\n"));
2383
+ this.say(t, c.gray("/subscribe <source> [what to do] wakes this tab's agent on its events · /unsubscribe <source> stops that"), false);
2384
+ },
2385
+ },
2386
+ {
2387
+ name: "subscribe", description: "Wake on an event source: this conversation (local), the agent, or all agents (global)", argumentHint: "[local|agent|global] <source> [what to do]",
2388
+ getArgumentCompletions: async (prefix) => {
2389
+ const words = prefix.split(/\s+/);
2390
+ const scoped = SCOPES.includes(words[0]);
2391
+ if (words.length > (scoped ? 2 : 1))
2392
+ return null;
2393
+ const typed = scoped ? (words[1] ?? "") : words[0];
2394
+ const lead = scoped ? `${words[0]} ` : "";
2395
+ const sources = (await this.client.sources().catch(() => [])).filter((x) => String(x.name).startsWith(typed)).map((x) => ({ value: `${lead}${x.name} `, label: x.name, description: `${x.type}${x.description ? ` · ${x.description}` : ""}` }));
2396
+ return scoped ? sources : [...SCOPES.filter((x) => x.startsWith(typed)).map((x) => ({ value: `${x} `, label: x, description: SCOPE_HELP[x] })), ...sources];
2397
+ },
2398
+ run: async (args) => {
2399
+ const t = chat();
2400
+ if (!t)
2401
+ return;
2402
+ const words = args.trim().split(/\s+/).filter(Boolean);
2403
+ // Said without a scope, it means here: this conversation. In an agent's main conversation that is the agent.
2404
+ const scope = SCOPES.includes(words[0]) ? words.shift() : "local";
2405
+ const [source, ...note] = words;
2406
+ if (!source)
2407
+ return this.flash("usage: /subscribe [local|agent|global] <source> [what the agent should do] (see /sources)");
2408
+ const details = { note: note.join(" ") || undefined };
2409
+ if (scope === "global") {
2410
+ const info = await this.client.subscribeAll(source, details);
2411
+ return void this.say(t, `${c.green("✓")} ${c.gray(`all agents are subscribed to ${source} (${info.running ? "running" : "not running"}). Each event wakes ${info.agents.join(", ") || "nobody yet"}, each in its main conversation.`)}`);
2412
+ }
2413
+ const local = scope === "local" && t.session !== "main";
2414
+ const info = await this.client.subscribeTo(t.agent, source, { ...details, session: local ? t.session : "main" });
2415
+ this.say(t, `${c.green("✓")} ${c.bold(t.agent)} ${c.gray(`is subscribed to ${source} (${info.running ? "running" : "not running"}). ${local ? "Each event arrives here, in this conversation, and wakes it. Closing this conversation ends the subscription." : `Each event arrives in its main conversation${t.session === "main" ? ", here," : ""} and wakes it.`}`)}`);
2416
+ },
2417
+ },
2418
+ {
2419
+ name: "unsubscribe", description: "End a subscription of this conversation, the agent, or all agents", argumentHint: "[local|agent|global] <source>",
2420
+ getArgumentCompletions: async (prefix) => (prefix.trim().includes(" ") ? null : (await this.client.sources().catch(() => [])).filter((x) => String(x.name).startsWith(prefix.trim()) && x.subscribers.length).map((x) => ({ value: x.name, label: x.name, description: `${x.type} · subscribed: ${x.subscribers.join(", ")}` }))),
2421
+ run: async (args) => {
2422
+ const t = chat();
2423
+ if (!t)
2424
+ return;
2425
+ const words = args.trim().split(/\s+/).filter(Boolean);
2426
+ const scope = SCOPES.includes(words[0]) ? words.shift() : t.session === "main" ? "agent" : "local";
2427
+ const source = words[0];
2428
+ if (!source)
2429
+ return this.flash("usage: /unsubscribe [local|agent|global] <source>");
2430
+ if (scope === "global")
2431
+ return void this.say(t, c.gray((await this.client.unsubscribeAll(source)).unsubscribed ? `all agents: no longer subscribed to ${source}` : `there was no subscription of all agents to ${source}`));
2432
+ const session = scope === "agent" ? "main" : t.session;
2433
+ const r = await this.client.unsubscribeFrom(t.agent, source, session);
2434
+ const what = session === "main" ? t.agent : "this conversation";
2435
+ this.say(t, c.gray(r.unsubscribed ? `${what} is no longer subscribed to ${source}` : `${what} was not subscribed to ${source} on its own (see /sources for who is)`));
2436
+ },
2437
+ },
2438
+ {
2439
+ name: "mcp", description: "MCP servers: list them, or sign in to one", argumentHint: "[login [name]]",
2440
+ getArgumentCompletions: async (prefix) => {
2441
+ if (!prefix.startsWith("login "))
2442
+ return [{ value: "login ", label: "login", description: "sign in to a remote server through the browser" }].filter((x) => x.value.startsWith(prefix));
2443
+ // Only the names here: asking every server for its state would take seconds.
2444
+ const servers = (await this.opts.mcp?.list(false).catch(() => [])) ?? [];
2445
+ const typed = prefix.slice(6).trim();
2446
+ return servers.filter((sv) => /^https?:/.test(sv.target) && sv.name.includes(typed)).map((sv) => ({ value: `login ${sv.name}`, label: sv.name, description: sv.target }));
2447
+ },
2448
+ run: async (args) => {
2449
+ const t = this.active;
2450
+ const mcp = this.opts.mcp;
2451
+ if (!mcp)
2452
+ return this.flash("not available in this UI; use pine mcp in a shell");
2453
+ const [sub, given] = args.trim().split(/\s+/);
2454
+ const table = (servers, checking) => servers.length
2455
+ ? servers.map((sv) => `${c.bold(sv.name.padEnd(14))} ${(/^connected/.test(sv.state ?? "") ? c.green : /sign-in/.test(sv.state ?? "") ? c.yellow : c.gray)((sv.state ?? (checking ? "checking…" : "")).padEnd(16))} ${c.gray(sv.scope === "global" ? `all agents: ${sv.agents.join(", ") || "nobody"}` : !sv.session ? `only ${sv.scope}` : sv.scope === t.agent && sv.session === t.session ? "only this conversation" : `only the conversation ${sv.session} of ${sv.scope}, not this one`)}\n${" ".repeat(15)}${c.gray(sv.target)}`).join("\n")
2456
+ : c.gray("no MCP servers configured");
2457
+ if (!sub) {
2458
+ // Show what is configured at once; whether each server connects arrives a moment later.
2459
+ const line = this.say(t, table(await mcp.list(false), true));
2460
+ void mcp.list(true).then((servers) => (line.setText(table(servers, false)), this.tui.requestRender())).catch(() => { });
2461
+ return;
2462
+ }
2463
+ if (sub !== "login")
2464
+ return this.flash("usage: /mcp, or /mcp login [name]");
2465
+ let name = given;
2466
+ if (!name) {
2467
+ const remote = (await mcp.list(false)).filter((sv) => /^https?:/.test(sv.target));
2468
+ if (!remote.length)
2469
+ return this.flash("no remote MCP server is configured");
2470
+ name = remote.length === 1 ? remote[0].name : await this.pick("Sign in to which server?", remote.map((sv) => ({ value: sv.name, label: sv.name, description: sv.target })));
2471
+ if (!name)
2472
+ return;
2473
+ }
2474
+ const line = this.say(t, c.gray(`signing in to ${name}… your browser opens the sign-in page`));
2475
+ let shown = "";
2476
+ const code = await mcp.login(name, (text) => {
2477
+ shown += text;
2478
+ line.setText(c.gray(shown.trim()));
2479
+ this.tui.requestRender();
2480
+ });
2481
+ if (code !== 0)
2482
+ return void this.say(t, c.red(`sign-in to ${name} did not complete`), false);
2483
+ await this.client.post("/mcp/refresh").catch(() => { });
2484
+ this.say(t, `${c.green("✓")} signed in to ${c.bold(name)}${c.gray(". Its tools are available from your next message.")}`, false);
2485
+ },
2486
+ },
2487
+ { name: "events", description: "Open the live event log", run: () => this.openEvents() },
2488
+ {
2489
+ name: "tasks", description: "Recent tasks of this agent",
2490
+ run: async () => {
2491
+ const t = this.active;
2492
+ const tasks = await this.client.get(`/tasks?limit=15${t.kind === "chat" ? `&agent=${t.agent}` : ""}`);
2493
+ this.say(t, tasks.reverse().map((x) => `${c.gray(`#${String(x.id).padEnd(4)}`)} ${(x.status === "done" ? c.green : x.status === "failed" ? c.red : c.yellow)(x.status.padEnd(9))} ${`${x.agent}/${x.session}`.padEnd(20)} ${c.gray(short(oneLine(x.meta?.label ?? x.prompt), 60))}`).join("\n") || c.gray("no tasks"));
2494
+ this.say(t, c.gray("/task <id> opens one and shows what it did"), false);
2495
+ },
2496
+ },
2497
+ {
2498
+ name: "task", description: "Show what one task did, step by step (a sub-agent, for example)", argumentHint: "<id>",
2499
+ getArgumentCompletions: async (prefix) => {
2500
+ const tasks = await this.client.get("/tasks?limit=40").catch(() => []);
2501
+ return tasks.filter((x) => String(x.id).startsWith(prefix.trim())).map((x) => ({ value: String(x.id), label: `#${x.id}`, description: `${x.depth > 0 ? childKind(x.kind) : x.kind} · ${x.agent} · ${x.status} · ${short(oneLine(x.meta?.label ?? x.prompt), 50)}` }));
2502
+ },
2503
+ run: (args) => (/^\d+$/.test(args.trim()) ? this.openTask(Number(args.trim())) : this.flash("usage: /task <id> (the ids are in /tasks)")),
2504
+ },
2505
+ { name: "approve", description: "Allow the action that waits for approval", argumentHint: "[id] [always]", run: (args) => this.answer(args.trim(), true) },
2506
+ { name: "deny", description: "Refuse the action that waits for approval", argumentHint: "[id]", run: (args) => this.answer(args.trim(), false) },
2507
+ {
2508
+ name: "state", description: "Shared state", argumentHint: "[key pattern]",
2509
+ run: async (args) => {
2510
+ const rows = await this.client.state(args.trim() || "#");
2511
+ this.say(this.active, rows.map((r) => `${c.bold(r.key)} = ${JSON.stringify(r.value)}`).join("\n") || c.gray("nothing stored"));
2512
+ },
2513
+ },
2514
+ {
2515
+ name: "emit", description: "Publish an event as yourself", argumentHint: "<topic> [json]",
2516
+ run: async (args) => {
2517
+ const m = args.trim().match(/^(\S+)\s*([\s\S]*)$/);
2518
+ if (!m)
2519
+ return this.flash("usage: /emit <topic> [json]");
2520
+ const r = await this.client.emit(m[1], m[2] ? JSON.parse(m[2]) : null);
2521
+ this.flash(`event #${r.id} published on ${m[1]}`);
2522
+ },
2523
+ },
2524
+ {
2525
+ name: "paste", description: "Attach the picture that is on the clipboard (a screenshot, for example) to your next message",
2526
+ run: async () => {
2527
+ if (!chat())
2528
+ return;
2529
+ const file = await this.clipboardImage();
2530
+ if (file)
2531
+ this.attachFile(file);
2532
+ else
2533
+ this.flash("there is no picture on the clipboard (text is pasted with your terminal's own paste)");
2534
+ },
2535
+ },
2536
+ {
2537
+ name: "notify", description: "Bell and notification when the agent is done or needs you while the terminal is not in front", argumentHint: "[on|off]",
2538
+ getArgumentCompletions: (prefix) => ["on", "off"].filter((x) => x.startsWith(prefix.trim())).map((x) => ({ value: x, label: x })),
2539
+ run: (args) => {
2540
+ const want = args.trim();
2541
+ if (want && want !== "on" && want !== "off")
2542
+ return this.flash("usage: /notify [on|off]");
2543
+ if (want) {
2544
+ this.notify = want === "on";
2545
+ this.saveTabs();
2546
+ }
2547
+ this.flash(this.notify ? "notifications are on: a bell and a notification when the agent is done, fails or needs your approval while this window is not in front" : "notifications are off");
2548
+ },
2549
+ },
2550
+ {
2551
+ name: "compact", description: "Shorten this conversation: its earlier part becomes a summary, which frees the model's context",
2552
+ run: async () => {
2553
+ const t = chat();
2554
+ if (t)
2555
+ this.adopt(t, (await this.client.compact(t.agent, t.session)).task);
2556
+ },
2557
+ },
2558
+ {
2559
+ name: "copy", description: "Copy the agent's last answer to the clipboard",
2560
+ run: async () => {
2561
+ const t = chat();
2562
+ if (!t)
2563
+ return;
2564
+ if (!t.lastAnswer)
2565
+ return this.flash("there is no answer to copy yet");
2566
+ const done = await this.copyText(t.lastAnswer);
2567
+ this.flash(done === true ? `copied the last answer (${t.lastAnswer.length} characters)` : `not copied: ${done}`);
2568
+ },
2569
+ },
2570
+ {
2571
+ name: "export", description: "Save this conversation as Markdown, or copy it", argumentHint: "[copy] [full]",
2572
+ getArgumentCompletions: (prefix) => [{ value: "copy", label: "copy", description: "to the clipboard instead of a file" }, { value: "full", label: "full", description: "with thinking and tool calls" }].filter((x) => x.value.startsWith(prefix.trim().split(/\s+/).at(-1) ?? "")),
2573
+ run: async (args) => {
2574
+ const t = chat();
2575
+ if (!t)
2576
+ return;
2577
+ const words = args.trim().split(/\s+/).filter(Boolean);
2578
+ const unknown = words.find((w) => w !== "copy" && w !== "full");
2579
+ if (unknown)
2580
+ return this.flash(`usage: /export [copy] [full] (not "${unknown}")`);
2581
+ const text = await this.markdownOf(t, words.includes("full"));
2582
+ if (words.includes("copy")) {
2583
+ const done = await this.copyText(text);
2584
+ return this.flash(done === true ? `copied the conversation as Markdown (${text.length} characters)` : `not copied: ${done}`);
2585
+ }
2586
+ const stamp = new Date().toLocaleString("sv-SE").replace(/[-:]/g, "").replace(" ", "-").slice(0, 13);
2587
+ const file = path.join(this.opts.cwd ?? process.cwd(), `pine-${`${t.agent}-${t.session}`.replace(/[^A-Za-z0-9._-]+/g, "_")}-${stamp}.md`);
2588
+ await fs.promises.writeFile(file, text, { flag: "wx" }).catch(async () => fs.promises.writeFile(file.replace(/\.md$/, `-${Date.now() % 1000}.md`), text));
2589
+ this.say(t, c.gray(`saved this conversation as ${tilde(file)}`));
2590
+ },
2591
+ },
2592
+ { name: "clear", description: "Clear this tab's view (the conversation is kept)", run: () => (this.active.doc.clear(), this.tui.requestRender()) },
2593
+ { name: "quit", description: "Leave", run: () => this.stop() },
2594
+ { name: "exit", description: "Leave", run: () => this.stop() },
2595
+ ];
2596
+ }
2597
+ async run(input) {
2598
+ const m = input.match(/^(\S+)\s*([\s\S]*)$/);
2599
+ const cmd = m && this.commands.find((x) => x.name === m[1]);
2600
+ if (!cmd)
2601
+ return this.flash(`unknown command /${m?.[1] ?? ""} · /help lists them`);
2602
+ try {
2603
+ await cmd.run(m[2] ?? "");
2604
+ }
2605
+ catch (e) {
2606
+ this.say(this.active, c.red(`/${cmd.name}: ${errText(e)}`));
2607
+ }
2608
+ }
2609
+ help() {
2610
+ const cmds = this.commands.filter((x) => x.name !== "exit").map((x) => ` ${c.accent(`/${x.name}`)}${x.argumentHint ? c.gray(` ${x.argumentHint}`) : ""}${" ".repeat(Math.max(1, 24 - x.name.length - (x.argumentHint?.length ?? -1) - 2))}${x.description}`);
2611
+ const keys = [
2612
+ ["enter", "send; while the agent works, the message goes into that work at its next step"], ["alt+enter", "send, but let it wait until the agent is done with what it is doing"], ["shift+enter", "new line"], ["esc", "stop the agent"], ["tab", "next tab (when the input is empty)"], ["shift+tab", "next mode: auto, plan, manual, bypass (when the input is empty)"],
2613
+ ["alt+1..9", "go to tab"], ["ctrl+t", "new conversation"], ["ctrl+w", "close tab"], ["ctrl+g", "open or close the code pane (changes, files, tool output)"], ["ctrl+r", "dictate the message instead of typing it (on a Mac); enter ends it"], ["pgup / pgdn", "scroll"], ["mouse", "click a tab, its ×, +, ▤ code, a web address, a thought (to open it, and anywhere on it to close it), or agent / conversation / folder / model / reasoning / mode in the bottom bar; drop files to attach"], ["ctrl+c twice, ctrl+d", "quit"],
2614
+ ].map(([k, d]) => ` ${c.accent(k.padEnd(22))} ${d}`);
2615
+ this.say(this.active, [c.bold("Commands"), ...cmds, "", c.bold("Keys"), ...keys].join("\n"));
2616
+ }
2617
+ // ---- approvals -------------------------------------------------------------------------------
2618
+ ask(tab, req) {
2619
+ if (this.dialog || tab !== this.active)
2620
+ return;
2621
+ const dialog = req.tool === "question"
2622
+ ? new QuestionDialog(req, (answer) => {
2623
+ this.closeDialog();
2624
+ if (answer === undefined)
2625
+ return; // later: the status line keeps saying that something waits
2626
+ void this.client.decide(req.id, true, false, { answer }).catch((e) => this.flash(errText(e)));
2627
+ })
2628
+ : new ApprovalDialog(req, (answer, values) => {
2629
+ this.closeDialog();
2630
+ if (answer === "later")
2631
+ return; // the status line keeps saying that an approval is open
2632
+ void this.client.decide(req.id, answer !== "deny", answer === "always", values).catch((e) => this.flash(errText(e)));
2633
+ });
2634
+ const handle = this.tui.showOverlay(dialog, { anchor: "center", width: "76%", minWidth: 40 });
2635
+ handle.focus();
2636
+ this.dialog = { id: req.id, handle, dismiss: () => this.closeDialog(), waits: true };
2637
+ this.tui.requestRender();
2638
+ }
2639
+ /** Forget the questions the daemon no longer has open: their cards say so, and a dialog for one closes. */
2640
+ async dropAnswered() {
2641
+ const pending = await this.client.approvals().catch(() => undefined);
2642
+ if (!pending)
2643
+ return;
2644
+ const open = new Set(pending.map((p) => p.id));
2645
+ for (const tab of this.tabs) {
2646
+ for (const [id, a] of tab.approvals) {
2647
+ if (open.has(id))
2648
+ continue;
2649
+ a.card.setText(`${c.gray("– no longer open:")} ${c.bold(a.req.tool)} ${c.gray("(pine was restarted, or the question ran out of time)")}`);
2650
+ tab.approvals.delete(id);
2651
+ if (this.dialog?.id === id)
2652
+ this.closeDialog();
2653
+ }
2654
+ }
2655
+ this.tui.requestRender();
2656
+ }
2657
+ closeDialog() {
2658
+ this.dialog?.handle.hide();
2659
+ this.dialog = undefined;
2660
+ this.dialogClosedAt = Date.now();
2661
+ this.tui.setFocus(this.editor);
2662
+ this.tui.requestRender();
2663
+ }
2664
+ async answer(args, allow) {
2665
+ const words = args.split(/\s+/).filter(Boolean);
2666
+ const always = allow && words.includes("always");
2667
+ const id = words.find((w) => w !== "always") ?? "";
2668
+ const pending = await this.client.approvals();
2669
+ const target = id || (pending.length === 1 ? pending[0].id : "");
2670
+ if (!target)
2671
+ return this.flash(pending.length ? `several requests wait: ${pending.map((p) => p.id).join(", ")}` : "nothing waits for approval");
2672
+ // One that needs a value from you is answered in its dialog, where the value is typed without being shown.
2673
+ const req = pending.find((p) => p.id === target);
2674
+ if (allow && req?.inputs?.length)
2675
+ return this.ask(this.active, req);
2676
+ const r = await this.client.decide(target, allow, always);
2677
+ if (!r.decided)
2678
+ this.flash("that request was already answered");
2679
+ }
2680
+ // ---- events ----------------------------------------------------------------------------------
2681
+ tabFor(p) {
2682
+ if (p?.root !== undefined) {
2683
+ const byRoot = this.tabs.find((t) => t.kind === "chat" && t.roots.has(p.root));
2684
+ if (byRoot)
2685
+ return byRoot;
2686
+ }
2687
+ return undefined;
2688
+ }
2689
+ onEvent(e) {
2690
+ const p = (e.payload ?? {});
2691
+ const [ns, , kind] = e.topic.split("/");
2692
+ this.logEvent(e);
2693
+ if (ns === "approval") {
2694
+ if (e.topic === "approval/requested") {
2695
+ const tab = this.tabFor(p) ?? this.active;
2696
+ // A question of the agent's is not a permission: it is shown as what it is.
2697
+ const card = p.tool === "question"
2698
+ ? this.say(tab, `${c.accent("? the agent asks")} ${short(oneLine(String(p.summary ?? "")), 300)}\n${c.gray(" answer it in the dialog, or with /approve")}`)
2699
+ : this.say(tab, `${c.yellow("⚠ approval needed")} ${c.bold(p.tool)} ${c.gray(short(oneLine(String(p.summary ?? "")), 120))}\n${c.gray(` ${p.why} · ${p.inputs?.length ? "it needs something only you have: /approve opens the dialog to enter it" : `/approve${p.remember ? ", /approve always" : ""}`} or /deny`)}`);
2700
+ tab.approvals.set(p.id, { card, req: p });
2701
+ this.attention(p.tool === "question" ? `pine: ${tab.agent} has a question for you` : `pine: ${tab.agent} needs your approval`);
2702
+ this.ask(tab, p);
2703
+ }
2704
+ else if (e.topic === "approval/decided") {
2705
+ for (const tab of this.tabs) {
2706
+ const a = tab.approvals.get(p.id);
2707
+ if (!a)
2708
+ continue;
2709
+ if (a.req.tool === "question")
2710
+ a.card.setText(`${c.accent("?")} ${short(oneLine(String(a.req.summary ?? "")), 300)}\n${c.gray(` ${p.allow ? `answered (${p.by})` : `no answer (${p.by})`}`)}`);
2711
+ else
2712
+ a.card.setText(`${p.allow ? c.green("✓ allowed") : c.red("✗ denied")} ${c.bold(a.req.tool)} ${c.gray(`(${p.by})${p.always ? ` · ${p.remember} will not ask again in this conversation` : ""}`)}`);
2713
+ tab.approvals.delete(p.id);
2714
+ }
2715
+ if (this.dialog?.id === p.id)
2716
+ this.closeDialog();
2717
+ this.tui.requestRender();
2718
+ }
2719
+ return;
2720
+ }
2721
+ if (ns !== "agent")
2722
+ return;
2723
+ if (kind === "goal")
2724
+ return this.goalEvent(p);
2725
+ // A tab on one task follows that task and whatever it starts itself.
2726
+ for (const t of this.tabs) {
2727
+ if (t.kind !== "task")
2728
+ continue;
2729
+ if (kind === "started" && p.parent !== undefined && t.roots.has(p.parent))
2730
+ t.roots.add(p.task);
2731
+ if (t.roots.has(p.task))
2732
+ this.live(t, kind, p, (p.depth ?? 0) - t.baseDepth);
2733
+ }
2734
+ if (kind === "steered") {
2735
+ // A message that went into running work: ours is on screen already, somebody else's is shown.
2736
+ const tab = this.tabs.find((t) => t.kind === "chat" && t.agent === p.agent && t.session === p.session);
2737
+ if (!tab || tab.roots.has(p.by))
2738
+ return;
2739
+ tab.roots.add(p.by);
2740
+ const i = tab.awaiting.findIndex((a) => String(p.prompt ?? "").startsWith(a));
2741
+ if (i >= 0)
2742
+ tab.awaiting.splice(i, 1);
2743
+ else
2744
+ this.user(tab, String(p.prompt ?? ""), p.kind === "prompt" ? "elsewhere" : p.kind);
2745
+ this.tui.requestRender();
2746
+ return;
2747
+ }
2748
+ if (kind === "started" && p.depth === 0) {
2749
+ // A top-level task: ours (sent from a tab) or someone else's in a session a tab shows.
2750
+ let tab = this.tabFor(p) ?? this.tabs.find((t) => t.kind === "chat" && t.agent === p.agent && t.session === p.session);
2751
+ if (!tab) {
2752
+ // An event woke the agent in a conversation nobody is looking at: say so where that agent is on screen.
2753
+ const home = p.kind === "event" ? this.tabs.find((t) => t.kind === "chat" && t.agent === p.agent) : undefined;
2754
+ if (home)
2755
+ this.button(home, `${c.yellow("⚡")} ${c.gray(`an event woke ${p.agent} in the conversation`)} ${c.bold(String(p.session))} ${c.accent("▸ open")}`, () => void this.openTab(p.agent, String(p.session)), true);
2756
+ return;
2757
+ }
2758
+ const i = tab.awaiting.findIndex((a) => String(p.prompt ?? "").startsWith(a));
2759
+ if (i >= 0) {
2760
+ tab.awaiting.splice(i, 1);
2761
+ // It waited behind work that esc just stopped: the next esc is not meant for it.
2762
+ if (tab.stopped && tab.stopped.waiting > 0 && Date.now() - tab.stopped.at < STOP_GRACE) {
2763
+ tab.stopped.waiting--;
2764
+ tab.stopped.spared.add(p.task);
2765
+ }
2766
+ }
2767
+ else if (p.compact) {
2768
+ this.say(tab, c.gray("⟲ shortening the conversation: its earlier part becomes a summary…"));
2769
+ }
2770
+ else if (p.requeued) {
2771
+ // A message that was given to work which ended, or was stopped, before reading it. It is on
2772
+ // screen already and is answered now; an esc pressed for the old work is not meant for it.
2773
+ if (tab.stopped && Date.now() - tab.stopped.at < STOP_GRACE)
2774
+ tab.stopped.spared.add(p.task);
2775
+ }
2776
+ else if (!tab.roots.has(p.task)) {
2777
+ if (p.kind === "event" && p.label)
2778
+ this.eventLine(tab, String(p.label), String(p.prompt ?? ""));
2779
+ // A round of a goal was announced by the goal's own line; its text is the same every round.
2780
+ else if (!isGoalRound(p.kind, p.label))
2781
+ this.user(tab, String(p.prompt ?? ""), p.kind === "prompt" ? "elsewhere" : p.kind);
2782
+ // What came with it and was not typed here: a photo sent on Telegram, a picture a camera saved.
2783
+ for (let n = 0; n < Number(p.images ?? 0); n++)
2784
+ this.picture(tab, `picture ${n + 1}`, () => this.client.taskImage(p.task, n));
2785
+ }
2786
+ tab.roots.add(p.task);
2787
+ tab.running.add(p.task);
2788
+ if (tab.running.size === 1) {
2789
+ tab.startedAt = Date.now();
2790
+ tab.toolCalls = 0;
2791
+ tab.tokens = { input: 0, output: 0, cached: 0 };
2792
+ }
2793
+ this.tui.requestRender();
2794
+ return;
2795
+ }
2796
+ const tab = this.tabFor(p);
2797
+ if (tab)
2798
+ this.live(tab, kind, p, p.depth ?? 0);
2799
+ }
2800
+ // ---- goal mode ---------------------------------------------------------------------------------
2801
+ // The daemon keeps the goal and decides everything about it; here it is asked for, and shown.
2802
+ /** One line on where a goal stands, with the judge's reason under it; `full` adds the objective. */
2803
+ goalLine(g, full = false) {
2804
+ const mark = g.status === "met" ? c.green("✓") : g.status === "active" ? c.accent("◎") : c.yellow("‖");
2805
+ const more = [...(g.reason ? [short(oneLine(g.reason), 200)] : []), ...(full ? [`the goal: ${short(oneLine(g.objective), 300)}`] : [])];
2806
+ return `${mark} ${c.bold("goal")} ${c.gray(g.note)}${more.map((m) => `\n${c.gray(` ${m}`)}`).join("")}`;
2807
+ }
2808
+ /** The daemon reports on a goal: it was set, a round was judged, it stopped or was cleared. */
2809
+ goalEvent(p) {
2810
+ for (const tab of this.tabs) {
2811
+ if (tab.kind !== "chat" || tab.agent !== p.agent || tab.session !== p.session)
2812
+ continue;
2813
+ tab.goal = p.event === "cleared" ? undefined : p;
2814
+ this.say(tab, this.goalLine(p));
2815
+ if (tab !== this.active)
2816
+ tab.unread = true;
2817
+ }
2818
+ this.tui.requestRender();
2819
+ }
2820
+ /** /goal: show it, set it, or pause, resume or clear it. All of it is the daemon's doing. */
2821
+ async goal(arg) {
2822
+ const t = this.active;
2823
+ if (t.kind !== "chat")
2824
+ return this.flash("switch to a conversation tab first");
2825
+ const word = arg.toLowerCase();
2826
+ if (!arg) {
2827
+ t.goal = (await this.client.goal(t.agent, t.session)).goal;
2828
+ return void this.say(t, t.goal ? this.goalLine(t.goal, true) : c.gray("this conversation has no goal · /goal <what should be reached> sets one, and the agent works until it is met"));
2829
+ }
2830
+ if (word === "pause" || word === "resume" || word === "clear") {
2831
+ // What changes is drawn when the daemon reports it.
2832
+ const done = await this.client.setGoal(t.agent, t.session, { action: word });
2833
+ if (word === "clear" && !done.cleared)
2834
+ this.flash("this conversation has no goal");
2835
+ return;
2836
+ }
2837
+ // The first round is the objective itself, sent as a message of yours.
2838
+ this.user(t, arg);
2839
+ t.awaiting.push(arg);
2840
+ t.scroll.scrollToEnd();
2841
+ try {
2842
+ await this.client.setGoal(t.agent, t.session, { objective: arg });
2843
+ }
2844
+ catch (e) {
2845
+ t.awaiting = t.awaiting.filter((a) => a !== arg);
2846
+ this.say(t, c.red(`✗ no goal set: ${errText(e)}`));
2847
+ }
2848
+ }
2849
+ /** Show one live event of a task in a tab. `depth` is counted from what the tab shows: 0 is its own task. */
2850
+ live(tab, kind, p, depth) {
2851
+ const indent = " ".repeat(Math.max(0, depth));
2852
+ const open = c.accent("▸ open");
2853
+ switch (kind) {
2854
+ case "started":
2855
+ if (depth <= 0) {
2856
+ tab.running.add(p.task);
2857
+ tab.startedAt = Date.now();
2858
+ break;
2859
+ }
2860
+ tab.children.set(p.task, { agent: p.agent, kind: p.kind, label: short(oneLine(String(p.label ?? p.prompt ?? "")), 60), running: true });
2861
+ this.button(tab, `${indent}${c.magenta("↳")} ${c.bold(p.agent)} ${c.gray(`${childKind(p.kind)} #${p.task}: ${short(oneLine(String(p.label ?? p.prompt ?? "")), 80)}`)} ${open}`, () => void this.openTask(p.task));
2862
+ break;
2863
+ case "thinking": {
2864
+ if (p.phase === "end") {
2865
+ tab.thinking = false;
2866
+ this.endThought(tab, p.task, p.ms);
2867
+ break;
2868
+ }
2869
+ tab.thinking = true;
2870
+ if (depth > 0 || !p.text)
2871
+ break; // a child's thoughts stay with the child, like its prose
2872
+ let thought = tab.thoughts.get(p.task);
2873
+ if (!thought)
2874
+ tab.thoughts.set(p.task, (thought = this.thought(tab)));
2875
+ thought.append(p.text);
2876
+ break;
2877
+ }
2878
+ case "todos":
2879
+ this.showSteps(tab, p.task, Array.isArray(p.items) ? p.items : []);
2880
+ break;
2881
+ case "delta": {
2882
+ tab.thinking = false;
2883
+ this.endThought(tab, p.task);
2884
+ if (depth > 0)
2885
+ break; // a child's prose stays with the child (its own tab shows it); its answer reaches the parent as a tool result
2886
+ let block = tab.blocks.get(p.task);
2887
+ if (!block) {
2888
+ block = { md: new Answer(""), text: "" };
2889
+ tab.blocks.set(p.task, block);
2890
+ this.add(tab, block.md);
2891
+ }
2892
+ block.text += p.text;
2893
+ block.md.setText(block.text);
2894
+ break;
2895
+ }
2896
+ case "message":
2897
+ this.endThought(tab, p.task);
2898
+ if (tab.blocks.has(p.task)) {
2899
+ if (depth === 0)
2900
+ tab.lastAnswer = tab.blocks.get(p.task).text;
2901
+ tab.streamed.set(p.task, tab.blocks.get(p.task).text);
2902
+ this.answerPictures(tab, p.agent, tab.blocks.get(p.task).text);
2903
+ }
2904
+ tab.blocks.delete(p.task);
2905
+ if (depth === 0) {
2906
+ tab.tokens = { input: p.input ?? 0, output: p.output ?? 0, cached: p.cached ?? 0 };
2907
+ if (p.context?.percent !== undefined)
2908
+ tab.context = p.context.percent;
2909
+ // How fast this call went: beside what the model thought in it, and in the line at the bottom.
2910
+ if (p.speed && (p.speed.read || p.speed.write))
2911
+ tab.speed = p.speed;
2912
+ }
2913
+ const ended = tab.thought;
2914
+ if (ended && ended.task === p.task) {
2915
+ if (depth === 0)
2916
+ ended.block.speed = speedText(p.speed);
2917
+ tab.thought = undefined;
2918
+ }
2919
+ break;
2920
+ case "tool": {
2921
+ tab.thinking = false;
2922
+ this.endThought(tab, p.task);
2923
+ tab.blocks.delete(p.task);
2924
+ tab.streamed.delete(p.task);
2925
+ const key = `${p.task}:${p.call}`;
2926
+ const label = `${c.bold(p.tool)}${p.subject ? ` ${c.gray(short(oneLine(p.subject), 100))}` : ""}`;
2927
+ if (p.phase === "start") {
2928
+ tab.toolCalls++;
2929
+ tab.tools.set(key, { line: this.say(tab, `${indent}${c.yellow("●")} ${label}`, depth === 0 && !tab.tools.size), label });
2930
+ }
2931
+ else {
2932
+ const t = tab.tools.get(key);
2933
+ const took = p.ms !== undefined ? c.gray(` ${p.ms < 1000 ? `${Math.round(p.ms)} ms` : `${(p.ms / 1000).toFixed(1)} s`}`) : "";
2934
+ const failed = p.ok ? "" : `\n${indent} ${c.red(short(oneLine(String(p.preview ?? "")), 160))}`;
2935
+ const text = `${indent}${p.ok ? c.green("✓") : c.red("✗")} ${t?.label ?? label}${took}${failed}`;
2936
+ // A call that began before this tab was opened has no line of its own yet.
2937
+ if (t)
2938
+ t.line.setText(text);
2939
+ else
2940
+ this.say(tab, text, false);
2941
+ tab.tools.delete(key);
2942
+ for (const id of (p.images ?? []))
2943
+ this.picture(tab, `from ${p.tool}`, () => this.client.toolImage(id));
2944
+ }
2945
+ break;
2946
+ }
2947
+ case "done":
2948
+ case "failed": {
2949
+ const block = tab.blocks.get(p.task);
2950
+ tab.blocks.delete(p.task);
2951
+ this.endThought(tab, p.task);
2952
+ if (depth > 0) {
2953
+ const child = tab.children.get(p.task);
2954
+ if (child)
2955
+ child.running = false;
2956
+ const n = p.stats?.tools?.length ?? 0;
2957
+ const how = p.status === "done" ? `${childKind(p.kind ?? child?.kind ?? "task")} #${p.task} answered (${Math.round((p.stats?.ms ?? 0) / 100) / 10} s${n ? `, ${n} tool call${n === 1 ? "" : "s"}` : ""})` : `${childKind(p.kind ?? child?.kind ?? "task")} #${p.task} ${p.status}: ${p.error ?? ""}`;
2958
+ this.button(tab, `${indent}${p.status === "done" ? c.green("✓") : c.red("✗")} ${c.bold(p.agent)} ${c.gray(how)} ${open}`, () => void this.openTask(p.task));
2959
+ break;
2960
+ }
2961
+ tab.running.delete(p.task);
2962
+ tab.thinking = false;
2963
+ this.takeStats(tab, p.stats);
2964
+ // What the turn left running is said at once, not at the next look.
2965
+ if (tab === this.active)
2966
+ void this.pollPrograms();
2967
+ if (p.status !== "cancelled" && !tab.running.size)
2968
+ this.attention(`pine: ${tab.agent} ${p.status === "done" ? "is done" : "stopped with an error"}`);
2969
+ if (p.status === "done") {
2970
+ // Streaming normally showed the answer already; this covers a missed stream.
2971
+ if (p.text)
2972
+ tab.lastAnswer = p.text;
2973
+ if (!block && !tab.streamed.get(p.task) && p.text) {
2974
+ this.add(tab, new Answer(p.text));
2975
+ this.answerPictures(tab, p.agent, p.text);
2976
+ }
2977
+ }
2978
+ else if (p.status === "cancelled")
2979
+ this.say(tab, c.gray("■ stopped"));
2980
+ else
2981
+ this.say(tab, c.red(`✗ ${p.status}${p.error && p.error !== p.status ? `: ${p.error}` : ""}`));
2982
+ tab.streamed.delete(p.task);
2983
+ if (tab.kind === "task")
2984
+ this.say(tab, c.gray(this.taskSummary(p.status, p.stats)));
2985
+ else
2986
+ void this.refreshTaints();
2987
+ break;
2988
+ }
2989
+ }
2990
+ // A tool that finished may have changed files, and a finished task has new output to show.
2991
+ if (this.codeOpen && tab === this.active && ((kind === "tool" && p.phase !== "start") || kind === "done" || kind === "failed"))
2992
+ this.code.touch();
2993
+ if (tab !== this.active)
2994
+ tab.unread = true;
2995
+ this.tui.requestRender();
2996
+ }
2997
+ logEvent(e) {
2998
+ const tab = this.tabs.find((t) => t.kind === "events");
2999
+ if (!tab?.log || /\/(delta|thinking|message)$/.test(e.topic))
3000
+ return;
3001
+ const time = new Date(e.ts).toLocaleTimeString("sv-SE");
3002
+ tab.lines.push(`${c.gray(time)} ${(e.trust === "owner" ? c.green : c.gray)(e.trust === "owner" ? "owner" : "other")} ${c.bold(e.topic)} ${c.gray(short(JSON.stringify(e.payload ?? null), 160))}`);
3003
+ if (tab.lines.length > 400)
3004
+ tab.lines.splice(0, tab.lines.length - 400);
3005
+ tab.log.setText(tab.lines.join("\n"));
3006
+ if (tab === this.active)
3007
+ this.tui.requestRender();
3008
+ }
3009
+ /** Ask again which conversations of the agents on screen are pinned. */
3010
+ async refreshPins() {
3011
+ const agents = [...new Set(this.tabs.filter((t) => t.kind === "chat").map((t) => t.agent))];
3012
+ const lists = await Promise.all(agents.map((a) => this.client.sessions(a).then((l) => l.filter((x) => x.pinned).map((x) => `${a}:${x.session}`)).catch(() => undefined)));
3013
+ // An agent that could not be asked keeps the marks it had.
3014
+ const next = new Set([...this.pins].filter((k) => lists.some((l, i) => l === undefined && k.startsWith(`${agents[i]}:`))));
3015
+ for (const l of lists)
3016
+ for (const k of l ?? [])
3017
+ next.add(k);
3018
+ this.pins = next;
3019
+ this.tui.requestRender();
3020
+ }
3021
+ async refreshTaints() {
3022
+ try {
3023
+ const s = await this.client.status();
3024
+ this.taints.clear();
3025
+ this.sessionModes.clear();
3026
+ this.bypassWhenTainted = s.bypassWhenTainted === true;
3027
+ for (const x of s.sessions) {
3028
+ const open = this.tabs.find((t) => t.kind === "chat" && t.agent === x.agent && t.session === x.session);
3029
+ if (open && x.context?.percent !== undefined)
3030
+ open.context = x.context.percent;
3031
+ if (x.tainted)
3032
+ this.taints.set(`${x.agent}:${x.session}`, x.tainted);
3033
+ this.sessionModes.set(`${x.agent}:${x.session}`, x.mode);
3034
+ }
3035
+ for (const [id, mode] of Object.entries(s.modes ?? {})) {
3036
+ const info = this.agents.find((a) => a.id === id);
3037
+ if (info)
3038
+ info.mode = mode;
3039
+ }
3040
+ // Bypass that stopped applying must not go unnoticed.
3041
+ for (const t of this.tabs) {
3042
+ if (t.kind !== "chat" || t.pauseNoted || !this.bypassPaused(t))
3043
+ continue;
3044
+ t.pauseNoted = true;
3045
+ this.say(t, c.yellow(`bypass is paused in this conversation: it has read outside content (${this.taints.get(`${t.agent}:${t.session}`)}).\n`) + c.gray("The agent is back inside its sandbox and asks before sending things out. /mode bypass offers a clean conversation or bypass here anyway; /reset starts over."));
3046
+ }
3047
+ this.tui.requestRender();
3048
+ }
3049
+ catch {
3050
+ // The footer just keeps its last state.
3051
+ }
3052
+ }
3053
+ bypassPaused(t) {
3054
+ const info = this.agents.find((a) => a.id === t.agent);
3055
+ return info?.mode === "bypass" && this.sessionModes.get(`${t.agent}:${t.session}`) === "auto";
3056
+ }
3057
+ // ---- chrome ----------------------------------------------------------------------------------
3058
+ renderHeader(width) {
3059
+ const line = new Line().add(c.bold(c.accent(" pine ")));
3060
+ this.tabs.forEach((t, i) => {
3061
+ const name = t.kind === "events" ? "events" : t.kind === "task" ? `${t.agent}↳#${t.task}` : t.session === "main" ? t.agent : `${t.agent}·${t.session}`;
3062
+ // A question that waits comes first: its task is still running, and a spinner would hide that it waits for the owner.
3063
+ const mark = t.approvals.size ? c.yellow("!") : t.running.size ? c.yellow(SPINNER[this.frame % SPINNER.length]) : t.unread ? c.accent("•") : " ";
3064
+ // A pinned conversation has the mark it has in the list of conversations.
3065
+ const star = t.kind === "chat" && this.pins.has(`${t.agent}:${t.session}`) ? "★ " : "";
3066
+ const label = ` ${i + 1} ${star}${short(name, 22)} `;
3067
+ line.add(t === this.active ? c.bgAccent(label) : c.gray(label), () => this.activate(t));
3068
+ line.add(t === this.active ? c.bgAccent("×") : c.gray("×"), () => this.closeTab(t));
3069
+ line.add(`${mark} `);
3070
+ });
3071
+ line.add(c.gray(" + "), () => void this.run("new"));
3072
+ // At the right edge, and always in view however many tabs there are: the button of the code pane.
3073
+ const right = new Line().add(this.connected ? "" : c.red(" reconnecting… "));
3074
+ if (this.active.kind === "chat")
3075
+ right.add(this.codeOpen ? c.bgAccent(" ▤ code ") : c.gray(" ▤ code "), () => this.showCode(!this.codeOpen));
3076
+ const room = Math.max(0, width - right.width);
3077
+ const at = Math.max(0, width - right.width);
3078
+ this.headerHits = [...line.hits.filter((h) => h.from < room).map((h) => ({ ...h, to: Math.min(h.to, room) })), ...right.hits.map((h) => ({ ...h, from: h.from + at, to: h.to + at }))];
3079
+ const left = truncateToWidth(line.text, room);
3080
+ return [truncateToWidth(left + " ".repeat(Math.max(0, room - visibleWidth(left))) + right.text, width), c.gray("─".repeat(width))];
3081
+ }
3082
+ renderAttachments(width) {
3083
+ const t = this.active;
3084
+ if (!t.attachments.length)
3085
+ return (this.attachHits = []), [];
3086
+ const kb = (n) => (n < 1024 * 1024 ? `${Math.max(1, Math.round(n / 1024))} KB` : `${(n / 1024 / 1024).toFixed(1)} MB`);
3087
+ const line = new Line().add(c.gray(" attached: "));
3088
+ t.attachments.forEach((a, i) => {
3089
+ line.add(`${c.bold(short(a.name, 28))} ${c.gray(kb(a.size))} `);
3090
+ line.add(c.gray("× "), () => {
3091
+ t.attachments.splice(i, 1);
3092
+ this.tui.requestRender();
3093
+ });
3094
+ line.add(" ");
3095
+ });
3096
+ this.attachHits = line.hits;
3097
+ return [truncateToWidth(line.text, width)];
3098
+ }
3099
+ renderStatus(width) {
3100
+ const t = this.active;
3101
+ let line = "";
3102
+ if (this.notice)
3103
+ line = c.yellow(this.notice);
3104
+ else if (this.voice) {
3105
+ const v = this.voice;
3106
+ line = v.fetching
3107
+ ? c.yellow("● the system is fetching its speech model for this language (once) …")
3108
+ : v.state === "starting"
3109
+ ? c.gray("● getting ready to listen …")
3110
+ : v.state === "finishing"
3111
+ ? c.gray("● finishing what was heard …")
3112
+ : `${c.red("●")} ${c.gray("listening · speak · enter when you are done · esc to throw it away")}`;
3113
+ }
3114
+ else if (t.approvals.size)
3115
+ line = c.yellow("waiting for your approval · enter opens the question · /approve or /deny");
3116
+ // A question in a tab that is not in front has no dialog here. Unanswered it counts as a no, so every tab says where it waits.
3117
+ else if (this.tabs.some((x) => x.approvals.size)) {
3118
+ const n = this.tabs.findIndex((x) => x.approvals.size);
3119
+ line = c.yellow(`tab ${n + 1} (${this.tabs[n].agent}${this.tabs[n].kind === "chat" && this.tabs[n].session !== "main" ? `·${this.tabs[n].session}` : ""}) is waiting for your approval · alt+${n + 1} goes there`);
3120
+ }
3121
+ else if (t.running.size) {
3122
+ const secs = Math.max(0, Math.round((Date.now() - t.startedAt) / 1000));
3123
+ const helpers = [...t.children.values()].filter((x) => x.running).length;
3124
+ const steps = t.todo?.items.length ? [`step ${Math.min(t.todo.items.length, t.todo.items.filter((x) => x.status === "done").length + 1)} of ${t.todo.items.length}`] : [];
3125
+ const parts = [t.thinking ? "thinking" : "working", `${secs}s`, ...steps, ...(t.toolCalls ? [`${t.toolCalls} tool call${t.toolCalls === 1 ? "" : "s"}`] : []), ...(helpers ? [`${helpers} sub-task${helpers === 1 ? "" : "s"} running`] : []), ...(t.tokens.output ? [`${t.tokens.input + t.tokens.cached}↑${t.tokens.cached ? ` (${Math.round((100 * t.tokens.cached) / (t.tokens.input + t.tokens.cached))}% cached)` : ""} ${t.tokens.output}↓`] : []), ...(speedText(t.speed) ? [speedText(t.speed)] : []), "esc to stop"];
3126
+ // A goal: which round this is, so that work that goes on by itself is seen to.
3127
+ if (t.goal?.status === "active")
3128
+ parts.unshift(`goal · round ${t.goal.round} of ${t.goal.until}`);
3129
+ line = `${c.yellow(SPINNER[this.frame % SPINNER.length])} ${c.gray(parts.join(" · "))}`;
3130
+ }
3131
+ else if (t.goal?.status === "active")
3132
+ line = c.gray(`◎ goal · round ${t.goal.round} of ${t.goal.until} · checking whether it is met · esc to pause`);
3133
+ // The agent's turn is over, and a command of its goes on: without a word that looks like a hang.
3134
+ else if (t.left?.list.length) {
3135
+ const background = t.left.list.filter((p) => p.background);
3136
+ const one = background[0] ?? t.left.list[0];
3137
+ const secs = one.seconds + Math.round((Date.now() - t.left.at) / 1000);
3138
+ const what = short(oneLine(one.command), 46);
3139
+ line = background.length
3140
+ ? `${c.yellow("●")} ${c.gray(`${background.length === 1 ? "a command runs" : `${background.length} commands run`} in the background: ${what} · ${elapsed(secs)} · ${t.agent} is told when it ends`)}`
3141
+ : `${c.yellow("●")} ${c.gray(`${t.left.list.length === 1 ? "a program is" : `${t.left.list.length} programs are`} still running: ${what} · ${elapsed(secs)} · /code running lists ${t.left.list.length === 1 ? "it" : "them"}`)}`;
3142
+ }
3143
+ return [truncateToWidth(` ${line}`, width)];
3144
+ }
3145
+ renderFooter(width) {
3146
+ const t = this.active;
3147
+ if (t.kind !== "chat")
3148
+ return (this.footerHits = []), [truncateToWidth(c.gray(t.kind === "task" ? ` task #${t.task} of ${t.agent} · read-only · ctrl+w closes this tab` : " live events"), width)];
3149
+ const info = this.agents.find((a) => a.id === t.agent);
3150
+ const taint = this.taints.get(`${t.agent}:${t.session}`);
3151
+ const mode = info?.mode ?? "auto";
3152
+ const modeText = `${mode}${this.bypassPaused(t) ? " (paused)" : ""}`;
3153
+ // Each part opens its list on a click: agent, conversation, model, mode.
3154
+ const line = new Line()
3155
+ .add(" ")
3156
+ .add(c.bold(t.agent), () => void this.pickAgent())
3157
+ .add(c.gray(" · "))
3158
+ .add(c.gray(t.session), () => void this.pickSession())
3159
+ .add(c.gray(" · "))
3160
+ .add(t.folder ? c.cyan(short(tilde(t.folder), 34)) : c.gray("no folder"), () => void this.pickFolder())
3161
+ .add(c.gray(" · "))
3162
+ .add(c.gray(info?.model ?? ""), () => void this.pickModel())
3163
+ .add(c.gray(" · "))
3164
+ .add(c.gray(`reasoning ${info?.thinking ?? "off"}`), () => void this.pickReasoning())
3165
+ .add(c.gray(" · "))
3166
+ .add(mode === "bypass" ? c.red(modeText) : mode === "manual" ? c.cyan(modeText) : mode === "plan" ? c.magenta(modeText) : mode === "safe" ? c.green(modeText) : c.gray(modeText), () => void this.pickMode());
3167
+ // How full the context window is. pi compacts the conversation by itself when it gets close to full.
3168
+ if (t.context !== undefined)
3169
+ line.add(c.gray(" · ")).add((t.context >= 85 ? c.red : t.context >= 65 ? c.yellow : c.gray)(`context ${t.context}%`));
3170
+ // How much of the last request the model server took from its cache. Low figures on a local model mean slow turns.
3171
+ if (t.cacheShare !== undefined)
3172
+ line.add(c.gray(" · ")).add((t.cacheShare < 50 ? c.yellow : c.gray)(`cache ${t.cacheShare}%`));
3173
+ // How fast the model read and wrote in the last task: what stays to be seen when the work is done.
3174
+ if (speedText(t.speed))
3175
+ line.add(c.gray(" · ")).add(c.gray(speedText(t.speed)));
3176
+ if (taint)
3177
+ line.add(c.yellow(" · outside content"));
3178
+ this.footerHits = line.hits;
3179
+ const right = c.gray("/help ");
3180
+ const gap = Math.max(1, width - line.width - visibleWidth(right));
3181
+ return [truncateToWidth(line.text + " ".repeat(gap) + right, width)];
3182
+ }
3183
+ }
3184
+ /** The system's own window for choosing a folder. Resolves with nothing when it is closed without a choice, or where there is none. */
3185
+ function chooseFolder() {
3186
+ if (process.platform !== "darwin")
3187
+ return Promise.resolve(undefined);
3188
+ return new Promise((resolve) => {
3189
+ const child = spawn("/usr/bin/osascript", ["-e", 'POSIX path of (choose folder with prompt "A folder for this conversation")'], { stdio: ["ignore", "pipe", "ignore"] });
3190
+ let out = "";
3191
+ child.stdout.on("data", (d) => (out += d));
3192
+ child.on("error", () => resolve(undefined));
3193
+ child.on("close", (code) => resolve(code === 0 && out.trim() ? out.trim() : undefined));
3194
+ });
3195
+ }