@pmndre/pine 0.22.1 → 0.33.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 (99) hide show
  1. package/README.md +2 -1
  2. package/changes.json +264 -0
  3. package/docs/SKILL.md +31 -7
  4. package/docs/references/agents.md +245 -21
  5. package/docs/references/coding.md +1 -1
  6. package/docs/references/computer.md +1 -1
  7. package/docs/references/configuration.md +14 -5
  8. package/docs/references/mcp.md +9 -0
  9. package/docs/references/operations.md +21 -10
  10. package/docs/references/overview.md +3 -1
  11. package/docs/references/security.md +83 -24
  12. package/docs/references/setup.md +55 -9
  13. package/docs/references/source-types.md +1418 -0
  14. package/docs/references/sources.md +333 -19
  15. package/docs/references/stack.md +1 -0
  16. package/docs/references/tui.md +86 -12
  17. package/examples/home/AGENTS.md +4 -0
  18. package/examples/home/TOOLS.md +5 -0
  19. package/examples/home/agents/main/workspace/AGENTS.md +1 -1
  20. package/examples/home/agents/main/workspace/TOOLS.md +5 -0
  21. package/mcp/browser.d.ts +6 -0
  22. package/mcp/browser.js +19 -0
  23. package/mcp/render.d.ts +1 -0
  24. package/mcp/render.js +237 -0
  25. package/package.json +6 -4
  26. package/src/actions.d.ts +6 -1
  27. package/src/actions.js +17 -4
  28. package/src/admin.d.ts +4 -0
  29. package/src/admin.js +25 -6
  30. package/src/agents.d.ts +167 -2
  31. package/src/agents.js +912 -45
  32. package/src/catalogue.d.ts +60 -0
  33. package/src/catalogue.js +791 -0
  34. package/src/cli.js +10 -7
  35. package/src/config.d.ts +53 -4
  36. package/src/config.js +30 -5
  37. package/src/goals.d.ts +1 -1
  38. package/src/goals.js +14 -1
  39. package/src/manual.js +24 -2
  40. package/src/mime.d.ts +78 -0
  41. package/src/mime.js +342 -0
  42. package/src/net.d.ts +11 -0
  43. package/src/net.js +29 -2
  44. package/src/pine.js +10 -1
  45. package/src/router.js +3 -3
  46. package/src/sandbox-linux.d.ts +3 -1
  47. package/src/sandbox-linux.js +5 -0
  48. package/src/security.d.ts +22 -6
  49. package/src/security.js +44 -13
  50. package/src/slots.d.ts +106 -0
  51. package/src/slots.js +250 -0
  52. package/src/source-types.d.ts +20 -0
  53. package/src/sources/calendar.d.ts +24 -0
  54. package/src/sources/calendar.js +265 -0
  55. package/src/sources/command.js +109 -4
  56. package/src/sources/discord.d.ts +4 -0
  57. package/src/sources/discord.js +298 -0
  58. package/src/sources/feed.d.ts +19 -0
  59. package/src/sources/feed.js +257 -0
  60. package/src/sources/http.js +154 -103
  61. package/src/sources/mail.d.ts +51 -0
  62. package/src/sources/mail.js +1013 -0
  63. package/src/sources/matrix.d.ts +4 -0
  64. package/src/sources/matrix.js +232 -0
  65. package/src/sources/modbus.d.ts +15 -0
  66. package/src/sources/modbus.js +240 -0
  67. package/src/sources/onvif.d.ts +35 -0
  68. package/src/sources/onvif.js +326 -0
  69. package/src/sources/presence.d.ts +80 -0
  70. package/src/sources/presence.js +480 -0
  71. package/src/sources/serial.d.ts +21 -0
  72. package/src/sources/serial.js +220 -0
  73. package/src/sources/slack.d.ts +16 -0
  74. package/src/sources/slack.js +1062 -0
  75. package/src/sources/smtp.d.ts +4 -0
  76. package/src/sources/smtp.js +360 -0
  77. package/src/sources/stream.d.ts +68 -0
  78. package/src/sources/stream.js +534 -0
  79. package/src/sources/syslog.d.ts +32 -0
  80. package/src/sources/syslog.js +243 -0
  81. package/src/sources/system.d.ts +14 -0
  82. package/src/sources/system.js +236 -0
  83. package/src/sources/system.swift +102 -0
  84. package/src/sources/telegram.js +34 -1
  85. package/src/sources.d.ts +41 -1
  86. package/src/sources.js +147 -24
  87. package/src/tools.d.ts +1 -1
  88. package/src/tools.js +304 -23
  89. package/src/tui/app.d.ts +35 -2
  90. package/src/tui/app.js +306 -43
  91. package/src/tui/levels.d.ts +68 -0
  92. package/src/tui/levels.js +273 -0
  93. package/src/tui/picture.d.ts +17 -1
  94. package/src/tui/picture.js +72 -5
  95. package/src/types.d.ts +3 -0
  96. package/src/update.d.ts +9 -1
  97. package/src/update.js +75 -3
  98. package/src/watching.d.ts +156 -0
  99. package/src/watching.js +609 -4
package/src/tui/app.d.ts CHANGED
@@ -113,6 +113,8 @@ export declare class PineTui {
113
113
  private dialog?;
114
114
  /** When a menu or question last closed. A key that closed it is not also a key for what lies under it. */
115
115
  private dialogClosedAt;
116
+ /** The requests whose dialog was opened once. One that arrived while another dialog was open is not among them, and is asked when that one is gone. */
117
+ private asked;
116
118
  /** Videos fetched from the daemon, as files for ffmpeg and the player. Removed when the UI closes. */
117
119
  private mediaDir?;
118
120
  private mediaCount;
@@ -146,7 +148,8 @@ export declare class PineTui {
146
148
  /** What is on screen, without colours. For tests and debugging. */
147
149
  screen(): string[];
148
150
  private newTab;
149
- openTab(agent: string, session: string): Promise<void>;
151
+ /** `front: false` opens it behind the tab the owner is in, marked as having something new. */
152
+ openTab(agent: string, session: string, front?: boolean): Promise<void>;
150
153
  /**
151
154
  * Open a tab on one task, typically a sub-agent: what it was given, what it thought and wrote,
152
155
  * every tool call with the start of its result. A running task is followed live.
@@ -176,10 +179,27 @@ export declare class PineTui {
176
179
  openFolder(dir: string): Promise<void>;
177
180
  private add;
178
181
  private say;
179
- /** A place for what a model thinks. Opening and closing it keeps it in the window. */
182
+ /** A place for what a model thinks. In a conversation it is part of the turn's work. */
180
183
  private thought;
184
+ /** Something in the conversation was opened or closed with a click: it stays in the window. */
185
+ private keepInView;
181
186
  /** The row of the conversation at which a component begins; without one, how many rows there are. */
182
187
  private rowOf;
188
+ /**
189
+ * The work of the turn that is going on in a conversation. It is one block for as long as
190
+ * nothing else comes in between; after a question to the owner, a message, a picture, what
191
+ * follows is a block of its own, so that everything stays in the order it happened.
192
+ */
193
+ private work;
194
+ /**
195
+ * Show something an agent did on the way to its answer. In a conversation it joins the turn's
196
+ * work; a tab on one task is there to show that task's work, and shows each thing by itself.
197
+ */
198
+ private did;
199
+ /** A task goes on working after it wrote something: those words were not its answer, and join the work. */
200
+ private foldWords;
201
+ /** The turn is over: its work becomes one line, unless somebody opened it. */
202
+ private endWork;
183
203
  /** A task's model stopped thinking: what it thought is closed, or stays open if somebody opened it. */
184
204
  private endThought;
185
205
  /** Ask what the commands of the conversation in front left running. Quietly: a daemon that does not answer changes nothing. */
@@ -278,6 +298,13 @@ export declare class PineTui {
278
298
  private run;
279
299
  private help;
280
300
  private ask;
301
+ /**
302
+ * Requests can be open side by side: a tool that asks from inside itself (remove_source) does so
303
+ * while its neighbours of the same step run, and one can arrive while a menu is open. Only one
304
+ * dialog fits, so the others have just their line in the conversation. Each of them gets its
305
+ * dialog when the one before it is gone. One that was put off is not asked again by itself.
306
+ */
307
+ private askNext;
281
308
  /** Forget the questions the daemon no longer has open: their cards say so, and a dialog for one closes. */
282
309
  private dropAnswered;
283
310
  private closeDialog;
@@ -287,6 +314,12 @@ export declare class PineTui {
287
314
  /** One line on where a goal stands, with the judge's reason under it; `full` adds the objective. */
288
315
  private goalLine;
289
316
  /** The daemon reports on a goal: it was set, a round was judged, it stopped or was cleared. */
317
+ /**
318
+ * A conversation was changed by another hand than this UI's: the main agent opened or closed a
319
+ * tab, gave a conversation another name, removed one or pinned it. The tabs follow. A tab that
320
+ * is opened this way never takes the place of the one the owner is in.
321
+ */
322
+ private followed;
290
323
  private goalEvent;
291
324
  /** /goal: show it, set it, or pause, resume or clear it. All of it is the daemon's doing. */
292
325
  private goal;
package/src/tui/app.js CHANGED
@@ -3,7 +3,7 @@ import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { CombinedAutocompleteProvider, Container, Editor, isKeyRelease, isKeyRepeat, matchesKey, fuzzyFilter, getCapabilities, HStack, hyperlink, ScrollView, setCapabilities, sliceByColumn, SelectList, Spacer, stripTerminalSequences, Text, truncateToWidth, TuiAltScreen, visibleWidth, VStack, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
6
- import { errText, expandHome, openInSystem, speedOf, speedText } from "../util.js";
6
+ import { errText, expandHome, openInSystem, safeName, speedOf, speedText } from "../util.js";
7
7
  import { Listening, voiceTools } from "./voice.js";
8
8
  import { CodePane, PANE_VIEWS } from "./code-pane.js";
9
9
  import { redoText, undoText } from "./undo.js";
@@ -47,7 +47,10 @@ class Split extends HStack {
47
47
  */
48
48
  class Doc extends Container {
49
49
  asText = () => false;
50
+ /** The width it was last drawn at, for working out where something lies in it. */
51
+ width = 80;
50
52
  render(width) {
53
+ this.width = width;
51
54
  const lines = super.render(width);
52
55
  return this.asText() ? picturesAsText(lines, () => true) : lines;
53
56
  }
@@ -324,13 +327,15 @@ class WithMicrophone {
324
327
  shown;
325
328
  listening;
326
329
  click;
330
+ focus;
327
331
  /** Where the microphone begins in the line, when it is drawn. */
328
332
  at = 0;
329
- constructor(inner, shown, listening, click) {
333
+ constructor(inner, shown, listening, click, focus) {
330
334
  this.inner = inner;
331
335
  this.shown = shown;
332
336
  this.listening = listening;
333
337
  this.click = click;
338
+ this.focus = focus;
334
339
  }
335
340
  invalidate() {
336
341
  this.inner.invalidate();
@@ -357,7 +362,14 @@ class WithMicrophone {
357
362
  this.click();
358
363
  return { handled: true, render: true };
359
364
  }
360
- return this.inner.handleMouse?.(e);
365
+ const result = this.inner.handleMouse?.(e);
366
+ if (!result?.focus)
367
+ return result;
368
+ // A click into the input asks for the keys. The library would give them to whatever handed
369
+ // the click on, which is this, and this takes none: the input would seem frozen until
370
+ // something else gave it the keys back. So the input gets them here, by name.
371
+ this.focus();
372
+ return { ...result, focus: false, handled: true, render: true };
361
373
  }
362
374
  }
363
375
  /** How many lines of a thought are shown while it is being thought. */
@@ -370,8 +382,6 @@ const PEEK = 4;
370
382
  class Thought {
371
383
  open = false;
372
384
  done = false;
373
- /** The width it was last drawn at, for working out where it lies in the conversation. */
374
- width = 80;
375
385
  text = "";
376
386
  started = Date.now();
377
387
  ms;
@@ -405,7 +415,6 @@ class Thought {
405
415
  return this.wrapped.lines;
406
416
  }
407
417
  render(width) {
408
- this.width = width;
409
418
  const all = this.lines(width);
410
419
  const secs = Math.max(1, Math.round((this.done ? (this.ms ?? 0) : Date.now() - this.started) / 1000));
411
420
  const took = secs < 60 ? `${secs}s` : `${Math.floor(secs / 60)}m ${secs % 60}s`;
@@ -426,6 +435,130 @@ class Thought {
426
435
  return { handled: true, render: true };
427
436
  }
428
437
  }
438
+ /** How many lines of a turn's work are shown while the agent is at it. */
439
+ const TAIL = 6;
440
+ /** How many tools the first line of a turn's work names. */
441
+ const KINDS = 3;
442
+ /**
443
+ * What an agent did between a message and its answer: tool calls, thoughts, words in between,
444
+ * what its sub-tasks report. While it works, the last few lines are shown under one line that says
445
+ * what there is so far. When the turn is over that one line is left, and a click on it opens all
446
+ * of it, as it was. A single call or thought is shown as it is: one line standing for one line
447
+ * helps nobody.
448
+ */
449
+ class Work {
450
+ open = false;
451
+ done = false;
452
+ parts = [];
453
+ started = Date.now();
454
+ ms = 0;
455
+ toggled;
456
+ rows = [];
457
+ constructor(toggled) {
458
+ this.toggled = toggled;
459
+ }
460
+ add(part) {
461
+ this.parts.push(part);
462
+ return part;
463
+ }
464
+ /** The turn is over, or something else came after this work. */
465
+ finish() {
466
+ if (this.done)
467
+ return;
468
+ this.done = true;
469
+ this.ms = Date.now() - this.started;
470
+ }
471
+ invalidate() {
472
+ for (const p of this.parts)
473
+ p.component.invalidate();
474
+ }
475
+ /** All of it is shown: somebody opened it, or opened a thought in it, which a few last lines would cut off. */
476
+ shown() {
477
+ return this.open || this.parts.some((p) => p.thought?.open);
478
+ }
479
+ /** Open it, or close it and with it what was opened inside. */
480
+ toggle() {
481
+ this.open = !this.shown();
482
+ if (!this.open)
483
+ for (const p of this.parts)
484
+ if (p.thought)
485
+ p.thought.open = false;
486
+ this.toggled(this);
487
+ }
488
+ /** The first line: how many tool calls, of which tools, how many thoughts, what failed, how long it took. */
489
+ head() {
490
+ const calls = this.parts.filter((p) => p.tool);
491
+ const tools = new Map();
492
+ for (const p of calls)
493
+ tools.set(p.tool, (tools.get(p.tool) ?? 0) + 1);
494
+ const sorted = [...tools].sort((a, b) => b[1] - a[1]);
495
+ const thoughts = this.parts.filter((p) => p.thought).length;
496
+ const count = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
497
+ const what = [
498
+ ...(calls.length ? [count(calls.length, "tool call"), ...sorted.slice(0, KINDS).map(([tool, n]) => (n > 1 ? `${tool} ×${n}` : tool))] : []),
499
+ ...(sorted.length > KINDS ? [`+${sorted.length - KINDS} more`] : []),
500
+ ...(thoughts ? [count(thoughts, "thought")] : []),
501
+ ];
502
+ if (!this.done)
503
+ what[0] = `${what[0] ?? "working"} so far`;
504
+ const failed = calls.filter((p) => p.failed).length;
505
+ const secs = Math.max(1, Math.round(this.ms / 1000));
506
+ const took = this.done ? ` · ${secs < 60 ? `${secs}s` : `${Math.floor(secs / 60)}m ${secs % 60}s`}` : "";
507
+ const click = this.shown() ? "click here to close" : this.done ? "click to open" : "click to see all";
508
+ return ` ${c.gray(`${this.shown() ? "▾" : "▸"} ${what.join(" · ")}`)}${failed ? `${c.gray(" · ")}${c.red(`${failed} failed`)}` : ""}${c.gray(`${took} · ${click}`)}`;
509
+ }
510
+ render(width) {
511
+ const out = [];
512
+ const rows = [];
513
+ const put = (line, row) => (out.push(line), rows.push(row));
514
+ const all = (part) => part.component.render(width).map((line, y, lines) => ({ line, row: { part, y, height: lines.length } }));
515
+ this.rows = rows;
516
+ if (this.parts.length < 2) {
517
+ for (const l of this.parts.flatMap(all))
518
+ put(l.line, l.row);
519
+ return out;
520
+ }
521
+ put(truncateToWidth(this.head(), width), "toggle");
522
+ if (this.shown()) {
523
+ this.parts.forEach((part, i) => {
524
+ // Words are set apart from the lines around them, as they are in the conversation.
525
+ if (i && (part.brief || this.parts[i - 1].brief))
526
+ put("", undefined);
527
+ for (const l of all(part))
528
+ put(l.line, l.row);
529
+ });
530
+ if (out.length > TAIL + 1)
531
+ put(` ${c.gray("▴ close")}`, "toggle");
532
+ }
533
+ else if (!this.done) {
534
+ const lines = this.parts.flatMap((part) => (part.brief ? [{ line: truncateToWidth(` ${c.gray(part.brief())}`, width), row: "toggle" }] : all(part)));
535
+ const tail = lines.slice(-TAIL);
536
+ // Not from the middle of something: a failed call's error without the call says little.
537
+ const whole = tail.findIndex((l) => l.row === "toggle" || !l.row || l.row.y === 0);
538
+ for (const l of tail.slice(Math.max(0, whole)))
539
+ put(l.line, l.row);
540
+ }
541
+ return out;
542
+ }
543
+ /** The line at which something inside begins, as it is drawn at this width; nothing if it is not in view. */
544
+ rowOf(inner, width) {
545
+ this.render(width);
546
+ const at = this.rows.findIndex((r) => r && r !== "toggle" && (r.part.component === inner || (r.part.component instanceof Linked && r.part.component.inner === inner)));
547
+ return at < 0 ? undefined : at;
548
+ }
549
+ handleMouse(e) {
550
+ const row = this.rows[e.y];
551
+ if (!row)
552
+ return undefined; // an empty line: left to text selection
553
+ if (row !== "toggle")
554
+ return row.part.component.handleMouse?.({ ...e, y: row.y, height: row.height });
555
+ if (e.button !== "left" || (e.type !== "press" && e.type !== "click" && e.type !== "release"))
556
+ return undefined;
557
+ if (e.type === "click")
558
+ this.toggle();
559
+ return { handled: true, render: true };
560
+ }
561
+ }
429
562
  const SCOPES = ["local", "agent", "global"];
430
563
  const SCOPE_HELP = { local: "only this conversation, until it is closed", agent: "the agent, in its main conversation", global: "every agent" };
431
564
  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" };
@@ -920,6 +1053,8 @@ export class PineTui {
920
1053
  dialog;
921
1054
  /** When a menu or question last closed. A key that closed it is not also a key for what lies under it. */
922
1055
  dialogClosedAt = 0;
1056
+ /** The requests whose dialog was opened once. One that arrived while another dialog was open is not among them, and is asked when that one is gone. */
1057
+ asked = new Set();
923
1058
  /** Videos fetched from the daemon, as files for ffmpeg and the player. Removed when the UI closes. */
924
1059
  mediaDir;
925
1060
  mediaCount = 0;
@@ -964,7 +1099,7 @@ export class PineTui {
964
1099
  this.dock = new VStack([
965
1100
  { component: this.status, shrink: 1, minSize: 0 },
966
1101
  { 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 },
1102
+ { component: new WithMicrophone(this.editor, () => this.active?.kind === "chat" && this.canListen(), () => this.voice !== undefined, () => void this.dictate(), () => this.tui.setFocus(this.editor)), shrink: 1, minSize: 3 },
968
1103
  { component: this.footer, shrink: 1, minSize: 0 },
969
1104
  ]);
970
1105
  this.code = new CodePane({
@@ -1101,16 +1236,20 @@ export class PineTui {
1101
1236
  this.tabs.push(tab);
1102
1237
  return tab;
1103
1238
  }
1104
- async openTab(agent, session) {
1239
+ /** `front: false` opens it behind the tab the owner is in, marked as having something new. */
1240
+ async openTab(agent, session, front = true) {
1105
1241
  const existing = this.tabs.find((t) => t.kind === "chat" && t.agent === agent && t.session === session);
1106
1242
  if (existing)
1107
- return this.activate(existing);
1243
+ return front ? this.activate(existing) : undefined;
1108
1244
  if (!this.agents.some((a) => a.id === agent))
1109
1245
  this.agents = await this.client.agents().catch(() => this.agents);
1110
1246
  if (!this.agents.some((a) => a.id === agent))
1111
1247
  return this.flash(`there is no agent called ${agent}`);
1112
1248
  const tab = this.newTab("chat", agent, session);
1113
- this.activate(tab);
1249
+ if (front)
1250
+ this.activate(tab);
1251
+ else
1252
+ tab.unread = true;
1114
1253
  this.saveTabs();
1115
1254
  void this.refreshPins();
1116
1255
  const info = this.agents.find((a) => a.id === agent);
@@ -1359,42 +1498,94 @@ export class PineTui {
1359
1498
  this.add(tab, t, gap);
1360
1499
  return t;
1361
1500
  }
1362
- /** A place for what a model thinks. Opening and closing it keeps it in the window. */
1501
+ /** A place for what a model thinks. In a conversation it is part of the turn's work. */
1363
1502
  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);
1503
+ const thought = new Thought((t) => this.keepInView(tab, t, t.open));
1504
+ this.did(tab, thought, { thought }, true);
1381
1505
  return thought;
1382
1506
  }
1507
+ /** Something in the conversation was opened or closed with a click: it stays in the window. */
1508
+ keepInView(tab, what, open) {
1509
+ const scroll = tab.scroll;
1510
+ if (open) {
1511
+ // It grows downwards from its first line. A window that follows the end would run after
1512
+ // the end and take that line out of sight, so it stays where it is.
1513
+ if (scroll.isFollowingEnd && this.rowOf(tab) - scroll.viewportHeight > this.rowOf(tab, what))
1514
+ scroll.scrollTo(scroll.scrollTop, { disableFollow: true });
1515
+ }
1516
+ else {
1517
+ // Closed from far down in it: the one line that is left must not end up above the window.
1518
+ const top = this.rowOf(tab, what);
1519
+ if (top < scroll.scrollTop)
1520
+ scroll.scrollTo(top);
1521
+ }
1522
+ this.tui.requestRender();
1523
+ }
1383
1524
  /** The row of the conversation at which a component begins; without one, how many rows there are. */
1384
1525
  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;
1526
+ const width = tab.doc.width;
1390
1527
  let row = 0;
1391
1528
  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;
1529
+ if (inner) {
1530
+ if (child === inner || (child instanceof Linked && child.inner === inner))
1531
+ return row;
1532
+ const at = child instanceof Work ? child.rowOf(inner, width) : undefined;
1533
+ if (at !== undefined)
1534
+ return row + at;
1535
+ }
1536
+ row += child.render(width).length;
1395
1537
  }
1396
1538
  return row;
1397
1539
  }
1540
+ /**
1541
+ * The work of the turn that is going on in a conversation. It is one block for as long as
1542
+ * nothing else comes in between; after a question to the owner, a message, a picture, what
1543
+ * follows is a block of its own, so that everything stays in the order it happened.
1544
+ */
1545
+ work(tab) {
1546
+ if (tab.work && tab.doc.children.at(-1) === tab.work)
1547
+ return tab.work;
1548
+ tab.work?.finish();
1549
+ tab.work = new Work((w) => this.keepInView(tab, w, w.open));
1550
+ if (tab.doc.children.length)
1551
+ tab.doc.addChild(new Spacer(1));
1552
+ tab.doc.addChild(tab.work);
1553
+ if (tab !== this.active)
1554
+ tab.unread = true;
1555
+ return tab.work;
1556
+ }
1557
+ /**
1558
+ * Show something an agent did on the way to its answer. In a conversation it joins the turn's
1559
+ * work; a tab on one task is there to show that task's work, and shows each thing by itself.
1560
+ */
1561
+ did(tab, component, part = {}, gap = false) {
1562
+ if (tab.kind !== "chat")
1563
+ return void this.add(tab, component, gap);
1564
+ return this.work(tab).add({ component: new Linked(component), ...part });
1565
+ }
1566
+ /** A task goes on working after it wrote something: those words were not its answer, and join the work. */
1567
+ foldWords(tab, task) {
1568
+ const said = tab.said;
1569
+ if (tab.kind !== "chat" || said?.task !== task)
1570
+ return;
1571
+ tab.said = undefined;
1572
+ const shown = tab.doc.children;
1573
+ const last = shown.at(-1);
1574
+ // Only where nothing came after them: a picture they point at stays with them, in view.
1575
+ if (!(last instanceof Linked) || last.inner !== said.block.md)
1576
+ return;
1577
+ shown.pop();
1578
+ if (shown.at(-1) instanceof Spacer)
1579
+ shown.pop();
1580
+ // A model's text on one line: nothing in it may move the cursor or colour the screen.
1581
+ this.work(tab).add({ component: last, brief: () => short(oneLine(stripTerminalSequences(said.block.text).replace(/[\x00-\x1f\x7f]/g, " ")), 160) });
1582
+ }
1583
+ /** The turn is over: its work becomes one line, unless somebody opened it. */
1584
+ endWork(tab) {
1585
+ tab.work?.finish();
1586
+ tab.work = undefined;
1587
+ tab.said = undefined;
1588
+ }
1398
1589
  /** A task's model stopped thinking: what it thought is closed, or stays open if somebody opened it. */
1399
1590
  endThought(tab, task, ms) {
1400
1591
  const block = tab.thoughts.get(task);
@@ -1553,6 +1744,7 @@ export class PineTui {
1553
1744
  live.clear();
1554
1745
  tab.awaiting = [];
1555
1746
  tab.thinking = false;
1747
+ this.endWork(tab);
1556
1748
  const history = (await this.client.history(tab.agent, tab.session).catch(() => [])).filter((t) => t.depth === 0).reverse();
1557
1749
  if (history.length)
1558
1750
  this.say(tab, c.gray(`── earlier in this session (${history.length}) ──`));
@@ -2634,8 +2826,22 @@ export class PineTui {
2634
2826
  const handle = this.tui.showOverlay(dialog, { anchor: "center", width: "76%", minWidth: 40 });
2635
2827
  handle.focus();
2636
2828
  this.dialog = { id: req.id, handle, dismiss: () => this.closeDialog(), waits: true };
2829
+ this.asked.add(req.id);
2637
2830
  this.tui.requestRender();
2638
2831
  }
2832
+ /**
2833
+ * Requests can be open side by side: a tool that asks from inside itself (remove_source) does so
2834
+ * while its neighbours of the same step run, and one can arrive while a menu is open. Only one
2835
+ * dialog fits, so the others have just their line in the conversation. Each of them gets its
2836
+ * dialog when the one before it is gone. One that was put off is not asked again by itself.
2837
+ */
2838
+ askNext() {
2839
+ if (this.dialog || this.stopped)
2840
+ return;
2841
+ const next = [...this.active.approvals.values()].find((a) => !this.asked.has(a.req.id));
2842
+ if (next)
2843
+ this.ask(this.active, next.req);
2844
+ }
2639
2845
  /** Forget the questions the daemon no longer has open: their cards say so, and a dialog for one closes. */
2640
2846
  async dropAnswered() {
2641
2847
  const pending = await this.client.approvals().catch(() => undefined);
@@ -2648,6 +2854,7 @@ export class PineTui {
2648
2854
  continue;
2649
2855
  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
2856
  tab.approvals.delete(id);
2857
+ this.asked.delete(id);
2651
2858
  if (this.dialog?.id === id)
2652
2859
  this.closeDialog();
2653
2860
  }
@@ -2660,6 +2867,8 @@ export class PineTui {
2660
2867
  this.dialogClosedAt = Date.now();
2661
2868
  this.tui.setFocus(this.editor);
2662
2869
  this.tui.requestRender();
2870
+ // After what closed this one has run to its end: a menu that leads to another menu opens that one first.
2871
+ setImmediate(() => this.askNext());
2663
2872
  }
2664
2873
  async answer(args, allow) {
2665
2874
  const words = args.split(/\s+/).filter(Boolean);
@@ -2712,12 +2921,15 @@ export class PineTui {
2712
2921
  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
2922
  tab.approvals.delete(p.id);
2714
2923
  }
2924
+ this.asked.delete(p.id);
2715
2925
  if (this.dialog?.id === p.id)
2716
2926
  this.closeDialog();
2717
2927
  this.tui.requestRender();
2718
2928
  }
2719
2929
  return;
2720
2930
  }
2931
+ if (e.topic === "pine/conversation")
2932
+ return void this.followed(p);
2721
2933
  if (ns !== "agent")
2722
2934
  return;
2723
2935
  if (kind === "goal")
@@ -2806,6 +3018,46 @@ export class PineTui {
2806
3018
  return `${mark} ${c.bold("goal")} ${c.gray(g.note)}${more.map((m) => `\n${c.gray(` ${m}`)}`).join("")}`;
2807
3019
  }
2808
3020
  /** The daemon reports on a goal: it was set, a round was judged, it stopped or was cleared. */
3021
+ /**
3022
+ * A conversation was changed by another hand than this UI's: the main agent opened or closed a
3023
+ * tab, gave a conversation another name, removed one or pinned it. The tabs follow. A tab that
3024
+ * is opened this way never takes the place of the one the owner is in.
3025
+ */
3026
+ async followed(p) {
3027
+ const agent = String(p.agent ?? "");
3028
+ const key = (s) => safeName(s).replace(/^_+/, "") || "main";
3029
+ const showing = this.tabs.filter((t) => t.kind === "chat" && t.agent === agent && key(t.session) === key(String(p.session ?? "")));
3030
+ if (p.change === "open") {
3031
+ if (!showing.length)
3032
+ await this.openTab(agent, String(p.session ?? "main"), false);
3033
+ }
3034
+ else if (p.change === "close") {
3035
+ for (const t of showing)
3036
+ if (this.tabs.length > 1)
3037
+ this.closeTab(t);
3038
+ }
3039
+ else if (p.change === "rename" && typeof p.to === "string") {
3040
+ for (const t of showing)
3041
+ t.session = p.to;
3042
+ if (showing.length)
3043
+ this.saveTabs();
3044
+ void this.refreshPins();
3045
+ }
3046
+ else if (p.change === "remove") {
3047
+ // A tab that showed it has nothing left to show.
3048
+ for (const t of showing)
3049
+ this.tabs.splice(this.tabs.indexOf(t), 1);
3050
+ if (!this.tabs.length)
3051
+ await this.openTab(agent, "main");
3052
+ else if (showing.includes(this.active))
3053
+ this.activate(this.tabs[0]);
3054
+ if (showing.length)
3055
+ this.saveTabs();
3056
+ }
3057
+ else if (p.change === "pin")
3058
+ void this.refreshPins();
3059
+ this.tui.requestRender();
3060
+ }
2809
3061
  goalEvent(p) {
2810
3062
  for (const tab of this.tabs) {
2811
3063
  if (tab.kind !== "chat" || tab.agent !== p.agent || tab.session !== p.session)
@@ -2858,7 +3110,7 @@ export class PineTui {
2858
3110
  break;
2859
3111
  }
2860
3112
  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));
3113
+ this.did(tab, new Button(new Text(`${indent}${c.magenta("↳")} ${c.bold(p.agent)} ${c.gray(`${childKind(p.kind)} #${p.task}: ${short(oneLine(String(p.label ?? p.prompt ?? "")), 80)}`)} ${open}`, 1, 0), () => void this.openTask(p.task)));
2862
3114
  break;
2863
3115
  case "thinking": {
2864
3116
  if (p.phase === "end") {
@@ -2870,8 +3122,10 @@ export class PineTui {
2870
3122
  if (depth > 0 || !p.text)
2871
3123
  break; // a child's thoughts stay with the child, like its prose
2872
3124
  let thought = tab.thoughts.get(p.task);
2873
- if (!thought)
3125
+ if (!thought) {
3126
+ this.foldWords(tab, p.task);
2874
3127
  tab.thoughts.set(p.task, (thought = this.thought(tab)));
3128
+ }
2875
3129
  thought.append(p.text);
2876
3130
  break;
2877
3131
  }
@@ -2888,6 +3142,7 @@ export class PineTui {
2888
3142
  block = { md: new Answer(""), text: "" };
2889
3143
  tab.blocks.set(p.task, block);
2890
3144
  this.add(tab, block.md);
3145
+ tab.said = { task: p.task, block };
2891
3146
  }
2892
3147
  block.text += p.text;
2893
3148
  block.md.setText(block.text);
@@ -2926,7 +3181,10 @@ export class PineTui {
2926
3181
  const label = `${c.bold(p.tool)}${p.subject ? ` ${c.gray(short(oneLine(p.subject), 100))}` : ""}`;
2927
3182
  if (p.phase === "start") {
2928
3183
  tab.toolCalls++;
2929
- tab.tools.set(key, { line: this.say(tab, `${indent}${c.yellow("●")} ${label}`, depth === 0 && !tab.tools.size), label });
3184
+ if (depth === 0)
3185
+ this.foldWords(tab, p.task);
3186
+ const line = new Text(`${indent}${c.yellow("●")} ${label}`, 1, 0);
3187
+ tab.tools.set(key, { line, label, part: this.did(tab, line, { tool: p.tool }, depth === 0 && !tab.tools.size) });
2930
3188
  }
2931
3189
  else {
2932
3190
  const t = tab.tools.get(key);
@@ -2937,7 +3195,9 @@ export class PineTui {
2937
3195
  if (t)
2938
3196
  t.line.setText(text);
2939
3197
  else
2940
- this.say(tab, text, false);
3198
+ this.did(tab, new Text(text, 1, 0), { tool: p.tool, failed: !p.ok });
3199
+ if (t?.part)
3200
+ t.part.failed = !p.ok;
2941
3201
  tab.tools.delete(key);
2942
3202
  for (const id of (p.images ?? []))
2943
3203
  this.picture(tab, `from ${p.tool}`, () => this.client.toolImage(id));
@@ -2955,11 +3215,13 @@ export class PineTui {
2955
3215
  child.running = false;
2956
3216
  const n = p.stats?.tools?.length ?? 0;
2957
3217
  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));
3218
+ this.did(tab, new Button(new Text(`${indent}${p.status === "done" ? c.green("✓") : c.red("✗")} ${c.bold(p.agent)} ${c.gray(how)} ${open}`, 1, 0), () => void this.openTask(p.task)));
2959
3219
  break;
2960
3220
  }
2961
3221
  tab.running.delete(p.task);
2962
3222
  tab.thinking = false;
3223
+ if (!tab.running.size)
3224
+ this.endWork(tab);
2963
3225
  this.takeStats(tab, p.stats);
2964
3226
  // What the turn left running is said at once, not at the next look.
2965
3227
  if (tab === this.active)
@@ -3061,8 +3323,9 @@ export class PineTui {
3061
3323
  const name = t.kind === "events" ? "events" : t.kind === "task" ? `${t.agent}↳#${t.task}` : t.session === "main" ? t.agent : `${t.agent}·${t.session}`;
3062
3324
  // A question that waits comes first: its task is still running, and a spinner would hide that it waits for the owner.
3063
3325
  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}`) ? "★ " : "";
3326
+ // A conversation that is kept for good has the mark it has in the list of conversations: a
3327
+ // pinned one, and an agent's main conversation, which always stays.
3328
+ const star = t.kind === "chat" && (t.session === "main" || this.pins.has(`${t.agent}:${t.session}`)) ? "★ " : "";
3066
3329
  const label = ` ${i + 1} ${star}${short(name, 22)} `;
3067
3330
  line.add(t === this.active ? c.bgAccent(label) : c.gray(label), () => this.activate(t));
3068
3331
  line.add(t === this.active ? c.bgAccent("×") : c.gray("×"), () => this.closeTab(t));