@akanjs/code 0.0.0 → 3.3.0-rc.71

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,242 @@
1
+ import type { CodeAgentEffort, CodeTranscript } from "akanjs/common";
2
+ import type { CodeAgent } from "../agent/CodeAgent";
3
+ import { SubagentPool } from "../agent/SubagentPool";
4
+ import { WorkspaceTrust } from "../agent/WorkspaceTrust";
5
+ import { McpServerConfig } from "../tools/McpServerConfig";
6
+ import { McpSignIn } from "../tools/McpSignIn";
7
+ import { McpTokenStore } from "../tools/McpTokenStore";
8
+ import type { CodeTuiExit } from "./CodeTui";
9
+ import { CodeTuiAutoCompact } from "./CodeTuiAutoCompact";
10
+ import { CodeTuiMcp } from "./CodeTuiMcp";
11
+ import { CodeTuiModels } from "./CodeTuiModels";
12
+ import type { CodeTuiOverlay } from "./CodeTuiOverlay";
13
+
14
+ interface CodeTuiCommandRunnerHost {
15
+ say: (text: string) => void;
16
+ fail: (error: unknown) => void;
17
+ leave: (exit: CodeTuiExit) => void;
18
+ openBrowser: (url: string) => void;
19
+ }
20
+
21
+ export class CodeTuiCommandRunner {
22
+ readonly #agent: CodeAgent;
23
+ readonly #transcript: CodeTranscript;
24
+ readonly #overlay: CodeTuiOverlay;
25
+ readonly #host: CodeTuiCommandRunnerHost;
26
+
27
+ constructor(agent: CodeAgent, transcript: CodeTranscript, overlay: CodeTuiOverlay, host: CodeTuiCommandRunnerHost) {
28
+ this.#agent = agent;
29
+ this.#transcript = transcript;
30
+ this.#overlay = overlay;
31
+ this.#host = host;
32
+ }
33
+
34
+ fork(argument: string) {
35
+ if (!this.#transcript.parts.some((part) => part.kind === "user"))
36
+ return this.#overlay.open("fork", "Nothing has been said in this session yet, so a fork of it is a new session.");
37
+ const from = this.#transcript.info?.sessionId ?? "";
38
+ try {
39
+ const forked = this.#agent.fork(argument.trim() || undefined);
40
+ this.#host.leave({ id: forked.id, notice: `forked — the original is akan code --resume ${from}` });
41
+ } catch (error: unknown) {
42
+ this.#host.fail(error);
43
+ }
44
+ }
45
+
46
+ agentList() {
47
+ const budget = this.#agent.profile.tools.subagent;
48
+ if (!budget) return "Sub-agents are off in this profile.";
49
+ const column = Math.max(...Object.keys(SubagentPool.kinds).map((kind) => kind.length)) + 2;
50
+ const kinds = Object.entries(SubagentPool.kinds).map(([kind, spec]) => `${kind.padEnd(column)}${spec.desc}`);
51
+ return [
52
+ ...kinds,
53
+ "",
54
+ `At most ${budget.maxConcurrent} at once, ${budget.maxDepth} deep, ${budget.budget} tokens for the whole tree.`,
55
+ "",
56
+ "Ask for one in a sentence — the model calls the tool. Its reading never enters this conversation.",
57
+ ].join("\n");
58
+ }
59
+
60
+ mcp(argument: string) {
61
+ const words = argument.split(" ").filter(Boolean);
62
+ const local = words.includes("--local");
63
+ const [verb, name, ...rest] = words.filter((word) => word !== "--local");
64
+ const root = this.#agent.workspaceRoot;
65
+ if (!verb) return this.#overlay.open("mcp", CodeTuiMcp.list(this.#mcpView()));
66
+ if (verb === "reload") return this.#reload("reconnected the MCP servers");
67
+ if (verb === "login" || verb === "logout") return this.#mcpAuth(verb, name);
68
+ if (verb !== "add" && verb !== "remove") {
69
+ const status = this.#agent.mcpServers().find((entry) => entry.name === verb);
70
+ if (status) return this.#overlay.open(`mcp · ${verb}`, CodeTuiMcp.tools(status));
71
+ return this.#overlay.open("mcp", [`There is no /mcp ${verb}.`, "", ...CodeTuiMcp.usage].join("\n"));
72
+ }
73
+ if (!name) return this.#overlay.open("mcp", [`Usage:`, "", ...CodeTuiMcp.usage].join("\n"));
74
+ if (!CodeTuiMcp.namePattern.test(name))
75
+ return this.#overlay.open("mcp", `"${name}" cannot name a server: letters, digits, dash and underscore only.`);
76
+ try {
77
+ if (verb === "remove") {
78
+ const scope = WorkspaceTrust.carry(root, "mcp", () =>
79
+ McpServerConfig.remove(root, name, local ? "workspace" : undefined),
80
+ );
81
+ const remaining = McpServerConfig.declared(root).find((entry) => entry.ref.name === name);
82
+ if (!scope)
83
+ return this.#overlay.open(
84
+ "mcp",
85
+ remaining
86
+ ? `"${name}" is not declared in this repo's file; the ${remaining.scope} file declares it — /mcp remove ${name} removes it there.`
87
+ : `No server named "${name}" is declared.`,
88
+ );
89
+ if (!remaining) return this.#reload(`removed ${name} from the ${scope} file`);
90
+ return this.#reload(
91
+ `removed ${name} from the ${scope} file — the ${remaining.scope} file still declares it, so it still applies; /mcp remove ${name} again to remove it there`,
92
+ );
93
+ }
94
+ const scope = local ? "workspace" : "global";
95
+ const ref = WorkspaceTrust.carry(root, "mcp", () => McpServerConfig.add(root, name, rest, scope));
96
+ const where = scope === "global" ? "every repo" : "this repo";
97
+ return this.#reload(`added ${name} · ${McpServerConfig.targetOf(ref)} · ${where}`);
98
+ } catch (error: unknown) {
99
+ this.#host.fail(error);
100
+ }
101
+ }
102
+
103
+ allowed(argument: string) {
104
+ if (argument === "clear") {
105
+ const count = this.#agent.allowed.clear();
106
+ return this.#host.say(
107
+ count ? "nothing is allowed any more · every command is asked about again" : "nothing was allowed",
108
+ );
109
+ }
110
+ if (argument) return this.#overlay.open("allowed", "Usage: /allowed [clear]");
111
+ this.#overlay.open("allowed", CodeTuiCommandRunner.allowedList(this.#agent.allowed.names));
112
+ }
113
+
114
+ static allowedList(names: string[]) {
115
+ const always =
116
+ "A networking command, a push or publish, rm and a command that runs another (sudo, xargs, sh …) are asked about every time.";
117
+ if (!names.length)
118
+ return [
119
+ "Nothing is allowed for this session yet.",
120
+ "",
121
+ "Answer a at an approval to stop being asked about that command until the session ends.",
122
+ always,
123
+ ].join("\n");
124
+ return [
125
+ ...names,
126
+ "",
127
+ "These run without asking until this session ends. /allowed clear forgets them.",
128
+ always,
129
+ ].join("\n");
130
+ }
131
+
132
+ // Sign-in is not awaited: it waits minutes on a person in the browser, and would freeze the prompt meanwhile.
133
+ #mcpAuth(verb: "login" | "logout", name: string | undefined) {
134
+ const root = this.#agent.workspaceRoot;
135
+ if (!name) return this.#overlay.open("mcp", [`Usage: /mcp ${verb} <name>`, "", ...CodeTuiMcp.usage].join("\n"));
136
+ const ref = McpServerConfig.read(root).find((entry) => entry.name === name);
137
+ if (verb === "logout") {
138
+ if (!McpTokenStore.clear(ref ?? { name })) return this.#overlay.open("mcp", `"${name}" is not signed in.`);
139
+ return this.#reload(`signed out of ${name}`);
140
+ }
141
+ if (!ref) return this.#overlay.open("mcp", `No server named "${name}" is declared.`);
142
+ this.#host.say(`signing in to ${name} — finish in the browser`);
143
+ void McpSignIn.run(ref, { open: this.#host.openBrowser, onNotice: (message) => this.#host.say(message) })
144
+ .then(() => this.#reload(`signed in to ${name}`))
145
+ .catch((error: unknown) => this.#host.fail(error));
146
+ }
147
+
148
+ #mcpView() {
149
+ const root = this.#agent.workspaceRoot;
150
+ const problem = McpServerConfig.problem(root);
151
+ return {
152
+ status: this.#agent.mcpServers(),
153
+ declared: McpServerConfig.declared(root),
154
+ files: McpServerConfig.files(root),
155
+ workspaceApproved: WorkspaceTrust.isTrusted(root, "mcp"),
156
+ ...(problem ? { problem } : {}),
157
+ };
158
+ }
159
+
160
+ // The engine binds its tool registry at construction, so a reload rebuilds the agent around this session.
161
+ #reload(notice: string) {
162
+ const id = this.#transcript.info?.sessionId;
163
+ if (!id || !this.#agent.sessions().some((entry) => entry.id === id))
164
+ return this.#overlay.open(
165
+ "mcp",
166
+ "This session is not on disk yet, so there is nothing to reopen. Say something first, or start a new `akan code`.",
167
+ );
168
+ this.#host.leave({ id, notice });
169
+ }
170
+
171
+ static peerList(peers: { id: string; name: string; cwd: string }[]) {
172
+ if (!peers.length) return "No other akan code session is running in this workspace.";
173
+ const column = Math.max(...peers.map((peer) => peer.name.length)) + 2;
174
+ const rows = peers.map((peer) => `${peer.name.padEnd(column)}${peer.id.slice(0, 8)} ${peer.cwd}`);
175
+ return [...rows, "", "/msg <peer> <text> hands one of them a message."].join("\n");
176
+ }
177
+
178
+ message(argument: string) {
179
+ const [target, ...rest] = argument.split(" ");
180
+ const text = rest.join(" ").trim();
181
+ if (!target || !text)
182
+ return this.#overlay.open(
183
+ "msg",
184
+ `Usage: /msg <peer> <text>\n\n${CodeTuiCommandRunner.peerList(this.#agent.peers())}`,
185
+ );
186
+ try {
187
+ const peer = this.#agent.send(target, text);
188
+ this.#host.say(`sent to ${peer.name}`);
189
+ } catch (error: unknown) {
190
+ this.#host.fail(error);
191
+ }
192
+ }
193
+
194
+ setEffort(argument: string) {
195
+ const levels = this.#agent.efforts();
196
+ if (!levels.length)
197
+ return this.#overlay.open("effort", "This model does no reasoning, so it has no effort to set.");
198
+ const wanted = argument.trim().toLowerCase();
199
+ if (!levels.includes(wanted as CodeAgentEffort))
200
+ return this.#overlay.open(
201
+ "effort",
202
+ `Usage: /effort <level>\n\nnow: ${this.#transcript.info?.effort ?? "unknown"}\n${levels.join(" · ")}`,
203
+ );
204
+ try {
205
+ this.#agent.setEffort(wanted as CodeAgentEffort);
206
+ // The engine clamps to what the provider serves, so the frame that came back is what actually took.
207
+ this.#host.say(`effort ${this.#transcript.info?.effort ?? wanted}`);
208
+ } catch (error: unknown) {
209
+ this.#host.fail(error);
210
+ }
211
+ }
212
+
213
+ setAutoCompact(argument: string) {
214
+ const percent = CodeTuiAutoCompact.parse(argument);
215
+ if (percent === undefined)
216
+ return this.#overlay.open("autocompact", CodeTuiAutoCompact.usage(this.#transcript.info));
217
+ try {
218
+ this.#agent.setAutoCompactAt(percent);
219
+ this.#host.say(CodeTuiAutoCompact.describe(this.#transcript.info));
220
+ } catch (error: unknown) {
221
+ this.#host.fail(error);
222
+ }
223
+ }
224
+
225
+ setModel(argument: string) {
226
+ const wanted = argument.trim();
227
+ const [provider, ...rest] = wanted.split("/");
228
+ if (provider && rest.length)
229
+ return void this.#agent
230
+ .setModel({ provider, id: rest.join("/") })
231
+ .catch((error: unknown) => this.#host.fail(error));
232
+ const catalogue = this.#agent.catalogue();
233
+ if (wanted === "providers") return this.#overlay.open("model · providers", CodeTuiModels.providers(catalogue));
234
+ if (!provider) return this.#overlay.open("model", CodeTuiModels.list(catalogue));
235
+ const listing = CodeTuiModels.ofProvider(catalogue, provider);
236
+ if (listing) return this.#overlay.open(`model · ${provider}`, listing);
237
+ return this.#overlay.open(
238
+ "model",
239
+ [`There is no provider called "${provider}".`, "", ...CodeTuiModels.usage].join("\n"),
240
+ );
241
+ }
242
+ }
@@ -0,0 +1,59 @@
1
+ export interface CodeTuiCommand {
2
+ name: string;
3
+ desc: string;
4
+ arg?: string;
5
+ }
6
+
7
+ export class CodeTuiCommands {
8
+ static readonly all: CodeTuiCommand[] = [
9
+ { name: "help", desc: "list these commands and the keys" },
10
+ { name: "tools", desc: "what this session can call" },
11
+ { name: "model", desc: "switch model, or list what is available", arg: "[<provider>/<id>]" },
12
+ { name: "effort", desc: "how hard the model thinks before it answers", arg: "<level>" },
13
+ { name: "thinking", desc: "show the model's reasoning, or fold it away again" },
14
+ { name: "compact", desc: "summarise the conversation to free the window", arg: "[notes]" },
15
+ { name: "autocompact", desc: "how full the window gets before it is summarised", arg: "[<percent>]" },
16
+ { name: "abort", desc: "stop the running turn" },
17
+ { name: "clear", desc: "wipe the screen; the model keeps the conversation" },
18
+ { name: "name", desc: "name this session", arg: "<text>" },
19
+ { name: "fork", desc: "continue this conversation twice; the copy takes over here", arg: "[name]" },
20
+ { name: "agents", desc: "what a sub-agent may be, and what one may spend" },
21
+ { name: "mcp", desc: "the MCP servers this session reached", arg: "[add|remove|login|reload]" },
22
+ { name: "allowed", desc: "the commands this session runs without asking", arg: "[clear]" },
23
+ { name: "peers", desc: "the other akan code sessions running here" },
24
+ { name: "msg", desc: "hand a message to another session", arg: "<peer> <text>" },
25
+ { name: "quit", desc: "leave the session" },
26
+ ];
27
+
28
+ /** The command prefix under the caret, or undefined once the caret has left the command's first word. */
29
+ static prefixOf(text: string, caret: number) {
30
+ if (!text.startsWith("/")) return undefined;
31
+ const head = text.slice(0, caret);
32
+ if (/\s/.test(head) || head.includes("\n")) return undefined;
33
+ return head.slice(1);
34
+ }
35
+
36
+ static matches(prefix: string) {
37
+ const needle = prefix.toLowerCase();
38
+ return CodeTuiCommands.all.filter((command) => command.name.startsWith(needle));
39
+ }
40
+
41
+ static help() {
42
+ const usage = (command: CodeTuiCommand) => `/${command.name}${command.arg ? ` ${command.arg}` : ""}`;
43
+ const column = Math.max(...CodeTuiCommands.all.map((command) => usage(command).length)) + 2;
44
+ const list = CodeTuiCommands.all.map((command) => `${usage(command).padEnd(column)}${command.desc}`).join("\n");
45
+ return [
46
+ list,
47
+ "",
48
+ "Keys: enter send · shift+enter newline · ↑↓ move (history at the edges) · ←→ move",
49
+ "esc interrupt · pgup/pgdn scroll · ^c quit",
50
+ "@ completes a file in this repo · ← at the start of the prompt lists past sessions",
51
+ "",
52
+ "Scroll: the wheel scrolls this transcript · hold shift to select text with the mouse instead",
53
+ "",
54
+ "Images: cmd+v attaches what is on the clipboard · ^v does too, without the terminal in the way",
55
+ "",
56
+ 'shift+enter needs a terminal that reports it — in VS Code bind it to send "\\\\u001b\\r".',
57
+ ].join("\n");
58
+ }
59
+ }
@@ -0,0 +1,168 @@
1
+ import { CodeTuiLines } from "./CodeTuiLines";
2
+
3
+ export interface CodeTuiEditorRow {
4
+ text: string;
5
+ /** Offset of this row's first character in the buffer. */
6
+ at: number;
7
+ }
8
+
9
+ export interface CodeTuiEditorLayout {
10
+ rows: CodeTuiEditorRow[];
11
+ /** Visual row of the caret, and its column in display cells. */
12
+ row: number;
13
+ col: number;
14
+ }
15
+
16
+ /** Moves by drawn row, and columns are display cells, so a caret crossing Hangul rows does not drift. */
17
+ export class CodeTuiEditor {
18
+ #text = "";
19
+ #caret = 0;
20
+
21
+ get text() {
22
+ return this.#text;
23
+ }
24
+
25
+ get caret() {
26
+ return this.#caret;
27
+ }
28
+
29
+ get isEmpty() {
30
+ return !this.#text.length;
31
+ }
32
+
33
+ set(text: string, caret = text.length) {
34
+ this.#text = text;
35
+ this.#caret = Math.max(0, Math.min(caret, text.length));
36
+ }
37
+
38
+ clear() {
39
+ this.set("");
40
+ }
41
+
42
+ /** Leaves the caret after the inserted text. */
43
+ replace(from: number, to: number, text: string) {
44
+ this.set(this.#text.slice(0, from) + text + this.#text.slice(to), from + text.length);
45
+ }
46
+
47
+ /** The whitespace-delimited token the caret sits in, as a range. */
48
+ token(): { from: number; to: number; text: string } {
49
+ const before = this.#text.slice(0, this.#caret);
50
+ const from = Math.max(before.lastIndexOf(" "), before.lastIndexOf("\n")) + 1;
51
+ const after = /\s/.exec(this.#text.slice(this.#caret));
52
+ const to = after ? this.#caret + (after.index ?? 0) : this.#text.length;
53
+ return { from, to, text: this.#text.slice(from, to) };
54
+ }
55
+
56
+ /** A keystroke or a whole paste; newlines are kept, CR and CRLF normalized to LF. */
57
+ insert(text: string) {
58
+ const clean = text.replace(/\r\n?/g, "\n");
59
+ this.set(this.#text.slice(0, this.#caret) + clean + this.#text.slice(this.#caret), this.#caret + clean.length);
60
+ }
61
+
62
+ /** Drops a backslash before the caret: terminals bind shift+enter as the shell continuation `\` + return. */
63
+ newline() {
64
+ if (this.#text.slice(0, this.#caret).endsWith("\\"))
65
+ this.set(this.#text.slice(0, this.#caret - 1) + this.#text.slice(this.#caret), this.#caret - 1);
66
+ this.insert("\n");
67
+ }
68
+
69
+ backspace() {
70
+ if (!this.#caret) return;
71
+ const at = CodeTuiEditor.#prev(this.#text, this.#caret);
72
+ this.set(this.#text.slice(0, at) + this.#text.slice(this.#caret), at);
73
+ }
74
+
75
+ deleteForward() {
76
+ if (this.#caret >= this.#text.length) return;
77
+ const at = CodeTuiEditor.#next(this.#text, this.#caret);
78
+ this.set(this.#text.slice(0, this.#caret) + this.#text.slice(at), this.#caret);
79
+ }
80
+
81
+ /** The word before the caret, and the run of spaces it sat behind. */
82
+ deleteWord() {
83
+ const before = this.#text.slice(0, this.#caret);
84
+ const at = before.replace(/\s*\S*$/, "").length;
85
+ this.set(before.slice(0, at) + this.#text.slice(this.#caret), at);
86
+ }
87
+
88
+ deleteToLineStart() {
89
+ const at = this.#text.lastIndexOf("\n", Math.max(0, this.#caret - 1)) + 1;
90
+ this.set(this.#text.slice(0, at) + this.#text.slice(this.#caret), at);
91
+ }
92
+
93
+ left() {
94
+ this.#caret = CodeTuiEditor.#prev(this.#text, this.#caret);
95
+ }
96
+
97
+ right() {
98
+ this.#caret = CodeTuiEditor.#next(this.#text, this.#caret);
99
+ }
100
+
101
+ wordLeft() {
102
+ this.#caret = this.#text.slice(0, this.#caret).replace(/\s*\S*$/, "").length;
103
+ }
104
+
105
+ wordRight() {
106
+ const rest = /^\s*\S*/.exec(this.#text.slice(this.#caret))?.[0] ?? "";
107
+ this.#caret = Math.min(this.#text.length, this.#caret + rest.length);
108
+ }
109
+
110
+ /** Moves one visual row, keeping the column; false when there is no row that way. */
111
+ move(direction: -1 | 1, width: number) {
112
+ const { rows, row, col } = this.layout(width);
113
+ const target = rows[row + direction];
114
+ if (!target) return false;
115
+ this.#caret = target.at + CodeTuiEditor.#indexAt(target.text, col);
116
+ return true;
117
+ }
118
+
119
+ homeOfRow(width: number) {
120
+ const { rows, row } = this.layout(width);
121
+ this.#caret = rows[row]?.at ?? 0;
122
+ }
123
+
124
+ endOfRow(width: number) {
125
+ const { rows, row } = this.layout(width);
126
+ const current = rows[row];
127
+ this.#caret = current ? current.at + current.text.length : this.#text.length;
128
+ }
129
+
130
+ layout(width: number): CodeTuiEditorLayout {
131
+ const room = Math.max(4, width);
132
+ const rows: CodeTuiEditorRow[] = [];
133
+ let at = 0;
134
+ for (const line of this.#text.split("\n")) {
135
+ // Character wrap, not word wrap: an editor must never move text the writer placed.
136
+ for (const text of line ? CodeTuiLines.chunks(line, room) : [""]) {
137
+ rows.push({ text, at });
138
+ at += text.length;
139
+ }
140
+ at += 1;
141
+ }
142
+ if (!rows.length) rows.push({ text: "", at: 0 });
143
+ // At a soft wrap the caret belongs to the new row, which is where the next character will be drawn.
144
+ let row = 0;
145
+ for (let index = 0; index < rows.length; index += 1) if ((rows[index]?.at ?? 0) <= this.#caret) row = index;
146
+ const current = rows[row] ?? { text: "", at: 0 };
147
+ return { rows, row, col: CodeTuiLines.width(current.text.slice(0, Math.max(0, this.#caret - current.at))) };
148
+ }
149
+
150
+ static #indexAt(row: string, col: number) {
151
+ let at = 0;
152
+ for (const char of row) {
153
+ if (CodeTuiLines.width(row.slice(0, at + char.length)) > col) break;
154
+ at += char.length;
155
+ }
156
+ return at;
157
+ }
158
+
159
+ static #prev(text: string, at: number) {
160
+ if (at <= 0) return 0;
161
+ return at - ([...text.slice(0, at)].at(-1)?.length ?? 1);
162
+ }
163
+
164
+ static #next(text: string, at: number) {
165
+ if (at >= text.length) return text.length;
166
+ return at + ([...text.slice(at)][0]?.length ?? 1);
167
+ }
168
+ }
@@ -0,0 +1,45 @@
1
+ /** Files for `@` mentions, listed once through git so `.gitignore` applies without a denylist of our own. */
2
+ export class CodeTuiFiles {
3
+ static readonly limit = 8;
4
+
5
+ readonly #root: string;
6
+ #all: string[] = [];
7
+ #loaded = false;
8
+
9
+ constructor(root: string) {
10
+ this.#root = root;
11
+ }
12
+
13
+ get ready() {
14
+ return this.#loaded;
15
+ }
16
+
17
+ async load() {
18
+ this.#all = await CodeTuiFiles.#list(this.#root);
19
+ this.#loaded = true;
20
+ }
21
+
22
+ /** Case-insensitive substring matches, shortest path first. */
23
+ match(query: string, limit = CodeTuiFiles.limit) {
24
+ const needle = query.toLowerCase();
25
+ if (!needle) return this.#all.slice(0, limit);
26
+ const hits = this.#all.filter((file) => file.toLowerCase().includes(needle));
27
+ return hits.sort((left, right) => left.length - right.length).slice(0, limit);
28
+ }
29
+
30
+ static async #list(root: string) {
31
+ try {
32
+ const proc = Bun.spawn(["git", "ls-files", "--cached", "--others", "--exclude-standard"], {
33
+ cwd: root,
34
+ stdout: "pipe",
35
+ stderr: "ignore",
36
+ });
37
+ const text = await new Response(proc.stdout).text();
38
+ if ((await proc.exited) !== 0) return [];
39
+ return text.split("\n").filter((line) => !!line.trim());
40
+ } catch {
41
+ // no git or no repo: complete nothing rather than walk the disk
42
+ return [];
43
+ }
44
+ }
45
+ }
@@ -0,0 +1,133 @@
1
+ import { type CodeTranscript, codeAgentClip } from "akanjs/common";
2
+ import { CodeTuiAgents } from "./CodeTuiAgents";
3
+ import type { CodeTuiSnapshot } from "./CodeTuiApp";
4
+ import { type CodeTuiLine, CodeTuiLines, type CodeTuiRow, type CodeTuiSpan } from "./CodeTuiLines";
5
+ import { CodeTuiParts } from "./CodeTuiParts";
6
+
7
+ export interface CodeTuiAskBlock {
8
+ rows: number;
9
+ above: number; // rows drawn above the prompt's first line, which the caret row is counted from
10
+ selected: number;
11
+ caret: { row: number; col: number } | undefined;
12
+ snapshot: Pick<CodeTuiSnapshot, "input" | "menu" | "menuSelected" | "options">;
13
+ }
14
+
15
+ export class CodeTuiFrame {
16
+ static readonly chromeRows = 1; // the hint row under the input
17
+ static readonly promptRuleRows = 1; // the rule above the prompt box, and its twin below
18
+ static readonly minBodyRows = 3; // the pane's header plus one line of conversation
19
+ static readonly maxInputRows = 8;
20
+ static readonly title = "Akan — write one line, deploy every stack";
21
+
22
+ readonly #transcript: CodeTranscript;
23
+ readonly #stdout: NodeJS.WriteStream;
24
+ #thinking: boolean;
25
+
26
+ constructor(transcript: CodeTranscript, stdout: NodeJS.WriteStream, thinking: boolean) {
27
+ this.#transcript = transcript;
28
+ this.#stdout = stdout;
29
+ this.#thinking = thinking;
30
+ }
31
+
32
+ // Ink overwrites rather than clips an overflowing column, so every row split of the frame has to be exact.
33
+ static layout(frameRows: number, askRows: number, railRows = 0) {
34
+ const room = Math.max(1, frameRows - CodeTuiFrame.minBodyRows - CodeTuiFrame.chromeRows - railRows);
35
+ const ask = Math.max(1, Math.min(askRows, room));
36
+ return {
37
+ ask,
38
+ bodyHeight: Math.max(CodeTuiFrame.minBodyRows, frameRows - ask - CodeTuiFrame.chromeRows - railRows),
39
+ };
40
+ }
41
+
42
+ // One row short: Ink treats a terminal-filling frame as fullscreen, erasing scrollback and misplacing the caret.
43
+ static frameRowsOf(terminalRows: number) {
44
+ return Math.max(CodeTuiFrame.minBodyRows + CodeTuiFrame.chromeRows + 1, terminalRows - 1);
45
+ }
46
+
47
+ toggleThinking() {
48
+ this.#thinking = !this.#thinking;
49
+ return this.#thinking;
50
+ }
51
+
52
+ lines(width: number): CodeTuiLine[] {
53
+ return [
54
+ ...CodeTuiLines.rows(this.#banner(), width, "banner"),
55
+ ...CodeTuiParts.lines(this.#transcript.parts, width, { thinking: this.#thinking }),
56
+ ];
57
+ }
58
+
59
+ // Dropped rather than windowed when it does not fit: half a list of running children reads as the whole one.
60
+ railRows(columns: number): CodeTuiLine[] {
61
+ const agents = this.#transcript.subagents;
62
+ if (!agents.length) return [];
63
+ const rows = CodeTuiAgents.rows(agents, this.#transcript.info?.name ?? "main", columns);
64
+ const room =
65
+ CodeTuiFrame.frameRowsOf(Math.max(10, this.#stdout.rows || 24)) -
66
+ CodeTuiFrame.minBodyRows -
67
+ CodeTuiFrame.chromeRows -
68
+ 2 * CodeTuiFrame.promptRuleRows -
69
+ 1;
70
+ return rows.length <= room ? rows : [];
71
+ }
72
+
73
+ #banner(): CodeTuiRow[] {
74
+ const cwd = this.#transcript.info?.cwd;
75
+ return [
76
+ { prefix: { text: "✻ ", color: "cyan" }, spans: [{ text: CodeTuiFrame.title, bold: true }] },
77
+ {
78
+ prefix: { text: " " },
79
+ spans: [{ text: cwd ? `${cwd} · /help for commands` : "/help for commands", dim: true }],
80
+ },
81
+ ];
82
+ }
83
+
84
+ static rule(left: string, right: string, width: number): CodeTuiSpan[] {
85
+ const room = (label: string) => (label ? 3 + CodeTuiLines.width(label) : 1);
86
+ const tail = right ? codeAgentClip(right, Math.max(1, width - 4)) : "";
87
+ const head = width - room(left) - room(tail) >= 0 ? left : "";
88
+ const fill = Math.max(0, width - room(head) - room(tail));
89
+ return [
90
+ ...(head
91
+ ? ([
92
+ { text: "─ ", dim: true },
93
+ { text: head, color: "cyan" },
94
+ { text: " ", dim: true },
95
+ ] satisfies CodeTuiSpan[])
96
+ : ([{ text: "─", dim: true }] satisfies CodeTuiSpan[])),
97
+ { text: "─".repeat(fill), dim: true },
98
+ ...(tail
99
+ ? ([
100
+ { text: " ", dim: true },
101
+ { text: tail, dim: true },
102
+ { text: " ─", dim: true },
103
+ ] satisfies CodeTuiSpan[])
104
+ : ([{ text: "─", dim: true }] satisfies CodeTuiSpan[])),
105
+ ];
106
+ }
107
+
108
+ queueLabel() {
109
+ const queue = this.#transcript.queue;
110
+ const parts: string[] = [];
111
+ if (queue.steering || queue.followUp) parts.push(`queued ${queue.steering + queue.followUp}`);
112
+ if (this.#transcript.compacting) parts.push("compacting");
113
+ return parts.join(" · ");
114
+ }
115
+
116
+ // The declared window stays visible: a wrong but self-consistent descriptor passes every check but a reader's.
117
+ statusLabel() {
118
+ const info = this.#transcript.info;
119
+ if (!info) return "starting…";
120
+ const context = this.#transcript.context;
121
+ const window = info.contextTokens ? `${Math.round(info.contextTokens / 1000)}k` : "";
122
+ const used = context?.max ? `${Math.round((context.used / context.max) * 100)}% of ${window}` : "";
123
+ const compactsAt = info.autoCompactAt ? `compacts at ${info.autoCompactAt}%` : "";
124
+ return [info.model?.name ?? "no model", used || (window && `${window} ctx`), compactsAt, info.profile, info.effort]
125
+ .filter((part) => !!part)
126
+ .join(" · ");
127
+ }
128
+
129
+ status() {
130
+ if (this.#transcript.compacting) return "compacting";
131
+ return this.#transcript.streaming ? "working" : "";
132
+ }
133
+ }