@akanjs/code 0.0.0 → 3.3.0-rc.70

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 (109) hide show
  1. package/README.ko.md +31 -0
  2. package/README.md +26 -4
  3. package/agent/AkanCodeCompaction.ts +49 -0
  4. package/agent/AkanCodeServices.ts +122 -0
  5. package/agent/AkanContextFiles.ts +94 -0
  6. package/agent/CodeAgent.ts +598 -0
  7. package/agent/CodeAgentAllowed.ts +35 -0
  8. package/agent/CodeAgentAsks.ts +66 -0
  9. package/agent/CodeAgentCommandLine.ts +372 -0
  10. package/agent/CodeAgentEventMapper.ts +225 -0
  11. package/agent/CodeAgentFrames.ts +57 -0
  12. package/agent/CodeAgentGate.ts +258 -0
  13. package/agent/CodeAgentProxy.ts +83 -0
  14. package/agent/CodeAgentRpcHost.ts +109 -0
  15. package/agent/CodeAgentRpcListener.ts +195 -0
  16. package/agent/CodeAgentStreamPrinter.ts +86 -0
  17. package/agent/CodeAgentSuspended.ts +85 -0
  18. package/agent/CodeAgentUi.ts +47 -0
  19. package/agent/CodeMailbox.ts +148 -0
  20. package/agent/CodeSessionFork.ts +56 -0
  21. package/agent/CodeSessionIndex.ts +78 -0
  22. package/agent/SubagentPool.ts +222 -0
  23. package/agent/WorkspaceTrust.ts +200 -0
  24. package/agent/akanCodeCompaction.test.ts +36 -0
  25. package/agent/akanCodeModel.ts +47 -0
  26. package/agent/akanCodeServices.test.ts +54 -0
  27. package/agent/akanContextFiles.test.ts +116 -0
  28. package/agent/akanSystemPrompt.ts +50 -0
  29. package/agent/codeAgent.test.ts +337 -0
  30. package/agent/codeAgentCommandLine.test.ts +212 -0
  31. package/agent/codeAgentContract.test.ts +757 -0
  32. package/agent/codeAgentHosts.ts +30 -0
  33. package/agent/codeAgentProxy.test.ts +125 -0
  34. package/agent/codeAgentRpcListener.test.ts +215 -0
  35. package/agent/codeAgentSuspended.test.ts +47 -0
  36. package/agent/codeMailbox.test.ts +76 -0
  37. package/agent/codeSessionFork.test.ts +58 -0
  38. package/agent/codeSessionIndex.test.ts +77 -0
  39. package/agent/consoleToStderr.ts +8 -0
  40. package/agent/jsonLines.ts +29 -0
  41. package/agent/stringArg.ts +5 -0
  42. package/bunfig.toml +2 -0
  43. package/feedback/DevLogFeedback.ts +82 -0
  44. package/feedback/PreviewFeedback.ts +46 -0
  45. package/feedback/TurnFeedback.ts +98 -0
  46. package/feedback/VerifyFeedback.ts +39 -0
  47. package/host/AkanCodeRunner.ts +297 -0
  48. package/host/CodeTrustPrompt.ts +57 -0
  49. package/host/codeRunnerPrompt.test.ts +181 -0
  50. package/host/hostGraph.test.ts +33 -0
  51. package/host/index.ts +2 -0
  52. package/index.ts +49 -0
  53. package/package.json +43 -9
  54. package/piDependencyPins.test.ts +45 -0
  55. package/test/preload.ts +3 -0
  56. package/tools/AkanCli.ts +56 -0
  57. package/tools/AkanCodePlugins.ts +145 -0
  58. package/tools/AkanEditScope.ts +53 -0
  59. package/tools/AkanEnvKeys.ts +50 -0
  60. package/tools/AkanToolPack.ts +87 -0
  61. package/tools/AkanVerifier.ts +30 -0
  62. package/tools/AskToolPack.ts +99 -0
  63. package/tools/DeepSeekWeb.ts +127 -0
  64. package/tools/MailToolPack.ts +76 -0
  65. package/tools/McpClient.ts +209 -0
  66. package/tools/McpOAuth.ts +233 -0
  67. package/tools/McpOAuthLoopback.ts +64 -0
  68. package/tools/McpServerConfig.ts +131 -0
  69. package/tools/McpSignIn.ts +158 -0
  70. package/tools/McpTokenStore.ts +128 -0
  71. package/tools/McpToolPack.ts +206 -0
  72. package/tools/SessionToolPack.ts +91 -0
  73. package/tools/WebToolPack.ts +315 -0
  74. package/tools/akanCodePlugins.test.ts +954 -0
  75. package/tools/askToolPack.test.ts +116 -0
  76. package/tools/deepSeekWeb.test.ts +113 -0
  77. package/tools/mcpOAuth.test.ts +648 -0
  78. package/tools/mcpServerConfig.test.ts +341 -0
  79. package/tsconfig.json +29 -0
  80. package/tui/CodeTui.tsx +394 -0
  81. package/tui/CodeTuiAgents.ts +65 -0
  82. package/tui/CodeTuiApp.test.tsx +251 -0
  83. package/tui/CodeTuiApp.tsx +312 -0
  84. package/tui/CodeTuiAutoCompact.ts +33 -0
  85. package/tui/CodeTuiClipboard.ts +94 -0
  86. package/tui/CodeTuiCommandRunner.ts +242 -0
  87. package/tui/CodeTuiCommands.ts +59 -0
  88. package/tui/CodeTuiEditor.ts +168 -0
  89. package/tui/CodeTuiFiles.ts +45 -0
  90. package/tui/CodeTuiFrame.ts +133 -0
  91. package/tui/CodeTuiLines.ts +117 -0
  92. package/tui/CodeTuiMarkdown.ts +159 -0
  93. package/tui/CodeTuiMcp.ts +111 -0
  94. package/tui/CodeTuiModels.ts +82 -0
  95. package/tui/CodeTuiMouse.ts +39 -0
  96. package/tui/CodeTuiOverlay.ts +148 -0
  97. package/tui/CodeTuiParts.ts +168 -0
  98. package/tui/CodeTuiPrompt.ts +271 -0
  99. package/tui/CodeTuiQuestion.ts +170 -0
  100. package/tui/codeTranscript.test.ts +445 -0
  101. package/tui/codeTui.test.tsx +1104 -0
  102. package/tui/codeTuiAgents.test.ts +61 -0
  103. package/tui/codeTuiClipboard.test.ts +16 -0
  104. package/tui/codeTuiCommands.test.ts +38 -0
  105. package/tui/codeTuiEditor.test.ts +122 -0
  106. package/tui/codeTuiFiles.test.ts +43 -0
  107. package/tui/codeTuiMarkdown.test.ts +91 -0
  108. package/tui/codeTuiMcp.test.ts +160 -0
  109. package/tui/codeTuiMouse.test.ts +61 -0
@@ -0,0 +1,394 @@
1
+ import { CodeTranscript } from "akanjs/common";
2
+ import { render } from "ink";
3
+ import type { CodeAgent } from "../agent/CodeAgent";
4
+ import { CodeTuiApp, type CodeTuiSnapshot, promptMarkWidth } from "./CodeTuiApp";
5
+ import { CodeTuiCommandRunner } from "./CodeTuiCommandRunner";
6
+ import { CodeTuiCommands } from "./CodeTuiCommands";
7
+ import { CodeTuiEditor } from "./CodeTuiEditor";
8
+ import { CodeTuiFrame } from "./CodeTuiFrame";
9
+ import type { CodeTuiSpan } from "./CodeTuiLines";
10
+ import { CodeTuiMouse } from "./CodeTuiMouse";
11
+ import { CodeTuiOverlay } from "./CodeTuiOverlay";
12
+ import { CodeTuiPrompt } from "./CodeTuiPrompt";
13
+ import { CodeTuiQuestion } from "./CodeTuiQuestion";
14
+
15
+ export interface CodeTuiOptions {
16
+ /** Draw the model's reasoning in full. Folded to one line otherwise, and `/thinking` flips it either way. */
17
+ thinking?: boolean;
18
+ notice?: string;
19
+ warnings?: string[];
20
+ openBrowser: (url: string) => void;
21
+ stdout?: NodeJS.WriteStream;
22
+ stdin?: NodeJS.ReadStream;
23
+ }
24
+
25
+ // The next frame clears the terminal, so a leaving session's last word travels with the id it switches to.
26
+ export interface CodeTuiExit {
27
+ id: string;
28
+ notice?: string;
29
+ }
30
+
31
+ export class CodeTui {
32
+ /** Ink throttles its own writes to `maxFps: 30`, so notifying faster only buys extra reconciles. */
33
+ static readonly frameMs = 34;
34
+ static readonly clipboardMs = CodeTuiPrompt.clipboardMs;
35
+ static readonly noticeMs = 4_000;
36
+ static readonly chromeRows = CodeTuiFrame.chromeRows;
37
+ static readonly promptRuleRows = CodeTuiFrame.promptRuleRows;
38
+ static readonly minBodyRows = CodeTuiFrame.minBodyRows;
39
+ static readonly maxInputRows = CodeTuiFrame.maxInputRows;
40
+ static readonly title = CodeTuiFrame.title;
41
+ static readonly imageMark = CodeTuiPrompt.imageMark;
42
+ static readonly freeTextKey = CodeTuiQuestion.freeTextKey;
43
+
44
+ // Bracketed paste: cmd+v over an image-only clipboard still sends an empty `ESC[200~`…`ESC[201~` pair.
45
+ static readonly pasteOn = "\u001b[?2004h";
46
+ static readonly pasteOff = "\u001b[?2004l";
47
+
48
+ readonly #agent: CodeAgent;
49
+ readonly #transcript = new CodeTranscript();
50
+ readonly #editor = new CodeTuiEditor();
51
+ readonly #frame: CodeTuiFrame;
52
+ readonly #overlay: CodeTuiOverlay;
53
+ readonly #prompt: CodeTuiPrompt;
54
+ readonly #question: CodeTuiQuestion;
55
+ readonly #runner: CodeTuiCommandRunner;
56
+ readonly #listeners = new Set<() => void>();
57
+ readonly #instance: ReturnType<typeof render>;
58
+ readonly #stdout: NodeJS.WriteStream;
59
+ #anchor: number | null = null; // last visible transcript row; null follows the tail
60
+ #switchTo: CodeTuiExit | undefined;
61
+ #notice = "";
62
+ readonly #opening: string;
63
+ readonly #warnings: string[];
64
+ #noticeTimer: ReturnType<typeof setTimeout> | null = null;
65
+ #frameTimer: ReturnType<typeof setTimeout> | null = null;
66
+ #cached: CodeTuiSnapshot | null = null;
67
+ #unsubscribe: (() => void) | undefined;
68
+ #exiting = false;
69
+
70
+ constructor(agent: CodeAgent, { thinking = false, notice, warnings = [], openBrowser, ...streams }: CodeTuiOptions) {
71
+ this.#agent = agent;
72
+ this.#opening = notice ?? "";
73
+ this.#warnings = warnings;
74
+ this.#stdout = streams.stdout ?? process.stdout;
75
+ this.#frame = new CodeTuiFrame(this.#transcript, this.#stdout, thinking);
76
+ const say = (text: string) => this.#say(text);
77
+ const fail = (error: unknown) => this.#fail(error);
78
+ const renderNow = () => this.#renderNow();
79
+ this.#overlay = new CodeTuiOverlay(agent, this.#transcript, { render: renderNow, say });
80
+ this.#prompt = new CodeTuiPrompt(agent, this.#transcript, this.#editor, this.#overlay, {
81
+ render: renderNow,
82
+ snapshot: this.#snapshot,
83
+ say,
84
+ fail,
85
+ command: (line) => this.#command(line),
86
+ });
87
+ this.#question = new CodeTuiQuestion(agent, this.#transcript, this.#editor, renderNow);
88
+ this.#runner = new CodeTuiCommandRunner(agent, this.#transcript, this.#overlay, {
89
+ say,
90
+ fail,
91
+ openBrowser,
92
+ leave: (exit) => {
93
+ this.#switchTo = exit;
94
+ this.#quit();
95
+ },
96
+ });
97
+ this.#stdout.on("resize", this.#onResize);
98
+ this.#instance = render(
99
+ <CodeTuiApp
100
+ actions={{
101
+ subscribe: this.#subscribe,
102
+ snapshot: this.#snapshot,
103
+ type: this.#prompt.type,
104
+ edit: this.#prompt.edit,
105
+ submit: this.#submit,
106
+ newline: this.#prompt.newline,
107
+ paste: this.#prompt.paste,
108
+ pasted: this.#prompt.pasted,
109
+ complete: this.#prompt.complete,
110
+ vertical: this.#vertical,
111
+ scroll: this.#scroll,
112
+ move: this.#move,
113
+ toggle: this.#question.toggle,
114
+ answerConfirm: this.#question.answerConfirm,
115
+ allowForSession: this.#question.allowForSession,
116
+ cancel: this.#cancel,
117
+ interrupt: this.#interrupt,
118
+ }}
119
+ />,
120
+ {
121
+ // Bun's `console.log` writes to fd 1 natively, bypassing `process.stdout.write`; only Ink's patch catches it.
122
+ patchConsole: true,
123
+ // Ink's own ctrl+c handler unmounts before `useInput` sees the key, skipping the host's interrupt and wipe.
124
+ exitOnCtrlC: false,
125
+ // Only the kitty protocol tells shift+enter from enter; `auto` enables it once the terminal answers a query.
126
+ kittyKeyboard: { mode: "auto" },
127
+ ...streams,
128
+ },
129
+ );
130
+ }
131
+
132
+ /** Resolves to the session the person chose to continue, when they chose one, and undefined on a plain quit. */
133
+ async run(seed?: string) {
134
+ this.#stdout.write(`${CodeTui.pasteOn}${CodeTuiMouse.on}`);
135
+ if (this.#opening) this.#say(this.#opening);
136
+ for (const warning of this.#warnings) this.#transcript.note("warning", warning);
137
+ this.#unsubscribe = this.#agent.on((event) => {
138
+ this.#transcript.apply(event);
139
+ if (event.type === "question") this.#question.open(event.question);
140
+ this.#scheduleFrame();
141
+ });
142
+ this.#agent.announce();
143
+ void this.#prompt.load().then(() => this.#renderNow());
144
+ this.#prompt.watchClipboard();
145
+ if (seed?.trim()) this.#prompt.send(seed.trim());
146
+ await this.#instance.waitUntilExit();
147
+ this.#close();
148
+ return this.#switchTo;
149
+ }
150
+
151
+ close() {
152
+ this.#quit();
153
+ }
154
+
155
+ #close() {
156
+ this.#prompt.unwatchClipboard();
157
+ if (this.#frameTimer) clearTimeout(this.#frameTimer);
158
+ if (this.#noticeTimer) clearTimeout(this.#noticeTimer);
159
+ this.#frameTimer = null;
160
+ this.#noticeTimer = null;
161
+ this.#stdout.off("resize", this.#onResize);
162
+ this.#unsubscribe?.();
163
+ this.#farewell();
164
+ }
165
+
166
+ #farewell() {
167
+ const info = this.#transcript.info;
168
+ if (this.#switchTo || !info?.sessionId || !this.#agent.sessions().length) return;
169
+ if (!this.#transcript.parts.some((part) => part.kind === "user")) return;
170
+ const name = info.name ? ` (${info.name})` : "";
171
+ this.#stdout.write(`Resume this session${name} with:\n akan code --resume ${info.sessionId}\n`);
172
+ }
173
+
174
+ #onResize = () => this.#renderNow();
175
+
176
+ #subscribe = (listener: () => void) => {
177
+ this.#listeners.add(listener);
178
+ return () => this.#listeners.delete(listener);
179
+ };
180
+
181
+ #scheduleFrame() {
182
+ if (this.#frameTimer) return;
183
+ this.#frameTimer = setTimeout(() => {
184
+ this.#frameTimer = null;
185
+ this.#renderNow();
186
+ }, CodeTui.frameMs);
187
+ }
188
+
189
+ #renderNow() {
190
+ this.#cached = null;
191
+ for (const listener of this.#listeners) listener();
192
+ }
193
+
194
+ static layout(frameRows: number, askRows: number, railRows = 0) {
195
+ return CodeTuiFrame.layout(frameRows, askRows, railRows);
196
+ }
197
+
198
+ static frameRowsOf(terminalRows: number) {
199
+ return CodeTuiFrame.frameRowsOf(terminalRows);
200
+ }
201
+
202
+ #snapshot = (): CodeTuiSnapshot => {
203
+ if (this.#cached) return this.#cached;
204
+ const columns = Math.max(40, this.#stdout.columns || 80);
205
+ const frameRows = CodeTui.frameRowsOf(Math.max(10, this.#stdout.rows || 24));
206
+ const question = this.#transcript.question;
207
+ const approval = this.#transcript.approval;
208
+ const mode = this.#question.typing ? "input" : CodeTuiQuestion.modeOf(question, approval);
209
+ const subagents = this.#frame.railRows(columns);
210
+ const ask =
211
+ mode === "input"
212
+ ? this.#prompt.block(columns, frameRows - subagents.length)
213
+ : this.#question.block(question, frameRows - subagents.length);
214
+ const { bodyHeight } = CodeTui.layout(frameRows, ask.rows, subagents.length);
215
+ const width = columns - 2;
216
+ const lines = this.#frame.lines(width);
217
+ const end = this.#anchor === null ? lines.length : Math.min(lines.length, Math.max(bodyHeight, this.#anchor));
218
+ const start = Math.max(0, end - bodyHeight);
219
+ const above = start;
220
+ const below = lines.length - end;
221
+ this.#cached = {
222
+ topRule: CodeTui.rule(
223
+ this.#anchor === null ? "" : `▲${above} ▼${below} paused`,
224
+ this.#transcript.info?.name ?? this.#transcript.info?.sessionId.slice(0, 8) ?? "",
225
+ columns,
226
+ ),
227
+ bottomRule: CodeTui.rule(this.#frame.queueLabel(), this.#frame.statusLabel(), columns),
228
+ lines: lines.slice(start, end),
229
+ above,
230
+ below,
231
+ following: this.#anchor === null,
232
+ overlay: this.#overlay.block(width, bodyHeight),
233
+ status: this.#frame.status(),
234
+ subagents,
235
+ mode,
236
+ placeholder: this.#question.placeholder(),
237
+ offered: this.#prompt.offered,
238
+ prompt: CodeTuiQuestion.promptOf(question, approval),
239
+ selected: ask.selected,
240
+ checked: this.#question.checked,
241
+ multiSelect: !!question?.multiSelect,
242
+ notice: this.#notice,
243
+ hint: this.#overlay.shown ? "esc close · ↑↓ scroll" : this.#question.hint(mode, !!question?.multiSelect),
244
+ columns,
245
+ frameRows,
246
+ bodyHeight,
247
+ cursor: ask.caret ? { x: promptMarkWidth + ask.caret.col, y: bodyHeight + ask.above + ask.caret.row } : null,
248
+ ...ask.snapshot,
249
+ };
250
+ return this.#cached;
251
+ };
252
+
253
+ static rule(left: string, right: string, width: number): CodeTuiSpan[] {
254
+ return CodeTuiFrame.rule(left, right, width);
255
+ }
256
+
257
+ #vertical = (delta: -1 | 1) => {
258
+ if (this.#overlay.picker) return this.#move(delta);
259
+ if (this.#overlay.shown) return this.#scroll(delta);
260
+ this.#prompt.vertical(delta);
261
+ };
262
+
263
+ #scroll = (delta: number) => {
264
+ if (this.#overlay.picker) return this.#move(Math.sign(delta));
265
+ if (this.#overlay.shown) return this.#overlay.scroll(delta);
266
+ const snapshot = this.#snapshot();
267
+ const total = snapshot.above + snapshot.lines.length + snapshot.below;
268
+ const rows = Math.max(1, snapshot.lines.length);
269
+ if (total <= rows) return;
270
+ const end = this.#anchor === null ? total : this.#anchor;
271
+ const next = Math.min(total, Math.max(rows, end + Math.trunc(delta)));
272
+ this.#anchor = next >= total ? null : next;
273
+ this.#renderNow();
274
+ };
275
+
276
+ #move = (delta: number) => {
277
+ if (this.#overlay.picker) return this.#overlay.move(delta);
278
+ this.#question.move(delta);
279
+ };
280
+
281
+ #cancel = () => {
282
+ if (this.#overlay.shown || this.#overlay.picker) return this.#overlay.dismiss();
283
+ if (this.#question.typing && this.#transcript.question?.options?.length) return this.#question.backToChoices();
284
+ const approval = this.#transcript.approval;
285
+ if (approval) return void this.#agent.approve(approval.approvalId, false);
286
+ const question = this.#transcript.question;
287
+ if (question) return void this.#question.answer(question.questionId, {});
288
+ if (this.#transcript.streaming) return void this.#agent.abort();
289
+ if (!this.#editor.isEmpty) {
290
+ this.#editor.clear();
291
+ this.#renderNow();
292
+ }
293
+ };
294
+
295
+ #interrupt = () => {
296
+ if (this.#transcript.streaming) {
297
+ void this.#agent.abort();
298
+ this.#say("interrupted — ^c again to quit");
299
+ return;
300
+ }
301
+ this.#quit();
302
+ };
303
+
304
+ #quit() {
305
+ if (this.#exiting) return;
306
+ this.#exiting = true;
307
+ this.#stdout.write(`${CodeTuiMouse.off}${CodeTui.pasteOff}`);
308
+ // clear() before unmount(): unmounting forgets the frame's height, so a later clear erases nothing.
309
+ this.#instance.clear();
310
+ this.#instance.unmount();
311
+ }
312
+
313
+ #submit = () => {
314
+ const picker = this.#overlay.picker;
315
+ if (picker) return this.#resume(picker.entries[picker.at]?.id);
316
+ const question = this.#transcript.question;
317
+ if (question) return void this.#question.answerCurrent(question.questionId);
318
+ this.#prompt.submit();
319
+ };
320
+
321
+ #resume(id: string | undefined) {
322
+ if (!id) return this.#overlay.dismiss();
323
+ if (id === this.#transcript.info?.sessionId) return this.#overlay.dismiss();
324
+ this.#switchTo = { id };
325
+ this.#quit();
326
+ }
327
+
328
+ #command(line: string) {
329
+ const [name, ...rest] = line.slice(1).split(" ");
330
+ const argument = rest.join(" ").trim();
331
+ switch (name) {
332
+ case "help":
333
+ return this.#overlay.open("help", CodeTuiCommands.help());
334
+ case "quit":
335
+ case "exit":
336
+ return this.#quit();
337
+ case "abort":
338
+ return void this.#agent.abort();
339
+ case "clear":
340
+ this.#anchor = null;
341
+ this.#transcript.clear();
342
+ return this.#say("screen cleared · the model still remembers · /compact shortens what it carries");
343
+ case "compact":
344
+ return void this.#agent.compact(argument || undefined).catch((error: unknown) => this.#fail(error));
345
+ case "autocompact":
346
+ return this.#runner.setAutoCompact(argument);
347
+ case "thinking":
348
+ return this.#say(
349
+ this.#frame.toggleThinking() ? "showing the model's reasoning" : "reasoning folded back to one line",
350
+ );
351
+ case "tools": {
352
+ const tools = this.#transcript.info?.tools ?? [];
353
+ return this.#overlay.open("tools", `${tools.length} tools\n\n${tools.join(" · ")}`);
354
+ }
355
+ case "model":
356
+ return this.#runner.setModel(argument);
357
+ case "effort":
358
+ return this.#runner.setEffort(argument);
359
+ case "peers":
360
+ return this.#overlay.open("peers", CodeTuiCommandRunner.peerList(this.#agent.peers()));
361
+ case "msg":
362
+ return this.#runner.message(argument);
363
+ case "fork":
364
+ return this.#runner.fork(argument);
365
+ case "agents":
366
+ return this.#overlay.open("agents", this.#runner.agentList());
367
+ case "mcp":
368
+ return this.#runner.mcp(argument);
369
+ case "allowed":
370
+ return this.#runner.allowed(argument);
371
+ case "name":
372
+ if (!argument) return this.#overlay.open("name", "Usage: /name <what this session is about>");
373
+ this.#agent.setName(argument);
374
+ return this.#say(`session named ${argument}`);
375
+ default:
376
+ return this.#overlay.open("unknown command", `There is no /${name}.\n\n${CodeTuiCommands.help()}`);
377
+ }
378
+ }
379
+
380
+ #fail(error: unknown) {
381
+ this.#transcript.note("error", String(error));
382
+ this.#renderNow();
383
+ }
384
+
385
+ #say(text: string) {
386
+ this.#notice = text;
387
+ if (this.#noticeTimer) clearTimeout(this.#noticeTimer);
388
+ this.#noticeTimer = setTimeout(() => {
389
+ this.#notice = "";
390
+ this.#renderNow();
391
+ }, CodeTui.noticeMs);
392
+ this.#renderNow();
393
+ }
394
+ }
@@ -0,0 +1,65 @@
1
+ import type { CodeAgentSubagent } from "akanjs/common";
2
+ import { type CodeTuiLine, CodeTuiLines, type CodeTuiSpan } from "./CodeTuiLines";
3
+
4
+ /** Every row is exactly one terminal line, never wrapped: the frame counts these rows before drawing them. */
5
+ export class CodeTuiAgents {
6
+ static readonly markWidth = 4; // ` ◯ ` on a child row, `❯ ⏺ ` on the session row
7
+ /** Below this much room for the description, the meta column is dropped. */
8
+ static readonly minDescription = 12;
9
+
10
+ static rows(agents: CodeAgentSubagent[], session: string, width: number, now = Date.now()): CodeTuiLine[] {
11
+ if (!agents.length) return [];
12
+ const kindColumn = Math.max(...agents.map((agent) => CodeTuiLines.width(agent.kind))) + 2;
13
+ return [
14
+ {
15
+ key: "agents:self",
16
+ spans: [{ text: "❯ ", color: "cyan" }, { text: "⏺ ", color: "green" }, { text: session }],
17
+ },
18
+ ...agents.map((agent, at) => ({
19
+ key: `agents:${agent.id || at}`,
20
+ spans: CodeTuiAgents.#row(agent, kindColumn, width, now),
21
+ })),
22
+ ];
23
+ }
24
+
25
+ static #row(agent: CodeAgentSubagent, kindColumn: number, width: number, now: number): CodeTuiSpan[] {
26
+ const meta = `${CodeTuiAgents.elapsed(now - agent.startedAt)} · ↓ ${CodeTuiAgents.tokens(agent.tokens)} tokens`;
27
+ const head = CodeTuiAgents.markWidth + kindColumn;
28
+ const room = width - head - CodeTuiLines.width(meta) - 2;
29
+ const spans: CodeTuiSpan[] = [{ text: " ◯ ", color: "yellow" }, { text: agent.kind.padEnd(kindColumn) }];
30
+ if (room < CodeTuiAgents.minDescription)
31
+ return [...spans, { text: CodeTuiAgents.#clip(agent.description, Math.max(1, width - head)) }];
32
+ const description = CodeTuiAgents.#clip(agent.description, room);
33
+ // Padded by display columns: `padEnd` counts code units and would push the meta column off after Hangul.
34
+ const pad = " ".repeat(Math.max(0, room - CodeTuiLines.width(description)));
35
+ return [...spans, { text: `${description}${pad}` }, { text: ` ${meta}`, dim: true }];
36
+ }
37
+
38
+ /** `47s`, `12m 30s`, `1h 2m`. */
39
+ static elapsed(ms: number) {
40
+ const total = Math.max(0, Math.round(ms / 1000));
41
+ const hours = Math.floor(total / 3600);
42
+ const minutes = Math.floor((total % 3600) / 60);
43
+ const seconds = total % 60;
44
+ if (hours) return `${hours}h ${minutes}m`;
45
+ if (minutes) return `${minutes}m ${seconds}s`;
46
+ return `${seconds}s`;
47
+ }
48
+
49
+ /** `842`, `12.4k`, `1.3M`. */
50
+ static tokens(count: number) {
51
+ if (count < 1_000) return `${Math.max(0, Math.round(count))}`;
52
+ if (count < 1_000_000) return `${(count / 1_000).toFixed(1)}k`;
53
+ return `${(count / 1_000_000).toFixed(1)}M`;
54
+ }
55
+
56
+ static #clip(text: string, width: number) {
57
+ if (CodeTuiLines.width(text) <= width) return text;
58
+ let clipped = "";
59
+ for (const char of text) {
60
+ if (CodeTuiLines.width(clipped + char) > width - 1) break;
61
+ clipped += char;
62
+ }
63
+ return `${clipped}…`;
64
+ }
65
+ }