@akanjs/code 0.0.0 → 3.3.0-rc.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.ko.md +31 -0
  2. package/README.md +26 -4
  3. package/agent/AkanCodeCompaction.ts +49 -0
  4. package/agent/AkanCodeServices.ts +122 -0
  5. package/agent/AkanContextFiles.ts +94 -0
  6. package/agent/CodeAgent.ts +598 -0
  7. package/agent/CodeAgentAllowed.ts +35 -0
  8. package/agent/CodeAgentAsks.ts +66 -0
  9. package/agent/CodeAgentCommandLine.ts +372 -0
  10. package/agent/CodeAgentEventMapper.ts +225 -0
  11. package/agent/CodeAgentFrames.ts +57 -0
  12. package/agent/CodeAgentGate.ts +258 -0
  13. package/agent/CodeAgentProxy.ts +83 -0
  14. package/agent/CodeAgentRpcHost.ts +109 -0
  15. package/agent/CodeAgentRpcListener.ts +195 -0
  16. package/agent/CodeAgentStreamPrinter.ts +86 -0
  17. package/agent/CodeAgentSuspended.ts +85 -0
  18. package/agent/CodeAgentUi.ts +47 -0
  19. package/agent/CodeMailbox.ts +148 -0
  20. package/agent/CodeSessionFork.ts +56 -0
  21. package/agent/CodeSessionIndex.ts +78 -0
  22. package/agent/SubagentPool.ts +222 -0
  23. package/agent/WorkspaceTrust.ts +200 -0
  24. package/agent/akanCodeCompaction.test.ts +36 -0
  25. package/agent/akanCodeModel.ts +47 -0
  26. package/agent/akanCodeServices.test.ts +54 -0
  27. package/agent/akanContextFiles.test.ts +116 -0
  28. package/agent/akanSystemPrompt.ts +50 -0
  29. package/agent/codeAgent.test.ts +337 -0
  30. package/agent/codeAgentCommandLine.test.ts +212 -0
  31. package/agent/codeAgentContract.test.ts +757 -0
  32. package/agent/codeAgentHosts.ts +30 -0
  33. package/agent/codeAgentProxy.test.ts +125 -0
  34. package/agent/codeAgentRpcListener.test.ts +215 -0
  35. package/agent/codeAgentSuspended.test.ts +47 -0
  36. package/agent/codeMailbox.test.ts +76 -0
  37. package/agent/codeSessionFork.test.ts +58 -0
  38. package/agent/codeSessionIndex.test.ts +77 -0
  39. package/agent/consoleToStderr.ts +8 -0
  40. package/agent/jsonLines.ts +29 -0
  41. package/agent/stringArg.ts +5 -0
  42. package/bunfig.toml +2 -0
  43. package/feedback/DevLogFeedback.ts +82 -0
  44. package/feedback/PreviewFeedback.ts +46 -0
  45. package/feedback/TurnFeedback.ts +98 -0
  46. package/feedback/VerifyFeedback.ts +39 -0
  47. package/host/AkanCodeRunner.ts +297 -0
  48. package/host/CodeTrustPrompt.ts +57 -0
  49. package/host/codeRunnerPrompt.test.ts +181 -0
  50. package/host/hostGraph.test.ts +33 -0
  51. package/host/index.ts +2 -0
  52. package/index.ts +49 -0
  53. package/package.json +43 -9
  54. package/piDependencyPins.test.ts +45 -0
  55. package/test/preload.ts +3 -0
  56. package/tools/AkanCli.ts +56 -0
  57. package/tools/AkanCodePlugins.ts +145 -0
  58. package/tools/AkanEditScope.ts +53 -0
  59. package/tools/AkanEnvKeys.ts +50 -0
  60. package/tools/AkanToolPack.ts +87 -0
  61. package/tools/AkanVerifier.ts +30 -0
  62. package/tools/AskToolPack.ts +99 -0
  63. package/tools/DeepSeekWeb.ts +127 -0
  64. package/tools/MailToolPack.ts +76 -0
  65. package/tools/McpClient.ts +209 -0
  66. package/tools/McpOAuth.ts +233 -0
  67. package/tools/McpOAuthLoopback.ts +64 -0
  68. package/tools/McpServerConfig.ts +131 -0
  69. package/tools/McpSignIn.ts +158 -0
  70. package/tools/McpTokenStore.ts +128 -0
  71. package/tools/McpToolPack.ts +206 -0
  72. package/tools/SessionToolPack.ts +91 -0
  73. package/tools/WebToolPack.ts +315 -0
  74. package/tools/akanCodePlugins.test.ts +954 -0
  75. package/tools/askToolPack.test.ts +116 -0
  76. package/tools/deepSeekWeb.test.ts +113 -0
  77. package/tools/mcpOAuth.test.ts +648 -0
  78. package/tools/mcpServerConfig.test.ts +341 -0
  79. package/tsconfig.json +29 -0
  80. package/tui/CodeTui.tsx +394 -0
  81. package/tui/CodeTuiAgents.ts +65 -0
  82. package/tui/CodeTuiApp.test.tsx +251 -0
  83. package/tui/CodeTuiApp.tsx +312 -0
  84. package/tui/CodeTuiAutoCompact.ts +33 -0
  85. package/tui/CodeTuiClipboard.ts +94 -0
  86. package/tui/CodeTuiCommandRunner.ts +242 -0
  87. package/tui/CodeTuiCommands.ts +59 -0
  88. package/tui/CodeTuiEditor.ts +168 -0
  89. package/tui/CodeTuiFiles.ts +45 -0
  90. package/tui/CodeTuiFrame.ts +133 -0
  91. package/tui/CodeTuiLines.ts +117 -0
  92. package/tui/CodeTuiMarkdown.ts +159 -0
  93. package/tui/CodeTuiMcp.ts +111 -0
  94. package/tui/CodeTuiModels.ts +82 -0
  95. package/tui/CodeTuiMouse.ts +39 -0
  96. package/tui/CodeTuiOverlay.ts +148 -0
  97. package/tui/CodeTuiParts.ts +168 -0
  98. package/tui/CodeTuiPrompt.ts +271 -0
  99. package/tui/CodeTuiQuestion.ts +170 -0
  100. package/tui/codeTranscript.test.ts +445 -0
  101. package/tui/codeTui.test.tsx +1104 -0
  102. package/tui/codeTuiAgents.test.ts +61 -0
  103. package/tui/codeTuiClipboard.test.ts +16 -0
  104. package/tui/codeTuiCommands.test.ts +38 -0
  105. package/tui/codeTuiEditor.test.ts +122 -0
  106. package/tui/codeTuiFiles.test.ts +43 -0
  107. package/tui/codeTuiMarkdown.test.ts +91 -0
  108. package/tui/codeTuiMcp.test.ts +160 -0
  109. package/tui/codeTuiMouse.test.ts +61 -0
@@ -0,0 +1,315 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import { isIP } from "node:net";
3
+ import type { ExtensionAPI, InlineExtension } from "@earendil-works/pi-coding-agent";
4
+ import { type CodeAgentProfile, codeAgentClip } from "akanjs/common";
5
+ import { Type } from "typebox";
6
+ import { codeAgentHostListed, codeAgentHostOf, codeAgentIsLoopback } from "../agent/codeAgentHosts";
7
+ import { DeepSeekWeb } from "./DeepSeekWeb";
8
+
9
+ export interface WebToolPackOptions {
10
+ profile: CodeAgentProfile;
11
+ /** Serves search after any key-named provider, and reads public pages to Markdown ahead of a direct fetch. */
12
+ deepseek?: DeepSeekWeb | undefined;
13
+ lookup?: ((host: string) => Promise<string[]>) | undefined;
14
+ }
15
+
16
+ interface SearchProvider {
17
+ name: string;
18
+ envKey: string;
19
+ search(key: string, query: string, count: number): Promise<string>;
20
+ }
21
+
22
+ interface WebSearcher {
23
+ name: string;
24
+ search(query: string, count: number, signal?: AbortSignal): Promise<string>;
25
+ }
26
+
27
+ interface WebPage {
28
+ status: number;
29
+ ok: boolean;
30
+ title: string;
31
+ text: string;
32
+ }
33
+
34
+ // web_search only with a provider key set: a tool that can never work costs prompt tokens and invites retries.
35
+ export class WebToolPack {
36
+ static readonly pageChars = 10_000;
37
+ static readonly maxResults = 10;
38
+ static readonly maxRedirects = 5;
39
+ static readonly #rememberedPages = 16;
40
+ readonly #options: WebToolPackOptions;
41
+ // A continuation reads the snapshot its first page came from; a fresh read always refetches, since a local dev
42
+ // page changes between edits.
43
+ readonly #pages = new Map<string, WebPage>();
44
+
45
+ constructor(options: WebToolPackOptions) {
46
+ this.#options = options;
47
+ }
48
+
49
+ static providers: SearchProvider[] = [
50
+ {
51
+ name: "brave",
52
+ envKey: "BRAVE_API_KEY",
53
+ search: async (key, query, count) => {
54
+ const url = `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=${count}`;
55
+ const response = await fetch(url, { headers: { "x-subscription-token": key, accept: "application/json" } });
56
+ const body = (await response.json()) as {
57
+ web?: { results?: { title: string; url: string; description: string }[] };
58
+ };
59
+ return (body.web?.results ?? []).map((r) => `- ${r.title}\n ${r.url}\n ${r.description}`).join("\n");
60
+ },
61
+ },
62
+ {
63
+ name: "tavily",
64
+ envKey: "TAVILY_API_KEY",
65
+ search: async (key, query, count) => {
66
+ const response = await fetch("https://api.tavily.com/search", {
67
+ method: "POST",
68
+ headers: { "content-type": "application/json" },
69
+ body: JSON.stringify({ api_key: key, query, max_results: count }),
70
+ });
71
+ const body = (await response.json()) as { results?: { title: string; url: string; content: string }[] };
72
+ return (body.results ?? []).map((r) => `- ${r.title}\n ${r.url}\n ${r.content}`).join("\n");
73
+ },
74
+ },
75
+ ];
76
+
77
+ /** Names the session allowlist must carry. Empty when the profile, or the environment, offers nothing. */
78
+ names() {
79
+ const names: string[] = [];
80
+ if (this.#options.profile.tools.web.fetch) names.push("web_fetch");
81
+ if (this.#options.profile.tools.web.search && this.#searcher()) names.push("web_search");
82
+ return names;
83
+ }
84
+
85
+ extension(): InlineExtension | undefined {
86
+ if (!this.names().length) return undefined;
87
+ return { name: "akan-web", factory: (pi: ExtensionAPI) => this.#register(pi) };
88
+ }
89
+
90
+ #register(pi: ExtensionAPI) {
91
+ if (this.#options.profile.tools.web.fetch) this.#registerFetch(pi);
92
+ const searcher = this.#searcher();
93
+ if (this.#options.profile.tools.web.search && searcher) this.#registerSearch(pi, searcher);
94
+ }
95
+
96
+ #registerFetch(pi: ExtensionAPI) {
97
+ const allowHosts = this.#options.profile.network.allowHosts;
98
+ pi.registerTool({
99
+ name: "web_fetch",
100
+ label: "Fetch",
101
+ description: `Fetch a URL and return its readable text, ${WebToolPack.pageChars} characters at a time. A longer page ends with the offset that continues it.`,
102
+ promptSnippet: "web_fetch: fetch a URL and return its readable text",
103
+ parameters: Type.Object({
104
+ url: Type.String({ description: "Absolute http(s) URL." }),
105
+ offset: Type.Optional(Type.Number({ description: "Character offset a previous call named, to read on." })),
106
+ }),
107
+ execute: async (_id, params, signal) => {
108
+ const refusal = WebToolPack.#refuseHost(params.url, allowHosts);
109
+ if (refusal) return { content: [{ type: "text", text: refusal }], details: undefined, isError: true };
110
+ const offset = Math.max(0, Math.floor(params.offset ?? 0));
111
+ const cached = offset ? this.#pages.get(params.url) : undefined;
112
+ const page = cached ?? (await this.#read(params.url, signal));
113
+ if (page.ok) this.#remember(params.url, page);
114
+ return {
115
+ content: [{ type: "text", text: WebToolPack.#window(params.url, page, offset) }],
116
+ details: undefined,
117
+ isError: !page.ok,
118
+ };
119
+ },
120
+ });
121
+ }
122
+
123
+ #registerSearch(pi: ExtensionAPI, searcher: WebSearcher) {
124
+ const hint =
125
+ searcher.name === "deepseek"
126
+ ? ` Keep the query within ${DeepSeekWeb.maxQueryChars} characters; site:, -site: and quoted phrases work.`
127
+ : "";
128
+ pi.registerTool({
129
+ name: "web_search",
130
+ label: "Search",
131
+ description: `Search the web (${searcher.name}) and return the top results as title, url and summary.${hint}`,
132
+ promptSnippet: "web_search: search the web and return titles, urls and snippets",
133
+ parameters: Type.Object({
134
+ query: Type.String(),
135
+ count: Type.Optional(
136
+ Type.Number({ description: `How many results, default 5, at most ${WebToolPack.maxResults}.` }),
137
+ ),
138
+ }),
139
+ execute: async (_id, params, signal) => {
140
+ const count = Math.min(Math.max(Math.round(params.count ?? 5), 1), WebToolPack.maxResults);
141
+ try {
142
+ const results = await searcher.search(params.query, count, signal);
143
+ return {
144
+ content: [{ type: "text", text: codeAgentClip(results || "(no results)", WebToolPack.pageChars) }],
145
+ details: undefined,
146
+ };
147
+ } catch (error: unknown) {
148
+ const message = error instanceof Error ? error.message : String(error);
149
+ return { content: [{ type: "text", text: message }], details: undefined, isError: true };
150
+ }
151
+ },
152
+ });
153
+ }
154
+
155
+ #searcher(): WebSearcher | undefined {
156
+ const provider = WebToolPack.providers.find((entry) => !!process.env[entry.envKey]);
157
+ if (provider)
158
+ return {
159
+ name: provider.name,
160
+ search: (query, count) => provider.search(process.env[provider.envKey] ?? "", query, count),
161
+ };
162
+ const deepseek = this.#options.deepseek;
163
+ return deepseek
164
+ ? { name: "deepseek", search: (query, count, signal) => deepseek.search(query, count, signal) }
165
+ : undefined;
166
+ }
167
+
168
+ async #read(url: string, signal?: AbortSignal): Promise<WebPage> {
169
+ const within = this.#boundOf(new URL(url).hostname);
170
+ const deepseek = this.#options.deepseek;
171
+ // DeepSeek follows a redirect on its own servers, where no host list reaches it.
172
+ if (deepseek && !within && !(await this.#isLocal(new URL(url).hostname))) {
173
+ try {
174
+ const page = await deepseek.fetch(url, signal);
175
+ return { status: 200, ok: true, title: page.title, text: page.content };
176
+ } catch (error: unknown) {
177
+ if (signal?.aborted) throw error;
178
+ }
179
+ }
180
+ const timeout = signal ? AbortSignal.any([signal, AbortSignal.timeout(20_000)]) : AbortSignal.timeout(20_000);
181
+ if (!within) {
182
+ const response = await fetch(url, { signal: timeout, redirect: "follow" });
183
+ return {
184
+ status: response.status,
185
+ ok: response.ok,
186
+ title: "",
187
+ text: WebToolPack.#readable(await response.text()),
188
+ };
189
+ }
190
+ return await WebToolPack.#readWithin(url, within, timeout);
191
+ }
192
+
193
+ #boundOf(hostname: string): ((host: string) => boolean) | undefined {
194
+ const { allowHosts, askOutside } = this.#options.profile.network;
195
+ if (allowHosts?.length) return (host) => allowHosts.includes(host);
196
+ const quiet = (host: string) => codeAgentIsLoopback(host) || codeAgentHostListed(host, askOutside ?? []);
197
+ return askOutside && quiet(hostname) ? quiet : undefined;
198
+ }
199
+
200
+ static async #readWithin(url: string, within: (host: string) => boolean, signal: AbortSignal): Promise<WebPage> {
201
+ let current = url;
202
+ for (let hop = 0; hop <= WebToolPack.maxRedirects; hop += 1) {
203
+ const response = await fetch(current, { signal, redirect: "manual" });
204
+ const location = response.headers.get("location");
205
+ if (response.status < 300 || response.status >= 400 || !location)
206
+ return {
207
+ status: response.status,
208
+ ok: response.ok,
209
+ title: "",
210
+ text: WebToolPack.#readable(await response.text()),
211
+ };
212
+ await response.body?.cancel();
213
+ const next = new URL(location, current).href;
214
+ const host = codeAgentHostOf(next);
215
+ if (!host || !within(host))
216
+ return {
217
+ status: response.status,
218
+ ok: false,
219
+ title: "",
220
+ text: `Redirected to ${next}, which this profile does not reach without asking. web_fetch that URL to follow it.`,
221
+ };
222
+ current = next;
223
+ }
224
+ return { status: 310, ok: false, title: "", text: `More than ${WebToolPack.maxRedirects} redirects.` };
225
+ }
226
+
227
+ #remember(url: string, page: WebPage) {
228
+ this.#pages.delete(url);
229
+ this.#pages.set(url, page);
230
+ const oldest = this.#pages.keys().next().value;
231
+ if (this.#pages.size > WebToolPack.#rememberedPages && oldest) this.#pages.delete(oldest);
232
+ }
233
+
234
+ static #window(url: string, page: WebPage, offset: number) {
235
+ const head = [`${page.status} ${url}`, page.title].filter(Boolean).join("\n");
236
+ const total = page.text.length;
237
+ if (offset && offset >= total)
238
+ return `${head}\n\nOffset ${offset} is past the end; the page has ${total} characters.`;
239
+ const end = Math.min(offset + WebToolPack.pageChars, total);
240
+ const rest = end < total ? `\n\n[characters ${offset}–${end} of ${total}; offset ${end} reads on]` : "";
241
+ return `${head}\n\n${page.text.slice(offset, end)}${rest}`;
242
+ }
243
+
244
+ // DeepSeek's servers cannot reach these, and an intranet name has no business leaving the machine.
245
+ async #isLocal(hostname: string) {
246
+ const host = hostname.replace(/^\[|\]$|\.$/g, "").toLowerCase();
247
+ if (isIP(host)) return WebToolPack.#isLocalAddress(host);
248
+ if (!host.includes(".") || /\.(localhost|local|internal|lan|home\.arpa)$/.test(host)) return true;
249
+ try {
250
+ const addresses = await (this.#options.lookup ?? WebToolPack.#lookup)(host);
251
+ return !addresses.length || addresses.some((address) => WebToolPack.#isLocalAddress(address));
252
+ } catch {
253
+ // Fails closed: an intranet name this machine cannot resolve right now is still an intranet name.
254
+ return true;
255
+ }
256
+ }
257
+
258
+ static async #lookup(host: string) {
259
+ return (await lookup(host, { all: true })).map((entry) => entry.address);
260
+ }
261
+
262
+ static #isLocalAddress(literal: string) {
263
+ const address = WebToolPack.#unmapped(literal);
264
+ if (isIP(address) === 6) return address === "::" || address === "::1" || /^(f[cd]|fe[89ab])/.test(address);
265
+ const [a = 0, b = 0] = address.split(".").map(Number);
266
+ return (
267
+ a === 0 ||
268
+ a === 10 ||
269
+ a === 127 ||
270
+ (a === 100 && b >= 64 && b <= 127) ||
271
+ (a === 169 && b === 254) ||
272
+ (a === 172 && b >= 16 && b <= 31) ||
273
+ (a === 192 && b === 168)
274
+ );
275
+ }
276
+
277
+ // The URL parser writes `[::ffff:127.0.0.1]` as `::ffff:7f00:1`; a resolver hands a mapped address back dotted.
278
+ static #unmapped(address: string) {
279
+ const mapped = /^::ffff:(?:(\d+\.\d+\.\d+\.\d+)|([0-9a-f]{1,4}):([0-9a-f]{1,4}))$/i.exec(address);
280
+ if (!mapped) return address;
281
+ if (mapped[1]) return mapped[1];
282
+ const high = Number.parseInt(mapped[2] ?? "0", 16);
283
+ const low = Number.parseInt(mapped[3] ?? "0", 16);
284
+ return [high >> 8, high & 255, low >> 8, low & 255].join(".");
285
+ }
286
+
287
+ static #refuseHost(url: string, allowHosts: string[] | undefined) {
288
+ let parsed: URL;
289
+ try {
290
+ parsed = new URL(url);
291
+ } catch {
292
+ return `"${url}" is not an absolute URL.`;
293
+ }
294
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return "Only http and https URLs can be fetched.";
295
+ if (allowHosts?.length && !allowHosts.includes(parsed.hostname))
296
+ return `This profile only allows ${allowHosts.join(", ")}.`;
297
+ return undefined;
298
+ }
299
+
300
+ /** Enough to read a documentation page; a full HTML parser is not worth a dependency for that. */
301
+ static #readable(html: string) {
302
+ return html
303
+ .replace(/<script[\s\S]*?<\/script[^<>]*>/gi, " ")
304
+ .replace(/<style[\s\S]*?<\/style[^<>]*>/gi, " ")
305
+ .replace(/<[^<>]+>/g, " ")
306
+ .replace(/&nbsp;/g, " ")
307
+ .replace(/&lt;/g, "<")
308
+ .replace(/&gt;/g, ">")
309
+ .replace(/&quot;/g, '"')
310
+ .replace(/&amp;/g, "&")
311
+ .replace(/[ \t]+/g, " ")
312
+ .replace(/\n{3,}/g, "\n\n")
313
+ .trim();
314
+ }
315
+ }