rookery-agent 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +4 -4
  2. package/package.json +3 -1
  3. package/packages/cli/dist/commands/tasks.js +1 -1
  4. package/packages/cli/dist/commands/tasks.js.map +1 -1
  5. package/packages/cli/package.json +1 -1
  6. package/packages/core/dist/agents/persona.js +1 -1
  7. package/packages/core/dist/agents/persona.js.map +1 -1
  8. package/packages/core/dist/config.d.ts +34 -1
  9. package/packages/core/dist/config.d.ts.map +1 -1
  10. package/packages/core/dist/config.js +79 -2
  11. package/packages/core/dist/config.js.map +1 -1
  12. package/packages/core/dist/cron/scheduler.d.ts +10 -3
  13. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  14. package/packages/core/dist/cron/scheduler.js +38 -13
  15. package/packages/core/dist/cron/scheduler.js.map +1 -1
  16. package/packages/core/dist/gateway/policy.d.ts +20 -3
  17. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  18. package/packages/core/dist/gateway/policy.js +18 -2
  19. package/packages/core/dist/gateway/policy.js.map +1 -1
  20. package/packages/core/dist/index.d.ts +4 -4
  21. package/packages/core/dist/index.d.ts.map +1 -1
  22. package/packages/core/dist/index.js +3 -3
  23. package/packages/core/dist/index.js.map +1 -1
  24. package/packages/core/dist/memory/db.d.ts +1 -1
  25. package/packages/core/dist/memory/db.d.ts.map +1 -1
  26. package/packages/core/dist/memory/db.js +138 -1
  27. package/packages/core/dist/memory/db.js.map +1 -1
  28. package/packages/core/dist/org/controller.d.ts +98 -113
  29. package/packages/core/dist/org/controller.d.ts.map +1 -1
  30. package/packages/core/dist/org/controller.js +679 -726
  31. package/packages/core/dist/org/controller.js.map +1 -1
  32. package/packages/core/dist/org/prompts.d.ts +17 -16
  33. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  34. package/packages/core/dist/org/prompts.js +76 -146
  35. package/packages/core/dist/org/prompts.js.map +1 -1
  36. package/packages/core/dist/org/store.d.ts +67 -5
  37. package/packages/core/dist/org/store.d.ts.map +1 -1
  38. package/packages/core/dist/org/store.js +202 -8
  39. package/packages/core/dist/org/store.js.map +1 -1
  40. package/packages/core/dist/org/tools.d.ts +9 -3
  41. package/packages/core/dist/org/tools.d.ts.map +1 -1
  42. package/packages/core/dist/org/tools.js +59 -35
  43. package/packages/core/dist/org/tools.js.map +1 -1
  44. package/packages/core/dist/providers/claude-code.d.ts +2 -1
  45. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  46. package/packages/core/dist/providers/claude-code.js +21 -10
  47. package/packages/core/dist/providers/claude-code.js.map +1 -1
  48. package/packages/core/dist/providers/claude-tui.d.ts +120 -7
  49. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -1
  50. package/packages/core/dist/providers/claude-tui.js +476 -41
  51. package/packages/core/dist/providers/claude-tui.js.map +1 -1
  52. package/packages/core/dist/runtime.d.ts +64 -12
  53. package/packages/core/dist/runtime.d.ts.map +1 -1
  54. package/packages/core/dist/runtime.js +520 -150
  55. package/packages/core/dist/runtime.js.map +1 -1
  56. package/packages/core/dist/types.d.ts +191 -13
  57. package/packages/core/dist/types.d.ts.map +1 -1
  58. package/packages/core/dist/types.js.map +1 -1
  59. package/packages/core/package.json +1 -1
  60. package/packages/server/dist/context.d.ts.map +1 -1
  61. package/packages/server/dist/context.js +11 -2
  62. package/packages/server/dist/context.js.map +1 -1
  63. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  64. package/packages/server/dist/gateways/push.js +135 -69
  65. package/packages/server/dist/gateways/push.js.map +1 -1
  66. package/packages/server/dist/gateways/telegram.d.ts +31 -8
  67. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  68. package/packages/server/dist/gateways/telegram.js +148 -47
  69. package/packages/server/dist/gateways/telegram.js.map +1 -1
  70. package/packages/server/dist/gateways/threads.d.ts +6 -1
  71. package/packages/server/dist/gateways/threads.d.ts.map +1 -1
  72. package/packages/server/dist/gateways/threads.js +21 -11
  73. package/packages/server/dist/gateways/threads.js.map +1 -1
  74. package/packages/server/dist/routes/config.d.ts.map +1 -1
  75. package/packages/server/dist/routes/config.js +27 -0
  76. package/packages/server/dist/routes/config.js.map +1 -1
  77. package/packages/server/dist/routes/org.d.ts.map +1 -1
  78. package/packages/server/dist/routes/org.js +68 -64
  79. package/packages/server/dist/routes/org.js.map +1 -1
  80. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  81. package/packages/server/dist/routes/ws.js +13 -7
  82. package/packages/server/dist/routes/ws.js.map +1 -1
  83. package/packages/server/dist/schemas.d.ts +116 -68
  84. package/packages/server/dist/schemas.d.ts.map +1 -1
  85. package/packages/server/dist/schemas.js +34 -17
  86. package/packages/server/dist/schemas.js.map +1 -1
  87. package/packages/server/dist/server.d.ts.map +1 -1
  88. package/packages/server/dist/server.js +28 -4
  89. package/packages/server/dist/server.js.map +1 -1
  90. package/packages/server/dist/services/stream.d.ts +9 -4
  91. package/packages/server/dist/services/stream.d.ts.map +1 -1
  92. package/packages/server/dist/services/stream.js.map +1 -1
  93. package/packages/server/dist/services/turns.d.ts +5 -0
  94. package/packages/server/dist/services/turns.d.ts.map +1 -1
  95. package/packages/server/dist/services/turns.js +48 -0
  96. package/packages/server/dist/services/turns.js.map +1 -1
  97. package/packages/server/package.json +1 -1
  98. package/packages/web/dist/assets/{abnfDiagram-O67JEVCF-B4qWcqra.js → abnfDiagram-O67JEVCF-D7YyFndQ.js} +1 -1
  99. package/packages/web/dist/assets/{arc-CQult7TN.js → arc-C_Zgk2dJ.js} +1 -1
  100. package/packages/web/dist/assets/{architectureDiagram-NJMV4G6O-DFTRvl66.js → architectureDiagram-NJMV4G6O-eI0adu1B.js} +1 -1
  101. package/packages/web/dist/assets/{blockDiagram-BEXU5L5S-TCFoK_k-.js → blockDiagram-BEXU5L5S-WAoOFUA9.js} +1 -1
  102. package/packages/web/dist/assets/{c4Diagram-YGBWAQC7-i5_GqhJa.js → c4Diagram-YGBWAQC7-DE8Zyhng.js} +1 -1
  103. package/packages/web/dist/assets/channel-egZxcyUK.js +1 -0
  104. package/packages/web/dist/assets/{chunk-2Q5K7J3B-BK6I2wfW.js → chunk-2Q5K7J3B-bnqLP2XD.js} +1 -1
  105. package/packages/web/dist/assets/{chunk-3FUC2YCW-Dw-TfKT0.js → chunk-3FUC2YCW-Ck1_SVe0.js} +2 -2
  106. package/packages/web/dist/assets/{chunk-5VM5RSS4-AE_XRNTT.js → chunk-5VM5RSS4-hDmC41gD.js} +1 -1
  107. package/packages/web/dist/assets/{chunk-GTNCS2PH-DO18WaaJ.js → chunk-GTNCS2PH-PoWvfCrT.js} +1 -1
  108. package/packages/web/dist/assets/{chunk-GWA4HPMP-3rdjszP_.js → chunk-GWA4HPMP-D3V0IG43.js} +1 -1
  109. package/packages/web/dist/assets/{chunk-JWPE2WC7-C93LH2D0.js → chunk-JWPE2WC7-BryfpHM5.js} +1 -1
  110. package/packages/web/dist/assets/{chunk-NETBCI7D-Dj7O3-H-.js → chunk-NETBCI7D-8ic1iEdT.js} +1 -1
  111. package/packages/web/dist/assets/{chunk-WEXAMYUT-BRFvQUIn.js → chunk-WEXAMYUT-nM8tmQT2.js} +1 -1
  112. package/packages/web/dist/assets/{chunk-XXDRQBXY-CXx6HMbz.js → chunk-XXDRQBXY-Do28F482.js} +1 -1
  113. package/packages/web/dist/assets/{classDiagram-v2-NBCMYWYE-BGXszxjn.js → classDiagram-v2-NBCMYWYE-Bop9oNNO.js} +1 -1
  114. package/packages/web/dist/assets/{cose-bilkent-JH36ORCC-BAuXqkne.js → cose-bilkent-JH36ORCC-a7f_bpnt.js} +1 -1
  115. package/packages/web/dist/assets/{cynefin-OW5HDTMX-plNzhY7J.js → cynefin-OW5HDTMX-DnArcis_.js} +1 -1
  116. package/packages/web/dist/assets/{cynefinDiagram-VND7K2PF-DuPlljFS.js → cynefinDiagram-VND7K2PF-vEuTb1GD.js} +1 -1
  117. package/packages/web/dist/assets/{dagre-6A5THRUB-CXzwdR-6.js → dagre-6A5THRUB-BgG4MynJ.js} +1 -1
  118. package/packages/web/dist/assets/{diagram-22UHCM2B-B7iv_V2D.js → diagram-22UHCM2B-DRCQpafv.js} +1 -1
  119. package/packages/web/dist/assets/{diagram-3UASUU5V-BMvi7gSi.js → diagram-3UASUU5V-BKgmAXde.js} +1 -1
  120. package/packages/web/dist/assets/{diagram-ATOU4E4O-NJ7EB5Qg.js → diagram-ATOU4E4O-B6Hsy36X.js} +1 -1
  121. package/packages/web/dist/assets/{diagram-CDSNMT55-DccMMNJ-.js → diagram-CDSNMT55-JflyfyoB.js} +1 -1
  122. package/packages/web/dist/assets/{diagram-MLGK6HIB-BbwGHK4g.js → diagram-MLGK6HIB-Dd2QPJjT.js} +1 -1
  123. package/packages/web/dist/assets/{diagram-MPIPVDR6-BbSSZfM3.js → diagram-MPIPVDR6-DE5QU60x.js} +1 -1
  124. package/packages/web/dist/assets/{ebnfDiagram-ZINNZB2B-BBfPNM85.js → ebnfDiagram-ZINNZB2B-D7AQ741b.js} +1 -1
  125. package/packages/web/dist/assets/{elk-276RUBZZ-dM3Y1d2a.js → elk-276RUBZZ-CeewBVLF.js} +1 -1
  126. package/packages/web/dist/assets/{erDiagram-OPXOYQCR-iWrUegxy.js → erDiagram-OPXOYQCR-mLLYkZ5c.js} +1 -1
  127. package/packages/web/dist/assets/{flowDiagram-KWPJA3E3-B6DYlbkV.js → flowDiagram-KWPJA3E3-DtpSpsQN.js} +1 -1
  128. package/packages/web/dist/assets/{ganttDiagram-FUAMR5RP-D7dSWZcC.js → ganttDiagram-FUAMR5RP-1_lh-3ky.js} +1 -1
  129. package/packages/web/dist/assets/{gitGraphDiagram-X574FWY7-DguFgcbW.js → gitGraphDiagram-X574FWY7-DoPXZuT5.js} +1 -1
  130. package/packages/web/dist/assets/index-Cw2Opmx7.js +648 -0
  131. package/packages/web/dist/assets/index-j0zBRCgT.css +32 -0
  132. package/packages/web/dist/assets/{infoDiagram-VRGFBTTK-CuiuO3uo.js → infoDiagram-VRGFBTTK-DQpRGGiD.js} +1 -1
  133. package/packages/web/dist/assets/{ishikawaDiagram-OU5B5YK6-wBS1_40m.js → ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js} +1 -1
  134. package/packages/web/dist/assets/{journeyDiagram-ZHPQQLJL-Bd1YE2gP.js → journeyDiagram-ZHPQQLJL-Bg-oeFjb.js} +1 -1
  135. package/packages/web/dist/assets/{kanban-definition-PNTS6WVX-BlQzv_X1.js → kanban-definition-PNTS6WVX-BnpI4VH8.js} +1 -1
  136. package/packages/web/dist/assets/{mermaid.core-p3CwmLUb.js → mermaid.core-BwBKxlRA.js} +4 -4
  137. package/packages/web/dist/assets/{mindmap-definition-NLK3R4M7-BlticnKl.js → mindmap-definition-NLK3R4M7-NBnnxEoO.js} +1 -1
  138. package/packages/web/dist/assets/{pegDiagram-GJSIUBJH-BbXsP47B.js → pegDiagram-GJSIUBJH-RrXXbIvO.js} +1 -1
  139. package/packages/web/dist/assets/{pieDiagram-5QR66LMP-BooBSBug.js → pieDiagram-5QR66LMP-B27q6Gso.js} +1 -1
  140. package/packages/web/dist/assets/{quadrantDiagram-O4NWA36T-CkXC6VCh.js → quadrantDiagram-O4NWA36T-DGDsdur2.js} +1 -1
  141. package/packages/web/dist/assets/{railroadDiagram-XR7U4H2S-BphzYiW-.js → railroadDiagram-XR7U4H2S-GdjkE3mI.js} +1 -1
  142. package/packages/web/dist/assets/{requirementDiagram-PLB6GJNP-PWpD4zpQ.js → requirementDiagram-PLB6GJNP-DjK0GfgO.js} +1 -1
  143. package/packages/web/dist/assets/{sankeyDiagram-IPEJSGJF-5Qm39Vfz.js → sankeyDiagram-IPEJSGJF-BG_AIkwF.js} +1 -1
  144. package/packages/web/dist/assets/{sequenceDiagram-PO4LG4MO-DA673J_w.js → sequenceDiagram-PO4LG4MO-CIQwUb4y.js} +1 -1
  145. package/packages/web/dist/assets/{sizeCapture-INFHLROL-1KsNwBhd.js → sizeCapture-INFHLROL-bpIoPxdJ.js} +1 -1
  146. package/packages/web/dist/assets/{stateDiagram-v2-GCMORJYK-D7O0UyHr.js → stateDiagram-v2-GCMORJYK-8hYXvPPv.js} +1 -1
  147. package/packages/web/dist/assets/{swimlanes-2SLR337P-culFSb1R.js → swimlanes-2SLR337P-gfflUMF9.js} +1 -1
  148. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +8 -0
  149. package/packages/web/dist/assets/{timeline-definition-EJHVYXUP-6GIO5p-k.js → timeline-definition-EJHVYXUP-PHMNoGTZ.js} +1 -1
  150. package/packages/web/dist/assets/{usecaseDiagram-POWQR4AR-BAGHDBzZ.js → usecaseDiagram-POWQR4AR-B2j5iteO.js} +1 -1
  151. package/packages/web/dist/assets/{vennDiagram-UO4OBE2U-PbtBvPRE.js → vennDiagram-UO4OBE2U-BzxtZ-_2.js} +1 -1
  152. package/packages/web/dist/assets/{wardleyDiagram-VNRHLVJA-9scbtDvX.js → wardleyDiagram-VNRHLVJA-DL7YbMpY.js} +1 -1
  153. package/packages/web/dist/assets/{xychartDiagram-PMCCYNJV-C51PiF4p.js → xychartDiagram-PMCCYNJV-CisgP1cT.js} +1 -1
  154. package/packages/web/dist/index.html +2 -2
  155. package/packages/web/package.json +1 -1
  156. package/packages/web/dist/assets/channel-D_4EmqNR.js +0 -1
  157. package/packages/web/dist/assets/index-B1QvSHA5.js +0 -660
  158. package/packages/web/dist/assets/index-zwMuaz90.css +0 -32
  159. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-kzTmK2BP.js +0 -8
@@ -35,6 +35,60 @@ export function loadPty() {
35
35
  .catch(() => null);
36
36
  return ptyModule;
37
37
  }
38
+ let mirrorModule;
39
+ /**
40
+ * A terminal emulator with no screen, fed the same bytes as the browser.
41
+ *
42
+ * A viewer that opens a terminal late used to get the raw byte history
43
+ * replayed - cursor moves and partial repaints computed for whatever size
44
+ * the terminal had back then, cut off at a byte limit wherever that fell.
45
+ * Played into a terminal of another size that came out skewed: prompt bars
46
+ * twice, lines broken halfway, colour runs ending in the wrong place. The
47
+ * mirror keeps the screen as it actually is, and a late viewer gets that,
48
+ * serialized - colours and all - at the size the process has now.
49
+ */
50
+ function loadMirror() {
51
+ mirrorModule ??= Promise.all([import('@xterm/headless'), import('@xterm/addon-serialize')])
52
+ .then(([headless, serialize]) => {
53
+ const Terminal = headless.Terminal ??
54
+ headless.default.Terminal;
55
+ const SerializeAddon = serialize.SerializeAddon ??
56
+ serialize.default.SerializeAddon;
57
+ return (cols, rows) => {
58
+ const TerminalClass = Terminal;
59
+ const SerializeClass = SerializeAddon;
60
+ const term = new TerminalClass({ cols, rows, scrollback: 5000, allowProposedApi: true });
61
+ const addon = new SerializeClass();
62
+ term.loadAddon(addon);
63
+ return {
64
+ write: (data, done) => term.write(data, done),
65
+ // Queued behind what is still waiting to be parsed: a write is
66
+ // processed later, a resize at once, and bytes painted for the old
67
+ // width then landed on the new one - overlapping, skewed lines.
68
+ resize: (c, r) => term.write('', () => term.resize(c, r)),
69
+ serialize: () => addon.serialize(),
70
+ text: () => {
71
+ const buffer = term.buffer.active;
72
+ const lines = [];
73
+ for (let y = buffer.viewportY; y < buffer.viewportY + term.rows; y += 1) {
74
+ lines.push(buffer.getLine(y)?.translateToString(true) ?? '');
75
+ }
76
+ return lines.join('\n');
77
+ },
78
+ dispose: () => term.dispose(),
79
+ };
80
+ };
81
+ })
82
+ .catch(() => null);
83
+ return mirrorModule;
84
+ }
85
+ // Loaded up front, not with the first terminal. The mirror replays what was
86
+ // painted before it existed, at the size it is created with; if the module
87
+ // took its time on first use, a browser could resize the process in between,
88
+ // and the early bytes were then replayed at the wrong width.
89
+ void loadMirror();
90
+ const PASTE_ON = String.fromCharCode(27) + '[?2004h';
91
+ const PASTE_OFF = String.fromCharCode(27) + '[?2004l';
38
92
  class TuiSession {
39
93
  info;
40
94
  pty;
@@ -42,6 +96,10 @@ class TuiSession {
42
96
  lingerMs;
43
97
  buffer = '';
44
98
  lingerTimer;
99
+ /** The screen as it is, for late viewers; unset where the emulator cannot load. */
100
+ mirror;
101
+ /** Whether the TUI has bracketed paste switched on right now. */
102
+ pasteMode = false;
45
103
  constructor(info, pty, cleanup, lingerMs) {
46
104
  this.info = info;
47
105
  this.pty = pty;
@@ -63,14 +121,30 @@ export class TuiSessionRegistry extends EventEmitter {
63
121
  this.kill(key);
64
122
  const session = new TuiSession({ key, providerSessionId, state: 'running', startedAt: Date.now(), cols: DEFAULT_COLS, rows: DEFAULT_ROWS }, pty, cleanup, lingerMs);
65
123
  this.#sessions.set(key, session);
124
+ // Everything painted before the emulator was ready is still in the raw
125
+ // buffer; it goes in first, and every later chunk after it.
126
+ void loadMirror().then((create) => {
127
+ if (!create || this.#sessions.get(key) !== session)
128
+ return;
129
+ const mirror = create(session.info.cols, session.info.rows);
130
+ mirror.write(session.buffer);
131
+ session.mirror = mirror;
132
+ });
66
133
  pty.onData((data) => {
67
134
  if (this.#sessions.get(key) !== session)
68
135
  return;
69
136
  session.buffer = (session.buffer + data).slice(-REPLAY_LIMIT);
137
+ session.mirror?.write(data);
138
+ const on = data.lastIndexOf(PASTE_ON);
139
+ const off = data.lastIndexOf(PASTE_OFF);
140
+ if (on !== off)
141
+ session.pasteMode = on > off;
70
142
  this.emit('data', key, data);
71
143
  });
72
144
  pty.onExit(() => {
73
145
  clearTimeout(session.lingerTimer);
146
+ session.mirror?.dispose();
147
+ session.mirror = undefined;
74
148
  session.cleanup();
75
149
  if (this.#sessions.get(key) !== session)
76
150
  return;
@@ -92,11 +166,37 @@ export class TuiSessionRegistry extends EventEmitter {
92
166
  list() {
93
167
  return [...this.#sessions.values()].map((session) => ({ ...session.info }));
94
168
  }
95
- /** The screen so far, for a viewer that opens the terminal late. */
169
+ /** The raw output so far - what the process wrote, not what the screen shows. */
96
170
  snapshot(key) {
97
171
  const session = this.#sessions.get(key);
98
172
  return session ? { info: { ...session.info }, data: session.buffer } : null;
99
173
  }
174
+ /**
175
+ * The screen as it is now, for a viewer that opens the terminal late:
176
+ * scrollback and visible screen serialized at the process's current size.
177
+ * Falls back to the raw output where there is no emulator.
178
+ */
179
+ async screen(key) {
180
+ const session = this.#sessions.get(key);
181
+ if (!session)
182
+ return null;
183
+ const mirror = session.mirror;
184
+ if (!mirror)
185
+ return { info: { ...session.info }, data: session.buffer };
186
+ // Parsing is asynchronous; wait until what has arrived is on the screen.
187
+ await new Promise((resolve) => mirror.write('', resolve));
188
+ if (session.mirror !== mirror)
189
+ return this.snapshot(key);
190
+ return { info: { ...session.info }, data: mirror.serialize() };
191
+ }
192
+ /** What the screen shows right now as plain text, or null without an emulator. */
193
+ screenText(key) {
194
+ return this.#sessions.get(key)?.mirror?.text() ?? null;
195
+ }
196
+ /** Whether the TUI takes pasted text as one paste right now. */
197
+ pasteMode(key) {
198
+ return this.#sessions.get(key)?.pasteMode ?? false;
199
+ }
100
200
  /** Keystrokes from a person. Typing into a finished terminal keeps it open longer. */
101
201
  write(key, data) {
102
202
  const session = this.#sessions.get(key);
@@ -117,8 +217,12 @@ export class TuiSessionRegistry extends EventEmitter {
117
217
  return;
118
218
  try {
119
219
  session.pty.resize(c, r);
220
+ session.mirror?.resize(c, r);
120
221
  session.info.cols = c;
121
222
  session.info.rows = r;
223
+ // Every other viewer of this terminal follows the new size instead of
224
+ // fighting it with its own (run-terminal.tsx).
225
+ this.emit('state', { ...session.info });
122
226
  }
123
227
  catch {
124
228
  // A pty that is exiting refuses a resize; nothing to keep.
@@ -337,6 +441,8 @@ class TerminalWatch {
337
441
  resumed;
338
442
  exitCode = null;
339
443
  lastActivity = Date.now();
444
+ /** The last time the screen changed - quiet here means the TUI sits at its prompt. */
445
+ lastScreen = Date.now();
340
446
  /** The newest text block - what a print run reports as its result. */
341
447
  lastBlock = '';
342
448
  /** Assistant entries read so far; growth after a Stop means work went on. */
@@ -488,6 +594,7 @@ async function spawnTerminal(spec, resumed) {
488
594
  });
489
595
  child.onData((data) => {
490
596
  watch.lastActivity = Date.now();
597
+ watch.lastScreen = watch.lastActivity;
491
598
  if (answered.size === STARTUP_DIALOGS.length)
492
599
  return;
493
600
  screen = (screen + data).slice(-20_000);
@@ -610,74 +717,402 @@ export async function* runTui(spec) {
610
717
  }
611
718
  /** A conversation terminal nobody has used for this long is closed. */
612
719
  const CONVERSATION_IDLE_MS = 60 * 60 * 1000;
720
+ /** Screen silence that means the TUI sits at its prompt, ready for keys. */
721
+ const READY_QUIET_MS = 800;
722
+ /** A fresh terminal paints, answers its dialogs and settles within this. */
723
+ const READY_LIMIT_MS = 30_000;
724
+ /** How long a typed message may take to show up in the transcript. */
725
+ const ACCEPT_LIMIT_MS = 15_000;
726
+ /** How often an unconfirmed message is looked after: Enter again, or typed again. */
727
+ const ACCEPT_RETRY_MS = 3000;
728
+ /**
729
+ * A panel or menu is open and waiting for Esc. Not the first-run dialogs:
730
+ * Esc there declines the folder and Claude Code quits.
731
+ */
732
+ function hasOpenPanel(screen) {
733
+ const lower = screen.toLowerCase();
734
+ if (lower.includes('trust this folder') || lower.includes('yes, i accept'))
735
+ return false;
736
+ return lower.includes('esc to cancel') || lower.includes('esc to close') || lower.includes('esc to exit');
737
+ }
738
+ /** The screen a command left, as text for the chat: without the hint lines and the empty tail. */
739
+ function commandOutput(screen, command) {
740
+ const lines = screen.split('\n');
741
+ // Only what came after the command line itself, not the conversation above it.
742
+ const at = lines.map((line) => line.includes(command)).lastIndexOf(true);
743
+ return lines
744
+ .slice(at + 1)
745
+ .filter((line) => !/esc to (cancel|close|exit)/i.test(line))
746
+ .join('\n')
747
+ .replace(/\s+$/, '')
748
+ .replace(/^\s*\n/, '');
749
+ }
750
+ /** Lines Claude Code draws under its input box, and only there. */
751
+ const INPUT_FOOTERS = ['shift+tab to cycle', '? for shortcuts', 'for shortcuts'];
752
+ /** How long an interrupted turn gets to write what it had before it is read as is. */
753
+ const INTERRUPT_SETTLE_MS = 1500;
754
+ /** Bracketed paste: the TUI takes the text as one paste, newlines and all. */
755
+ const PASTE_START = ESC + '[200~';
756
+ const PASTE_END = ESC + '[201~';
757
+ /**
758
+ * The `UserPromptSubmit` hook of a conversation terminal: whatever Rookery
759
+ * wrote into the context file for this one message goes to Claude Code as
760
+ * `additionalContext`, and the file is emptied so the next message - typed in
761
+ * the terminal by a person, say - does not get it again. Single quotes only:
762
+ * the command runs through whichever shell Claude Code picks.
763
+ */
764
+ export function promptContextHookCommand(contextFile) {
765
+ const node = process.execPath.replace(/\\/g, '/');
766
+ const target = contextFile.replace(/\\/g, '/').replace(/'/g, "\\'");
767
+ const script = "const fs=require('fs');const f='" + target + "';let t='';" +
768
+ "try{t=fs.readFileSync(f,'utf8');fs.writeFileSync(f,'')}catch(e){}" +
769
+ "if(t.trim())process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:'UserPromptSubmit',additionalContext:t}}))";
770
+ return `"${node}" -e "${script}"`;
771
+ }
772
+ /** The context file of a conversation terminal, next to its Stop marker. */
773
+ export function contextFileFor(workDir) {
774
+ return join(workDir, 'context.md');
775
+ }
776
+ /**
777
+ * One conversation, one Claude Code process. A person may type into it from
778
+ * the terminal view, and Rookery types into it for every chat message - from
779
+ * the web, from Telegram, or a report-back from work handed off earlier. What
780
+ * Rookery typed comes back to the caller of `submit`; what a person typed
781
+ * comes back through `onTurn`. Both are the same process and the same
782
+ * transcript, which is the point: the chat and the terminal are one
783
+ * conversation, not two views taking turns writing to it.
784
+ */
785
+ export class ConversationTerminal {
786
+ watch;
787
+ handlers;
788
+ #pending = null;
789
+ /** Submissions run one after another, never interleaved. */
790
+ #queue = Promise.resolve();
791
+ #spawned = Date.now();
792
+ /** Prompts a person typed since the last answer, and what came of them. */
793
+ #typed = [];
794
+ #typedEvents = [];
795
+ #typedStarted = Date.now();
796
+ constructor(watch, handlers) {
797
+ this.watch = watch;
798
+ this.handlers = handlers;
799
+ }
800
+ get key() {
801
+ return this.watch.spec.key;
802
+ }
803
+ get providerSessionId() {
804
+ return this.watch.spec.sessionId;
805
+ }
806
+ alive() {
807
+ return stillOpen(this.watch);
808
+ }
809
+ /** Whether a submitted message is being answered right now. */
810
+ get busy() {
811
+ return this.#pending !== null;
812
+ }
813
+ close() {
814
+ tuiSessions.kill(this.key);
815
+ }
816
+ /** Nothing being answered right now, neither a submitted message nor a typed one. */
817
+ async whenIdle(limitMs = 10 * 60 * 1000) {
818
+ const deadline = Date.now() + limitMs;
819
+ while (Date.now() < deadline && this.alive()) {
820
+ const working = this.#pending !== null || this.#typed.length > 0 || tuiSessions.info(this.key)?.state === 'running';
821
+ if (!working)
822
+ return;
823
+ await sleep(POLL_MS);
824
+ }
825
+ }
826
+ /**
827
+ * Type one message into the terminal and wait for its answer. `context`
828
+ * reaches Claude Code through the `UserPromptSubmit` hook rather than as
829
+ * part of the message, so the transcript - and the terminal a person may be
830
+ * watching - shows exactly what was said, nothing Rookery added.
831
+ */
832
+ submit(input) {
833
+ const run = this.#queue.then(() => this.#submit(input));
834
+ this.#queue = run.catch(() => undefined);
835
+ return run;
836
+ }
837
+ async #submit(input) {
838
+ const failed = (error) => ({
839
+ prompt: input.prompt,
840
+ answer: '',
841
+ events: [],
842
+ providerSessionId: this.providerSessionId,
843
+ usage: { durationMs: 0 },
844
+ error,
845
+ });
846
+ if (!this.alive())
847
+ return failed('The terminal is closed.');
848
+ await this.#ready(input.signal);
849
+ if (input.signal?.aborted)
850
+ return failed('Cancelled before it was sent.');
851
+ if (!this.alive())
852
+ return failed('The terminal closed before the message could be sent.');
853
+ await writeFile(contextFileFor(this.watch.spec.workDir), input.context ?? '').catch(() => undefined);
854
+ // A turn started while the Stop marker still holds the last answer would
855
+ // end the moment it began.
856
+ await this.watch.clearMarker();
857
+ let pending;
858
+ const ended = new Promise((resolve) => {
859
+ pending = {
860
+ prompt: input.prompt,
861
+ onEvent: input.onEvent,
862
+ events: [],
863
+ started: Date.now(),
864
+ accepted: false,
865
+ done: resolve,
866
+ };
867
+ });
868
+ if (!pending)
869
+ return failed('The terminal could not take the message.');
870
+ const mine = pending;
871
+ this.#pending = mine;
872
+ tuiSessions.markRunning(this.key);
873
+ this.#type(input.prompt);
874
+ const onAbort = () => {
875
+ // Esc is what a person presses: Claude Code stops, keeps what it had,
876
+ // and writes no Stop payload - so the turn is closed here instead.
877
+ tuiSessions.write(this.key, ESC);
878
+ setTimeout(() => void this.#interrupted(mine), INTERRUPT_SETTLE_MS);
879
+ };
880
+ if (input.signal?.aborted)
881
+ onAbort();
882
+ else
883
+ input.signal?.addEventListener('abort', onAbort, { once: true });
884
+ // A slash command or a `!` shell line is the terminal's own business: it
885
+ // may never reach the model, so no Stop hook comes. Once the screen has
886
+ // settled without a model turn starting, it is done - whatever it showed
887
+ // is on the terminal, which is where a command's output lives anyway.
888
+ const command = /^[/!]/.test(input.prompt.trim());
889
+ if (command) {
890
+ void (async () => {
891
+ const typedAt = Date.now();
892
+ while (this.#pending === mine && !mine.accepted && Date.now() - typedAt < ACCEPT_LIMIT_MS) {
893
+ await sleep(POLL_MS * 2);
894
+ if (Date.now() - typedAt > 2500 && Date.now() - this.watch.lastScreen > 1500 && !mine.accepted) {
895
+ // What the command put on the screen is its answer - the chat
896
+ // cannot see the terminal, so `/cost` there shows the costs. A
897
+ // panel it opened is closed again, or the next message would be
898
+ // typed into it.
899
+ const screen = tuiSessions.screenText(this.key) ?? '';
900
+ const output = commandOutput(screen, input.prompt.trim());
901
+ // Fenced: a panel is laid out in columns, and markdown would reflow it.
902
+ this.#settle(mine, { answer: output ? '```\n' + output + '\n```' : '' });
903
+ if (hasOpenPanel(screen))
904
+ tuiSessions.write(this.key, ESC);
905
+ return;
906
+ }
907
+ }
908
+ // Still running past the limit (a command that started real work
909
+ // settles through the Stop hook instead): never leave it hanging.
910
+ if (this.#pending === mine && !mine.accepted)
911
+ this.#settle(mine, { answer: '' });
912
+ })();
913
+ }
914
+ // The message has to arrive. Every few seconds without it in the
915
+ // transcript, the screen says why: the text sits in the input box (a
916
+ // paste the TUI held on to) and gets another Enter, or it is not there at
917
+ // all (keys swallowed while the TUI was still setting up) and is typed
918
+ // again. Past the limit it is an error, not a turn waiting for ever.
919
+ void (async () => {
920
+ if (command)
921
+ return;
922
+ const typedAt = Date.now();
923
+ const snippet = input.prompt.replace(/\s+/g, ' ').trim().slice(0, 24);
924
+ while (Date.now() - typedAt < ACCEPT_LIMIT_MS * 2) {
925
+ await sleep(ACCEPT_RETRY_MS);
926
+ if (this.#pending !== mine || mine.accepted)
927
+ return;
928
+ const screen = tuiSessions.screenText(this.key);
929
+ const waiting = screen === null || screen.includes('[Pasted text') || screen.replace(/\s+/g, ' ').includes(snippet);
930
+ if (waiting)
931
+ tuiSessions.write(this.key, '\r');
932
+ else
933
+ this.#type(input.prompt);
934
+ }
935
+ if (this.#pending !== mine || mine.accepted)
936
+ return;
937
+ this.#settle(mine, { error: 'The terminal did not take the message.' });
938
+ })();
939
+ try {
940
+ return await ended;
941
+ }
942
+ finally {
943
+ input.signal?.removeEventListener('abort', onAbort);
944
+ }
945
+ }
946
+ /**
947
+ * Wait until the TUI sits at its prompt: not working, quiet for a moment,
948
+ * and - where the screen can be read - showing the footer Claude Code only
949
+ * draws under a live input box. Quiet alone was not enough: a fresh
950
+ * terminal pauses while its startup hooks run, and keys typed into that
951
+ * pause are swallowed.
952
+ */
953
+ async #ready(signal) {
954
+ const deadline = Date.now() + READY_LIMIT_MS;
955
+ let closed = 0;
956
+ while (Date.now() < deadline && !signal?.aborted && this.alive()) {
957
+ const working = tuiSessions.info(this.key)?.state === 'running' || this.#typed.length > 0;
958
+ const quiet = Date.now() - this.#spawned > 1500 && Date.now() - this.watch.lastScreen > READY_QUIET_MS;
959
+ const screen = tuiSessions.screenText(this.key);
960
+ const prompt = screen === null || INPUT_FOOTERS.some((footer) => screen.includes(footer));
961
+ if (!working && quiet && prompt)
962
+ return;
963
+ // A panel left open - by a command typed in the terminal, say - sits
964
+ // where the input box would be. Esc closes it, as a person would.
965
+ if (!working && quiet && screen !== null && hasOpenPanel(screen) && closed < 3) {
966
+ closed += 1;
967
+ tuiSessions.write(this.key, ESC);
968
+ await sleep(READY_QUIET_MS);
969
+ }
970
+ await sleep(POLL_MS);
971
+ }
972
+ }
973
+ /** The message as keystrokes: pasted whole where the TUI allows it, then Enter. */
974
+ #type(prompt) {
975
+ const body = tuiSessions.pasteMode(this.key) ? PASTE_START + prompt + PASTE_END : prompt.replace(/\r?\n/g, ' ');
976
+ tuiSessions.write(this.key, body);
977
+ // Enter on its own write, a beat later: in the same chunk the TUI can read
978
+ // it as part of the paste rather than as the key that sends it.
979
+ setTimeout(() => tuiSessions.write(this.key, '\r'), 200);
980
+ }
981
+ async #interrupted(pending) {
982
+ if (this.#pending !== pending)
983
+ return;
984
+ for (const event of await this.watch.read().catch(() => []))
985
+ this.take(event);
986
+ this.#settle(pending, { interrupted: true });
987
+ }
988
+ #settle(pending, extra) {
989
+ if (this.#pending !== pending)
990
+ return;
991
+ this.#pending = null;
992
+ let lastText = '';
993
+ for (const event of pending.events)
994
+ if (event.type === 'text')
995
+ lastText = event.delta.replace(/^\n\n/, '');
996
+ pending.done({
997
+ prompt: pending.prompt,
998
+ answer: extra.answer ?? lastText,
999
+ events: pending.events,
1000
+ ...(this.watch.model ? { model: this.watch.model } : {}),
1001
+ providerSessionId: this.providerSessionId,
1002
+ usage: {
1003
+ durationMs: Date.now() - pending.started,
1004
+ ...(this.watch.contextTokens !== undefined ? { contextTokens: this.watch.contextTokens } : {}),
1005
+ },
1006
+ ...(extra.interrupted ? { interrupted: true } : {}),
1007
+ ...(extra.error ? { error: extra.error } : {}),
1008
+ });
1009
+ tuiSessions.linger(this.key);
1010
+ }
1011
+ /** From the read loop: one transcript event, for the submitted turn if there is one. */
1012
+ take(event) {
1013
+ const pending = this.#pending;
1014
+ if (event.type === 'status' && event.label === 'input' && event.detail) {
1015
+ // The first message after a submission is the one Rookery typed.
1016
+ if (pending && !pending.accepted) {
1017
+ pending.accepted = true;
1018
+ return;
1019
+ }
1020
+ if (!pending) {
1021
+ if (this.#typed.length === 0 && this.#typedEvents.length === 0)
1022
+ this.#typedStarted = Date.now();
1023
+ this.#typed.push(event.detail);
1024
+ tuiSessions.markRunning(this.key);
1025
+ }
1026
+ return;
1027
+ }
1028
+ if (event.type !== 'text' && event.type !== 'thinking' && event.type !== 'tool')
1029
+ return;
1030
+ if (pending) {
1031
+ pending.accepted = true;
1032
+ pending.events.push(event);
1033
+ pending.onEvent(event);
1034
+ }
1035
+ else {
1036
+ this.#typedEvents.push(event);
1037
+ }
1038
+ }
1039
+ /** From the read loop: the Stop hook fired and the transcript caught up. */
1040
+ stopped(reported) {
1041
+ const pending = this.#pending;
1042
+ if (pending) {
1043
+ if (this.watch.apiError)
1044
+ this.#settle(pending, { error: this.watch.apiError });
1045
+ else
1046
+ this.#settle(pending, { answer: reported || this.watch.lastBlock });
1047
+ return;
1048
+ }
1049
+ const answer = reported || this.watch.lastBlock;
1050
+ if (this.#typed.length || answer) {
1051
+ this.handlers.onTurn({
1052
+ prompt: this.#typed.join('\n\n'),
1053
+ answer,
1054
+ events: this.#typedEvents,
1055
+ ...(this.watch.model ? { model: this.watch.model } : {}),
1056
+ providerSessionId: this.providerSessionId,
1057
+ usage: {
1058
+ durationMs: Date.now() - this.#typedStarted,
1059
+ ...(this.watch.contextTokens !== undefined ? { contextTokens: this.watch.contextTokens } : {}),
1060
+ },
1061
+ });
1062
+ }
1063
+ this.#typed = [];
1064
+ this.#typedEvents = [];
1065
+ // Answered: waiting for the person again.
1066
+ tuiSessions.linger(this.key);
1067
+ }
1068
+ /** From the read loop: the process is gone, and a turn still waiting on it ends. */
1069
+ exited() {
1070
+ const pending = this.#pending;
1071
+ if (pending)
1072
+ this.#settle(pending, { error: this.watch.apiError ?? 'Claude Code closed its terminal before answering.' });
1073
+ }
1074
+ }
613
1075
  /**
614
1076
  * Opens a conversation in Claude Code's own terminal. There is no task and
615
- * no end: a person types, Claude answers, and every answer is reported as a
616
- * turn so the conversation's history stays whole. It runs until somebody
617
- * closes it, switches the conversation back to chat, or leaves it untouched
618
- * for an hour.
1077
+ * no end: a person or Rookery types, Claude answers. It runs until somebody
1078
+ * closes it, or until nobody has used it for an hour; the next message then
1079
+ * starts it again on the same session.
619
1080
  */
620
1081
  export async function startConversationTerminal(spec, resumed, handlers) {
621
1082
  const watch = await spawnTerminal({ ...spec, lingerMs: CONVERSATION_IDLE_MS }, resumed);
1083
+ const terminal = new ConversationTerminal(watch, handlers);
622
1084
  // A conversation terminal waits for its person first - idle, not working,
623
1085
  // and closed by itself after an hour of nobody typing.
624
1086
  tuiSessions.linger(spec.key);
625
1087
  void (async () => {
626
- let prompts = [];
627
- let events = [];
628
- let turnStarted = Date.now();
629
- const take = (event) => {
630
- if (event.type === 'status' && event.label === 'input' && event.detail) {
631
- if (prompts.length === 0 && events.length === 0)
632
- turnStarted = Date.now();
633
- prompts.push(event.detail);
634
- tuiSessions.markRunning(spec.key);
635
- }
636
- else if (event.type === 'text' || event.type === 'thinking' || event.type === 'tool') {
637
- events.push(event);
638
- }
639
- };
640
1088
  try {
641
1089
  while (stillOpen(watch)) {
642
1090
  await sleep(POLL_MS);
643
1091
  for (const event of await watch.read())
644
- take(event);
1092
+ terminal.take(event);
645
1093
  const payload = await watch.marker();
646
1094
  if (payload) {
647
1095
  const reported = typeof payload.last_assistant_message === 'string' ? payload.last_assistant_message.trim() : '';
648
1096
  const settled = await watch.settle(reported);
649
1097
  for (const event of settled.events)
650
- take(event);
1098
+ terminal.take(event);
651
1099
  await watch.clearMarker();
652
- const holds = settled.holds;
653
- if (!holds)
1100
+ if (!settled.holds)
654
1101
  continue;
655
- const answer = reported || watch.lastBlock;
656
- if (prompts.length || answer) {
657
- handlers.onTurn({
658
- prompt: prompts.join('\n\n'),
659
- answer,
660
- events,
661
- ...(watch.model ? { model: watch.model } : {}),
662
- providerSessionId: spec.sessionId,
663
- usage: {
664
- durationMs: Date.now() - turnStarted,
665
- ...(watch.contextTokens !== undefined ? { contextTokens: watch.contextTokens } : {}),
666
- },
667
- });
668
- }
669
- prompts = [];
670
- events = [];
671
- // Answered: waiting for the person again.
672
- tuiSessions.linger(spec.key);
1102
+ terminal.stopped(reported);
673
1103
  }
674
1104
  if (Date.now() - watch.lastActivity > CONVERSATION_IDLE_MS)
675
1105
  tuiSessions.kill(spec.key);
676
1106
  }
677
1107
  }
1108
+ catch {
1109
+ // A read that throws past its own guards ends the watch, not the server.
1110
+ }
678
1111
  finally {
1112
+ terminal.exited();
679
1113
  handlers.onExit();
680
1114
  }
681
1115
  })();
1116
+ return terminal;
682
1117
  }
683
1118
  //# sourceMappingURL=claude-tui.js.map