@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,251 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { esc, FakeStdout, makeStdin, nextFrame } from "@akanjs/devkit/test/fakeTerminal";
3
+ import { render } from "ink";
4
+ import { type CodeTuiActions, CodeTuiApp, type CodeTuiSnapshot } from "./CodeTuiApp";
5
+ import type { CodeTuiLine } from "./CodeTuiLines";
6
+
7
+ const keys = {
8
+ up: `${esc}[A`,
9
+ down: `${esc}[B`,
10
+ enter: "\r",
11
+ escape: esc,
12
+ ctrlC: String.fromCharCode(3),
13
+ pageUp: `${esc}[5~`,
14
+ backspace: String.fromCharCode(127),
15
+ };
16
+
17
+ const lineOf = (key: string, text: string): CodeTuiLine => ({ key, spans: [{ text }] });
18
+
19
+ interface Harness {
20
+ stdout: FakeStdout;
21
+ calls: string[];
22
+ unmount: () => void;
23
+ press: (input: string) => Promise<void>;
24
+ }
25
+
26
+ const harnesses: Harness[] = [];
27
+
28
+ const mount = (patch: Partial<CodeTuiSnapshot> = {}): Harness => {
29
+ const stdout = new FakeStdout(90, 16);
30
+ const stdin = makeStdin();
31
+ const calls: string[] = [];
32
+ const snapshot: CodeTuiSnapshot = {
33
+ topRule: [
34
+ { text: "─".repeat(80), dim: true },
35
+ { text: " 01a0bcae ─", dim: true },
36
+ ],
37
+ bottomRule: [
38
+ { text: "─".repeat(40), dim: true },
39
+ { text: " DeepSeek V4 Flash · 4% of 1000k · local ─", dim: true },
40
+ ],
41
+ overlay: null,
42
+ offered: false,
43
+ subagents: [],
44
+ lines: [lineOf("a", "› add a comment module"), lineOf("b", "✓ list_modules")],
45
+ above: 0,
46
+ below: 0,
47
+ following: true,
48
+ status: "",
49
+ mode: "input",
50
+ input: [""],
51
+ cursor: { x: 2, y: 14 },
52
+ menu: [],
53
+ menuSelected: 0,
54
+ placeholder: "ask for something, / for commands",
55
+ prompt: "",
56
+ options: [],
57
+ selected: 0,
58
+ checked: [],
59
+ multiSelect: false,
60
+ notice: "",
61
+ hint: "enter send · ↑↓ history · esc interrupt",
62
+ columns: 90,
63
+ frameRows: 16,
64
+ bodyHeight: 13,
65
+ ...patch,
66
+ };
67
+ const actions: CodeTuiActions = {
68
+ subscribe: () => () => undefined,
69
+ snapshot: () => snapshot,
70
+ type: (text) => calls.push(`type:${text}`),
71
+ edit: (action) => calls.push(`edit:${action}`),
72
+ submit: () => calls.push("submit"),
73
+ newline: () => calls.push("newline"),
74
+ paste: () => calls.push("paste"),
75
+ pasted: (text) => calls.push(`pasted:${text}`),
76
+ complete: () => calls.push("complete"),
77
+ vertical: (delta) => calls.push(`vertical:${delta}`),
78
+ scroll: (delta) => calls.push(`scroll:${delta}`),
79
+ move: (delta) => calls.push(`move:${delta}`),
80
+ toggle: () => calls.push("toggle"),
81
+ answerConfirm: (value) => calls.push(`answerConfirm:${value}`),
82
+ allowForSession: () => calls.push("allowForSession"),
83
+ cancel: () => calls.push("cancel"),
84
+ interrupt: () => calls.push("interrupt"),
85
+ };
86
+ const instance = render(<CodeTuiApp actions={actions} />, {
87
+ stdout: stdout as unknown as NodeJS.WriteStream,
88
+ stdin: stdin as unknown as NodeJS.ReadStream,
89
+ patchConsole: false,
90
+ exitOnCtrlC: false,
91
+ });
92
+ const harness: Harness = {
93
+ stdout,
94
+ calls,
95
+ unmount: () => instance.unmount(),
96
+ press: async (input: string) => {
97
+ stdin.write(input);
98
+ await nextFrame();
99
+ },
100
+ };
101
+ harnesses.push(harness);
102
+ return harness;
103
+ };
104
+
105
+ afterEach(() => {
106
+ for (const harness of harnesses.splice(0)) harness.unmount();
107
+ });
108
+
109
+ describe("CodeTuiApp", () => {
110
+ test("draws the session line, the transcript and the input row", async () => {
111
+ const { stdout } = mount();
112
+ await nextFrame();
113
+ const frame = stdout.lastFrame;
114
+ expect(frame).toContain("01a0bcae");
115
+ expect(frame).toContain("4% of 1000k");
116
+ expect(frame).toContain("add a comment module");
117
+ expect(frame).toContain("ask for something, / for commands");
118
+ expect(frame).toContain("enter send");
119
+ });
120
+
121
+ test("running sub-agents draw between the prompt and the model line", async () => {
122
+ const { stdout } = mount({
123
+ subagents: [
124
+ lineOf("agents:self", "❯ ⏺ main"),
125
+ lineOf("agents:c0", " ◯ explore Counting desc strings 12m 30s · ↓ 301.3k tokens"),
126
+ ],
127
+ });
128
+ await nextFrame();
129
+ const frame = stdout.lastFrame;
130
+ expect(frame).toContain("◯ explore");
131
+ expect(frame).toContain("↓ 301.3k tokens");
132
+ expect(frame.indexOf("ask for something")).toBeLessThan(frame.indexOf("◯ explore"));
133
+ expect(frame.indexOf("◯ explore")).toBeLessThan(frame.indexOf("4% of 1000k"));
134
+ });
135
+
136
+ test("an overlay covers the transcript and says how much of itself is off screen", async () => {
137
+ const { stdout } = mount({
138
+ overlay: { title: "help", lines: [lineOf("h", "/help · /tools")], above: 0, below: 7, selectable: false },
139
+ });
140
+ await nextFrame();
141
+ expect(stdout.lastFrame).toContain("help");
142
+ expect(stdout.lastFrame).toContain("▼7");
143
+ expect(stdout.lastFrame).not.toContain("add a comment module");
144
+ });
145
+
146
+ test("typing goes to the input and enter sends it", async () => {
147
+ const harness = mount();
148
+ await harness.press("hi");
149
+ await harness.press(keys.enter);
150
+ expect(harness.calls).toEqual(["type:hi", "submit"]);
151
+ });
152
+
153
+ test("the arrows move within the prompt; the controller falls through to history at its edges", async () => {
154
+ const harness = mount();
155
+ await harness.press(keys.up);
156
+ await harness.press(keys.down);
157
+ expect(harness.calls).toEqual(["vertical:-1", "vertical:1"]);
158
+ });
159
+
160
+ test("page keys scroll in every mode, so a question never hides what led to it", async () => {
161
+ const harness = mount({ mode: "select", options: [{ key: "a", label: "akan" }], bodyHeight: 13 });
162
+ await harness.press(keys.pageUp);
163
+ expect(harness.calls[0]).toStartWith("scroll:-");
164
+ });
165
+
166
+ test("a select question takes the arrows and enter instead", async () => {
167
+ const harness = mount({
168
+ mode: "select",
169
+ prompt: "? Which app?",
170
+ options: [
171
+ { key: "akan", label: "akan" },
172
+ { key: "minimal", label: "minimal" },
173
+ ],
174
+ selected: 1,
175
+ bodyHeight: 12,
176
+ });
177
+ await nextFrame();
178
+ expect(harness.stdout.lastFrame).toContain("? Which app?");
179
+ await harness.press(keys.down);
180
+ await harness.press(keys.enter);
181
+ expect(harness.calls).toEqual(["move:1", "submit"]);
182
+ });
183
+
184
+ test("space toggles only when the question is multi-select", async () => {
185
+ const single = mount({ mode: "select", options: [{ key: "a", label: "akan" }], bodyHeight: 13 });
186
+ await single.press(" ");
187
+ expect(single.calls).toEqual([]);
188
+ const multi = mount({
189
+ mode: "select",
190
+ multiSelect: true,
191
+ checked: ["a"],
192
+ options: [{ key: "a", label: "akan" }],
193
+ bodyHeight: 13,
194
+ });
195
+ await multi.press(" ");
196
+ expect(multi.calls).toEqual(["toggle"]);
197
+ expect(multi.stdout.lastFrame).toContain("[x] akan");
198
+ });
199
+
200
+ test("an approval is y or n, and escape is a no", async () => {
201
+ const harness = mount({ mode: "confirm", prompt: "approve? write a.ts [y/n]", bodyHeight: 14 });
202
+ await nextFrame();
203
+ expect(harness.stdout.lastFrame).toContain("approve? write a.ts");
204
+ await harness.press("y");
205
+ await harness.press("n");
206
+ await harness.press(keys.escape);
207
+ expect(harness.calls).toEqual(["answerConfirm:true", "answerConfirm:false", "cancel"]);
208
+ });
209
+
210
+ test("a at an approval is the answer for the rest of the session, and is not typed anywhere else", async () => {
211
+ const confirm = mount({ mode: "confirm", prompt: "approve? run: bun test [y/n/a]", bodyHeight: 14 });
212
+ await confirm.press("a");
213
+ await confirm.press("A");
214
+ expect(confirm.calls).toEqual(["allowForSession", "allowForSession"]);
215
+ const input = mount();
216
+ await input.press("a");
217
+ expect(input.calls).toEqual(["type:a"]);
218
+ });
219
+
220
+ test("a confirm question does not treat a stray letter as text", async () => {
221
+ const harness = mount({ mode: "confirm", prompt: "? Continue?", bodyHeight: 14 });
222
+ await harness.press("q");
223
+ expect(harness.calls).toEqual([]);
224
+ });
225
+
226
+ test("ctrl-c is an interrupt, not a type", async () => {
227
+ const harness = mount();
228
+ await harness.press(keys.ctrlC);
229
+ expect(harness.calls).toEqual(["interrupt"]);
230
+ });
231
+
232
+ test("backspace deletes rather than typing a control character", async () => {
233
+ const harness = mount({ input: ["abc"] });
234
+ await harness.press(keys.backspace);
235
+ expect(harness.calls).toEqual(["edit:backspace"]);
236
+ });
237
+
238
+ test("a working turn changes the input marker so the state is visible while typing", async () => {
239
+ const { stdout } = mount({ status: "working", placeholder: "type to steer, esc to interrupt" });
240
+ await nextFrame();
241
+ expect(stdout.lastFrame).toContain("◐");
242
+ expect(stdout.lastFrame).toContain("type to steer");
243
+ });
244
+
245
+ test("a notice replaces the hints until it expires", async () => {
246
+ const { stdout } = mount({ notice: "interrupted — ^c again to quit" });
247
+ await nextFrame();
248
+ expect(stdout.lastFrame).toContain("interrupted");
249
+ expect(stdout.lastFrame).not.toContain("enter send");
250
+ });
251
+ });
@@ -0,0 +1,312 @@
1
+ import { Box, Text, useCursor, useInput } from "ink";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import type { CodeTuiLine, CodeTuiSpan } from "./CodeTuiLines";
4
+ import { CodeTuiMouse } from "./CodeTuiMouse";
5
+
6
+ export interface CodeTuiOption {
7
+ key: string;
8
+ label: string;
9
+ detail?: string;
10
+ }
11
+
12
+ export interface CodeTuiSnapshot {
13
+ topRule: CodeTuiSpan[];
14
+ bottomRule: CodeTuiSpan[];
15
+ lines: CodeTuiLine[]; // windowed and wrapped by the controller: one entry is exactly one row
16
+ above: number;
17
+ below: number;
18
+ following: boolean;
19
+ // `selectable`: enter picks the highlighted row rather than closing the overlay.
20
+ overlay: { title: string; lines: CodeTuiLine[]; above: number; below: number; selectable: boolean } | null;
21
+ status: string;
22
+ subagents: CodeTuiLine[];
23
+ mode: "input" | "select" | "confirm";
24
+ input: string[];
25
+ placeholder: string;
26
+ offered: boolean; // the clipboard holds an image to attach
27
+ cursor: { x: number; y: number } | null; // in frame cells, so an IME draws its composing text at the caret
28
+ prompt: string;
29
+ options: CodeTuiOption[];
30
+ selected: number;
31
+ checked: string[];
32
+ multiSelect: boolean;
33
+ menu: CodeTuiOption[];
34
+ menuSelected: number;
35
+ notice: string;
36
+ hint: string;
37
+ columns: number;
38
+ frameRows: number;
39
+ bodyHeight: number;
40
+ }
41
+
42
+ export interface CodeTuiActions {
43
+ subscribe: (listener: () => void) => () => void;
44
+ snapshot: () => CodeTuiSnapshot;
45
+ type: (text: string) => void;
46
+ edit: (key: CodeTuiEditKey) => void;
47
+ submit: () => void;
48
+ newline: () => void;
49
+ paste: () => void;
50
+ pasted: (text: string) => void;
51
+ complete: () => void;
52
+ vertical: (delta: -1 | 1) => void;
53
+ scroll: (delta: number) => void;
54
+ move: (delta: number) => void;
55
+ toggle: () => void;
56
+ answerConfirm: (value: boolean) => void;
57
+ allowForSession: () => void;
58
+ cancel: () => void;
59
+ interrupt: () => void;
60
+ }
61
+
62
+ export type CodeTuiEditKey =
63
+ | "backspace"
64
+ | "delete"
65
+ | "left"
66
+ | "right"
67
+ | "wordLeft"
68
+ | "wordRight"
69
+ | "home"
70
+ | "end"
71
+ | "deleteWord"
72
+ | "deleteToStart";
73
+
74
+ export const promptMarkWidth = 2; // the `› ` / `◐ ` marker every prompt row carries
75
+
76
+ // Ink strips the leading ESC of the bracketed-paste markers `ESC[200~` / `ESC[201~` before the handler sees them.
77
+ const pasteOpen = "[200~";
78
+ const pasteClose = "[201~";
79
+
80
+ // A shift+enter binding sent as `\` + return arrives as one unparsed chunk; the ESC-separated spelling is split by
81
+ // Ink instead, which is why its backslash is removed in `CodeTuiEditor.newline`.
82
+ const continuation = /^[^\r\n]*\\(?:\r\n|[\r\n])$/;
83
+
84
+ const Styled = ({ span }: { span: CodeTuiSpan }) => (
85
+ <Text
86
+ bold={span.bold}
87
+ color={span.color}
88
+ dimColor={span.dim}
89
+ italic={span.italic}
90
+ strikethrough={span.strikethrough}
91
+ underline={span.underline}
92
+ >
93
+ {span.text}
94
+ </Text>
95
+ );
96
+
97
+ const Line = ({ line }: { line: CodeTuiLine }) => (
98
+ <Text wrap="truncate">
99
+ {line.spans.map((span, at) => (
100
+ <Styled key={`${line.key}:${at}`} span={span} />
101
+ ))}
102
+ </Text>
103
+ );
104
+
105
+ const Transcript = ({ lines, width, height }: { lines: CodeTuiLine[]; width: number; height: number }) => (
106
+ <Box flexDirection="column" width={width} height={height} paddingX={1}>
107
+ {lines.map((line) => (
108
+ <Line key={line.key} line={line} />
109
+ ))}
110
+ </Box>
111
+ );
112
+
113
+ const Overlay = ({
114
+ overlay,
115
+ width,
116
+ height,
117
+ }: {
118
+ overlay: NonNullable<CodeTuiSnapshot["overlay"]>;
119
+ width: number;
120
+ height: number;
121
+ }) => (
122
+ <Box borderDimColor borderStyle="round" flexDirection="column" height={height} paddingX={1} width={width}>
123
+ <Text wrap="truncate">
124
+ <Text bold color="cyan">
125
+ {overlay.title}
126
+ </Text>
127
+ {overlay.above || overlay.below ? <Text dimColor>{` ▲${overlay.above} ▼${overlay.below}`}</Text> : null}
128
+ </Text>
129
+ {overlay.lines.map((line) => (
130
+ <Line key={line.key} line={line} />
131
+ ))}
132
+ </Box>
133
+ );
134
+
135
+ const Rule = ({ spans }: { spans: CodeTuiSpan[] }) => (
136
+ <Text wrap="truncate">
137
+ {spans.map((span, at) => (
138
+ <Styled key={`${at}:${span.text}`} span={span} />
139
+ ))}
140
+ </Text>
141
+ );
142
+
143
+ interface MenuProps {
144
+ options: CodeTuiOption[];
145
+ selected: number;
146
+ marker: boolean;
147
+ checked?: string[];
148
+ }
149
+
150
+ const Menu = ({ options, selected, marker, checked }: MenuProps) => (
151
+ <Box flexDirection="column">
152
+ {options.map((option, idx) => (
153
+ <Text key={option.key} wrap="truncate">
154
+ <Text color={idx === selected ? "cyan" : undefined}>{idx === selected ? "❯ " : " "}</Text>
155
+ {checked ? <Text>{checked.includes(option.key) ? "[x] " : "[ ] "}</Text> : null}
156
+ <Text bold={idx === selected && marker}>{option.label}</Text>
157
+ {option.detail ? <Text dimColor>{` ${option.detail}`}</Text> : null}
158
+ </Text>
159
+ ))}
160
+ </Box>
161
+ );
162
+
163
+ export const CodeTuiApp = ({ actions }: { actions: CodeTuiActions }) => {
164
+ const [snapshot, setSnapshot] = useState(actions.snapshot);
165
+ const pasting = useRef<string[] | null>(null);
166
+ const mouse = useRef(new CodeTuiMouse());
167
+ const { setCursorPosition } = useCursor();
168
+
169
+ useEffect(() => {
170
+ const unsubscribe = actions.subscribe(() => setSnapshot(actions.snapshot()));
171
+ setSnapshot(actions.snapshot());
172
+ return unsubscribe;
173
+ }, [actions]);
174
+
175
+ // Set during render: `useCursor` applies the value from the next render's insertion effect, so a position set
176
+ // after commit trails a frame behind — and an IME draws its composing text wherever the cursor is.
177
+ setCursorPosition(snapshot.cursor ?? undefined);
178
+
179
+ useInput((input, key) => {
180
+ const page = Math.max(1, snapshot.bodyHeight - 3);
181
+ // A paste is collected whole: a pasted newline would otherwise submit half of it.
182
+ if (input === pasteOpen) {
183
+ pasting.current = [];
184
+ return;
185
+ }
186
+ if (input === pasteClose) {
187
+ const text = pasting.current?.join("") ?? "";
188
+ pasting.current = null;
189
+ return actions.pasted(text);
190
+ }
191
+ if (pasting.current) {
192
+ pasting.current.push(key.return ? "\n" : key.tab ? "\t" : input);
193
+ return;
194
+ }
195
+ // Before every key: a wheel report is a CSI sequence that would otherwise be typed into the prompt.
196
+ const wheel = mouse.current.read(input);
197
+ if (wheel) {
198
+ if (wheel.rows) actions.scroll(wheel.rows);
199
+ if (wheel.rest) actions.type(wheel.rest);
200
+ return;
201
+ }
202
+ if (key.ctrl && input === "c") return actions.interrupt();
203
+ if (key.pageUp) return actions.scroll(-page);
204
+ if (key.pageDown) return actions.scroll(page);
205
+ if (key.escape) return actions.cancel();
206
+ if (snapshot.overlay) {
207
+ if (key.upArrow) return actions.scroll(-1);
208
+ if (key.downArrow) return actions.scroll(1);
209
+ if (key.return) return snapshot.overlay.selectable ? actions.submit() : actions.cancel();
210
+ return;
211
+ }
212
+ if (snapshot.mode === "confirm") {
213
+ if (input === "y" || input === "Y") return actions.answerConfirm(true);
214
+ if (input === "n" || input === "N") return actions.answerConfirm(false);
215
+ if (input === "a" || input === "A") return actions.allowForSession();
216
+ return;
217
+ }
218
+ if (snapshot.mode === "select") {
219
+ if (key.upArrow) return actions.move(-1);
220
+ if (key.downArrow) return actions.move(1);
221
+ if (input === " " && snapshot.multiSelect) return actions.toggle();
222
+ if (key.return) return actions.submit();
223
+ return;
224
+ }
225
+ if (key.tab) return actions.complete();
226
+ if (key.upArrow) return actions.vertical(-1);
227
+ if (key.downArrow) return actions.vertical(1);
228
+ if (key.leftArrow) return actions.edit(key.meta ? "wordLeft" : "left");
229
+ if (key.rightArrow) return actions.edit(key.meta ? "wordRight" : "right");
230
+ // Without the kitty protocol, shift+enter arrives as ESC+CR (meta+return) or a bare LF, which is ^j.
231
+ if (key.return && (key.shift || key.meta)) return actions.newline();
232
+ if (key.ctrl && input === "j") return actions.newline();
233
+ if (continuation.test(input)) {
234
+ actions.type(input.replace(/[\r\n]+$/, ""));
235
+ return actions.newline();
236
+ }
237
+ if (key.return) return actions.submit();
238
+ if (key.backspace || key.delete) return actions.edit(key.meta ? "deleteWord" : "backspace");
239
+ if (key.ctrl && input === "w") return actions.edit("deleteWord");
240
+ if (key.ctrl && input === "u") return actions.edit("deleteToStart");
241
+ if (key.ctrl && input === "a") return actions.edit("home");
242
+ if (key.ctrl && input === "e") return actions.edit("end");
243
+ if (key.ctrl && input === "d") return actions.edit("delete");
244
+ if (key.ctrl && input === "v") return actions.paste();
245
+ if (input && !key.ctrl && !key.meta) return actions.type(input);
246
+ });
247
+
248
+ const paneWidth = snapshot.columns;
249
+ return (
250
+ <Box flexDirection="column" width={paneWidth} height={snapshot.frameRows}>
251
+ {snapshot.overlay ? (
252
+ <Overlay height={snapshot.bodyHeight} overlay={snapshot.overlay} width={paneWidth} />
253
+ ) : (
254
+ <Transcript height={snapshot.bodyHeight} lines={snapshot.lines} width={paneWidth} />
255
+ )}
256
+ {snapshot.menu.length ? <Menu marker options={snapshot.menu} selected={snapshot.menuSelected} /> : null}
257
+ <Rule spans={snapshot.topRule} />
258
+ {snapshot.mode === "input" ? (
259
+ <Box flexDirection="column">
260
+ {snapshot.offered ? (
261
+ <Text dimColor wrap="truncate">
262
+ {" ⧉ an image is on your clipboard — cmd+v or ^v attaches it"}
263
+ </Text>
264
+ ) : null}
265
+ {snapshot.input.map((row, at) => (
266
+ <Text key={`in:${at}`} wrap="truncate">
267
+ <Text color={snapshot.status ? "yellow" : "cyan"}>
268
+ {at === 0 ? (snapshot.status ? "◐ " : "› ") : " "}
269
+ </Text>
270
+ {at === 0 && !row && snapshot.input.length === 1 ? (
271
+ <Text dimColor>{snapshot.placeholder}</Text>
272
+ ) : (
273
+ <Text>{row}</Text>
274
+ )}
275
+ </Text>
276
+ ))}
277
+ </Box>
278
+ ) : (
279
+ <Box flexDirection="column">
280
+ <Text color="yellow" wrap="truncate">
281
+ {snapshot.prompt}
282
+ </Text>
283
+ {snapshot.options.length ? (
284
+ <Menu
285
+ checked={snapshot.multiSelect ? snapshot.checked : undefined}
286
+ marker={false}
287
+ options={snapshot.options}
288
+ selected={snapshot.selected}
289
+ />
290
+ ) : null}
291
+ </Box>
292
+ )}
293
+ {snapshot.subagents.length ? (
294
+ <Box flexDirection="column">
295
+ {snapshot.subagents.map((line) => (
296
+ <Line key={line.key} line={line} />
297
+ ))}
298
+ </Box>
299
+ ) : null}
300
+ <Rule spans={snapshot.bottomRule} />
301
+ {snapshot.notice ? (
302
+ <Text color="cyan" wrap="truncate">
303
+ {snapshot.notice}
304
+ </Text>
305
+ ) : (
306
+ <Text dimColor wrap="truncate">
307
+ {snapshot.hint}
308
+ </Text>
309
+ )}
310
+ </Box>
311
+ );
312
+ };
@@ -0,0 +1,33 @@
1
+ import type { CodeAgentSessionInfo } from "akanjs/common";
2
+ import { AkanCodeCompaction } from "../agent/AkanCodeCompaction";
3
+
4
+ export class CodeTuiAutoCompact {
5
+ /** `60` and `60%` both name a step; anything else is undefined. */
6
+ static parse(argument: string) {
7
+ const percent = Number(argument.trim().replace(/%$/, ""));
8
+ return argument.trim() && AkanCodeCompaction.isStep(percent) ? percent : undefined;
9
+ }
10
+
11
+ static describe(info: CodeAgentSessionInfo | undefined) {
12
+ const percent = info?.autoCompactAt;
13
+ const label = `autocompact ${percent ? `${percent}%` : "default"}`;
14
+ const window = info?.contextTokens;
15
+ if (!window) return label;
16
+ const threshold = AkanCodeCompaction.thresholdOf(window, percent);
17
+ const k = (tokens: number) => `${Math.round(tokens / 1000)}k`;
18
+ const capped =
19
+ percent && threshold < Math.floor((window * percent) / 100)
20
+ ? `, the latest that still leaves ${k(window - threshold)} for the reply`
21
+ : "";
22
+ return `${label} · compacts above ${k(threshold)} of ${k(window)}${capped}`;
23
+ }
24
+
25
+ static usage(info: CodeAgentSessionInfo | undefined) {
26
+ return [
27
+ "Usage: /autocompact <percent>",
28
+ "",
29
+ `now: ${CodeTuiAutoCompact.describe(info)}`,
30
+ `${AkanCodeCompaction.steps.join(" · ")} — 100 is the default`,
31
+ ].join("\n");
32
+ }
33
+ }
@@ -0,0 +1,94 @@
1
+ import { existsSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+
5
+ export class CodeTuiClipboard {
6
+ static readonly imageTypes = [".png", ".jpg", ".jpeg", ".gif", ".webp"] as const;
7
+
8
+ // A pasted image arrives as its file path (a macOS screenshot too, via its temp file). Split only where a new
9
+ // absolute path starts: a screenshot's own name contains spaces.
10
+ static imagePathsIn(text: string) {
11
+ const pieces = text.split("\n").flatMap((line) => line.split(/ (?=\/)/));
12
+ const images: string[] = [];
13
+ const rest: string[] = [];
14
+ for (const piece of pieces) {
15
+ const file = CodeTuiClipboard.imagePathIn(piece);
16
+ if (file) images.push(file);
17
+ else if (piece.trim()) rest.push(piece);
18
+ }
19
+ return { images, rest: rest.join(" ") };
20
+ }
21
+
22
+ static imagePathIn(text: string) {
23
+ const file = text
24
+ .trim()
25
+ .replace(/^['"]|['"]$/g, "")
26
+ .replace(/\\ /g, " ");
27
+ if (!file || file.includes("\n")) return undefined;
28
+ const lower = file.toLowerCase();
29
+ if (!CodeTuiClipboard.imageTypes.some((ext) => lower.endsWith(ext))) return undefined;
30
+ return existsSync(file) ? file : undefined;
31
+ }
32
+
33
+ /** The PNG on the clipboard as a file, or undefined when the clipboard holds no image. */
34
+ static async image(): Promise<string | undefined> {
35
+ const png = await CodeTuiClipboard.#read();
36
+ if (!png?.length) return undefined;
37
+ const file = path.join(tmpdir(), `akan-code-${Date.now()}.png`);
38
+ await Bun.write(file, png);
39
+ return file;
40
+ }
41
+
42
+ /** Whether there is an image to fetch, which is cheap enough to ask on a timer. */
43
+ static has() {
44
+ try {
45
+ return Bun.Image.hasClipboardImage();
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+
51
+ static async #read(): Promise<Uint8Array | undefined> {
52
+ // Bun reads the clipboard natively; the shell-outs below cover a clipboard flavour it declines.
53
+ try {
54
+ const image = Bun.Image.fromClipboard();
55
+ if (image) return new Uint8Array(await image.png().toBuffer());
56
+ } catch {
57
+ // unreadable here: the fallbacks get their turn
58
+ }
59
+ if (process.platform === "darwin") return await CodeTuiClipboard.#darwin();
60
+ for (const command of [
61
+ ["wl-paste", "--no-newline", "--type", "image/png"],
62
+ ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"],
63
+ ]) {
64
+ const bytes = await CodeTuiClipboard.#bytes(command);
65
+ if (bytes?.length) return bytes;
66
+ }
67
+ return undefined;
68
+ }
69
+
70
+ // `osascript` cannot write bytes, so macOS hands the PNG over as AppleScript's hex literal `«data PNGf…»`.
71
+ static async #darwin() {
72
+ const bytes = await CodeTuiClipboard.#bytes(["osascript", "-e", CodeTuiClipboard.ask]);
73
+ return CodeTuiClipboard.fromAppleScript(bytes ? new TextDecoder().decode(bytes) : undefined);
74
+ }
75
+
76
+ static readonly ask = "the clipboard as «class PNGf»";
77
+
78
+ /** `«data PNGf…»` → the bytes; anything else → undefined. */
79
+ static fromAppleScript(out: string | undefined) {
80
+ const hex = /«data PNGf([0-9A-Fa-f]*)»/.exec(out ?? "")?.[1];
81
+ if (!hex || hex.length % 2) return undefined;
82
+ return Uint8Array.from((hex.match(/../g) ?? []).map((byte) => Number.parseInt(byte, 16)));
83
+ }
84
+
85
+ static async #bytes(command: string[]) {
86
+ try {
87
+ const proc = Bun.spawn(command, { stdout: "pipe", stderr: "ignore" });
88
+ const bytes = new Uint8Array(await new Response(proc.stdout).arrayBuffer());
89
+ return (await proc.exited) === 0 ? bytes : undefined;
90
+ } catch {
91
+ return undefined;
92
+ }
93
+ }
94
+ }