@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,35 @@
1
+ /**
2
+ * @file cli/legacy/modelKey.ts
3
+ * @description LEGACY(model-key): the CLI's part of sending model keys with
4
+ * the request (the SDK's is legacy/modelKey.ts).
5
+ *
6
+ * A reset of an agent whose credential set holds the key needs no key for
7
+ * an image that reads the set; an image from before that reads only the key
8
+ * sent with the reset, so the CLI still finds one ({@link resetKeyForOlderImages}).
9
+ * Once those images are gone, delete this file with the SDK's, and remove
10
+ * every piece marked LEGACY(model-key) (`git grep -n 'LEGACY(model-key)'`):
11
+ * the compiler lists this file's call site, the marks find the rest (the
12
+ * secret-env pins, messages about the key given at create/reset).
13
+ */
14
+
15
+ /**
16
+ * The key a reset sends for older images when the set holds the provider's
17
+ * key already. The key on this machine goes along and the set is left as it
18
+ * is (`keepStoredModelKey`); with none here the owner is asked (`pick`), and
19
+ * skipping sends none.
20
+ */
21
+ export async function resetKeyForOlderImages(
22
+ provider: string,
23
+ name: string,
24
+ saved: string | null,
25
+ out: (line: string) => void,
26
+ pick: () => Promise<string | null>,
27
+ ): Promise<{ apiKey?: string; keepStoredModelKey: boolean }> {
28
+ if (saved) {
29
+ out(`the agent uses ${name} from cred (cred <agent> set model changes it); an image from before model keys in cred uses the ${provider} key on this machine, sent with the reset`);
30
+ return { apiKey: saved, keepStoredModelKey: true };
31
+ }
32
+ out(`the agent uses ${name} from cred; an image from before model keys in cred also needs it with the reset (a key given here also replaces the one in cred)`);
33
+ const key = await pick();
34
+ return key ? { apiKey: key, keepStoredModelKey: false } : { keepStoredModelKey: true };
35
+ }
@@ -0,0 +1,615 @@
1
+ /**
2
+ * The session prompt while a turn runs. The reply prints above the prompt:
3
+ * whole lines stay as they are, and the line still being written is drawn
4
+ * just above the prompt and redrawn as text arrives. The prompt stays where
5
+ * the owner types, so what they type stays on screen and can be edited.
6
+ * Above the prompt, below the reply, the turn's status line (a spinner and
7
+ * what the agent does) and what the owner sent during the turn (steered into
8
+ * it, or queued for after it) are shown until they are delivered.
9
+ *
10
+ * Everything between the top of that region and the prompt is drawn here,
11
+ * one terminal row per line (a long line is cut into rows here, so the
12
+ * number of rows is known); the prompt and what is typed are readline's,
13
+ * which keeps its own count of the rows the cursor sits below the prompt's
14
+ * start. A redraw moves up both counts, clears to the end of the screen and
15
+ * draws the region again. readline writes a new line on Enter and clears the
16
+ * line it held; those keys are seen before and after readline handles them
17
+ * (`liveKeys`), so the redraw that follows knows where the region starts.
18
+ *
19
+ * Without a terminal (piped output) a turn prints as before: PlainTurn.
20
+ */
21
+ import type * as readline from 'node:readline';
22
+ import type { Writable } from 'node:stream';
23
+ import { cleanCell, cleanStream } from './commands/cells';
24
+
25
+ /** The prompt of a message's next line. */
26
+ export const CONT_PROMPT = '… ';
27
+
28
+ /** How a turn's output reaches the screen. */
29
+ export interface TurnView {
30
+ /** True when the prompt stays on screen during the turn. */
31
+ readonly live: boolean;
32
+ /** Reply text, in order (cleaned here). */
33
+ write(s: string): void;
34
+ /** A line about the turn (a notice, an inserted message read): above the
35
+ * line the reply is writing, which stays whole. */
36
+ note(text: string): void;
37
+ /** The status line (null hides it). `breakLine`: the reply's last line is
38
+ * unfinished (only a turn without a live prompt needs it). */
39
+ status(text: string | null, breakLine?: boolean): void;
40
+ /** A line after what the reply has written so far (where the view keeps
41
+ * the reply's unfinished line apart; else as `note`). */
42
+ after?(text: string): void;
43
+ /** How many lines came between the reply's text so far (after()): the
44
+ * reply's next text is marked as the agent's again. */
45
+ readonly breaks?: number;
46
+ /** Something the prompt shows changed: redraw soon. */
47
+ refresh(): void;
48
+ /** Said after the status line's time (` · Esc to stop`) by a view whose prompt does not say it. */
49
+ readonly stopHint?: string;
50
+ /** An activity label of the turn ("tool/call bash"), for a view that sums up each run of tool calls. */
51
+ activity?(label: string): void;
52
+ /** The turn is over: the region and its prompt go, the reply's unfinished
53
+ * line is left as written (no line break). */
54
+ end(): void;
55
+ }
56
+
57
+ /** What the live prompt reads from the shell's line queue. */
58
+ export interface LiveInput {
59
+ /** Lines of a message begun but not sent (a line ended with \, Option+Enter, a paste). */
60
+ drafting?(): string[];
61
+ /** Entries waiting for the next prompt, oldest first. */
62
+ queued?(): Array<{ text: string }>;
63
+ /** Put the newest waiting entry back to be edited; false when there is none. */
64
+ recall?(): boolean;
65
+ /** How many entries wait with the agent (↑ takes the newest back by cancelling it there). */
66
+ held?(): number;
67
+ /** Queue what is being edited for the next prompt; false when nothing is. */
68
+ queueEdit?(): boolean;
69
+ /** The shell's Tab completion of the text before the cursor (completeLine). */
70
+ complete?(before: string): [string[], string];
71
+ }
72
+
73
+ function commonPrefix(list: readonly string[]): string {
74
+ if (!list.length) return '';
75
+ let p = list[0];
76
+ for (const s of list) while (!s.startsWith(p)) p = p.slice(0, -1);
77
+ return p;
78
+ }
79
+
80
+ /**
81
+ * Tab on `line` with the cursor at `cursor`, as readline does it: what the
82
+ * candidates share is filled in; when that adds nothing and there are
83
+ * several, `list` has them to show. Exported for the tests.
84
+ */
85
+ export function completeAt(
86
+ line: string,
87
+ cursor: number,
88
+ complete: (before: string) => [string[], string],
89
+ ): { line: string; cursor: number; list: string[] | null } {
90
+ let hits: string[];
91
+ let sub: string;
92
+ try {
93
+ [hits, sub] = complete(line.slice(0, cursor));
94
+ } catch {
95
+ return { line, cursor, list: null };
96
+ }
97
+ if (!hits.length) return { line, cursor, list: null };
98
+ const prefix = commonPrefix(hits.filter(Boolean));
99
+ if (prefix.startsWith(sub) && prefix.length > sub.length) {
100
+ const add = prefix.slice(sub.length);
101
+ return { line: line.slice(0, cursor) + add + line.slice(cursor), cursor: cursor + add.length, list: null };
102
+ }
103
+ if (!sub.startsWith(prefix)) {
104
+ const at = cursor - sub.length;
105
+ return { line: line.slice(0, at) + prefix + line.slice(cursor), cursor: at + prefix.length, list: null };
106
+ }
107
+ return { line, cursor, list: hits.length > 1 ? hits : null };
108
+ }
109
+
110
+ /** What the live prompt shows besides the reply, read at every redraw. */
111
+ export interface LiveState {
112
+ /** The prompt, e.g. `agent 625 (replying, Esc stops) › `. */
113
+ prompt: string;
114
+ /** Lines above the prompt: what was steered into the turn, what waits. */
115
+ notes: string[];
116
+ }
117
+
118
+ type Key = { name?: string; meta?: boolean; ctrl?: boolean; shift?: boolean };
119
+
120
+ /** The parts of a terminal readline the live prompt uses. */
121
+ type LiveRl = readline.Interface & { prevRows?: number; history?: string[] };
122
+
123
+ /**
124
+ * The code points Unicode's East Asian Width calls Wide or Fullwidth (15.1):
125
+ * two columns in a terminal. Everything else, the Ambiguous ones among them
126
+ * (`—`, `→`, `─`, `❯`), is one, as terminals outside CJK locales draw them.
127
+ */
128
+ const WIDE: ReadonlyArray<readonly [number, number]> = [
129
+ [0x1100, 0x115f], [0x231a, 0x231b], [0x2329, 0x232a], [0x23e9, 0x23ec], [0x23f0, 0x23f0], [0x23f3, 0x23f3],
130
+ [0x25fd, 0x25fe], [0x2614, 0x2615], [0x2648, 0x2653], [0x267f, 0x267f], [0x2693, 0x2693], [0x26a1, 0x26a1],
131
+ [0x26aa, 0x26ab], [0x26bd, 0x26be], [0x26c4, 0x26c5], [0x26ce, 0x26ce], [0x26d4, 0x26d4], [0x26ea, 0x26ea],
132
+ [0x26f2, 0x26f3], [0x26f5, 0x26f5], [0x26fa, 0x26fa], [0x26fd, 0x26fd], [0x2705, 0x2705], [0x270a, 0x270b],
133
+ [0x2728, 0x2728], [0x274c, 0x274c], [0x274e, 0x274e], [0x2753, 0x2755], [0x2757, 0x2757], [0x2795, 0x2797],
134
+ [0x27b0, 0x27b0], [0x27bf, 0x27bf], [0x2b1b, 0x2b1c], [0x2b50, 0x2b50], [0x2b55, 0x2b55], [0x2e80, 0x303e],
135
+ [0x3041, 0x33ff], [0x3400, 0x4dbf], [0x4e00, 0x9fff], [0xa000, 0xa4cf], [0xa960, 0xa97f], [0xac00, 0xd7a3],
136
+ [0xf900, 0xfaff], [0xfe10, 0xfe19], [0xfe30, 0xfe6f], [0xff00, 0xff60], [0xffe0, 0xffe6], [0x16fe0, 0x16fe4],
137
+ [0x17000, 0x18cff], [0x1b000, 0x1b2ff], [0x1f004, 0x1f004], [0x1f0cf, 0x1f0cf], [0x1f18e, 0x1f18e], [0x1f191, 0x1f19a],
138
+ [0x1f200, 0x1f202], [0x1f210, 0x1f23b], [0x1f240, 0x1f248], [0x1f250, 0x1f251], [0x1f260, 0x1f265], [0x1f300, 0x1f320],
139
+ [0x1f32d, 0x1f335], [0x1f337, 0x1f37c], [0x1f37e, 0x1f393], [0x1f3a0, 0x1f3ca], [0x1f3cf, 0x1f3d3], [0x1f3e0, 0x1f3f0],
140
+ [0x1f3f4, 0x1f3f4], [0x1f3f8, 0x1f43e], [0x1f440, 0x1f440], [0x1f442, 0x1f4fc], [0x1f4ff, 0x1f53d], [0x1f54b, 0x1f54e],
141
+ [0x1f550, 0x1f567], [0x1f57a, 0x1f57a], [0x1f595, 0x1f596], [0x1f5a4, 0x1f5a4], [0x1f5fb, 0x1f64f], [0x1f680, 0x1f6c5],
142
+ [0x1f6cc, 0x1f6cc], [0x1f6d0, 0x1f6d2], [0x1f6d5, 0x1f6d7], [0x1f6dc, 0x1f6df], [0x1f6eb, 0x1f6ec], [0x1f6f4, 0x1f6fc],
143
+ [0x1f7e0, 0x1f7eb], [0x1f7f0, 0x1f7f0], [0x1f90c, 0x1f93a], [0x1f93c, 0x1f945], [0x1f947, 0x1f9ff], [0x1fa70, 0x1faff],
144
+ [0x20000, 0x2fffd], [0x30000, 0x3fffd],
145
+ ];
146
+
147
+ /**
148
+ * Columns a code point takes in a terminal: 0 for controls and combining or
149
+ * zero-width marks, 2 for East Asian Wide and Fullwidth ones ({@link WIDE}),
150
+ * 1 for everything else.
151
+ */
152
+ export function charCols(cp: number): number {
153
+ if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return 0;
154
+ if ((cp >= 0x300 && cp <= 0x36f) || (cp >= 0x200b && cp <= 0x200f) || cp === 0x2060 || (cp >= 0x20d0 && cp <= 0x20ff)
155
+ || (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0xfe20 && cp <= 0xfe2f) || (cp >= 0xe0100 && cp <= 0xe01ef)) return 0;
156
+ if (cp < 0x1100) return 1;
157
+ for (const [a, b] of WIDE) {
158
+ if (cp < a) return 1;
159
+ if (cp <= b) return 2;
160
+ }
161
+ return 1;
162
+ }
163
+
164
+ /** One screen row of a line: its text (tabs as spaces) and where it ends in the line. */
165
+ export interface Row { text: string; end: number }
166
+
167
+ /** A line cut into rows of at most `cols` columns. */
168
+ export function splitRows(line: string, cols: number): Row[] {
169
+ const rows: Row[] = [];
170
+ let text = '';
171
+ let w = 0;
172
+ let i = 0;
173
+ for (const ch of line) {
174
+ const tab = ch === '\t';
175
+ let c = tab ? 8 - (w % 8) : charCols(ch.codePointAt(0)!);
176
+ if (w + c > cols && text) {
177
+ rows.push({ text, end: i });
178
+ text = '';
179
+ w = 0;
180
+ if (tab) c = 8;
181
+ }
182
+ text += tab ? ' '.repeat(c) : ch;
183
+ w += c;
184
+ i += ch.length;
185
+ }
186
+ rows.push({ text, end: i });
187
+ return rows;
188
+ }
189
+
190
+ /**
191
+ * A line cut into rows of at most `cols` columns at word boundaries: a row
192
+ * ends after a space where one is (the space is not shown), mid-word only for
193
+ * a word longer than a row. For text that stays in the scrollback: copied,
194
+ * it breaks between words.
195
+ */
196
+ export function wrapWords(line: string, cols: number): string[] {
197
+ const out: string[] = [];
198
+ let rest = line;
199
+ while (rest) {
200
+ const rows = splitRows(rest, cols);
201
+ if (rows.length === 1) { out.push(rows[0].text.trimEnd()); break; }
202
+ const cut = rows[0].end;
203
+ // The last space in the first row, or right after it.
204
+ const sp = rest[cut] === ' ' ? cut : rest.lastIndexOf(' ', cut - 1);
205
+ if (sp > 0) {
206
+ out.push(rest.slice(0, sp).replace(/\t/g, ' ').trimEnd());
207
+ rest = rest.slice(sp + 1);
208
+ } else {
209
+ out.push(rows[0].text);
210
+ rest = rest.slice(cut);
211
+ }
212
+ }
213
+ return out.length ? out : [''];
214
+ }
215
+
216
+ /** A string's width on a terminal, in columns (tabs to the next stop of 8). */
217
+ export function textCols(s: string): number {
218
+ let w = 0;
219
+ for (const ch of s) w += ch === '\t' ? 8 - (w % 8) : charCols(ch.codePointAt(0)!);
220
+ return w;
221
+ }
222
+
223
+ const hasWide = (s: string): boolean => [...s].some((ch) => charCols(ch.codePointAt(0)!) === 2);
224
+
225
+ /** A word cut where it may break: between wide characters (CJK), and a run
226
+ * of other characters (Latin, digits, punctuation) whole. */
227
+ function pieces(tok: string): string[] {
228
+ if (!hasWide(tok)) return [tok];
229
+ const out: string[] = [];
230
+ let run = '';
231
+ for (const ch of tok) {
232
+ if (charCols(ch.codePointAt(0)!) === 2) {
233
+ if (run) { out.push(run); run = ''; }
234
+ out.push(ch);
235
+ } else {
236
+ run += ch;
237
+ }
238
+ }
239
+ if (run) out.push(run);
240
+ return out;
241
+ }
242
+
243
+ /** A run wider than `room` broken after its commas (JSON, a list), when it has any. */
244
+ function afterCommas(run: string, room: number): string[] {
245
+ if (textCols(run) <= room || !run.includes(',')) return [run];
246
+ return run.match(/[^,]*,|[^,]+$/g) ?? [run];
247
+ }
248
+
249
+ /**
250
+ * A line of prose in rows of at most `cols` columns, broken between words (as
251
+ * Claude Code does), for text that stays in the scrollback: further rows start
252
+ * under the line's text — its indent, a list item's text after `- `, `* ` or
253
+ * `1. ` (also right after `agent> `) or the CLI's own marks (`⚠ `, `◆ `, `· `,
254
+ * `↳ `, `⏹ `, `→ `), a value after a label and two spaces
255
+ * (`gas 1.2 OG …`, also `pending refund : 0.2 OG …`), the text after an
256
+ * `error:` / `fix:` / `usage:` / `hint:` / `→` the CLI's messages start with,
257
+ * or what was typed after a prompt (`agent 625 › `).
258
+ * A word wider than a row (a URL, a path) is left whole on a row of its own,
259
+ * for the terminal to fold, so it still copies whole; one with commas (JSON)
260
+ * breaks after them. Wide characters (CJK) break between them, and a run of
261
+ * Latin letters, digits or punctuation next to them stays whole. No row starts
262
+ * with a space it did not have.
263
+ */
264
+ export function wrapProse(line: string, cols: number): string[] {
265
+ if (cols < 8 || textCols(line) <= cols) return [line];
266
+ // A speaker (`agent> `) or a prompt (`agent 625 › `) first, then the indent
267
+ // and a list marker.
268
+ const speaker = /^(?:[\w-]+> |[^›\n]{1,40}› )/.exec(line)?.[0] ?? '';
269
+ // List markers, and the marks the CLI's own lines start with (a warning, a
270
+ // notice, a tool run, a read message, a step): further rows go under the text.
271
+ const marker = /^\s*(?:(?:[-*•⚠◆·↳⏹→]|\d{1,3}[.)])\s+)?/.exec(line.slice(speaker.length))![0];
272
+ const lead = speaker + marker;
273
+ let indentW = speaker.includes('›') ? textCols(lead) : textCols(marker);
274
+ const label = speaker ? undefined : /^\s*(?:\S+(?: \S+){0,3}? {2,}(?::\s+)?|(?:error(?: \([A-Z_]+\))?|fix|usage|hint):\s+|→\s+)(?=\S)/.exec(line)?.[0];
275
+ if (label && textCols(label) > indentW && textCols(label) <= Math.min(30, cols / 2)) indentW = textCols(label);
276
+ if (indentW > cols / 2) indentW = 0;
277
+ const indent = ' '.repeat(indentW);
278
+ const rows: string[] = [];
279
+ let row = lead;
280
+ let w = textCols(lead);
281
+ let empty = true; // no word on this row yet
282
+ const newRow = (): void => {
283
+ rows.push(row.trimEnd());
284
+ row = indent;
285
+ w = indentW;
286
+ empty = true;
287
+ };
288
+ let space = '';
289
+ for (const tok of line.slice(lead.length).match(/\s+|\S+/g) ?? []) {
290
+ if (/^\s/.test(tok)) { space = tok; continue; }
291
+ const sp = empty ? '' : space;
292
+ space = '';
293
+ const ww = textCols(tok);
294
+ if (w + textCols(sp) + ww <= cols) {
295
+ row += sp + tok;
296
+ w += textCols(sp) + ww;
297
+ empty = false;
298
+ continue;
299
+ }
300
+ const parts = pieces(tok).flatMap((p) => afterCommas(p, cols - indentW));
301
+ if (parts.length === 1) {
302
+ // One word: on the next row; wider than a row, alone and whole.
303
+ if (!empty) newRow();
304
+ row += tok;
305
+ w += ww;
306
+ empty = false;
307
+ if (w > cols) newRow();
308
+ continue;
309
+ }
310
+ // Breakable: as much as fits here, the rest on the rows after.
311
+ if (!empty) {
312
+ if (w + textCols(sp) + textCols(parts[0]) <= cols) { row += sp; w += textCols(sp); } else newRow();
313
+ }
314
+ for (const p of parts) {
315
+ const pw = textCols(p);
316
+ if (w + pw > cols && !empty) newRow();
317
+ row += p;
318
+ w += pw;
319
+ empty = false;
320
+ if (w > cols) newRow();
321
+ }
322
+ }
323
+ if (!empty || !rows.length) rows.push(row.trimEnd());
324
+ return rows;
325
+ }
326
+
327
+ /** Text of several lines, each wrapped by {@link wrapProse}. */
328
+ export function wrapText(text: string, cols: number): string {
329
+ return text.split('\n').map((l) => wrapProse(l, cols).join('\n')).join('\n');
330
+ }
331
+
332
+ /** A line in one row of at most `cols` columns, cut with an ellipsis. */
333
+ export function fitRow(line: string, cols: number): string {
334
+ const rows = splitRows(line, cols);
335
+ if (rows.length === 1) return rows[0].text;
336
+ return `${splitRows(line, Math.max(1, cols - 2))[0].text}…`;
337
+ }
338
+
339
+ let current: LiveTurn | null = null;
340
+
341
+ /**
342
+ * The key hooks of the live prompt: `before` runs ahead of readline's own
343
+ * key handling, `after` behind it (and behind the line queue's), `tab` in
344
+ * place of completion. They do nothing unless a turn is on screen. run()
345
+ * wires them to the terminal's keys and to the completer.
346
+ */
347
+ export const liveKeys = {
348
+ before(key?: Key): void { current?.beforeKey(key ?? {}); },
349
+ after(key?: Key): void { current?.afterKey(key ?? {}); },
350
+ /** True when a turn took the Tab (it queues what is typed): no completion then. */
351
+ tab(): boolean { return current ? current.tab() : false; },
352
+ };
353
+
354
+ /** The live prompt of one turn. See the file comment. */
355
+ export class LiveTurn implements TurnView {
356
+ readonly live = true;
357
+ private partial = '';
358
+ private committed = '';
359
+ private statusText: string | null = null;
360
+ /** Rows drawn above the prompt. */
361
+ private rows = 0;
362
+ private promptShown = false;
363
+ private timer: ReturnType<typeof setTimeout> | null = null;
364
+ private ended = false;
365
+ private closed = false;
366
+ private snap: { cursor: number; end: number; line: boolean } | null = null;
367
+ private stash: string[] | null = null;
368
+ private readonly onLine = (): void => { if (this.snap) this.snap.line = true; };
369
+ private readonly onClose = (): void => { this.closed = true; };
370
+
371
+ constructor(
372
+ private readonly rl: LiveRl,
373
+ private readonly output: Writable & { columns?: number; rows?: number },
374
+ private readonly input: LiveInput,
375
+ private readonly state: () => LiveState,
376
+ private readonly throttleMs = 25,
377
+ ) {
378
+ current?.end();
379
+ current = this;
380
+ rl.on('line', this.onLine);
381
+ rl.on('close', this.onClose);
382
+ this.paint(0);
383
+ }
384
+
385
+ write(s: string): void {
386
+ const t = cleanStream(s);
387
+ if (!t || this.ended) return;
388
+ const all = this.partial + t;
389
+ const nl = all.lastIndexOf('\n');
390
+ if (nl < 0) {
391
+ this.partial = all;
392
+ } else {
393
+ // Finished lines stay in the scrollback: broken between words.
394
+ this.committed += wrapText(all.slice(0, nl + 1), this.cols());
395
+ this.partial = all.slice(nl + 1);
396
+ }
397
+ this.schedule();
398
+ }
399
+
400
+ /** The width text is wrapped to: the terminal's, less one. */
401
+ private cols(): number {
402
+ return Math.max(20, (this.output.columns || 80) - 1);
403
+ }
404
+
405
+ note(text: string): void {
406
+ // After the turn (a late answer to a steer): below it, as written.
407
+ if (this.ended) { this.output.write(cleanStream(text)); return; }
408
+ const t = cleanStream(text).replace(/^\n+/, '').replace(/\n+$/, '');
409
+ if (!t) return;
410
+ this.committed += `${wrapText(t, this.cols())}\n`;
411
+ this.schedule();
412
+ }
413
+
414
+ status(text: string | null): void {
415
+ const t = text === null ? null : cleanCell(text);
416
+ if (t === this.statusText) return;
417
+ this.statusText = t;
418
+ this.schedule();
419
+ }
420
+
421
+ /** A line after what the reply has written so far (its unfinished line
422
+ * ends there): something that happened at this point of the turn. */
423
+ /** Lines put between the reply's text (after()). */
424
+ breaks = 0;
425
+
426
+ after(text: string): void {
427
+ if (this.ended) { this.output.write(cleanStream(text)); return; }
428
+ const t = cleanStream(text).replace(/^\n+/, '').replace(/\n+$/, '');
429
+ if (!t) return;
430
+ this.breaks++;
431
+ this.committed += `${this.partial ? `${wrapText(this.partial, this.cols())}\n` : ''}${wrapText(t, this.cols())}\n`;
432
+ this.partial = '';
433
+ this.schedule();
434
+ }
435
+
436
+ refresh(): void {
437
+ this.schedule();
438
+ }
439
+
440
+ end(): void {
441
+ if (this.ended) return;
442
+ if (this.timer) clearTimeout(this.timer);
443
+ this.timer = null;
444
+ const up = this.rows + this.cursorRows();
445
+ this.output.write(`${up > 0 ? `\x1b[${up}A` : ''}\r\x1b[J${this.committed}${wrapText(this.partial, this.cols())}`);
446
+ this.committed = '';
447
+ this.ended = true;
448
+ if (current === this) current = null;
449
+ this.rl.off('line', this.onLine);
450
+ this.rl.off('close', this.onClose);
451
+ // The prompt is gone; the next one is drawn from here.
452
+ this.rl.prevRows = 0;
453
+ if (!this.closed) this.rl.setPrompt('');
454
+ }
455
+
456
+ beforeKey(key: Key): void {
457
+ if (this.ended || this.closed || !this.promptShown) return;
458
+ this.snap = { cursor: this.cursorRows(), end: this.endRows(), line: false };
459
+ // ↑ on an empty prompt takes back the newest queued entry, instead of
460
+ // readline's history (emptied for this one key).
461
+ if (key.name === 'up' && !key.ctrl && !key.meta && !key.shift && this.rl.line === ''
462
+ && !this.input.drafting?.().length && (this.input.queued?.().length || this.input.held?.()) && Array.isArray(this.rl.history)) {
463
+ this.stash = this.rl.history;
464
+ this.rl.history = [];
465
+ }
466
+ }
467
+
468
+ afterKey(key: Key): void {
469
+ const snap = this.snap;
470
+ this.snap = null;
471
+ if (!snap || this.ended) return;
472
+ if (this.stash) {
473
+ this.rl.history = this.stash;
474
+ this.stash = null;
475
+ this.input.recall?.();
476
+ this.paint(this.rows + snap.cursor);
477
+ return;
478
+ }
479
+ // Enter: readline moved below what was typed and cleared it; what the
480
+ // line becomes (a steer, a queued entry, a draft line) is known a
481
+ // moment later.
482
+ if (snap.line) {
483
+ this.paint(this.rows + snap.end + 1);
484
+ this.schedule();
485
+ return;
486
+ }
487
+ // Option+Enter, the end of a paste: the line queue took what was typed
488
+ // into the draft and cleared the line; the screen still shows it. Ctrl-U
489
+ // may have cleared the draft's earlier lines.
490
+ if ((key.meta && (key.name === 'return' || key.name === 'enter')) || key.name === 'paste-end' || (key.ctrl && key.name === 'u')) {
491
+ this.paint(this.rows + snap.cursor);
492
+ }
493
+ }
494
+
495
+ tab(): boolean {
496
+ if (this.ended || this.closed) return false;
497
+ const cursor = this.snap?.cursor ?? this.cursorRows();
498
+ // A command is completed, as when no turn runs (several candidates show
499
+ // above the prompt); other text is queued for the next turn.
500
+ const edit = this.rl as unknown as { line: string; cursor: number };
501
+ if (edit.line.trimStart().startsWith('/') && !this.input.drafting?.().length && this.input.complete) {
502
+ const r = completeAt(edit.line, edit.cursor, this.input.complete);
503
+ edit.line = r.line;
504
+ edit.cursor = r.cursor;
505
+ if (r.list) this.committed += `${r.list.join(' ')}\n`;
506
+ this.paint(this.rows + cursor);
507
+ return true;
508
+ }
509
+ if (this.input.queueEdit?.()) this.paint(this.rows + cursor);
510
+ return true;
511
+ }
512
+
513
+ /** Rows the cursor sits below the prompt's first row. */
514
+ private cursorRows(): number {
515
+ return this.promptShown && !this.closed ? this.rl.getCursorPos().rows : 0;
516
+ }
517
+
518
+ /** Rows the end of what is typed sits below the prompt's first row. */
519
+ private endRows(): number {
520
+ if (!this.promptShown || this.closed) return 0;
521
+ const edit = this.rl as unknown as { cursor: number; line: string };
522
+ const at = edit.cursor;
523
+ edit.cursor = edit.line.length;
524
+ const { rows } = this.rl.getCursorPos();
525
+ edit.cursor = at;
526
+ return rows;
527
+ }
528
+
529
+ private schedule(): void {
530
+ if (this.ended || this.timer) return;
531
+ this.timer = setTimeout(() => {
532
+ this.timer = null;
533
+ this.paint();
534
+ }, this.throttleMs);
535
+ }
536
+
537
+ private paint(up = this.rows + this.cursorRows()): void {
538
+ if (this.ended) return;
539
+ if (this.timer) clearTimeout(this.timer);
540
+ this.timer = null;
541
+ const cols = Math.max(20, (this.output.columns || 80) - 1);
542
+ const st = this.state();
543
+ const draft = this.input.drafting?.() ?? [];
544
+ let text = `${up > 0 ? `\x1b[${up}A` : ''}\r\x1b[J${this.committed}`;
545
+ this.committed = '';
546
+ // Below the reply: the status line, what was sent during the turn, the
547
+ // message begun (each a row, a few at most).
548
+ const below: string[] = [];
549
+ if (this.statusText) below.push(fitRow(` ${this.statusText}`, cols));
550
+ const notes = st.notes.length > 4 ? [...st.notes.slice(0, 3), `… and ${st.notes.length - 3} more`] : st.notes;
551
+ for (const n of notes) below.push(fitRow(` ${cleanCell(n)}`, cols));
552
+ if (draft.length) {
553
+ const shown = draft.length > 4 ? [draft[0], `(${draft.length - 3} more lines)`, ...draft.slice(-2)] : draft;
554
+ shown.forEach((d, i) => below.push(fitRow(`${i === 0 ? st.prompt : CONT_PROMPT}${cleanCell(d)}`, cols)));
555
+ }
556
+ // The reply's unfinished line, in what is left of the screen above the
557
+ // prompt; past that, its first rows are written for good.
558
+ let partial = this.partial ? splitRows(this.partial, cols) : [];
559
+ const most = Math.max(1, Math.min(12, (this.output.rows || 24) - 4 - below.length));
560
+ if (partial.length > most) {
561
+ // Written for good, broken between words: whole rows go until what is
562
+ // left fits.
563
+ while (splitRows(this.partial, cols).length > most) {
564
+ const rows = splitRows(this.partial, cols);
565
+ const cut = rows[0].end;
566
+ const sp = this.partial[cut] === ' ' ? cut : this.partial.lastIndexOf(' ', cut - 1);
567
+ const at = sp > 0 ? sp : cut;
568
+ text += `${this.partial.slice(0, at).replace(/\t/g, ' ').trimEnd()}\n`;
569
+ this.partial = this.partial.slice(sp > 0 ? sp + 1 : cut);
570
+ }
571
+ partial = splitRows(this.partial, cols);
572
+ }
573
+ const rows = [...partial.map((r) => r.text), ...below];
574
+ for (const r of rows) text += `${r}\n`;
575
+ this.rows = rows.length;
576
+ this.output.cork();
577
+ this.output.write(text);
578
+ if (this.closed) {
579
+ this.promptShown = false;
580
+ } else {
581
+ this.rl.setPrompt(draft.length ? CONT_PROMPT : st.prompt);
582
+ this.rl.prevRows = 0;
583
+ this.rl.prompt(true);
584
+ this.promptShown = true;
585
+ }
586
+ this.output.uncork();
587
+ }
588
+ }
589
+
590
+ /** A turn without a live prompt: written as it comes, as before. */
591
+ export class PlainTurn implements TurnView {
592
+ readonly live = false;
593
+ private shown = false;
594
+
595
+ constructor(private readonly term: (s: string) => void) {}
596
+
597
+ write(s: string): void { this.term(cleanStream(s)); }
598
+
599
+ note(text: string): void { this.term(cleanStream(text)); }
600
+
601
+ status(text: string | null, breakLine = false): void {
602
+ if (text === null) {
603
+ if (this.shown) { this.term('\r\x1b[2K'); this.shown = false; }
604
+ return;
605
+ }
606
+ // Never over the reply's own unfinished line: break to a fresh one.
607
+ if (!this.shown && breakLine) this.term('\n');
608
+ this.term(`\r\x1b[2K ${cleanCell(text)}`);
609
+ this.shown = true;
610
+ }
611
+
612
+ refresh(): void { /* no prompt to redraw */ }
613
+
614
+ end(): void { this.status(null); }
615
+ }