@0gfoundation/0g-agentdna 0.4.0 → 0.5.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 (255) hide show
  1. package/GUIDE.md +190 -40
  2. package/OPERATORS.md +164 -0
  3. package/OPERATORS.zh.md +141 -0
  4. package/PROVIDERS.md +6 -0
  5. package/PROVIDERS.zh.md +3 -1
  6. package/README.md +84 -11
  7. package/dist/AgentClient.d.ts +374 -26
  8. package/dist/AgentClient.d.ts.map +1 -1
  9. package/dist/AgentClient.js +323 -40
  10. package/dist/AgentClient.js.map +1 -1
  11. package/dist/AgenticID.d.ts +170 -80
  12. package/dist/AgenticID.d.ts.map +1 -1
  13. package/dist/AgenticID.js +300 -42
  14. package/dist/AgenticID.js.map +1 -1
  15. package/dist/AttestorClient.d.ts +115 -31
  16. package/dist/AttestorClient.d.ts.map +1 -1
  17. package/dist/AttestorClient.js +276 -56
  18. package/dist/AttestorClient.js.map +1 -1
  19. package/dist/Credentials.d.ts +574 -0
  20. package/dist/Credentials.d.ts.map +1 -0
  21. package/dist/Credentials.js +838 -0
  22. package/dist/Credentials.js.map +1 -0
  23. package/dist/Operators.d.ts +60 -0
  24. package/dist/Operators.d.ts.map +1 -0
  25. package/dist/Operators.js +38 -0
  26. package/dist/Operators.js.map +1 -0
  27. package/dist/Providers.d.ts +13 -0
  28. package/dist/Providers.d.ts.map +1 -1
  29. package/dist/Providers.js +20 -1
  30. package/dist/Providers.js.map +1 -1
  31. package/dist/Releases.d.ts +51 -0
  32. package/dist/Releases.d.ts.map +1 -0
  33. package/dist/Releases.js +72 -0
  34. package/dist/Releases.js.map +1 -0
  35. package/dist/ReputationClient.d.ts +47 -3
  36. package/dist/ReputationClient.d.ts.map +1 -1
  37. package/dist/ReputationClient.js +204 -78
  38. package/dist/ReputationClient.js.map +1 -1
  39. package/dist/ServeProof.d.ts +70 -23
  40. package/dist/ServeProof.d.ts.map +1 -1
  41. package/dist/ServeProof.js +94 -35
  42. package/dist/ServeProof.js.map +1 -1
  43. package/dist/ServeSession.d.ts +17 -2
  44. package/dist/ServeSession.d.ts.map +1 -1
  45. package/dist/ServeSession.js +77 -9
  46. package/dist/ServeSession.js.map +1 -1
  47. package/dist/Settings.d.ts +25 -1
  48. package/dist/Settings.d.ts.map +1 -1
  49. package/dist/Settings.js +53 -1
  50. package/dist/Settings.js.map +1 -1
  51. package/dist/TrustRegistry.d.ts +28 -0
  52. package/dist/TrustRegistry.d.ts.map +1 -0
  53. package/dist/TrustRegistry.js +67 -0
  54. package/dist/TrustRegistry.js.map +1 -0
  55. package/dist/abi.d.ts +346 -34
  56. package/dist/abi.d.ts.map +1 -1
  57. package/dist/abi.js +150 -30
  58. package/dist/abi.js.map +1 -1
  59. package/dist/cli/attach.d.ts +79 -0
  60. package/dist/cli/attach.d.ts.map +1 -0
  61. package/dist/cli/attach.js +253 -0
  62. package/dist/cli/attach.js.map +1 -0
  63. package/dist/cli/commands/cells.d.ts +45 -0
  64. package/dist/cli/commands/cells.d.ts.map +1 -1
  65. package/dist/cli/commands/cells.js +77 -0
  66. package/dist/cli/commands/cells.js.map +1 -1
  67. package/dist/cli/commands/cred.d.ts +12 -0
  68. package/dist/cli/commands/cred.d.ts.map +1 -0
  69. package/dist/cli/commands/cred.js +43 -0
  70. package/dist/cli/commands/cred.js.map +1 -0
  71. package/dist/cli/commands/doctor.d.ts.map +1 -1
  72. package/dist/cli/commands/doctor.js +44 -35
  73. package/dist/cli/commands/doctor.js.map +1 -1
  74. package/dist/cli/commands/interactive.d.ts +597 -21
  75. package/dist/cli/commands/interactive.d.ts.map +1 -1
  76. package/dist/cli/commands/interactive.js +5082 -1323
  77. package/dist/cli/commands/interactive.js.map +1 -1
  78. package/dist/cli/commands/list.d.ts +5 -5
  79. package/dist/cli/commands/list.d.ts.map +1 -1
  80. package/dist/cli/commands/list.js +21 -26
  81. package/dist/cli/commands/list.js.map +1 -1
  82. package/dist/cli/commands/providers.d.ts +4 -0
  83. package/dist/cli/commands/providers.d.ts.map +1 -1
  84. package/dist/cli/commands/providers.js +19 -5
  85. package/dist/cli/commands/providers.js.map +1 -1
  86. package/dist/cli/commands/releases.d.ts +13 -0
  87. package/dist/cli/commands/releases.d.ts.map +1 -0
  88. package/dist/cli/commands/releases.js +65 -0
  89. package/dist/cli/commands/releases.js.map +1 -0
  90. package/dist/cli/commands/settings.d.ts +5 -0
  91. package/dist/cli/commands/settings.d.ts.map +1 -1
  92. package/dist/cli/commands/settings.js +70 -24
  93. package/dist/cli/commands/settings.js.map +1 -1
  94. package/dist/cli/commands/status.d.ts +2 -1
  95. package/dist/cli/commands/status.d.ts.map +1 -1
  96. package/dist/cli/commands/status.js +22 -19
  97. package/dist/cli/commands/status.js.map +1 -1
  98. package/dist/cli/config.d.ts +48 -1
  99. package/dist/cli/config.d.ts.map +1 -1
  100. package/dist/cli/config.js +114 -5
  101. package/dist/cli/config.js.map +1 -1
  102. package/dist/cli/credentials.d.ts +179 -0
  103. package/dist/cli/credentials.d.ts.map +1 -0
  104. package/dist/cli/credentials.js +1443 -0
  105. package/dist/cli/credentials.js.map +1 -0
  106. package/dist/cli/download.d.ts +21 -0
  107. package/dist/cli/download.d.ts.map +1 -0
  108. package/dist/cli/download.js +89 -0
  109. package/dist/cli/download.js.map +1 -0
  110. package/dist/cli/env.d.ts +6 -0
  111. package/dist/cli/env.d.ts.map +1 -1
  112. package/dist/cli/env.js +18 -6
  113. package/dist/cli/env.js.map +1 -1
  114. package/dist/cli/envelope.d.ts +4 -2
  115. package/dist/cli/envelope.d.ts.map +1 -1
  116. package/dist/cli/envelope.js +10 -6
  117. package/dist/cli/envelope.js.map +1 -1
  118. package/dist/cli/errors.d.ts +45 -1
  119. package/dist/cli/errors.d.ts.map +1 -1
  120. package/dist/cli/errors.js +77 -0
  121. package/dist/cli/errors.js.map +1 -1
  122. package/dist/cli/inference.d.ts.map +1 -1
  123. package/dist/cli/inference.js +7 -0
  124. package/dist/cli/inference.js.map +1 -1
  125. package/dist/cli/inkView.d.ts +341 -0
  126. package/dist/cli/inkView.d.ts.map +1 -0
  127. package/dist/cli/inkView.js +1019 -0
  128. package/dist/cli/inkView.js.map +1 -0
  129. package/dist/cli/legacy/modelKey.d.ts +24 -0
  130. package/dist/cli/legacy/modelKey.d.ts.map +1 -0
  131. package/dist/cli/legacy/modelKey.js +32 -0
  132. package/dist/cli/legacy/modelKey.js.map +1 -0
  133. package/dist/cli/livePrompt.d.ts +212 -0
  134. package/dist/cli/livePrompt.d.ts.map +1 -0
  135. package/dist/cli/livePrompt.js +576 -0
  136. package/dist/cli/livePrompt.js.map +1 -0
  137. package/dist/cli/main.js +206 -72
  138. package/dist/cli/main.js.map +1 -1
  139. package/dist/cli/modelkey.d.ts +64 -0
  140. package/dist/cli/modelkey.d.ts.map +1 -0
  141. package/dist/cli/modelkey.js +113 -0
  142. package/dist/cli/modelkey.js.map +1 -0
  143. package/dist/cli/outboxSync.d.ts +51 -0
  144. package/dist/cli/outboxSync.d.ts.map +1 -0
  145. package/dist/cli/outboxSync.js +210 -0
  146. package/dist/cli/outboxSync.js.map +1 -0
  147. package/dist/cli/plain.d.ts +46 -0
  148. package/dist/cli/plain.d.ts.map +1 -0
  149. package/dist/cli/plain.js +260 -0
  150. package/dist/cli/plain.js.map +1 -0
  151. package/dist/cli/proofs.d.ts +5 -0
  152. package/dist/cli/proofs.d.ts.map +1 -1
  153. package/dist/cli/proofs.js +20 -0
  154. package/dist/cli/proofs.js.map +1 -1
  155. package/dist/cli/ref.d.ts.map +1 -1
  156. package/dist/cli/ref.js +3 -2
  157. package/dist/cli/ref.js.map +1 -1
  158. package/dist/cli/releaseNotice.d.ts +64 -0
  159. package/dist/cli/releaseNotice.d.ts.map +1 -0
  160. package/dist/cli/releaseNotice.js +194 -0
  161. package/dist/cli/releaseNotice.js.map +1 -0
  162. package/dist/cli/sdk.d.ts +18 -0
  163. package/dist/cli/sdk.d.ts.map +1 -1
  164. package/dist/cli/sdk.js +99 -1
  165. package/dist/cli/sdk.js.map +1 -1
  166. package/dist/cli/settings.d.ts +87 -6
  167. package/dist/cli/settings.d.ts.map +1 -1
  168. package/dist/cli/settings.js +270 -18
  169. package/dist/cli/settings.js.map +1 -1
  170. package/dist/cli/textfit.d.ts +28 -0
  171. package/dist/cli/textfit.d.ts.map +1 -0
  172. package/dist/cli/textfit.js +111 -0
  173. package/dist/cli/textfit.js.map +1 -0
  174. package/dist/constants.d.ts +1 -1
  175. package/dist/constants.js +1 -1
  176. package/dist/context.d.ts +26 -0
  177. package/dist/context.d.ts.map +1 -1
  178. package/dist/context.js +1 -0
  179. package/dist/context.js.map +1 -1
  180. package/dist/index.d.ts +19 -11
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +35 -2
  183. package/dist/index.js.map +1 -1
  184. package/dist/legacy/modelKey.d.ts +67 -0
  185. package/dist/legacy/modelKey.d.ts.map +1 -0
  186. package/dist/legacy/modelKey.js +80 -0
  187. package/dist/legacy/modelKey.js.map +1 -0
  188. package/dist/legacy/serveProofV1.d.ts +56 -0
  189. package/dist/legacy/serveProofV1.d.ts.map +1 -0
  190. package/dist/legacy/serveProofV1.js +91 -0
  191. package/dist/legacy/serveProofV1.js.map +1 -0
  192. package/dist/provider-catalog.json +3 -2
  193. package/dist/secretEnv.d.ts +18 -3
  194. package/dist/secretEnv.d.ts.map +1 -1
  195. package/dist/secretEnv.js +16 -2
  196. package/dist/secretEnv.js.map +1 -1
  197. package/dist/types.d.ts +63 -1
  198. package/dist/types.d.ts.map +1 -1
  199. package/dist/viemErrors.d.ts +30 -0
  200. package/dist/viemErrors.d.ts.map +1 -0
  201. package/dist/viemErrors.js +36 -0
  202. package/dist/viemErrors.js.map +1 -0
  203. package/package.json +5 -1
  204. package/src/AgentClient.ts +622 -68
  205. package/src/AgenticID.ts +345 -56
  206. package/src/AttestorClient.ts +330 -83
  207. package/src/Credentials.ts +1027 -0
  208. package/src/Operators.ts +71 -0
  209. package/src/Providers.ts +20 -0
  210. package/src/Releases.ts +95 -0
  211. package/src/ReputationClient.ts +231 -79
  212. package/src/ServeProof.ts +123 -39
  213. package/src/ServeSession.ts +91 -9
  214. package/src/Settings.ts +61 -1
  215. package/src/TrustRegistry.ts +75 -0
  216. package/src/abi.ts +153 -30
  217. package/src/cli/attach.ts +257 -0
  218. package/src/cli/commands/cells.ts +104 -0
  219. package/src/cli/commands/cred.ts +44 -0
  220. package/src/cli/commands/doctor.ts +45 -37
  221. package/src/cli/commands/interactive.ts +4120 -664
  222. package/src/cli/commands/list.ts +21 -30
  223. package/src/cli/commands/providers.ts +17 -4
  224. package/src/cli/commands/releases.ts +60 -0
  225. package/src/cli/commands/settings.ts +75 -28
  226. package/src/cli/commands/status.ts +24 -21
  227. package/src/cli/config.ts +119 -4
  228. package/src/cli/credentials.ts +1379 -0
  229. package/src/cli/download.ts +80 -0
  230. package/src/cli/env.ts +22 -7
  231. package/src/cli/envelope.ts +10 -6
  232. package/src/cli/errors.ts +92 -0
  233. package/src/cli/inference.ts +8 -1
  234. package/src/cli/inkView.ts +969 -0
  235. package/src/cli/legacy/modelKey.ts +35 -0
  236. package/src/cli/livePrompt.ts +615 -0
  237. package/src/cli/main.ts +206 -76
  238. package/src/cli/modelkey.ts +124 -0
  239. package/src/cli/outboxSync.ts +231 -0
  240. package/src/cli/plain.ts +260 -0
  241. package/src/cli/proofs.ts +27 -0
  242. package/src/cli/ref.ts +5 -4
  243. package/src/cli/releaseNotice.ts +200 -0
  244. package/src/cli/sdk.ts +87 -7
  245. package/src/cli/settings.ts +272 -22
  246. package/src/cli/textfit.ts +95 -0
  247. package/src/constants.ts +1 -1
  248. package/src/context.ts +28 -0
  249. package/src/index.ts +50 -7
  250. package/src/legacy/modelKey.ts +80 -0
  251. package/src/legacy/serveProofV1.ts +124 -0
  252. package/src/provider-catalog.json +3 -2
  253. package/src/secretEnv.ts +18 -3
  254. package/src/types.ts +60 -1
  255. package/src/viemErrors.ts +39 -0
@@ -0,0 +1,1019 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InkTurn = exports.InkScreen = exports.InkEditor = exports.MIN_COLS = exports.MIN_ROWS = exports.WAITING_TURN = exports.WAITING_AGENT = exports.INK_PROMPT = exports.FRAME_MS = void 0;
4
+ exports.loadInk = loadInk;
5
+ exports.inkLoadError = inkLoadError;
6
+ exports.wrapRows = wrapRows;
7
+ exports.openInkScreen = openInkScreen;
8
+ /**
9
+ * The agent session on a terminal, drawn with Ink and laid out like Claude
10
+ * Code's input area. From the bottom up:
11
+ *
12
+ * agent 625 · Enter steers · Tab queues · ↑ takes back · Esc stops (footer)
13
+ * ────────────────────────────────────────────────────────────────
14
+ * ❯ what the owner is typing█ (input)
15
+ * ────────────────────────────────────────────────────────────────
16
+ * ⠹ running a command… (14s · Esc to stop) 2 notices · 1 new file
17
+ * ❯ a message sent during the turn queued (highlighted, waiting)
18
+ * the reply's line being written (the transcript's tail)
19
+ *
20
+ * and above all of that the transcript, which scrolls: the owner's messages
21
+ * as `❯ text`, replies, command output, notices, one line per run of the
22
+ * agent's tool calls (`ran 3 commands`).
23
+ *
24
+ * Only the region below the transcript is Ink's: it is redrawn in place.
25
+ * Transcript text is written through Ink's `useStdout().write` (Ink's
26
+ * equivalent of `<Static>` for strings): Ink clears its region, the text is
27
+ * written as it is (an OSC 8 link in it stays a link; Ink's own text layout
28
+ * would cut it up) and the region is drawn again under it. Every row of the
29
+ * region is cut to the terminal's width here, so its height is known and
30
+ * kept below the screen's (Ink clears the whole terminal, scrollback too,
31
+ * when its output is taller than the screen). Frames are at least
32
+ * {@link FRAME_MS} apart: Ink renders a change at once only when its last
33
+ * render is more than 32 ms old, and writing transcript text redraws Ink's
34
+ * last frame, which must be the current one.
35
+ *
36
+ * The keys are the shell's (the session's keypress events, readline's own
37
+ * handler set aside meanwhile): {@link InkEditor} edits the line the way
38
+ * readline does and stands in for readline under the shell's line queue
39
+ * (interactive.ts lineQueue), which keeps every rule about steering,
40
+ * queueing, pastes and questions it already has.
41
+ */
42
+ const node_events_1 = require("node:events");
43
+ const node_stream_1 = require("node:stream");
44
+ const node_url_1 = require("node:url");
45
+ const cells_1 = require("./commands/cells");
46
+ const livePrompt_1 = require("./livePrompt");
47
+ /** The fewest milliseconds between two frames (Ink throttles at 32). */
48
+ exports.FRAME_MS = 40;
49
+ /** The prompt of the owner's message, in the box and in the transcript. */
50
+ exports.INK_PROMPT = '❯ ';
51
+ /** What a message sent during a turn waits for: the agent to read it (Enter), the next turn (Tab, or a command). */
52
+ exports.WAITING_AGENT = 'waiting for the agent';
53
+ exports.WAITING_TURN = 'next turn';
54
+ /** The lines of a long message of the owner's that the transcript keeps. */
55
+ const OWNER_LINES = 8;
56
+ /** The fewest terminal rows and columns the view is drawn on (the shell's prompt serves smaller ones). */
57
+ exports.MIN_ROWS = 12;
58
+ exports.MIN_COLS = 30;
59
+ const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧'];
60
+ let loading;
61
+ let loadError;
62
+ /**
63
+ * Ink and React, or null when they cannot be loaded (then the shell keeps
64
+ * its readline prompt). Ink is an ES module and this package is CommonJS:
65
+ * it is imported with a real dynamic `import()` (TypeScript would turn one
66
+ * written here into `require`, which cannot load Ink's top-level await).
67
+ */
68
+ function loadInk() {
69
+ loading ?? (loading = (async () => {
70
+ try {
71
+ const importEsm = new Function('url', 'return import(url)');
72
+ const ink = (await importEsm((0, node_url_1.pathToFileURL)(require.resolve('ink')).href));
73
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
74
+ const React = require('react');
75
+ if (typeof ink.render !== 'function' || typeof React.createElement !== 'function')
76
+ throw new Error('unexpected module shape');
77
+ return { React, ink };
78
+ }
79
+ catch (e) {
80
+ loadError = (0, cells_1.cleanCell)(e.message ?? String(e)).slice(0, 160);
81
+ return null;
82
+ }
83
+ })());
84
+ return loading;
85
+ }
86
+ /** Why {@link loadInk} gave null. */
87
+ function inkLoadError() { return loadError; }
88
+ /** Readline's history size. */
89
+ const HISTORY = 30;
90
+ /** Readline's crlfDelay: an LF this soon after a CR is the same Enter. */
91
+ const CRLF_MS = 100;
92
+ /**
93
+ * The line being edited, with readline's keys (Emacs bindings, history with
94
+ * prefix search) and the parts of a readline interface the shell's line
95
+ * queue reads and writes: `line`, `cursor`, `history`, the prompt, and the
96
+ * `line`, `close` and `keypress` events. A `line` event is emitted on Enter
97
+ * (also between a paste's start and end, where the queue collects them),
98
+ * after the line went into the history; `close` on Ctrl-D at an empty line.
99
+ */
100
+ class InkEditor extends node_events_1.EventEmitter {
101
+ constructor() {
102
+ super(...arguments);
103
+ this.terminal = true;
104
+ this.line = '';
105
+ this.cursor = 0;
106
+ this.prevRows = 0;
107
+ this.history = [];
108
+ /** Lines entered meanwhile stay out of the history (a secret is typed). */
109
+ this.noHistory = false;
110
+ /** Between a bracketed paste's start and end. */
111
+ this.pasting = false;
112
+ this.shown = '';
113
+ this.hist = -1;
114
+ this.saved = '';
115
+ this.search = '';
116
+ this.returnAt = 0;
117
+ /** Called when the prompt changes (a question came up): the view redraws. */
118
+ this.changed = () => undefined;
119
+ }
120
+ setPrompt(q) { this.shown = q; this.changed(); }
121
+ getPrompt() { return this.shown; }
122
+ /** As readline: the cursor goes to the line's start unless kept. */
123
+ prompt(preserveCursor) { if (!preserveCursor)
124
+ this.cursor = 0; this.changed(); }
125
+ /** Put text at the cursor. */
126
+ insert(s) {
127
+ this.hist = -1;
128
+ this.line = this.line.slice(0, this.cursor) + s + this.line.slice(this.cursor);
129
+ this.cursor += s.length;
130
+ }
131
+ /** Replace `n` characters before the cursor with `s`. */
132
+ replaceBefore(n, s) {
133
+ this.hist = -1;
134
+ const at = Math.max(0, this.cursor - n);
135
+ this.line = this.line.slice(0, at) + s + this.line.slice(this.cursor);
136
+ this.cursor = at + s.length;
137
+ }
138
+ /** One key, as readline handles it on a terminal (Esc, Tab outside a paste and Ctrl-C are the caller's). */
139
+ handle(s, key) {
140
+ const name = key.name;
141
+ if (name === 'paste-start') {
142
+ this.pasting = true;
143
+ return;
144
+ }
145
+ if (name === 'paste-end') {
146
+ this.pasting = false;
147
+ return;
148
+ }
149
+ if (key.ctrl && !key.meta) {
150
+ switch (name) {
151
+ case 'a':
152
+ this.cursor = 0;
153
+ return;
154
+ case 'e':
155
+ this.cursor = this.line.length;
156
+ return;
157
+ case 'b':
158
+ this.move(-1);
159
+ return;
160
+ case 'f':
161
+ this.move(1);
162
+ return;
163
+ case 'h':
164
+ this.backspace();
165
+ return;
166
+ case 'd':
167
+ if (this.line === '')
168
+ this.emit('close');
169
+ else
170
+ this.del();
171
+ return;
172
+ case 'u':
173
+ this.hist = -1;
174
+ this.line = this.line.slice(this.cursor);
175
+ this.cursor = 0;
176
+ return;
177
+ case 'k':
178
+ this.hist = -1;
179
+ this.line = this.line.slice(0, this.cursor);
180
+ return;
181
+ case 'w':
182
+ this.deleteWordLeft();
183
+ return;
184
+ case 'p':
185
+ this.histPrev();
186
+ return;
187
+ case 'n':
188
+ this.histNext();
189
+ return;
190
+ case 'left':
191
+ this.cursor -= this.wordLeft();
192
+ return;
193
+ case 'right':
194
+ this.cursor += this.wordRight();
195
+ return;
196
+ default: return;
197
+ }
198
+ }
199
+ if (key.meta) {
200
+ switch (name) {
201
+ case 'b':
202
+ case 'left':
203
+ this.cursor -= this.wordLeft();
204
+ return;
205
+ case 'f':
206
+ case 'right':
207
+ this.cursor += this.wordRight();
208
+ return;
209
+ case 'd':
210
+ this.hist = -1;
211
+ this.line = this.line.slice(0, this.cursor) + this.line.slice(this.cursor + this.wordRight());
212
+ return;
213
+ case 'backspace':
214
+ this.deleteWordLeft();
215
+ return;
216
+ default: return; // Option/Alt+Enter: the line queue's
217
+ }
218
+ }
219
+ switch (name) {
220
+ case 'return':
221
+ this.returnAt = Date.now();
222
+ this.enter();
223
+ return;
224
+ case 'enter':
225
+ if (this.returnAt === 0 || Date.now() - this.returnAt > CRLF_MS)
226
+ this.enter();
227
+ this.returnAt = 0;
228
+ return;
229
+ case 'backspace':
230
+ this.backspace();
231
+ return;
232
+ case 'delete':
233
+ this.del();
234
+ return;
235
+ case 'left':
236
+ this.move(-1);
237
+ return;
238
+ case 'right':
239
+ this.move(1);
240
+ return;
241
+ case 'home':
242
+ this.cursor = 0;
243
+ return;
244
+ case 'end':
245
+ this.cursor = this.line.length;
246
+ return;
247
+ case 'up':
248
+ this.histPrev();
249
+ return;
250
+ case 'down':
251
+ this.histNext();
252
+ return;
253
+ case 'tab':
254
+ this.insert('\t');
255
+ return; // inside a paste
256
+ case 'escape': return;
257
+ default:
258
+ // eslint-disable-next-line no-control-regex
259
+ if (s && !/[\u0000-\u001f\u007f]/.test(s))
260
+ this.insert(s);
261
+ }
262
+ }
263
+ enter() {
264
+ const l = this.line;
265
+ if (!this.noHistory && l.trim() && this.history[0] !== l) {
266
+ this.history.unshift(l);
267
+ if (this.history.length > HISTORY)
268
+ this.history.pop();
269
+ }
270
+ this.hist = -1;
271
+ this.line = '';
272
+ this.cursor = 0;
273
+ this.emit('line', l);
274
+ }
275
+ /** UTF-16 units of the character before (-1) or at (1) the cursor. */
276
+ charLen(dir) {
277
+ const at = dir < 0 ? this.cursor - 1 : this.cursor;
278
+ if (at < 0 || at >= this.line.length)
279
+ return 0;
280
+ const c = this.line.charCodeAt(at);
281
+ if (dir < 0 && c >= 0xdc00 && c <= 0xdfff && at > 0)
282
+ return 2;
283
+ if (dir > 0 && c >= 0xd800 && c <= 0xdbff && at + 1 < this.line.length)
284
+ return 2;
285
+ return 1;
286
+ }
287
+ move(dir) { this.cursor += dir * this.charLen(dir); }
288
+ backspace() {
289
+ const n = this.charLen(-1);
290
+ if (n)
291
+ this.replaceBefore(n, '');
292
+ }
293
+ del() {
294
+ const n = this.charLen(1);
295
+ if (!n)
296
+ return;
297
+ this.hist = -1;
298
+ this.line = this.line.slice(0, this.cursor) + this.line.slice(this.cursor + n);
299
+ }
300
+ // Readline's word boundaries (a run of word characters or of other
301
+ // non-space characters, with the spaces next to it), with letters and
302
+ // digits of every script as word characters, not only ASCII ones.
303
+ wordLeft() {
304
+ const before = [...this.line.slice(0, this.cursor)].reverse().join('');
305
+ return (/^\s*(?:[^\p{L}\p{N}_\s]+|[\p{L}\p{N}_]+)?/u.exec(before)?.[0] ?? '').length;
306
+ }
307
+ wordRight() {
308
+ return (/^\s*(?:[^\p{L}\p{N}_\s]+|[\p{L}\p{N}_]+)\s*/u.exec(this.line.slice(this.cursor))?.[0] ?? '').length;
309
+ }
310
+ deleteWordLeft() {
311
+ const n = this.wordLeft();
312
+ if (n)
313
+ this.replaceBefore(n, '');
314
+ }
315
+ setLine(l) {
316
+ this.line = l;
317
+ this.cursor = l.length;
318
+ }
319
+ // ↑/↓: older and newer entries starting with what was typed before ↑.
320
+ histPrev() {
321
+ if (this.hist === -1) {
322
+ this.saved = this.line;
323
+ this.search = this.line;
324
+ }
325
+ for (let i = this.hist + 1; i < this.history.length; i++) {
326
+ const h = this.history[i];
327
+ if (h.startsWith(this.search) && h !== this.line) {
328
+ this.hist = i;
329
+ this.setLine(h);
330
+ return;
331
+ }
332
+ }
333
+ }
334
+ histNext() {
335
+ if (this.hist === -1)
336
+ return;
337
+ for (let i = this.hist - 1; i >= 0; i--) {
338
+ const h = this.history[i];
339
+ if (h.startsWith(this.search) && h !== this.line) {
340
+ this.hist = i;
341
+ this.setLine(h);
342
+ return;
343
+ }
344
+ }
345
+ this.hist = -1;
346
+ this.setLine(this.saved);
347
+ }
348
+ }
349
+ exports.InkEditor = InkEditor;
350
+ const CSI = /\u001b\[[0-?]*[ -/]*[@-~]|\u009b[0-?]*[ -/]*[@-~]/g;
351
+ /** The width of a row as this file measures it (erring wide). */
352
+ function width(text) {
353
+ let w = 0;
354
+ for (const ch of text)
355
+ w += (0, livePrompt_1.charCols)(ch.codePointAt(0));
356
+ return w;
357
+ }
358
+ /**
359
+ * A line in rows of at most `cols` columns, broken between words (a row ends
360
+ * after a space, which is not shown; mid-word only for a word longer than a
361
+ * row). `end`: where the next row starts in the line.
362
+ */
363
+ function wrapRows(line, cols) {
364
+ const rows = [];
365
+ let at = 0;
366
+ while (at < line.length) {
367
+ const rest = line.slice(at);
368
+ const split = (0, livePrompt_1.splitRows)(rest, cols);
369
+ if (split.length === 1) {
370
+ rows.push({ text: split[0].text, end: line.length });
371
+ break;
372
+ }
373
+ const cut = split[0].end;
374
+ const sp = rest[cut] === ' ' ? cut : rest.lastIndexOf(' ', cut - 1);
375
+ if (sp > 0) {
376
+ rows.push({ text: rest.slice(0, sp).replace(/\t/g, ' ').trimEnd(), end: at + sp + 1 });
377
+ at += sp + 1;
378
+ }
379
+ else {
380
+ rows.push({ text: split[0].text, end: at + cut });
381
+ at += cut;
382
+ }
383
+ }
384
+ return rows.length ? rows : [{ text: '', end: 0 }];
385
+ }
386
+ function oneLine(text) {
387
+ const lines = text.split('\n');
388
+ return lines.length > 1 ? `${lines[0]} (+${lines.length - 1} line${lines.length === 2 ? '' : 's'})` : lines[0];
389
+ }
390
+ /**
391
+ * The Ink session view: the transcript's writer, the region below it, and
392
+ * the keys. One per session; {@link close} hands the terminal back.
393
+ */
394
+ class InkScreen {
395
+ constructor(o) {
396
+ this.o = o;
397
+ this.editor = new InkEditor();
398
+ this.context = { agent: () => '', counts: () => '' };
399
+ /** Transcript text to write with the next frame: whole lines. */
400
+ this.pending = '';
401
+ /** The transcript's unfinished line (a reply being written): in the region. */
402
+ this.tail = '';
403
+ this.masked = false;
404
+ this.waitStatus = null;
405
+ this.completions = null;
406
+ this.turnView = null;
407
+ this.inst = null;
408
+ this.writeOut = null;
409
+ this.timer = null;
410
+ this.lastFrame = 0;
411
+ this.closing = false;
412
+ this.hidden = false;
413
+ /** Closed: what is written from now on goes to the terminal as it is. */
414
+ this.done = false;
415
+ this.settled = [];
416
+ this.onResize = () => this.schedule();
417
+ /** Lines put between a reply's text (the owner's message read, a line
418
+ * after it): its next text is marked as the agent's again. */
419
+ this.breaks = 0;
420
+ this.frameMs = Math.max(exports.FRAME_MS, o.frameMs ?? exports.FRAME_MS);
421
+ this.colors = o.colors ?? true;
422
+ this.h = o.lib.React.createElement.bind(o.lib.React);
423
+ const ink = o.lib.ink;
424
+ // The writer of transcript text, from Ink's stdout context.
425
+ this.Grab = () => { this.writeOut = ink.useStdout().write; return null; };
426
+ this.ask = o.makeAsk(this.editor, (kind, q, e) => this.echo(kind, q, e.text));
427
+ this.editor.changed = () => this.schedule();
428
+ }
429
+ /** Draw the region for the first time. */
430
+ mount() {
431
+ const { ink } = this.o.lib;
432
+ this.inst = ink.render(this.tree(), {
433
+ stdout: this.o.stdout,
434
+ stderr: this.o.stderr ?? this.o.stdout,
435
+ // Ink never reads the keyboard here: the shell's keypress events come in through key().
436
+ stdin: Object.assign(new node_stream_1.PassThrough(), { isTTY: false }),
437
+ exitOnCtrlC: false,
438
+ patchConsole: this.o.patchConsole ?? true,
439
+ });
440
+ this.lastFrame = Date.now();
441
+ this.o.stdout.on('resize', this.onResize);
442
+ this.schedule();
443
+ }
444
+ // ── what the shell writes ──
445
+ /** Text for the transcript, cleaned by the caller (interactive.ts `out`). */
446
+ write(s) {
447
+ if (!s)
448
+ return;
449
+ const all = this.tail + s;
450
+ const nl = all.lastIndexOf('\n');
451
+ if (nl < 0) {
452
+ this.tail = all;
453
+ }
454
+ else {
455
+ // Finished lines stay in the scrollback: broken between words.
456
+ this.pending += (0, livePrompt_1.wrapText)(all.slice(0, nl + 1), this.wrapCols());
457
+ this.tail = all.slice(nl + 1);
458
+ }
459
+ this.schedule();
460
+ }
461
+ /** The width text for the transcript is wrapped to: the terminal's, less one. */
462
+ wrapCols() {
463
+ return Math.max(20, (this.o.stdout.columns || 80) - 1);
464
+ }
465
+ /**
466
+ * The shell's own text with escape sequences in it (interactive.ts
467
+ * `term`): an OSC 8 link stays as it is in whole lines; cursor and erase
468
+ * sequences, which would move the region from under Ink, go; a write of
469
+ * nothing but sequences (a terminal reset) is left out.
470
+ */
471
+ raw(s) {
472
+ const text = s.replace(CSI, '').replace(/\r/g, '');
473
+ if (!(0, cells_1.cleanStream)(text))
474
+ return;
475
+ if (/\u001b\]/.test(text) && !this.tail && text.endsWith('\n')) {
476
+ this.pending += text;
477
+ this.schedule();
478
+ return;
479
+ }
480
+ this.write((0, cells_1.cleanStream)(text));
481
+ }
482
+ /** A block for the transcript now, after the line being written (printAbovePrompt). */
483
+ print(text) {
484
+ this.breakTail();
485
+ let t = text.replace(CSI, '').replace(/\r/g, '').replace(/^\n+/, '');
486
+ if (!t)
487
+ return;
488
+ // Broken between words, unless it carries a link (the shell's own sequence).
489
+ if (!/\u001b/.test(t))
490
+ t = (0, livePrompt_1.wrapText)(t, this.wrapCols());
491
+ this.pending += t.endsWith('\n') ? t : `${t}\n`;
492
+ this.schedule();
493
+ }
494
+ /** A whole line above the line being written (a turn's note). */
495
+ note(text) {
496
+ this.pending += `${/\u001b/.test(text) ? text : (0, livePrompt_1.wrapText)(text, this.wrapCols())}\n`;
497
+ this.schedule();
498
+ }
499
+ /** A whole line after the line being written, which ends there. */
500
+ after(text) {
501
+ this.breakTail();
502
+ this.breaks++;
503
+ this.note(text);
504
+ }
505
+ /** The owner's message in the transcript: `❯ text`, highlighted. */
506
+ owner(text) {
507
+ this.breakTail();
508
+ this.breaks++;
509
+ let shown = text;
510
+ try {
511
+ shown = this.o.ownerText?.(text) ?? text;
512
+ }
513
+ catch { /* as typed */ }
514
+ let lines = (0, cells_1.cleanStream)(shown).split('\n');
515
+ // A long one (a big paste): its first lines and how many more.
516
+ if (lines.length > OWNER_LINES + 2)
517
+ lines = [...lines.slice(0, OWNER_LINES), `… (+${lines.length - OWNER_LINES} more lines)`];
518
+ // Each line broken between words, its further rows under its text.
519
+ const rows = lines.flatMap((l) => (0, livePrompt_1.wrapProse)(l, Math.max(18, this.wrapCols() - 2)));
520
+ const [on, off] = this.colors ? ['\u001b[100m', '\u001b[49m'] : ['', ''];
521
+ this.pending += `${rows.map((l, i) => `${on}${i ? ' ' : exports.INK_PROMPT}${l} ${off}`).join('\n')}\n`;
522
+ this.schedule();
523
+ }
524
+ /** A dim line (a run of tool calls) after what is written so far. */
525
+ dim(text) {
526
+ this.breakTail();
527
+ const [on, off] = this.colors ? ['\u001b[2m', '\u001b[22m'] : ['', ''];
528
+ this.pending += `${on}${(0, livePrompt_1.fitRow)((0, cells_1.cleanCell)(text), Math.max(20, (this.o.stdout.columns || 80) - 1))}${off}\n`;
529
+ this.schedule();
530
+ }
531
+ /** The line being written ends here. */
532
+ breakTail() {
533
+ if (!this.tail)
534
+ return;
535
+ this.pending += `${(0, livePrompt_1.wrapText)(this.tail, this.wrapCols())}\n`;
536
+ this.tail = '';
537
+ }
538
+ /** A question cancelled with Esc or Ctrl-C (`typed`: what its line held): it stays in the transcript as it was. */
539
+ cancelled(q, typed = '') {
540
+ this.questionLine(q, this.masked ? '' : typed);
541
+ }
542
+ /** The status row while no turn runs (a wait for the agent to start); null hides it. */
543
+ status(text) {
544
+ const t = text === null ? null : (0, cells_1.cleanCell)(text);
545
+ if (t === this.waitStatus)
546
+ return;
547
+ this.waitStatus = t;
548
+ this.schedule();
549
+ }
550
+ /** A chat turn's view. `steers`: Enter puts a message into the turn. */
551
+ turn(o = {}) {
552
+ this.turnView?.end();
553
+ const t = new InkTurn(this, o.steered ?? (() => []), !!o.steers, o.next ?? (() => []));
554
+ this.turnView = t;
555
+ this.completions = null;
556
+ this.schedule();
557
+ return t;
558
+ }
559
+ /** @internal */
560
+ endTurn(t) {
561
+ if (this.turnView === t)
562
+ this.turnView = null;
563
+ // Tab's candidates were for what was typed during the turn.
564
+ this.completions = null;
565
+ this.schedule();
566
+ }
567
+ /** @internal */
568
+ summarize(labels) {
569
+ try {
570
+ return this.o.summarize(labels);
571
+ }
572
+ catch {
573
+ return '';
574
+ }
575
+ }
576
+ /** Ask a secret: what is typed shows as `*` and stays out of the history. */
577
+ async secret(run) {
578
+ this.masked = true;
579
+ this.editor.noHistory = true;
580
+ this.schedule();
581
+ try {
582
+ return await run();
583
+ }
584
+ finally {
585
+ this.masked = false;
586
+ this.editor.noHistory = false;
587
+ this.schedule();
588
+ }
589
+ }
590
+ /** Something the region shows changed. */
591
+ refresh() { this.schedule(); }
592
+ echo(kind, q, text) {
593
+ // A bare Enter at the message prompt (a refresh) leaves no line behind.
594
+ if (kind === 'message') {
595
+ if (text.trim())
596
+ this.owner(text);
597
+ return;
598
+ }
599
+ this.questionLine(q, this.masked ? '*'.repeat([...text].length) : text);
600
+ }
601
+ questionLine(q, text) {
602
+ this.breakTail();
603
+ this.pending += `${(0, cells_1.cleanStream)(q.replace(/^\n+/, ''))}${(0, cells_1.cleanStream)(text)}\n`;
604
+ this.schedule();
605
+ }
606
+ // ── keys ──
607
+ /** One key of the session (the shell routes every keypress here while the view is up). */
608
+ key(s, key = {}) {
609
+ if (this.closing)
610
+ return;
611
+ const e = this.editor;
612
+ const plain = !key.ctrl && !key.meta && !key.shift;
613
+ if (key.name !== 'tab')
614
+ this.completions = null;
615
+ if (key.ctrl && key.name === 'c') {
616
+ e.emit('keypress', s, key);
617
+ this.o.onInterrupt();
618
+ this.schedule();
619
+ return;
620
+ }
621
+ if (key.name === 'tab' && !e.pasting && !key.ctrl && !key.meta) {
622
+ // During a turn Tab queues what is typed for the next turn, unless it
623
+ // is a command, which it completes as at the prompt.
624
+ const command = e.line.trimStart().startsWith('/') && !this.ask.drafting?.().length;
625
+ if (this.turnView && !command)
626
+ this.ask.queueEdit?.();
627
+ else
628
+ this.complete();
629
+ }
630
+ else if (key.name === 'backspace' && plain && !e.pasting && e.cursor === 0 && this.ask.unwind?.()) {
631
+ // The line before comes back, joined.
632
+ }
633
+ else if (key.ctrl && !key.meta && key.name === 'u' && !e.pasting && this.ask.drafting?.().length && this.ask.clearBox?.()) {
634
+ // Ctrl-U on a message of several lines: all of it goes, not only this line.
635
+ }
636
+ else if (key.name === 'up' && plain && !e.pasting && !this.ask.waiting?.() && e.line === ''
637
+ && !this.ask.drafting?.().length && (this.ask.queued?.().length || this.ask.held?.count())) {
638
+ // ↑ on an empty line while the shell is busy: the newest queued entry, back to edit.
639
+ this.ask.recall?.();
640
+ }
641
+ else {
642
+ e.handle(s, key);
643
+ }
644
+ e.emit('keypress', s, key);
645
+ if (key.name === 'escape')
646
+ this.o.onEscape();
647
+ this.schedule();
648
+ }
649
+ // As readline: the candidates' common start is filled in; when it adds
650
+ // nothing, the candidates are listed under the box.
651
+ complete() {
652
+ const e = this.editor;
653
+ const r = (0, livePrompt_1.completeAt)(e.line, e.cursor, (before) => this.o.complete(before));
654
+ if (r.line !== e.line)
655
+ e.replaceBefore(e.cursor, r.line.slice(0, r.cursor));
656
+ if (r.list)
657
+ this.completions = r.list;
658
+ }
659
+ // ── frames ──
660
+ /** @internal Redraw at the next frame. */
661
+ schedule() {
662
+ if (this.done) {
663
+ const t = this.pending + this.tail;
664
+ this.pending = '';
665
+ this.tail = '';
666
+ if (t)
667
+ this.o.stdout.write(t);
668
+ return;
669
+ }
670
+ if (this.timer || !this.inst || this.hidden)
671
+ return;
672
+ const wait = Math.max(0, this.lastFrame + this.frameMs - Date.now());
673
+ this.timer = setTimeout(() => this.frame(), wait);
674
+ }
675
+ /** Resolves once nothing is due: what was pending is on the screen, no
676
+ * frame waits, and a frame's time has passed (Ink's own 32 ms window), so
677
+ * the screen is the last frame (tests). */
678
+ async settle() {
679
+ for (let i = 0; i < 25; i++) {
680
+ if (this.timer)
681
+ await new Promise((r) => this.settled.push(r));
682
+ await new Promise((r) => setTimeout(r, this.frameMs));
683
+ if (!this.timer)
684
+ return;
685
+ }
686
+ }
687
+ frame() {
688
+ if (this.timer)
689
+ clearTimeout(this.timer);
690
+ this.timer = null;
691
+ if (!this.inst)
692
+ return;
693
+ this.lastFrame = Date.now();
694
+ const { tree, commit } = this.layout();
695
+ const text = this.pending + commit;
696
+ this.pending = '';
697
+ try {
698
+ this.inst.rerender(tree);
699
+ if (text)
700
+ (this.writeOut ?? ((t) => this.o.stdout.write(t)))(text);
701
+ }
702
+ catch {
703
+ // Ink failed to draw: the text still reaches the terminal.
704
+ if (text)
705
+ this.o.stdout.write(text);
706
+ }
707
+ for (const r of this.settled.splice(0))
708
+ r();
709
+ }
710
+ tree(rows = []) {
711
+ return this.h(this.o.lib.ink.Box, { flexDirection: 'column' }, this.h(this.Grab), ...rows);
712
+ }
713
+ text(props, ...children) {
714
+ const p = { ...(props ?? {}) };
715
+ if (!this.colors)
716
+ for (const k of ['color', 'backgroundColor', 'dimColor'])
717
+ delete p[k];
718
+ return this.h(this.o.lib.ink.Text, p, ...children);
719
+ }
720
+ /** The region's rows, bottom part first measured, and the tail rows that no longer fit (to the transcript). */
721
+ layout() {
722
+ if (this.hidden) {
723
+ const commit = this.tail ? `${this.tail}\n` : '';
724
+ this.tail = '';
725
+ return { tree: this.tree(), commit };
726
+ }
727
+ const cols = Math.max(20, (this.o.stdout.columns || 80) - 1);
728
+ const height = Math.max(exports.MIN_ROWS, this.o.stdout.rows || 24);
729
+ const turn = this.turnView;
730
+ const w = this.ask.waiting?.() ?? null;
731
+ // What was sent during the turn and waits: inserted into it (for the
732
+ // agent to read at its next step), or for the next turn.
733
+ const waiting = [
734
+ ...(turn ? turn.steered().map((text) => ({ text, how: exports.WAITING_AGENT })) : []),
735
+ ...(this.ask.queued?.() ?? []).map((q) => ({ text: q.text, how: exports.WAITING_TURN })),
736
+ // Taken by the agent as a new message: it waits for its own turn.
737
+ ...(turn ? turn.next().map((text) => ({ text, how: exports.WAITING_TURN })) : []),
738
+ ];
739
+ const shownWaiting = waiting.length > 4 ? [...waiting.slice(0, 3), { text: '', how: `… and ${waiting.length - 3} more` }] : waiting;
740
+ const named = (t) => { try {
741
+ return this.o.ownerText?.(t) ?? t;
742
+ }
743
+ catch {
744
+ return t;
745
+ } };
746
+ let waitRows = shownWaiting.map(({ text, how }) => {
747
+ if (!text)
748
+ return this.text({ dimColor: true }, ` ${how}`);
749
+ const main = (0, livePrompt_1.fitRow)(`${exports.INK_PROMPT}${(0, cells_1.cleanCell)(oneLine(named(text)))} `, Math.max(8, cols - how.length - 2));
750
+ return this.text(null, this.text({ backgroundColor: 'gray' }, main), this.text({ dimColor: true }, ` ${how}`));
751
+ });
752
+ // The status row: what the agent does (or what is awaited), and what waits for the owner.
753
+ const counts = this.context.counts();
754
+ const left = turn ? turn.statusLine() : this.waitStatus;
755
+ let statusRow = null;
756
+ if (left || counts) {
757
+ const room = Math.max(4, cols - (counts ? width(counts) + 2 : 0));
758
+ statusRow = this.h(this.o.lib.ink.Box, { width: cols, justifyContent: 'space-between' }, this.text(null, left ? (0, livePrompt_1.fitRow)(left, room) : ''), this.text({ color: 'yellow' }, counts ? (0, livePrompt_1.fitRow)(counts, cols - 1) : ''));
759
+ }
760
+ // The input: the message's earlier lines, then the line with the cursor.
761
+ const draft = this.ask.drafting?.() ?? [];
762
+ const asking = w && w.kind !== 'message';
763
+ const first = asking ? (0, cells_1.cleanCell)(w.q.replace(/^\n+/, '')).trimStart() : exports.INK_PROMPT;
764
+ let draftShown = draft.length > 4 ? [draft[0], `(${draft.length - 3} more lines)`, ...draft.slice(-2)] : draft;
765
+ const lineRows = this.lineRows(draft.length ? ' ' : first, cols, Math.max(1, height - 14));
766
+ const back = !w && waiting.some((x) => x.how === exports.WAITING_TURN) ? ' · ↑ edits queued' : '';
767
+ // Esc first: on a narrow screen what is cut is the end.
768
+ const hint = turn
769
+ ? `Esc stops · ${turn.steers ? 'Enter steers · Tab queues' : 'Enter queues'}${back}`
770
+ : asking ? 'Esc cancels' : w ? 'Tab completes · /help' : back.slice(3);
771
+ // While a wait is on the status row (a start, a reset), it says the phase.
772
+ const state = this.waitStatus ? '' : this.context.state?.() ?? '';
773
+ const footer = [this.context.agent(), state, hint].filter(Boolean).join(' · ');
774
+ let footerRow = footer ? this.text({ dimColor: true }, (0, livePrompt_1.fitRow)(footer, cols)) : null;
775
+ let compRows = this.completions ? this.candidateRows(this.completions, cols).map((r) => this.text({ dimColor: true }, r)) : [];
776
+ const rule = this.text({ dimColor: true }, '─'.repeat(cols));
777
+ const count = () => waitRows.length + (statusRow ? 1 : 0) + 2 + draftShown.length + lineRows.length + (footerRow ? 1 : 0) + compRows.length;
778
+ // A short screen: the least needed goes first, so the region stays below the screen's height.
779
+ const budget = height - 2;
780
+ if (count() > budget)
781
+ compRows = compRows.slice(0, 1);
782
+ if (count() > budget)
783
+ compRows = [];
784
+ if (count() > budget)
785
+ waitRows = waitRows.slice(-1);
786
+ if (count() > budget)
787
+ draftShown = draftShown.length ? [`(${draft.length} earlier lines)`] : [];
788
+ if (count() > budget)
789
+ footerRow = null;
790
+ if (count() > budget)
791
+ statusRow = null;
792
+ const inputRows = [
793
+ ...draftShown.map((d, i) => this.text(null, (0, livePrompt_1.fitRow)(`${i === 0 ? first : ' '}${(0, cells_1.cleanCell)(d)}`, cols))),
794
+ ...lineRows,
795
+ ];
796
+ const below = [
797
+ ...waitRows,
798
+ ...(statusRow ? [statusRow] : []),
799
+ rule,
800
+ ...inputRows,
801
+ rule,
802
+ ...(footerRow ? [footerRow] : []),
803
+ ...compRows,
804
+ ];
805
+ // The tail in what is left of the screen, wrapped between words; past
806
+ // that, its first rows go to the transcript as they are shown.
807
+ let commit = '';
808
+ let tailRows = this.tail ? wrapRows(this.tail, cols) : [];
809
+ const room = Math.max(0, height - 1 - below.length);
810
+ if (tailRows.length > room) {
811
+ const head = tailRows.slice(0, tailRows.length - room);
812
+ commit = head.map((r) => `${r.text}\n`).join('');
813
+ this.tail = this.tail.slice(head[head.length - 1].end);
814
+ tailRows = tailRows.slice(head.length);
815
+ }
816
+ return { tree: this.tree([...tailRows.map((r) => this.text(null, r.text)), ...below]), commit };
817
+ }
818
+ /** Tab's candidates in columns, at most three rows (the last one says how many more). */
819
+ candidateRows(list, cols) {
820
+ const items = list.map((c) => (0, cells_1.cleanCell)(c) || ' ');
821
+ const colW = Math.min(cols, Math.max(...items.map(width)) + 2);
822
+ const per = Math.max(1, Math.floor(cols / colW));
823
+ const rows = [];
824
+ for (let i = 0; i < items.length && rows.length < 3; i += per) {
825
+ rows.push((0, livePrompt_1.fitRow)(items.slice(i, i + per).map((c) => c + ' '.repeat(Math.max(0, colW - width(c)))).join('').trimEnd(), cols));
826
+ }
827
+ const shown = Math.min(items.length, per * 3);
828
+ if (shown < items.length)
829
+ rows[2] = (0, livePrompt_1.fitRow)(`${rows[2].slice(0, Math.max(0, cols - 14))}… +${items.length - shown} more`, cols);
830
+ return rows;
831
+ }
832
+ /** The line being edited after `prefix`, in rows, the cursor inverted; at most `max` rows, around the cursor. */
833
+ lineRows(prefix, cols, max) {
834
+ const e = this.editor;
835
+ // The owner's own text, one display unit per UTF-16 unit, so the cursor's offset holds.
836
+ // eslint-disable-next-line no-control-regex
837
+ const safe = (t) => t.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').replace(/\p{Cf}/gu, (m) => ' '.repeat(m.length));
838
+ const pre = (0, cells_1.cleanCell)(prefix);
839
+ const disp = pre + (this.masked ? '*'.repeat([...e.line].length) : safe(e.line));
840
+ const at = pre.length + (this.masked ? [...e.line.slice(0, e.cursor)].length : e.cursor);
841
+ const rows = (0, livePrompt_1.splitRows)(disp, cols).map((r, i, all) => ({ start: i ? all[i - 1].end : 0, end: r.end }));
842
+ const last = rows[rows.length - 1];
843
+ if (at >= disp.length && width(disp.slice(last.start)) + 1 > cols)
844
+ rows.push({ start: disp.length, end: disp.length });
845
+ let cur = rows.findIndex((r) => at >= r.start && at < r.end);
846
+ if (cur < 0)
847
+ cur = rows.length - 1;
848
+ const from = Math.max(0, Math.min(cur - max + 1, rows.length - max));
849
+ return rows.slice(from, from + max).map((r, i) => {
850
+ if (from + i !== cur)
851
+ return this.text(null, disp.slice(r.start, r.end));
852
+ const ch = at < disp.length ? String.fromCodePoint(disp.codePointAt(at)) : ' ';
853
+ return this.text(null, disp.slice(r.start, at), this.h(this.o.lib.ink.Text, { inverse: true }, ch), disp.slice(at + ch.length, r.end));
854
+ });
855
+ }
856
+ // ── leaving ──
857
+ /** Take the region off the screen now, without waiting for a frame (the process is ending). */
858
+ closeNow() {
859
+ if (this.done || !this.inst)
860
+ return;
861
+ this.closing = true;
862
+ this.hidden = true;
863
+ if (this.timer)
864
+ clearTimeout(this.timer);
865
+ this.timer = null;
866
+ this.o.stdout.off('resize', this.onResize);
867
+ try {
868
+ this.inst.clear();
869
+ if (this.pending || this.tail)
870
+ this.o.stdout.write(this.pending + (this.tail ? `${this.tail}\n` : ''));
871
+ this.pending = '';
872
+ this.tail = '';
873
+ this.inst.unmount();
874
+ }
875
+ catch { /* the process is ending */ }
876
+ this.inst = null;
877
+ this.done = true;
878
+ }
879
+ /** Take the region off the screen and give the terminal back; what is pending is written first. */
880
+ async close() {
881
+ if (this.closing)
882
+ return;
883
+ this.closing = true;
884
+ this.turnView?.end();
885
+ this.o.stdout.off('resize', this.onResize);
886
+ if (!this.inst) {
887
+ this.done = true;
888
+ this.schedule();
889
+ return;
890
+ }
891
+ // No other frame from here: the last one hides the region and writes
892
+ // what is pending, drawn at once (more than Ink's 32 ms after the one
893
+ // before), so unmounting has nothing left to draw.
894
+ this.hidden = true;
895
+ if (this.timer)
896
+ clearTimeout(this.timer);
897
+ this.timer = null;
898
+ const wait = this.lastFrame + this.frameMs - Date.now();
899
+ if (wait > 0)
900
+ await new Promise((r) => setTimeout(r, wait));
901
+ this.frame();
902
+ try {
903
+ this.inst.clear();
904
+ this.inst.unmount();
905
+ }
906
+ catch { /* the terminal is the shell's again either way */ }
907
+ this.inst = null;
908
+ this.done = true;
909
+ }
910
+ }
911
+ exports.InkScreen = InkScreen;
912
+ /**
913
+ * A chat turn under the Ink view: the reply goes to the transcript (its
914
+ * unfinished line drawn just above the region), the status row says what
915
+ * the agent does, and each run of tool calls becomes one dim line when the
916
+ * reply goes on or the turn ends.
917
+ */
918
+ class InkTurn {
919
+ constructor(screen, steered, steers, next = () => []) {
920
+ this.screen = screen;
921
+ this.steered = steered;
922
+ this.steers = steers;
923
+ this.next = next;
924
+ this.live = true;
925
+ /** Added to the status line's time (interactive.ts paintStatus). */
926
+ this.stopHint = ' · Esc to stop';
927
+ this.statusText = null;
928
+ this.labels = [];
929
+ /** A run's line was just written: the reply's next text starts it own line. */
930
+ this.gap = false;
931
+ this.ended = false;
932
+ this.spin = 0;
933
+ this.t0 = Date.now();
934
+ this.tick = setInterval(() => { this.spin++; screen.refresh(); }, 1000);
935
+ this.tick.unref?.();
936
+ }
937
+ write(s) {
938
+ if (this.ended)
939
+ return;
940
+ let t = (0, cells_1.cleanStream)(s);
941
+ if (!t)
942
+ return;
943
+ this.closeRun();
944
+ if (this.gap) {
945
+ t = t.replace(/^\n+/, '');
946
+ if (!t)
947
+ return;
948
+ this.gap = false;
949
+ }
950
+ this.screen.write(t);
951
+ }
952
+ note(text) {
953
+ if (this.ended) {
954
+ this.screen.write((0, cells_1.cleanStream)(text));
955
+ return;
956
+ }
957
+ const t = (0, cells_1.cleanStream)(text).replace(/^\n+/, '').replace(/\n+$/, '');
958
+ if (t)
959
+ this.screen.note(t);
960
+ }
961
+ /** A line after what the reply has written so far: its line ends there. */
962
+ after(text) {
963
+ if (this.ended) {
964
+ this.screen.write((0, cells_1.cleanStream)(text));
965
+ return;
966
+ }
967
+ this.closeRun();
968
+ const t = (0, cells_1.cleanStream)(text).replace(/^\n+/, '').replace(/\n+$/, '');
969
+ if (t)
970
+ this.screen.after(t);
971
+ }
972
+ /** Lines that came between the reply's text (TurnView.breaks). */
973
+ get breaks() { return this.screen.breaks; }
974
+ status(text) {
975
+ const t = text === null ? null : (0, cells_1.cleanCell)(text);
976
+ if (t === this.statusText)
977
+ return;
978
+ this.statusText = t;
979
+ this.screen.refresh();
980
+ }
981
+ /** An activity label as the stream reports it ("tool/call bash", "thinking"). */
982
+ activity(label) {
983
+ if (!this.ended)
984
+ this.labels.push(label);
985
+ }
986
+ refresh() { this.screen.refresh(); }
987
+ end() {
988
+ if (this.ended)
989
+ return;
990
+ this.closeRun();
991
+ this.ended = true;
992
+ clearInterval(this.tick);
993
+ this.screen.endTurn(this);
994
+ }
995
+ /** The status row's text: the turn's own status, or how long it has been replying. */
996
+ statusLine() {
997
+ if (this.statusText)
998
+ return this.statusText;
999
+ return `${SPIN[this.spin % SPIN.length]} replying… (${Math.floor((Date.now() - this.t0) / 1000)}s${this.stopHint})`;
1000
+ }
1001
+ closeRun() {
1002
+ if (!this.labels.length)
1003
+ return;
1004
+ const sum = this.screen.summarize(this.labels);
1005
+ this.labels = [];
1006
+ if (!sum)
1007
+ return;
1008
+ this.screen.dim(`· ${sum}`);
1009
+ this.gap = true;
1010
+ }
1011
+ }
1012
+ exports.InkTurn = InkTurn;
1013
+ /** Mount the view (throws when Ink cannot draw). */
1014
+ function openInkScreen(o) {
1015
+ const screen = new InkScreen(o);
1016
+ screen.mount();
1017
+ return screen;
1018
+ }
1019
+ //# sourceMappingURL=inkView.js.map