@akanjs/devkit 3.0.0-beta.12 → 3.0.0-beta.14

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.
package/cloud/cloudApi.ts CHANGED
@@ -2,6 +2,11 @@ import type { Workspace } from "../commandDecorators";
2
2
  import type { AccessToken, AccessTokenDto, HostConfig } from "./constants";
3
3
  import { GlobalConfig } from "./globalConfig";
4
4
 
5
+ interface HttpRequestOptions {
6
+ headers?: Record<string, string>;
7
+ signal?: AbortSignal;
8
+ }
9
+
5
10
  class HttpClient {
6
11
  readonly baseUrl: string;
7
12
  readonly headers: Record<string, string> = {};
@@ -9,15 +14,16 @@ class HttpClient {
9
14
  this.baseUrl = baseUrl;
10
15
  this.headers = headers;
11
16
  }
12
- async get<T>(url: string, { headers }: { headers?: Record<string, string> } = {}): Promise<T> {
17
+ async get<T>(url: string, { headers, signal }: HttpRequestOptions = {}): Promise<T> {
13
18
  const response = await fetch(`${this.baseUrl}${url}`, {
14
19
  headers: {
15
20
  "Content-Type": "application/json",
16
21
  ...this.headers,
17
22
  ...headers,
18
23
  },
24
+ ...(signal ? { signal } : {}),
19
25
  });
20
- return await response.json();
26
+ return await HttpClient.#body<T>(response, url);
21
27
  }
22
28
  async getFile(url: string, localPath: string, headers?: Record<string, string>): Promise<void> {
23
29
  const response = await fetch(`${this.baseUrl}${url}`, {
@@ -26,7 +32,7 @@ class HttpClient {
26
32
  if (!response.ok) throw new Error(`Failed to download file: ${response.status} ${response.statusText}`);
27
33
  await Bun.write(localPath, response);
28
34
  }
29
- async post<T>(url: string, data: unknown, { headers }: { headers?: Record<string, string> } = {}): Promise<T> {
35
+ async post<T>(url: string, data: unknown, { headers, signal }: HttpRequestOptions = {}): Promise<T> {
30
36
  const isFormData = data instanceof FormData;
31
37
  const response = await fetch(`${this.baseUrl}${url}`, {
32
38
  method: "POST",
@@ -34,8 +40,18 @@ class HttpClient {
34
40
  headers: isFormData
35
41
  ? { ...this.headers, ...headers }
36
42
  : { "Content-Type": "application/json", ...this.headers, ...headers },
43
+ ...(signal ? { signal } : {}),
37
44
  });
38
- return await response.json();
45
+ return await HttpClient.#body<T>(response, url);
46
+ }
47
+ /**
48
+ * A route that does not exist answers the error *page*, not JSON, so parsing first reports a syntax error at
49
+ * `<` and buries the status that says what is actually wrong. Read the status before the body.
50
+ */
51
+ static async #body<T>(response: Response, url: string): Promise<T> {
52
+ const text = await response.text();
53
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}: ${text.slice(0, 200)}`);
54
+ return JSON.parse(text) as T;
39
55
  }
40
56
  setHeaders(headers: Record<string, string>) {
41
57
  Object.assign(this.headers, headers);
@@ -132,16 +148,27 @@ export class CloudApi {
132
148
  this.#api.setHeaders({ Authorization: `Bearer ${this.#accessToken.jwt}` });
133
149
  return this.#accessToken;
134
150
  }
151
+ /**
152
+ * The `/tunnel` segment is the model's refName, which every database module's endpoints carry and the service
153
+ * modules above — `_cloud`, which owns `uploadEnv` and `getRemoteSelf` — do not. Dropping it to match those
154
+ * neighbours answers 404, and the control plane returns an HTML error page that fails as a JSON parse error.
155
+ */
135
156
  async requestTunnel(input: { name: string; ttlMinutes?: number }): Promise<TunnelGrant> {
136
- return await this.#api.post<TunnelGrant>(`/requestTunnel`, input);
157
+ return await this.#api.post<TunnelGrant>(`/tunnel/requestTunnel`, input);
137
158
  }
138
159
  /** The generated name of the model's own `inSelf` slice: a hand-written `listTunnels` would collide with it. */
139
160
  async tunnelListInSelf(): Promise<TunnelSummary[]> {
140
- return await this.#api.get<TunnelSummary[]>(`/tunnelListInSelf`);
141
- }
142
- /** Hands the grant back. The CLI calls this "stop", which is what the operator is doing, not what it does. */
161
+ return await this.#api.get<TunnelSummary[]>(`/tunnel/tunnelListInSelf`);
162
+ }
163
+ /**
164
+ * Hands the grant back. The CLI calls this "stop", which is what the operator is doing, not what it does.
165
+ *
166
+ * Bounded because every caller is on the way out: an unreachable control plane is exactly the state a session
167
+ * ends in, and an unbounded `fetch` there holds the event loop open long after the work is done. Losing the
168
+ * release costs nothing — the share expires on its own TTL.
169
+ */
143
170
  async revokeTunnel(code: string): Promise<boolean> {
144
- return await this.#api.post<boolean>(`/revokeTunnel`, { code });
171
+ return await this.#api.post<boolean>(`/tunnel/revokeTunnel`, { code }, { signal: AbortSignal.timeout(5_000) });
145
172
  }
146
173
  async getRemoteSelf(): Promise<{ id: string; nickname: string } | null> {
147
174
  try {
@@ -1,5 +1,4 @@
1
1
  import type { Dayjs } from "dayjs";
2
- import type { SupportedLlmModel } from "../aiEditor";
3
2
  import { GlobalConfig } from "./globalConfig";
4
3
 
5
4
  export const basePath = `${Bun.env.HOME ?? Bun.env.USERPROFILE}/.akan`;
@@ -28,12 +27,10 @@ export interface RemoteEnvServerConfig {
28
27
  export interface AkanGlobalConfig {
29
28
  cloudHost: { [key: string]: HostConfigDto };
30
29
  remoteEnvServers: Record<string, RemoteEnvServerConfig>;
31
- llm: { model: SupportedLlmModel; apiKey: string } | null;
32
30
  }
33
31
  export const defaultAkanGlobalConfig: AkanGlobalConfig = {
34
32
  cloudHost: {},
35
33
  remoteEnvServers: {},
36
- llm: null,
37
34
  };
38
35
 
39
36
  export interface AccessTokenDto {
@@ -30,7 +30,7 @@ export class GlobalConfig {
30
30
  };
31
31
  }
32
32
  /**
33
- * This file holds the cloud jwt, a refresh token that does not expire, and the LLM api key, so it is
33
+ * This file holds the cloud jwt and a refresh token that does not expire, so it is
34
34
  * written owner-only — the same `0600` the runtime gives its control socket. `Bun.write` takes no mode
35
35
  * and lands on `0666 & ~umask` (0644 on a default shell), so the mode is applied after the write; an
36
36
  * existing world-readable file is tightened by the next write rather than left as it was found.
@@ -49,14 +49,6 @@ export class GlobalConfig {
49
49
  akanConfig.cloudHost[config.host] = GlobalConfig.toHostConfigDto(config);
50
50
  await GlobalConfig.#setAkanGlobalConfig(akanConfig);
51
51
  }
52
- static async getLlmConfig(): Promise<AkanGlobalConfig["llm"]> {
53
- const akanConfig = await GlobalConfig.#getAkanGlobalConfig();
54
- return akanConfig.llm ?? null;
55
- }
56
- static async setLlmConfig(llmConfig: AkanGlobalConfig["llm"]) {
57
- const akanConfig = await GlobalConfig.#getAkanGlobalConfig();
58
- await GlobalConfig.#setAkanGlobalConfig({ ...akanConfig, llm: llmConfig });
59
- }
60
52
  static async getRemoteEnvServers(): Promise<AkanGlobalConfig["remoteEnvServers"]> {
61
53
  const akanConfig = await GlobalConfig.#getAkanGlobalConfig();
62
54
  return akanConfig.remoteEnvServers;
@@ -11,7 +11,7 @@ import { type Command, program } from "commander";
11
11
  import { AppSelectionMemory } from "../appSelectionMemory";
12
12
  import { AppExecutor, Executor, LibExecutor, ModuleExecutor, PkgExecutor, WorkspaceExecutor } from "../executors";
13
13
  // Import the owning modules directly, never the root barrel: `..` re-exports all 41 devkit modules,
14
- // so a barrel import here drags ink, @trapezedev/project, ssh2, @langchain/* and the cloud stack into
14
+ // so a barrel import here drags ink, @trapezedev/project, ssh2 and the cloud stack into
15
15
  // every process that registers a command (measured: 236MB vs 3MB).
16
16
  import { FileSys } from "../fileSys";
17
17
  import { getDirname } from "../getDirname";
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  // Module paths, never a barrel. The `@akanjs/devkit` root re-exports all 41 modules, which would drag
3
- // @trapezedev/project, the @langchain stack, ssh2, ink and the cloud stack in; and `frontendBuild`'s own
3
+ // @trapezedev/project, ssh2, ink and the cloud stack in; and `frontendBuild`'s own
4
4
  // barrel reaches `cssCompiler`/`ssrBaseArtifactBuilder`, which pull tailwindcss + @tailwindcss/node
5
5
  // (~40MB) into a process that then holds them for the whole dev session. Phase 2 moved css compilation
6
6
  // into the batch worker, so this process has no use for them — `entryModuleGraph.test.ts` keeps it that way.
package/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Types only, deliberately. This barrel re-exports all 40 devkit facets, so a single *value* import
2
2
  // from it loads every one of them — measured at 417MB / 654ms, versus 38MB / 38ms for the one subpath
3
3
  // the caller actually needed. That is how `commandDecorators/command.ts` silently put ink, typescript,
4
- // ssh2, @trapezedev/project, @langchain/* and the cloud stack into every process that registered a CLI
4
+ // ssh2, @trapezedev/project and the cloud stack into every process that registered a CLI
5
5
  // command, and it is the single largest regression this package can suffer from a one-line edit.
6
6
  //
7
7
  // `export type *` erases at runtime (verified on Bun 1.3.14: the re-exported module is never loaded),
@@ -12,7 +12,6 @@
12
12
  //
13
13
  // Import values from the owning facet instead: `import { FileSys } from "@akanjs/devkit/fileSys"`.
14
14
  // Keep this file type-only; do not "fix" a TS1362 by widening an entry back to `export *`.
15
- export type * from "./aiEditor";
16
15
  export type * from "./akanApp";
17
16
  export type * from "./akanConfig";
18
17
  export type * from "./akanContext";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.0.0-beta.12",
3
+ "version": "3.0.0-beta.14",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -39,12 +39,9 @@
39
39
  },
40
40
  "dependencies": {
41
41
  "@inquirer/prompts": "^8.4.3",
42
- "@langchain/core": "^1.1.47",
43
- "@langchain/deepseek": "^1.0.26",
44
- "@langchain/openai": "^1.4.6",
45
42
  "@tailwindcss/node": "^4.3.0",
46
43
  "@trapezedev/project": "^7.1.4",
47
- "akanjs": "3.0.0-beta.12",
44
+ "akanjs": "3.0.0-beta.14",
48
45
  "chalk": "^5.6.2",
49
46
  "commander": "^14.0.3",
50
47
  "dayjs": "^1.11.20",
@@ -1,112 +0,0 @@
1
- import { Logger } from "akanjs/common";
2
- import chalk from "chalk";
3
- import { AbstractDoc, type AbstractKind } from "./abstractDoc";
4
- import { AiSession } from "./aiEditor";
5
- import type { SysExecutor } from "./executors";
6
-
7
- export interface AbstractCompactOptions {
8
- module?: string | null;
9
- minLines?: number;
10
- interactive?: boolean;
11
- }
12
-
13
- export interface AbstractCompactReport {
14
- path: string;
15
- beforeLines: number;
16
- afterLines: number;
17
- status: "compacted" | "unchanged" | "failed";
18
- }
19
-
20
- /** Rewrites bloated `*.abstract.md` files down to the invariants their source files cannot show. */
21
- export class AbstractCompactor {
22
- static readonly #reviewRequest = `Review the compacted file you just wrote against the original.
23
- - Did you drop an invariant, a security reason, or a workflow step that the source files cannot show by themselves? Restore it.
24
- - Did you keep anything that only restates code, scaffold wording, or history? Remove it.
25
- - Is it in the same language as the original, within the line budget, and one short line per bullet?
26
- Respond with exactly one \`\`\`markdown code block holding the corrected file and nothing else. If nothing needs to change, repeat the file unchanged.`;
27
-
28
- #sys: SysExecutor;
29
- #minLines: number;
30
- #interactive: boolean;
31
- constructor(
32
- sys: SysExecutor,
33
- { minLines = AbstractDoc.compactMinLines, interactive = false }: AbstractCompactOptions = {},
34
- ) {
35
- this.#sys = sys;
36
- this.#minLines = minLines;
37
- this.#interactive = interactive;
38
- }
39
- async compactAll({ module }: { module?: string | null } = {}) {
40
- const docs = await AbstractDoc.findAll(this.#sys, { module });
41
- const targets = docs.filter((doc) => doc.lineCount > this.#minLines);
42
- const reports: AbstractCompactReport[] = [];
43
- // One file at a time: each doc gets its own AI session, and parallel runs would interleave the
44
- // streamed response with each other and with the interactive confirm prompt.
45
- for (const doc of targets) reports.push(await this.compact(doc));
46
- return { scanned: docs.length, reports };
47
- }
48
- async compact(doc: AbstractDoc): Promise<AbstractCompactReport> {
49
- const session = new AiSession("compactAbstract", {
50
- workspace: this.#sys.workspace,
51
- cacheKey: `${this.#sys.name}-${doc.moduleName}`,
52
- });
53
- const approve = !this.#interactive;
54
- const compacted = await session.editMarkdown(this.#request(doc), { approve });
55
- const reviewed = await session.editMarkdown(AbstractCompactor.#reviewRequest, { approve });
56
- // The review answers in prose when it finds nothing to fix, so the first compaction is the fallback.
57
- const next = [reviewed, compacted]
58
- .map((candidate) => candidate.trim())
59
- .find((candidate) => doc.canReplaceWith(candidate));
60
- const beforeLines = doc.lineCount;
61
- if (!next) {
62
- Logger.rawLog(chalk.yellow(`${doc.path}: the editor returned no shorter abstract, keeping the current file`));
63
- return { path: doc.path, beforeLines, afterLines: beforeLines, status: "failed" };
64
- }
65
- if (next === doc.content.trim())
66
- return { path: doc.path, beforeLines, afterLines: beforeLines, status: "unchanged" };
67
- const content = `${next}\n`;
68
- await this.#sys.writeFile(doc.path, content);
69
- return { path: doc.path, beforeLines, afterLines: AbstractDoc.lineCountOf(content), status: "compacted" };
70
- }
71
- #targetShape(kind: AbstractKind) {
72
- if (kind === "other")
73
- return " - keep the headings that still carry information and drop the rest; do not impose a new structure";
74
- return [
75
- " - `# <name> Abstract` title line",
76
- " - one declarative sentence naming what this module owns",
77
- " - `## Rules` — two to five bullets, each an invariant the code cannot show by itself",
78
- " - optional `## Workflow` — the lifecycle as an arrow chain (`draft -> signed -> active`) or a few bullets",
79
- ].join("\n");
80
- }
81
- #request(doc: AbstractDoc) {
82
- return `You are compacting an Akan.js abstract file.
83
-
84
- An abstract is the summary a coding agent reads before changing a module. Repeated edits have made this one
85
- bloated, and it has to shrink back to what the source files cannot show by themselves.
86
-
87
- # Target file
88
- ${this.#sys.type}s/${this.#sys.name}/${doc.path} (${doc.kind} module "${doc.moduleName}", ${doc.lineCount} lines)
89
-
90
- # Source files in the same folder
91
- ${doc.siblingFiles.join(", ") || "none"}
92
-
93
- # Current content
94
- \`\`\`markdown
95
- ${doc.content}
96
- \`\`\`
97
-
98
- # Rules for the compacted file
99
- - Write it in the SAME language as the current content. Never translate.
100
- - Keep every invariant, constraint, security reason, and workflow step that the source files cannot show by
101
- themselves. Merge duplicates instead of dropping either one.
102
- - Delete what the code already states: field lists, types, labels, signatures, file lists, and imports.
103
- - Delete scaffold and placeholder wording, changelog or migration history, TODOs, and any instruction about
104
- reading or updating this file.
105
- - Never invent a rule that the current content does not state.
106
- - Keep every bullet to one short line, and stay under ${AbstractDoc.compactMinLines} lines in total.
107
- - Shape:
108
- ${this.#targetShape(doc.kind)}
109
-
110
- Respond with exactly one \`\`\`markdown code block holding the whole new file and nothing else.`;
111
- }
112
- }
package/aiEditor.test.ts DELETED
@@ -1,60 +0,0 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { parseTypescriptFileBlocks, preserveTypescriptResponseContent } from "./aiEditor";
3
-
4
- describe("parseTypescriptFileBlocks", () => {
5
- test("parses TypeScript file blocks with common fence variants", () => {
6
- const writes = parseTypescriptFileBlocks(`
7
- \`\`\`ts
8
-
9
- // File: lib/car/car.constant.ts
10
-
11
- export const car = "car";
12
- \`\`\`
13
-
14
- \`\`\`tsx
15
- // File: lib/car/Car.Unit.tsx
16
- export const CarUnit = () => null;
17
- \`\`\`
18
- `);
19
-
20
- expect(writes).toEqual([
21
- {
22
- filePath: "lib/car/car.constant.ts",
23
- content: 'export const car = "car";',
24
- },
25
- {
26
- filePath: "lib/car/Car.Unit.tsx",
27
- content: "export const CarUnit = () => null;",
28
- },
29
- ]);
30
- });
31
-
32
- test("keeps previous code response when validation responds with prose only", () => {
33
- const previousContent = `
34
- \`\`\`typescript
35
- // File: lib/car/car.constant.ts
36
- export const car = "car";
37
- \`\`\`
38
- `;
39
- const nextContent = "The generated file meets all specified requirements. No rewrite is necessary.";
40
-
41
- expect(preserveTypescriptResponseContent(previousContent, nextContent)).toBe(previousContent);
42
- });
43
-
44
- test("uses next code response when validation rewrites with parseable files", () => {
45
- const previousContent = `
46
- \`\`\`typescript
47
- // File: lib/car/car.constant.ts
48
- export const car = "car";
49
- \`\`\`
50
- `;
51
- const nextContent = `
52
- \`\`\`typescript
53
- // File: lib/car/car.constant.ts
54
- export const car = "updated";
55
- \`\`\`
56
- `;
57
-
58
- expect(preserveTypescriptResponseContent(previousContent, nextContent)).toBe(nextContent);
59
- });
60
- });
package/aiEditor.ts DELETED
@@ -1,387 +0,0 @@
1
- import { input, select } from "@inquirer/prompts";
2
- import {
3
- AIMessage,
4
- type BaseMessage,
5
- HumanMessage,
6
- mapChatMessagesToStoredMessages,
7
- mapStoredMessagesToChatMessages,
8
- type StoredMessage,
9
- } from "@langchain/core/messages";
10
- import { ChatDeepSeek } from "@langchain/deepseek";
11
- import { ChatOpenAI } from "@langchain/openai";
12
- import { Logger } from "akanjs/common";
13
- import chalk from "chalk";
14
-
15
- import { GlobalConfig } from "./cloud";
16
- import type { Executor, WorkspaceExecutor } from "./executors";
17
- import { Spinner } from "./spinner";
18
- import type { FileContent } from "./types";
19
-
20
- const MAX_ASK_TRY = 300;
21
-
22
- const deepSeekLlmModels = ["deepseek-v4-flash", "deepseek-v4-pro"] as const;
23
-
24
- const openAiLlmModels = ["gpt-5.5"] as const;
25
-
26
- export const supportedLlmModels = [...deepSeekLlmModels, ...openAiLlmModels] as const;
27
- export type SupportedLlmModel = (typeof supportedLlmModels)[number];
28
- type OpenAiLlmModel = (typeof openAiLlmModels)[number];
29
-
30
- const isOpenAiLlmModel = (model: SupportedLlmModel): model is OpenAiLlmModel =>
31
- openAiLlmModels.includes(model as OpenAiLlmModel);
32
-
33
- interface EditOptions {
34
- onReasoning?: (reasoning: string) => void;
35
- onChunk?: (chunk: string) => void;
36
- maxTry?: number;
37
- validate?: string[];
38
- approve?: boolean;
39
- fallbackToPreviousTypescript?: boolean;
40
- }
41
-
42
- export const parseTypescriptFileBlocks = (text: string): FileContent[] => {
43
- const fileBlocks: FileContent[] = [];
44
- const codeBlockRegex = /```(?:typescript|ts|tsx)\s*\n([\s\S]*?)```/gi;
45
- const filePathRegex = /^\s*\/\/\s*File:\s*(.+?)\s*$/im;
46
-
47
- for (const codeBlock of text.matchAll(codeBlockRegex)) {
48
- const content = codeBlock[1]?.trim();
49
- if (!content) continue;
50
-
51
- const filePath = filePathRegex.exec(content)?.[1]?.trim();
52
- if (!filePath) continue;
53
-
54
- fileBlocks.push({
55
- filePath,
56
- content: content.replace(filePathRegex, "").trim(),
57
- });
58
- }
59
-
60
- return fileBlocks;
61
- };
62
-
63
- export const preserveTypescriptResponseContent = (previousContent: string, nextContent: string) => {
64
- const previousWrites = parseTypescriptFileBlocks(previousContent);
65
- const nextWrites = parseTypescriptFileBlocks(nextContent);
66
- if (previousWrites.length > 0 && nextWrites.length === 0) return previousContent;
67
- return nextContent;
68
- };
69
-
70
- export class AiSession {
71
- static #cacheDir = "node_modules/.cache/akan/aiSession";
72
- static #chat: ChatDeepSeek | ChatOpenAI | null = null;
73
- static async init({ temperature = 0, useExisting = true }: { temperature?: number; useExisting?: boolean } = {}) {
74
- if (useExisting) {
75
- const llmConfig = await AiSession.getLlmConfig();
76
- if (llmConfig) {
77
- AiSession.#setChatModel(llmConfig.model, llmConfig.apiKey);
78
- Logger.rawLog(chalk.dim(`🤖akan editor uses existing LLM config (${llmConfig.model})`));
79
- return AiSession;
80
- }
81
- } else Logger.rawLog(chalk.yellow("🤖akan-editor is not initialized. LLM configuration should be set first."));
82
-
83
- const llmConfig = await AiSession.#requestLlmConfig();
84
- const { model, apiKey } = llmConfig;
85
-
86
- await AiSession.#validateApiKey(model, apiKey);
87
- const session = AiSession.#setChatModel(model, apiKey, { temperature });
88
- await session.setLlmConfig({ model, apiKey });
89
- return session;
90
- }
91
- static #setChatModel(model: SupportedLlmModel, apiKey: string, { temperature = 0 }: { temperature?: number } = {}) {
92
- AiSession.#chat = AiSession.#createChatModel(model, apiKey, {
93
- temperature,
94
- streaming: true,
95
- });
96
- return AiSession;
97
- }
98
- static #createChatModel(
99
- model: SupportedLlmModel,
100
- apiKey: string,
101
- { temperature = 0, streaming = false }: { temperature?: number; streaming?: boolean } = {},
102
- ) {
103
- if (isOpenAiLlmModel(model))
104
- return new ChatOpenAI({
105
- modelName: model,
106
- temperature,
107
- streaming,
108
- openAIApiKey: apiKey,
109
- });
110
- return new ChatDeepSeek({
111
- modelName: model,
112
- temperature,
113
- streaming,
114
- apiKey,
115
- });
116
- }
117
- static async getLlmConfig() {
118
- return await GlobalConfig.getLlmConfig();
119
- }
120
- static async setLlmConfig(llmConfig: { model: SupportedLlmModel; apiKey: string } | null) {
121
- await GlobalConfig.setLlmConfig(llmConfig);
122
- return AiSession;
123
- }
124
- static async #requestLlmConfig() {
125
- const model = await select<SupportedLlmModel>({
126
- message: "Select a LLM model",
127
- choices: supportedLlmModels,
128
- });
129
- const apiKey = await input({ message: "Enter your API key" });
130
- return { model, apiKey };
131
- }
132
- static async #validateApiKey(modelName: SupportedLlmModel, apiKey: string) {
133
- const spinner = new Spinner("Validating LLM API key...", {
134
- prefix: `🤖akan-editor`,
135
- }).start();
136
- const chat = AiSession.#createChatModel(modelName, apiKey);
137
- try {
138
- await chat.invoke("Hi, and just say 'ok'");
139
- spinner.succeed("LLM API key is valid");
140
- return true;
141
- } catch (error) {
142
- spinner.fail(
143
- chalk.red(
144
- `LLM API key is invalid. Please check your API key and try again. You can set it again by running "akan set-llm" or reset by running "akan reset-llm"`,
145
- ),
146
- );
147
- throw error;
148
- }
149
- }
150
- static async clearCache(workspaceRoot: string) {
151
- const cacheDir = `${workspaceRoot}/${AiSession.#cacheDir}`;
152
- await Bun.$`rm -rf ${cacheDir}`;
153
- }
154
-
155
- messageHistory: BaseMessage[] = [];
156
- readonly sessionKey: string;
157
- isCacheLoaded: boolean = false;
158
- workspace: WorkspaceExecutor;
159
- constructor(
160
- type: string,
161
- {
162
- workspace,
163
- cacheKey,
164
- isContinued,
165
- }: {
166
- workspace: WorkspaceExecutor;
167
- cacheKey?: string;
168
- isContinued?: boolean;
169
- },
170
- ) {
171
- this.workspace = workspace;
172
- this.sessionKey = `${type}${cacheKey ? `-${cacheKey}` : ""}`;
173
- if (isContinued) this.#cacheLoadPromise = this.#loadCache();
174
- }
175
- #cacheLoadPromise: Promise<void> | null = null;
176
- async #loadCache() {
177
- const cacheFile = `${AiSession.#cacheDir}/${this.sessionKey}.json`;
178
- const isCacheExists = await this.workspace.exists(cacheFile);
179
- if (isCacheExists)
180
- this.messageHistory = mapStoredMessagesToChatMessages(
181
- (await this.workspace.readJson(cacheFile)) as StoredMessage[],
182
- );
183
- else this.messageHistory = [];
184
- this.isCacheLoaded = isCacheExists;
185
- }
186
- async #saveCache() {
187
- const cacheFilePath = `${AiSession.#cacheDir}/${this.sessionKey}.json`;
188
- await this.workspace.writeJson(cacheFilePath, mapChatMessagesToStoredMessages(this.messageHistory));
189
- }
190
- async ask(
191
- question: string,
192
- {
193
- onReasoning = (reasoning: string) => {
194
- Logger.raw(chalk.dim(reasoning));
195
- },
196
- onChunk = (chunk: string) => {
197
- Logger.raw(chunk);
198
- },
199
- }: EditOptions = {},
200
- ): Promise<{ content: string; messageHistory: BaseMessage[] }> {
201
- if (!AiSession.#chat) await AiSession.init();
202
- if (this.#cacheLoadPromise) await this.#cacheLoadPromise;
203
-
204
- if (!AiSession.#chat) throw new Error("Failed to initialize the AI session");
205
- const loader = new Spinner(`${AiSession.#chat.model} is thinking...`, {
206
- prefix: `🤖akan-editor`,
207
- }).start();
208
- try {
209
- const humanMessage = new HumanMessage(question);
210
- this.messageHistory.push(humanMessage);
211
- const stream = await AiSession.#chat.stream(this.messageHistory);
212
- let reasoningResponse = "",
213
- fullResponse = "";
214
- for await (const chunk of stream) {
215
- if (loader.isSpinning()) loader.succeed(`${AiSession.#chat.model} responded`);
216
-
217
- if (!fullResponse.length) {
218
- const reasoningContent = (chunk.additional_kwargs as { reasoning_content?: string }).reasoning_content ?? "";
219
- if (reasoningContent.length) {
220
- reasoningResponse += reasoningContent;
221
- onReasoning(reasoningContent);
222
- continue;
223
- } else if (chunk.content.length) {
224
- reasoningResponse += "\n";
225
- onReasoning(reasoningResponse);
226
- }
227
- }
228
-
229
- const content = chunk.content;
230
- if (typeof content === "string") {
231
- fullResponse += content;
232
- onChunk(content); // Send individual chunks to callback
233
- }
234
- }
235
- fullResponse += "\n";
236
- onChunk("\n");
237
- this.messageHistory.push(new AIMessage(fullResponse));
238
- return { content: fullResponse, messageHistory: this.messageHistory };
239
- } catch {
240
- loader.fail(`${AiSession.#chat.model} failed to respond`);
241
- throw new Error("Failed to stream response");
242
- }
243
- }
244
- async edit(
245
- question: string,
246
- { onChunk, onReasoning, maxTry = MAX_ASK_TRY, validate, approve, fallbackToPreviousTypescript }: EditOptions = {},
247
- ) {
248
- for (let tryCount = 0; tryCount < maxTry; tryCount++) {
249
- let response = await this.ask(question, { onChunk, onReasoning });
250
- if (validate?.length && tryCount === 0) {
251
- const validateQuestion = `Double check if the response meets the requirements and conditions, and follow the instructions. If not, rewrite it.
252
- ${validate.map((v) => `- ${v}`).join("\n")}`;
253
- const validateResponse = await this.ask(validateQuestion, {
254
- onChunk,
255
- onReasoning,
256
- });
257
- response = {
258
- ...validateResponse,
259
- content: fallbackToPreviousTypescript
260
- ? preserveTypescriptResponseContent(response.content, validateResponse.content)
261
- : validateResponse.content,
262
- };
263
- }
264
- const isConfirmed = approve
265
- ? true
266
- : await select({
267
- message: "Do you want to edit the response?",
268
- choices: [
269
- { name: "✅ Yes, confirm and apply this result", value: true },
270
- { name: "🔄 No, I want to edit it more", value: false },
271
- ],
272
- });
273
- if (isConfirmed) {
274
- await this.#saveCache();
275
- return response.content;
276
- }
277
- question = await input({ message: "What do you want to change?" });
278
- tryCount++;
279
- }
280
- throw new Error("Failed to edit");
281
- }
282
- async editTypescript(question: string, options: EditOptions = {}) {
283
- const content = await this.edit(question, options);
284
- return this.#getTypescriptCode(content);
285
- }
286
- #getTypescriptCode(content: string) {
287
- //! will be deprecated
288
- const code = /```(typescript|tsx)([\s\S]*?)```/.exec(content);
289
- // 2번째로 해야 반환되는데 모르겟음 아무튼 일단 이렇게 함.
290
-
291
- return code?.[2] ?? content;
292
- // return code ? code[1] : content;
293
- }
294
- addToolMessgaes(messages: { type: string; content: string }[]) {
295
- // const toolMessages = messages.map(
296
- // (message) => new ToolMessage({ content: message.content, tool_call_id: message.type })
297
- // );
298
- const toolMessages = messages.map((message) => new HumanMessage(message.content));
299
- this.messageHistory.push(...toolMessages);
300
- return this;
301
- }
302
- async writeTypescripts(question: string, executor: Executor, options: EditOptions = {}) {
303
- const content = await this.edit(question, {
304
- ...options,
305
- fallbackToPreviousTypescript: true,
306
- });
307
- const writes = this.#getTypescriptCodes(content);
308
- if (!writes.length)
309
- throw new Error(
310
- "No parseable TypeScript file blocks were found in the AI response. Include `// File: <path>` in each code block.",
311
- );
312
- for (const write of writes) await executor.writeFile(write.filePath, write.content);
313
- return await this.#tryFixTypescripts(writes, executor, options);
314
- }
315
- async #editTypescripts(question: string, options: EditOptions = {}, fallbackWrites?: FileContent[]) {
316
- const content = await this.edit(question, {
317
- ...options,
318
- fallbackToPreviousTypescript: true,
319
- });
320
- const writes = this.#getTypescriptCodes(content);
321
- if (!writes.length && fallbackWrites?.length) return fallbackWrites;
322
- if (!writes.length)
323
- throw new Error(
324
- "No parseable TypeScript file blocks were found in the AI response. Include `// File: <path>` in each code block.",
325
- );
326
- return writes;
327
- }
328
- async #tryFixTypescripts(writes: FileContent[], executor: Executor, options: EditOptions = {}) {
329
- const MAX_EDIT_TRY = 5;
330
- for (let tryCount = 0; tryCount < MAX_EDIT_TRY; tryCount++) {
331
- const loader = new Spinner(`Type checking and linting...`, {
332
- prefix: `🤖akan-editor`,
333
- }).start();
334
- const fileChecks = await Promise.all(
335
- writes.map(async ({ filePath }) => {
336
- const lintResult = await executor.lint(filePath, { fix: true });
337
- const typeCheckResult = await executor.typeCheckAsync(filePath);
338
- const hasTypeErrors = typeCheckResult.fileErrors.length > 0;
339
- const hasLintErrors = lintResult.errors.length > 0;
340
- const needFix = hasTypeErrors || hasLintErrors;
341
- return { filePath, typeCheckResult, lintResult, needFix };
342
- }),
343
- );
344
- const hasAnyFix = fileChecks.some((fileCheck) => fileCheck.needFix);
345
- if (hasAnyFix) {
346
- loader.fail("Type checking and linting has some errors, try to fix them");
347
- fileChecks.forEach((fileCheck) => {
348
- Logger.rawLog(
349
- `TypeCheck Result \n${fileCheck.typeCheckResult.message}\nLint Result \n${fileCheck.lintResult.message}`,
350
- );
351
- this.addToolMessgaes([
352
- { type: "typescript", content: fileCheck.typeCheckResult.message },
353
- { type: "eslint", content: fileCheck.lintResult.message },
354
- ]);
355
- });
356
- writes = await this.#editTypescripts(
357
- "Fix the typescript and eslint errors",
358
- {
359
- ...options,
360
- validate: undefined,
361
- approve: true,
362
- },
363
- writes,
364
- );
365
- for (const write of writes) await executor.writeFile(write.filePath, write.content);
366
- } else {
367
- loader.succeed("Type checking and linting has no errors");
368
- return writes;
369
- }
370
- }
371
- throw new Error("Failed to create scalar");
372
- }
373
- #getTypescriptCodes(text: string): FileContent[] {
374
- return parseTypescriptFileBlocks(text);
375
- }
376
- async editMarkdown(request: string, options: EditOptions = {}) {
377
- const content = await this.edit(request, options);
378
- return this.#getMarkdownContent(content);
379
- }
380
- #getMarkdownContent(text: string) {
381
- const searchText = "```markdown";
382
- const firstIndex = text.indexOf("```markdown");
383
- const lastIndex = text.lastIndexOf("```");
384
- if (firstIndex === -1) return text;
385
- else return text.slice(firstIndex + searchText.length, lastIndex).trim();
386
- }
387
- }