@akanjs/code 0.0.0-stage → 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 +30 -2
  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 +50 -4
  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,258 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { akanCodePaths } from "@akanjs/devkit/codeAgent";
6
+ import type { CodeAgentProfile } from "akanjs/common";
7
+ import { CodeAgentAllowed } from "./CodeAgentAllowed";
8
+ import { CodeAgentCommandLine } from "./CodeAgentCommandLine";
9
+ import { codeAgentHostListed, codeAgentHostOf, codeAgentIsLoopback } from "./codeAgentHosts";
10
+ import { stringArg } from "./stringArg";
11
+
12
+ const writeTools = new Set(["write", "edit"]);
13
+ const commandTools = new Set(["bash"]);
14
+ // A client in command position (after a separator, `sh -c '`, `-exec`), past `VAR=value` and wrappers like `timeout 5`.
15
+ // Gaps are spaces and tabs only: a newline is itself a separator, and letting `\s` take it too backtracks polynomially.
16
+ const networkClients = new RegExp(
17
+ String.raw`(?:^[ \t]*|[\n;&|(\`{][ \t]*|\s-\w*c\s+['"][ \t]*|\s-exec(?:dir)?\s+)(?:(?:[A-Za-z_]\w*=\S*|${CodeAgentCommandLine.wrappers.join("|")}|-\S+|\d\S*)[ \t]+)*(?:[^\s;&|()\`'"]*\/)?(${CodeAgentCommandLine.networkClients.join("|")})(?=$|[\s;&|)\`'"])`,
18
+ "g",
19
+ );
20
+ const urlPattern = /\b[a-z][a-z0-9+.-]*:\/\/[^\s'"`<>|;&()]+/gi;
21
+ // curl and wget read a `host:port` argument without a scheme as http.
22
+ const hostPortPattern = /(?<=^|[\s'"=])(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+):\d{1,5}(?=[/?#\s'"]|$)/gi;
23
+ // A glob in a command that also matches these names is a broad sweep (`*.ts`), not an aim at one secret file.
24
+ const ordinaryNames = ["index.ts", "a.ts", "a.tsx", "a.js", "a.json", "a.yaml", "a.md", "a.txt", "a.log", "README"];
25
+
26
+ export interface GateVerdict {
27
+ /** `undefined` means the call may run without asking. */
28
+ block?: string;
29
+ approval?: string;
30
+ /** Refused, not run, when nobody can be asked: the call would leave the machine. */
31
+ strict?: boolean;
32
+ /** The command names an "allow for this session" answer stops asking about; absent when that answer is not offered. */
33
+ remember?: string[];
34
+ }
35
+
36
+ interface NameRule {
37
+ glob: Bun.Glob;
38
+ samples: string[];
39
+ }
40
+
41
+ // Gated here, not in the engine's file-ops port: a throw there reads to the model as a tool bug, and it retries.
42
+ export class CodeAgentGate {
43
+ readonly allowed = new CodeAgentAllowed();
44
+ readonly #profile: CodeAgentProfile;
45
+ readonly #realRoot: string;
46
+ readonly #deny: Bun.Glob[];
47
+ readonly #allow: Bun.Glob[];
48
+ readonly #deniedFragments: string[];
49
+ readonly #nameRules: NameRule[];
50
+
51
+ constructor(profile: CodeAgentProfile) {
52
+ this.#profile = profile;
53
+ this.#realRoot = CodeAgentGate.#real(path.resolve(profile.paths.root));
54
+ const home = homedir();
55
+ const codeHome = path.resolve(akanCodePaths.globalDir());
56
+ const patterns = [
57
+ ...(profile.paths.deny ?? []).map((pattern) =>
58
+ pattern.startsWith("~/") ? path.join(home, pattern.slice(2)) : pattern,
59
+ ),
60
+ ...(profile.paths.deny?.length ? [`${codeHome}/**`] : []),
61
+ ];
62
+ this.#deny = patterns.map((pattern) => new Bun.Glob(pattern));
63
+ this.#allow = (profile.paths.allow ?? []).map((pattern) => new Bun.Glob(pattern));
64
+ this.#deniedFragments = [
65
+ ...new Set(
66
+ (profile.paths.deny ?? [])
67
+ .flatMap(CodeAgentGate.#expandBraces)
68
+ .flatMap((pattern) => CodeAgentGate.#fragmentsOf(pattern, home)),
69
+ ),
70
+ ].filter(Boolean);
71
+ this.#nameRules = (profile.paths.deny ?? []).flatMap((pattern) => {
72
+ const name = /^\*\*\/([^/]+)$/.exec(pattern)?.[1];
73
+ if (!name || name === "**") return [];
74
+ const samples = CodeAgentGate.#expandBraces(name).map((entry) => entry.replace(/[*?]/g, "x"));
75
+ return [{ glob: new Bun.Glob(name), samples }];
76
+ });
77
+ }
78
+
79
+ verdict(toolName: string, args: unknown): GateVerdict {
80
+ const target = stringArg(args, "path");
81
+ if (target) {
82
+ const denied = this.#deniedReason(target);
83
+ if (denied) return { block: denied };
84
+ }
85
+ const command = stringArg(args, "command");
86
+ if (command) {
87
+ const denied = this.#deniedCommandReason(command);
88
+ if (denied) return { block: denied };
89
+ }
90
+ const network = this.#networkApproval(toolName, args);
91
+ if (network) return { approval: network, strict: true };
92
+ if (!this.#needsApproval(toolName)) return {};
93
+ const names = command && commandTools.has(toolName) ? CodeAgentGate.#allowable(command) : undefined;
94
+ const remember = names && this.allowed.missing(names);
95
+ if (remember && !remember.length) return {};
96
+ return { approval: CodeAgentGate.#summarize(toolName, args), ...(remember ? { remember } : {}) };
97
+ }
98
+
99
+ // The network pattern is asked as well as the reader: either one naming a client keeps the line asked about.
100
+ static #allowable(command: string) {
101
+ return CodeAgentGate.#networkClientsIn(command).length ? undefined : CodeAgentCommandLine.allowable(command);
102
+ }
103
+
104
+ static #networkClientsIn(command: string) {
105
+ return [...command.matchAll(networkClients)].map((match) => match[1]);
106
+ }
107
+
108
+ // A speed bump, not a boundary: a shell reaches any path; the real boundary is the `pod` profile's container.
109
+ // It stops the obvious accident (`cat .env`) from persisting a live key into the transcript.
110
+ #deniedCommandReason(command: string) {
111
+ const hit =
112
+ this.#deniedFragments.find((fragment) => command.includes(fragment)) ??
113
+ CodeAgentGate.#wordsOf(command).find((word) => this.#namesDeniedFile(word));
114
+ if (!hit) return undefined;
115
+ return `The command names "${hit}", which the profile's deny list covers. Ask the user for the value instead of reading the file.`;
116
+ }
117
+
118
+ #namesDeniedFile(word: string) {
119
+ const expanded = CodeAgentGate.#expandHome(word);
120
+ const name = path.basename(expanded);
121
+ if (/[*?[{]/.test(name)) {
122
+ const swept = new Bun.Glob(name);
123
+ if (ordinaryNames.some((ordinary) => swept.match(ordinary))) return false;
124
+ return this.#nameRules.some((rule) => rule.samples.some((sample) => swept.match(sample)));
125
+ }
126
+ const absolute = path.resolve(this.#profile.paths.root, expanded);
127
+ return this.#deny.some((glob) => glob.match(expanded) || glob.match(absolute));
128
+ }
129
+
130
+ #deniedReason(target: string) {
131
+ const absolute = path.resolve(this.#profile.paths.root, CodeAgentGate.#expandPath(target));
132
+ const relative = path.relative(path.resolve(this.#profile.paths.root), absolute);
133
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
134
+ return `Path is outside the agent root (${this.#profile.paths.root}).`;
135
+ // The deny list also judges the real path, so a link inside the root cannot lend a denied file an innocent name;
136
+ // the root is judged as written, since a linked package or lib leads out of it on purpose.
137
+ const real = CodeAgentGate.#real(absolute);
138
+ const candidates = [
139
+ [absolute, relative],
140
+ [real, path.relative(this.#realRoot, real)],
141
+ ];
142
+ if (candidates.some(([candidate, rel]) => this.#deny.some((glob) => glob.match(candidate) || glob.match(rel))))
143
+ return "Path is on the profile's deny list (secrets and environment files are never readable).";
144
+ if (this.#allow.length && !this.#allow.some((glob) => glob.match(absolute) || glob.match(relative)))
145
+ return "Path is outside the profile's allow list.";
146
+ return undefined;
147
+ }
148
+
149
+ #networkApproval(toolName: string, args: unknown) {
150
+ const quiet = this.#profile.network.askOutside;
151
+ if (!quiet) return undefined;
152
+ if (toolName === "web_fetch") {
153
+ const url = stringArg(args, "url");
154
+ const host = url ? codeAgentHostOf(url) : undefined;
155
+ if (!host || codeAgentIsLoopback(host) || codeAgentHostListed(host, quiet)) return undefined;
156
+ return `fetch ${url}`;
157
+ }
158
+ const command = stringArg(args, "command");
159
+ if (!command || !commandTools.has(toolName)) return undefined;
160
+ const clients = CodeAgentGate.#networkClientsIn(command);
161
+ if (!clients.length) return undefined;
162
+ // Only loopback is exempt here: a listed host still takes an upload under someone else's account.
163
+ const hosts = [
164
+ ...[...command.matchAll(urlPattern)].map((match) => codeAgentHostOf(match[0])),
165
+ ...[...command.matchAll(hostPortPattern)].map((match) => codeAgentHostOf(`http://${match[0]}`)),
166
+ ];
167
+ const httpOnly = clients.every((client) => client === "curl" || client === "wget");
168
+ if (httpOnly && hosts.length && hosts.every((host) => host && codeAgentIsLoopback(host))) return undefined;
169
+ return `reach the network: ${command.slice(0, 200)}`;
170
+ }
171
+
172
+ #needsApproval(toolName: string) {
173
+ switch (this.#profile.approval) {
174
+ case "never":
175
+ return false;
176
+ case "writes":
177
+ return writeTools.has(toolName);
178
+ case "commands":
179
+ return commandTools.has(toolName);
180
+ case "all":
181
+ return true;
182
+ default:
183
+ return false;
184
+ }
185
+ }
186
+
187
+ // The engine's own path reading: `@` is stripped, `~` and `file://` expand, odd spaces become plain ones.
188
+ static #expandPath(target: string) {
189
+ const value = target.replace(/[  -    ]/g, " ").replace(/^@/, "");
190
+ if (/^file:\/\//.test(value)) {
191
+ try {
192
+ return fileURLToPath(value);
193
+ } catch {
194
+ return value;
195
+ }
196
+ }
197
+ return CodeAgentGate.#expandHome(value);
198
+ }
199
+
200
+ static #expandHome(value: string) {
201
+ const home = /^(?:~|\$HOME|\$\{HOME\})(?=\/|$)/.exec(value);
202
+ return home ? path.join(homedir(), value.slice(home[0].length)) : value;
203
+ }
204
+
205
+ static #real(absolute: string) {
206
+ const rest: string[] = [];
207
+ let head = absolute;
208
+ for (;;) {
209
+ try {
210
+ return path.join(realpathSync(head), ...rest);
211
+ } catch {
212
+ const parent = path.dirname(head);
213
+ if (parent === head) return absolute;
214
+ rest.unshift(path.basename(head));
215
+ head = parent;
216
+ }
217
+ }
218
+ }
219
+
220
+ static #wordsOf(command: string) {
221
+ return command.split(/[\s;&|<>()`'"=,@]+/).filter(Boolean);
222
+ }
223
+
224
+ static #expandBraces(pattern: string): string[] {
225
+ const open = pattern.indexOf("{");
226
+ const close = open >= 0 ? pattern.indexOf("}", open) : -1;
227
+ if (close < 0) return [pattern];
228
+ const head = pattern.slice(0, open);
229
+ const tail = pattern.slice(close + 1);
230
+ return pattern
231
+ .slice(open + 1, close)
232
+ .split(",")
233
+ .flatMap((choice) => CodeAgentGate.#expandBraces(`${head}${choice}${tail}`));
234
+ }
235
+
236
+ // A glob cannot match a shell line, so a deny pattern is reduced to a literal; a mid-pattern wildcard is dropped.
237
+ static #fragmentsOf(pattern: string, home: string) {
238
+ if (pattern.startsWith("~/")) {
239
+ const rest = pattern.slice(2).replace(/\/\*\*$/, "");
240
+ return rest.includes("*")
241
+ ? []
242
+ : ["~/", "$HOME/", "$" + "{HOME}/", `${home}/`].map((prefix) => `${prefix}${rest}`);
243
+ }
244
+ const trimmed = pattern
245
+ .replace(/^\*\*\//, "")
246
+ .replace(/\/\*\*$/, "/")
247
+ .replace(/^\*+/, "")
248
+ .replace(/\*+$/, "");
249
+ return trimmed.includes("*") ? [] : [trimmed];
250
+ }
251
+
252
+ static #summarize(toolName: string, args: unknown) {
253
+ const record = (args ?? {}) as Record<string, unknown>;
254
+ if (toolName === "bash") return `run: ${String(record.command ?? "").slice(0, 200)}`;
255
+ const target = stringArg(args, "path");
256
+ return target ? `${toolName} ${target}` : toolName;
257
+ }
258
+ }
@@ -0,0 +1,83 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { AkanCodeEnv } from "@akanjs/devkit/codeAgent";
3
+ import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
4
+ import { type CodeAgentProfile, trimTrailingSlashes } from "akanjs/common";
5
+ import { akanCodeDefaultModel } from "./akanCodeModel";
6
+
7
+ interface PreparedRequest {
8
+ model: { provider: string; baseUrl?: string };
9
+ options: { apiKey?: string };
10
+ }
11
+
12
+ type PrepareRequest = (model: unknown, options?: Record<string, unknown>) => Promise<PreparedRequest>;
13
+
14
+ export interface CodeAgentProxyOptions {
15
+ baseUrl: string;
16
+ providers: string[];
17
+ tokenFile?: string;
18
+ token?: string;
19
+ }
20
+
21
+ /** `baseUrl` may carry `{provider}` for a proxy that fronts several providers under one host. */
22
+ export class CodeAgentProxy {
23
+ static readonly placeholderKey = "akan-code-proxy";
24
+
25
+ readonly baseUrl: string;
26
+ readonly providers: string[];
27
+ readonly #tokenFile?: string;
28
+ readonly #token?: string;
29
+
30
+ constructor({ baseUrl, providers, tokenFile, token }: CodeAgentProxyOptions) {
31
+ this.baseUrl = trimTrailingSlashes(baseUrl);
32
+ this.providers = providers;
33
+ this.#tokenFile = tokenFile;
34
+ this.#token = token;
35
+ if (!tokenFile && !token)
36
+ throw new Error("AKAN_CODE_PROXY_URL needs AKAN_CODE_PROXY_TOKEN_FILE or AKAN_CODE_PROXY_TOKEN");
37
+ }
38
+
39
+ static fromEnv(profile?: CodeAgentProfile): CodeAgentProxy | null {
40
+ const baseUrl = AkanCodeEnv.get("AKAN_CODE_PROXY_URL")?.trim() || profile?.network.proxyBaseUrl;
41
+ if (!baseUrl) return null;
42
+ const providers = (AkanCodeEnv.get("AKAN_CODE_PROXY_PROVIDERS") ?? akanCodeDefaultModel.provider)
43
+ .split(",")
44
+ .map((provider) => provider.trim())
45
+ .filter(Boolean);
46
+ return new CodeAgentProxy({
47
+ baseUrl,
48
+ providers,
49
+ tokenFile: AkanCodeEnv.get("AKAN_CODE_PROXY_TOKEN_FILE")?.trim() || undefined,
50
+ token: AkanCodeEnv.get("AKAN_CODE_PROXY_TOKEN")?.trim() || undefined,
51
+ });
52
+ }
53
+
54
+ baseUrlFor(provider: string) {
55
+ return this.baseUrl.replaceAll("{provider}", provider);
56
+ }
57
+
58
+ //* Read per request, not cached: the host rotates the token while a session is still running.
59
+ async token() {
60
+ if (!this.#tokenFile) return this.#token ?? "";
61
+ const token = (await readFile(this.#tokenFile, "utf8")).trim();
62
+ if (!token) throw new Error(`${this.#tokenFile} is empty`);
63
+ return token;
64
+ }
65
+
66
+ // `prepareRequest` is the one path every request takes. It is engine-private, so an upgrade that drops it must
67
+ // fail here at boot rather than send a request with no key.
68
+ async apply(runtime: ModelRuntime) {
69
+ const target = runtime as unknown as { prepareRequest?: PrepareRequest };
70
+ const original = target.prepareRequest?.bind(runtime);
71
+ if (!original) throw new Error("The model runtime no longer exposes prepareRequest; update CodeAgentProxy");
72
+ for (const provider of this.providers) await runtime.setRuntimeApiKey(provider, CodeAgentProxy.placeholderKey);
73
+ target.prepareRequest = async (model, options = {}) => {
74
+ const apiKey = await this.token();
75
+ const prepared = await original(model, { ...options, apiKey });
76
+ return {
77
+ ...prepared,
78
+ model: { ...prepared.model, baseUrl: this.baseUrlFor(prepared.model.provider) },
79
+ options: { ...prepared.options, apiKey },
80
+ };
81
+ };
82
+ }
83
+ }
@@ -0,0 +1,109 @@
1
+ import type { CodeAgentCommand, CodeAgentEvent, CodeAgentReply, CodeAgentRequest } from "akanjs/common";
2
+ import type { CodeAgent } from "./CodeAgent";
3
+
4
+ // stdout carries only frames because `consoleToStderr` was imported before the engine (Bun's console bypasses it).
5
+ export class CodeAgentRpcHost {
6
+ readonly #agent: CodeAgent;
7
+ #write: ((line: string) => void) | null;
8
+ #buffer = "";
9
+ #started = false;
10
+ #resolveShutdown: () => void = () => {};
11
+ readonly shutdown = new Promise<void>((resolve) => {
12
+ this.#resolveShutdown = resolve;
13
+ });
14
+
15
+ constructor(agent: CodeAgent, write: ((line: string) => void) | null = (line) => process.stdout.write(line)) {
16
+ this.#agent = agent;
17
+ this.#write = write;
18
+ }
19
+
20
+ async serve(input: AsyncIterable<Uint8Array> = process.stdin) {
21
+ this.start();
22
+ const decoder = new TextDecoder();
23
+ for await (const chunk of input) await this.feed(decoder.decode(chunk, { stream: true }));
24
+ await this.#agent.abort().catch(() => {});
25
+ }
26
+
27
+ start() {
28
+ if (this.#started) return;
29
+ this.#started = true;
30
+ this.#agent.on((event) => this.#emit(event));
31
+ this.#agent.announce();
32
+ }
33
+
34
+ //* Frames with no client attached are dropped; the next client catches up with `get_state { sinceSeq }`.
35
+ attach(write: ((line: string) => void) | null) {
36
+ this.#write = write;
37
+ this.#buffer = "";
38
+ }
39
+
40
+ async feed(text: string) {
41
+ this.#buffer += text;
42
+ let index = this.#buffer.indexOf("\n");
43
+ while (index >= 0) {
44
+ const line = this.#buffer.slice(0, index).trim();
45
+ this.#buffer = this.#buffer.slice(index + 1);
46
+ if (line) await this.#handle(line);
47
+ index = this.#buffer.indexOf("\n");
48
+ }
49
+ }
50
+
51
+ async #handle(line: string) {
52
+ let request: CodeAgentRequest;
53
+ try {
54
+ request = JSON.parse(line) as CodeAgentRequest;
55
+ } catch {
56
+ return this.#emit({ type: "error", message: "malformed command frame", fatal: false, seq: -1 });
57
+ }
58
+ // A client that always opens with its token still connects where none is asked for.
59
+ if (request && typeof request === "object" && "auth" in request && !request.command)
60
+ return this.#reply({ type: "reply", id: "auth", ok: true });
61
+ try {
62
+ this.#reply({ type: "reply", id: request.id, ok: true, data: await this.#run(request.command) });
63
+ } catch (error) {
64
+ this.#reply({ type: "reply", id: request.id, ok: false, error: String(error) });
65
+ }
66
+ //* After the reply, so a socket transport that closes on shutdown has already written the acknowledgement.
67
+ if (request.command?.type === "shutdown") this.#resolveShutdown();
68
+ }
69
+
70
+ // `prompt` replies on acceptance, not completion, so the client can still send `abort` while the turn runs.
71
+ async #run(command: CodeAgentCommand): Promise<unknown> {
72
+ switch (command.type) {
73
+ case "prompt":
74
+ void this.#agent.prompt(command.message, command.images);
75
+ return { accepted: true };
76
+ case "answer":
77
+ return { handled: await this.#agent.answer(command.questionId, command.answer) };
78
+ case "approve":
79
+ return { handled: await this.#agent.approve(command.approvalId, command.approved, command.remember) };
80
+ case "abort":
81
+ await this.#agent.abort();
82
+ return { aborted: true };
83
+ case "compact":
84
+ await this.#agent.compact(command.instructions);
85
+ return { compacted: true };
86
+ case "set_model":
87
+ await this.#agent.setModel({ provider: command.provider, id: command.modelId });
88
+ return await this.#agent.state();
89
+ case "set_auto_compact":
90
+ this.#agent.setAutoCompactAt(command.percent);
91
+ return await this.#agent.state();
92
+ case "get_state":
93
+ return await this.#agent.state(command.sinceSeq === undefined ? {} : { sinceSeq: command.sinceSeq });
94
+ case "shutdown":
95
+ this.#agent.dispose();
96
+ return { shutdown: true };
97
+ default:
98
+ throw new Error(`Unsupported command: ${command.type}`);
99
+ }
100
+ }
101
+
102
+ #emit(event: CodeAgentEvent) {
103
+ this.#write?.(`${JSON.stringify({ type: "event", event })}\n`);
104
+ }
105
+
106
+ #reply(reply: CodeAgentReply) {
107
+ this.#write?.(`${JSON.stringify(reply)}\n`);
108
+ }
109
+ }
@@ -0,0 +1,195 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { chmodSync, existsSync, rmSync } from "node:fs";
3
+ import type { Socket, SocketListener } from "bun";
4
+ import type { CodeAgentRpcHost } from "./CodeAgentRpcHost";
5
+ import { codeAgentIsLoopback } from "./codeAgentHosts";
6
+
7
+ export type CodeAgentRpcAddress = { unix: string } | { hostname: string; port: number };
8
+
9
+ export interface CodeAgentRpcListenerOptions {
10
+ token?: string | null;
11
+ }
12
+
13
+ interface ClientState {
14
+ pending: Buffer | null;
15
+ decoder: TextDecoder;
16
+ admitted: boolean;
17
+ preface: string;
18
+ timer: ReturnType<typeof setTimeout> | null;
19
+ }
20
+
21
+ // One client at a time: a reconnecting control plane replaces a socket that has not timed out yet.
22
+ // A connection is a client only once its first line authenticates: until then it cannot displace the current one.
23
+ export class CodeAgentRpcListener {
24
+ static readonly prefaceLimit = 4_096;
25
+ static readonly prefaceMs = 5_000;
26
+ readonly #host: CodeAgentRpcHost;
27
+ readonly #address: CodeAgentRpcAddress;
28
+ readonly #token: string | null;
29
+ #listener: SocketListener<ClientState> | null = null;
30
+ #client: Socket<ClientState> | null = null;
31
+
32
+ constructor(host: CodeAgentRpcHost, address: CodeAgentRpcAddress, options: CodeAgentRpcListenerOptions = {}) {
33
+ this.#host = host;
34
+ this.#address = address;
35
+ this.#token =
36
+ options.token !== undefined ? options.token : "unix" in address ? null : CodeAgentRpcListener.newToken();
37
+ }
38
+
39
+ static newToken() {
40
+ return randomBytes(32).toString("base64url");
41
+ }
42
+
43
+ static parse(spec: string, { anyHost = false }: { anyHost?: boolean } = {}): CodeAgentRpcAddress {
44
+ if (spec.startsWith("unix:")) return { unix: spec.slice("unix:".length) };
45
+ const rest = spec.startsWith("tcp:") ? spec.slice("tcp:".length) : spec;
46
+ const separator = rest.lastIndexOf(":");
47
+ const hostname = (separator >= 0 ? rest.slice(0, separator) : "") || "127.0.0.1";
48
+ const port = Number(separator >= 0 ? rest.slice(separator + 1) : rest);
49
+ if (!Number.isInteger(port) || port < 0 || port > 65_535)
50
+ throw new Error(`--rpc-listen takes unix:<path> or tcp:[host:]<port>, not "${spec}"`);
51
+ if (!anyHost && !codeAgentIsLoopback(hostname))
52
+ throw new Error(
53
+ `--rpc-listen ${spec} would be reachable from other machines. Bind 127.0.0.1, or pass --rpc-bind-any to mean it.`,
54
+ );
55
+ return { hostname, port };
56
+ }
57
+
58
+ get port(): number | null {
59
+ const port = this.#listener && "port" in this.#listener ? this.#listener.port : null;
60
+ return typeof port === "number" ? port : null;
61
+ }
62
+
63
+ get token() {
64
+ return this.#token;
65
+ }
66
+
67
+ listen() {
68
+ if ("unix" in this.#address && existsSync(this.#address.unix)) rmSync(this.#address.unix);
69
+ const socket = {
70
+ open: (client: Socket<ClientState>) => this.#open(client),
71
+ data: (client: Socket<ClientState>, data: Buffer) => this.#data(client, data),
72
+ drain: (client: Socket<ClientState>) => this.#drain(client),
73
+ close: (client: Socket<ClientState>) => this.#close(client),
74
+ error: (client: Socket<ClientState>) => this.#close(client),
75
+ };
76
+ if ("unix" in this.#address) {
77
+ // Created owner-only, so no other user can connect in the moment before the chmod.
78
+ const umask = process.umask(0o177);
79
+ try {
80
+ this.#listener = Bun.listen<ClientState>({ unix: this.#address.unix, socket });
81
+ } finally {
82
+ process.umask(umask);
83
+ }
84
+ chmodSync(this.#address.unix, 0o600);
85
+ } else
86
+ this.#listener = Bun.listen<ClientState>({ hostname: this.#address.hostname, port: this.#address.port, socket });
87
+ this.#host.start();
88
+ return this;
89
+ }
90
+
91
+ async serve() {
92
+ if (!this.#listener) this.listen();
93
+ await this.#host.shutdown;
94
+ this.stop();
95
+ }
96
+
97
+ stop() {
98
+ this.#client?.end();
99
+ this.#client = null;
100
+ this.#host.attach(null);
101
+ this.#listener?.stop(true);
102
+ this.#listener = null;
103
+ if ("unix" in this.#address && existsSync(this.#address.unix)) rmSync(this.#address.unix);
104
+ }
105
+
106
+ #open(client: Socket<ClientState>) {
107
+ client.data = { pending: null, decoder: new TextDecoder(), admitted: false, preface: "", timer: null };
108
+ client.data.timer = setTimeout(() => {
109
+ if (!client.data.admitted) client.end();
110
+ }, CodeAgentRpcListener.prefaceMs);
111
+ }
112
+
113
+ #data(client: Socket<ClientState>, data: Buffer) {
114
+ const text = client.data.decoder.decode(data, { stream: true });
115
+ if (client.data.admitted) {
116
+ if (client === this.#client) void this.#host.feed(text);
117
+ return;
118
+ }
119
+ client.data.preface += text;
120
+ const preface = client.data.preface.trimStart();
121
+ // A browser or any other protocol speaks first with something other than a JSON frame.
122
+ if (preface && !preface.startsWith("{")) {
123
+ client.end();
124
+ return;
125
+ }
126
+ if (!this.#token) {
127
+ this.#admit(client);
128
+ return void this.#host.feed(preface);
129
+ }
130
+ const newline = preface.indexOf("\n");
131
+ if (newline < 0) {
132
+ if (preface.length > CodeAgentRpcListener.prefaceLimit) client.end();
133
+ return;
134
+ }
135
+ if (!this.#authenticates(preface.slice(0, newline))) {
136
+ client.write(`${JSON.stringify({ type: "reply", id: "auth", ok: false, error: "unauthorized" })}\n`);
137
+ client.end();
138
+ return;
139
+ }
140
+ this.#admit(client);
141
+ this.#write(client, `${JSON.stringify({ type: "reply", id: "auth", ok: true })}\n`);
142
+ const rest = preface.slice(newline + 1);
143
+ if (rest) void this.#host.feed(rest);
144
+ }
145
+
146
+ #admit(client: Socket<ClientState>) {
147
+ if (client.data.timer) clearTimeout(client.data.timer);
148
+ client.data.timer = null;
149
+ client.data.admitted = true;
150
+ client.data.preface = "";
151
+ const previous = this.#client;
152
+ this.#client = client;
153
+ previous?.end();
154
+ this.#host.attach((line) => this.#write(client, line));
155
+ }
156
+
157
+ #authenticates(line: string) {
158
+ if (!this.#token) return true;
159
+ let auth: unknown;
160
+ try {
161
+ auth = (JSON.parse(line) as { auth?: unknown }).auth;
162
+ } catch {
163
+ return false;
164
+ }
165
+ if (typeof auth !== "string") return false;
166
+ const digest = (value: string) => createHash("sha256").update(value).digest();
167
+ return timingSafeEqual(digest(auth), digest(this.#token));
168
+ }
169
+
170
+ //* A socket write may take only part of a frame; the rest waits for `drain`, and frames behind it queue in order.
171
+ #write(client: Socket<ClientState>, line: string) {
172
+ if (client !== this.#client) return;
173
+ const bytes = Buffer.from(line);
174
+ if (client.data.pending) {
175
+ client.data.pending = Buffer.concat([client.data.pending, bytes]);
176
+ return;
177
+ }
178
+ const written = client.write(bytes);
179
+ if (written < bytes.length) client.data.pending = bytes.subarray(Math.max(0, written));
180
+ }
181
+
182
+ #drain(client: Socket<ClientState>) {
183
+ const pending = client.data.pending;
184
+ if (!pending) return;
185
+ const written = client.write(pending);
186
+ client.data.pending = written < pending.length ? pending.subarray(Math.max(0, written)) : null;
187
+ }
188
+
189
+ #close(client: Socket<ClientState>) {
190
+ if (client.data?.timer) clearTimeout(client.data.timer);
191
+ if (client !== this.#client) return;
192
+ this.#client = null;
193
+ this.#host.attach(null);
194
+ }
195
+ }