@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
package/bunfig.toml ADDED
@@ -0,0 +1,2 @@
1
+ [test]
2
+ preload = ["./test/preload.ts"]
@@ -0,0 +1,82 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { AkanEditScope } from "../tools/AkanEditScope";
4
+ import type { TurnFeedbackSource } from "./TurnFeedback";
5
+
6
+ export interface DevLogFeedbackOptions {
7
+ workspaceRoot: string;
8
+ cwd: string;
9
+ apps: string[];
10
+ /** Hot reload finishes after the turn does, so the read waits for it. */
11
+ graceMs?: number;
12
+ maxLines?: number;
13
+ }
14
+
15
+ const errorPattern = /\bERROR\b|\bFATAL\b|\[stderr\]|error:|Error:|✖|Unhandled|Cannot find|is not a function/;
16
+ const noisePattern = /DEBUG|\bWARN\b|MCP catalogue|rate limit/;
17
+
18
+ // dev.log is the only file carrying the dev host's own build output; lint and typecheck pass on code that dies at run.
19
+ export class DevLogFeedback implements TurnFeedbackSource {
20
+ readonly key = "dev-server";
21
+ readonly #options: Required<DevLogFeedbackOptions>;
22
+ readonly #marks = new Map<string, number>();
23
+ #baseline: ReadonlySet<string> = new Set();
24
+
25
+ constructor(options: DevLogFeedbackOptions) {
26
+ this.#options = { graceMs: 1_500, maxLines: 30, ...options };
27
+ }
28
+
29
+ async begin() {
30
+ for (const app of this.#options.apps) this.#marks.set(app, DevLogFeedback.#sizeOf(this.#pathOf(app)));
31
+ this.#baseline = await AkanEditScope.baseline(this.#options.cwd);
32
+ }
33
+
34
+ async observe() {
35
+ const running = this.#options.apps.filter((app) => existsSync(this.#pathOf(app)));
36
+ if (!running.length) return undefined;
37
+ // A turn that wrote nothing cannot have broken the app; without this gate another person's dev server reopens it.
38
+ if (!(await AkanEditScope.since(this.#options.cwd, this.#baseline)).paths.length) return undefined;
39
+ await Bun.sleep(this.#options.graceMs);
40
+ const reports: string[] = [];
41
+ for (const app of running) {
42
+ const lines = await this.#linesSince(app);
43
+ if (lines.length) reports.push(`**${app}** dev server:\n\`\`\`\n${lines.join("\n")}\n\`\`\``);
44
+ }
45
+ if (!reports.length) return undefined;
46
+ return [
47
+ "The dev server logged errors after your edits:",
48
+ ...reports,
49
+ `Full log: ${running.map((app) => path.relative(this.#options.workspaceRoot, this.#pathOf(app))).join(", ")}`,
50
+ ].join("\n\n");
51
+ }
52
+
53
+ async #linesSince(app: string) {
54
+ const file = this.#pathOf(app);
55
+ const from = this.#marks.get(app) ?? 0;
56
+ const size = DevLogFeedback.#sizeOf(file);
57
+ // A smaller file means `akan start` rotated to a new session mid-turn; its own boot output is not a finding.
58
+ if (size <= from) return [];
59
+ const text = await Bun.file(file).slice(from, size).text();
60
+ this.#marks.set(app, size);
61
+ return text
62
+ .split("\n")
63
+ .filter((line) => errorPattern.test(line) && !noisePattern.test(line))
64
+ .slice(-this.#options.maxLines);
65
+ }
66
+
67
+ #pathOf(app: string) {
68
+ return path.join(this.#options.workspaceRoot, "local", "apps", app, "runtime", "dev.log");
69
+ }
70
+
71
+ /** The port is allocated, not predicted, so the log's `ready` line is the only record of this session's URL. */
72
+ static async previewUrl(workspaceRoot: string, app: string) {
73
+ const file = path.join(workspaceRoot, "local", "apps", app, "runtime", "dev.log");
74
+ if (!existsSync(file)) return undefined;
75
+ const matches = [...(await Bun.file(file).text()).matchAll(/ready \(pid=\d+\) — (https?:\/\/\S+)/g)];
76
+ return matches.at(-1)?.[1];
77
+ }
78
+
79
+ static #sizeOf(file: string) {
80
+ return existsSync(file) ? statSync(file).size : 0;
81
+ }
82
+ }
@@ -0,0 +1,46 @@
1
+ import { PreviewView } from "@akanjs/devkit/preview";
2
+ import { AkanEditScope } from "../tools/AkanEditScope";
3
+ import type { TurnFeedbackFinding, TurnFeedbackSource } from "./TurnFeedback";
4
+
5
+ export interface PreviewFeedbackOptions {
6
+ cwd: string;
7
+ /** Origin of a running dev server. Without one the source is inert. */
8
+ previewUrl?: string;
9
+ /** Every akan route sits under `/:lang`, so a bare path renders nothing. */
10
+ routes?: string[];
11
+ /** Only a model whose input includes images gets a screenshot attached. */
12
+ canSeeImages?: boolean;
13
+ }
14
+
15
+ // Findings are text, not screenshots: a few hundred tokens, readable by any model, and naming the defect.
16
+ export class PreviewFeedback implements TurnFeedbackSource {
17
+ readonly key = "preview";
18
+ readonly #options: PreviewFeedbackOptions;
19
+ #baseline: ReadonlySet<string> = new Set();
20
+
21
+ constructor(options: PreviewFeedbackOptions) {
22
+ this.#options = options;
23
+ }
24
+
25
+ async begin() {
26
+ this.#baseline = await AkanEditScope.baseline(this.#options.cwd);
27
+ }
28
+
29
+ async observe(): Promise<TurnFeedbackFinding | undefined> {
30
+ if (!this.#options.previewUrl || !PreviewView.available) return undefined;
31
+ const scope = await AkanEditScope.since(this.#options.cwd, this.#baseline);
32
+ if (!scope.touchesTsx) return undefined;
33
+ const findings: string[] = [];
34
+ const images: { data: string; mimeType: string }[] = [];
35
+ for (const route of this.#options.routes ?? ["/en/"]) {
36
+ const url = new URL(route, this.#options.previewUrl).toString();
37
+ const probe = await PreviewView.probe(url, { screenshot: !!this.#options.canSeeImages });
38
+ const problems = [...probe.pageErrors, ...probe.consoleErrors, ...probe.consoleWarnings, ...probe.domFindings];
39
+ if (!problems.length) continue;
40
+ findings.push(`**${url}**\n${problems.map((line) => `- ${line}`).join("\n")}`);
41
+ if (probe.screenshot) images.push({ data: probe.screenshot, mimeType: "image/png" });
42
+ }
43
+ if (!findings.length) return undefined;
44
+ return { text: ["The rendered page has problems after your UI edits:", ...findings].join("\n\n"), images };
45
+ }
46
+ }
@@ -0,0 +1,98 @@
1
+ import type { ExtensionAPI, InlineExtension } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** A base64 PNG, attached only when the active model can read one. */
4
+ export interface TurnFeedbackImage {
5
+ data: string;
6
+ mimeType: string;
7
+ }
8
+
9
+ export interface TurnFeedbackFinding {
10
+ text: string;
11
+ images?: TurnFeedbackImage[];
12
+ }
13
+
14
+ export interface TurnFeedbackSource {
15
+ /** Budget is counted per key, so one stuck source cannot spend another's attempts. */
16
+ key: string;
17
+ /** Record whatever "before" this source compares against. Never throws — a source that cannot arm is skipped. */
18
+ begin(): Promise<void> | void;
19
+ /** What the turn caused that the agent cannot see, or `undefined` when there is nothing to say. */
20
+ observe(): Promise<TurnFeedbackFinding | string | undefined> | TurnFeedbackFinding | string | undefined;
21
+ }
22
+
23
+ export interface TurnFeedbackOptions {
24
+ /** How many times one source may reopen a turn before it gives up and lets the human see it. */
25
+ budget: number;
26
+ onNotice?: (message: string) => void;
27
+ }
28
+
29
+ // The engine's `agent_end` hook cannot veto the end of a turn, so a finding is a follow-up that opens a new one.
30
+ // The budget is load-bearing: without it one unfixable error reopens turns until the context or the wallet runs out.
31
+ export class TurnFeedback {
32
+ readonly #sources: TurnFeedbackSource[];
33
+ readonly #options: TurnFeedbackOptions;
34
+ readonly #spent = new Map<string, number>();
35
+
36
+ constructor(sources: TurnFeedbackSource[], options: TurnFeedbackOptions) {
37
+ this.#sources = sources;
38
+ this.#options = options;
39
+ }
40
+
41
+ extension(): InlineExtension {
42
+ return {
43
+ name: "akan-turn-feedback",
44
+ factory: (pi: ExtensionAPI) => {
45
+ pi.on("agent_start", async () => {
46
+ await Promise.all(this.#sources.map((source) => TurnFeedback.#quietly(() => source.begin())));
47
+ });
48
+ pi.on("agent_end", async () => {
49
+ const message = await this.collect();
50
+ if (message) pi.sendUserMessage(message, { deliverAs: "followUp" });
51
+ });
52
+ },
53
+ };
54
+ }
55
+
56
+ async collect() {
57
+ const texts: string[] = [];
58
+ const images: TurnFeedbackImage[] = [];
59
+ const reopened: string[] = [];
60
+ for (const source of this.#sources) {
61
+ const finding = await TurnFeedback.#quietly(() => source.observe());
62
+ if (!finding) {
63
+ this.#spent.delete(source.key);
64
+ continue;
65
+ }
66
+ const spent = this.#spent.get(source.key) ?? 0;
67
+ if (spent >= this.#options.budget) {
68
+ this.#options.onNotice?.(`${source.key}: still failing after ${spent} attempts — handing back to you.`);
69
+ continue;
70
+ }
71
+ this.#spent.set(source.key, spent + 1);
72
+ reopened.push(source.key);
73
+ if (typeof finding === "string") texts.push(finding);
74
+ else {
75
+ texts.push(finding.text);
76
+ images.push(...(finding.images ?? []));
77
+ }
78
+ }
79
+ if (!texts.length) return undefined;
80
+ this.#options.onNotice?.(`${reopened.join(" · ")} reopened the turn — esc stops it`);
81
+ const text = [
82
+ "The previous turn left problems you cannot see from the transcript. Fix them, then stop.",
83
+ ...texts,
84
+ ].join("\n\n");
85
+ return images.length
86
+ ? [{ type: "text" as const, text }, ...images.map((image) => ({ type: "image" as const, ...image }))]
87
+ : text;
88
+ }
89
+
90
+ /** Every source is best-effort: no dev server, no git, no preview — all of them mean "nothing to report". */
91
+ static async #quietly<T>(fn: () => T | Promise<T>) {
92
+ try {
93
+ return await fn();
94
+ } catch {
95
+ return undefined;
96
+ }
97
+ }
98
+ }
@@ -0,0 +1,39 @@
1
+ import { AkanEditScope } from "../tools/AkanEditScope";
2
+ import { AkanVerifier } from "../tools/AkanVerifier";
3
+ import type { TurnFeedbackSource } from "./TurnFeedback";
4
+
5
+ export interface VerifyFeedbackOptions {
6
+ cwd: string;
7
+ /** A read-only profile reports what is stale instead of running a chain that would write generated files. */
8
+ readOnly?: boolean;
9
+ }
10
+
11
+ // A hook, not a reliance on the akan_verify tool: the observed failure is a model finishing without calling it.
12
+ export class VerifyFeedback implements TurnFeedbackSource {
13
+ readonly key = "verify";
14
+ readonly #options: VerifyFeedbackOptions;
15
+ readonly #verifier: AkanVerifier;
16
+ #baseline: ReadonlySet<string> = new Set();
17
+
18
+ constructor(options: VerifyFeedbackOptions) {
19
+ this.#options = options;
20
+ this.#verifier = new AkanVerifier(options.cwd);
21
+ }
22
+
23
+ async begin() {
24
+ this.#baseline = await AkanEditScope.baseline(this.#options.cwd);
25
+ }
26
+
27
+ async observe() {
28
+ const scope = await AkanEditScope.since(this.#options.cwd, this.#baseline);
29
+ if (!scope.apps.length && !scope.libs.length && !scope.pkgs.length) return undefined;
30
+ if (this.#options.readOnly) return VerifyFeedback.#readOnlyNotice(scope.needsSync, [...scope.apps, ...scope.libs]);
31
+ const report = await this.#verifier.verify(scope.paths);
32
+ return report.ok ? undefined : report.text;
33
+ }
34
+
35
+ static #readOnlyNotice(needsSync: boolean, targets: string[]) {
36
+ if (!needsSync) return undefined;
37
+ return `Files were added or removed under ${targets.join(", ")}, so the generated barrels are stale. This profile does not write, so run \`akan sync ${targets.join(" ")}\` yourself before trusting a typecheck.`;
38
+ }
39
+ }
@@ -0,0 +1,297 @@
1
+ // Leaf and lazy imports only: `serve` must take over the console before the engine loads.
2
+ import { randomBytes } from "node:crypto";
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { AkanCodeEnv, akanCodePaths } from "@akanjs/devkit/codeAgent";
6
+ import type { Workspace } from "@akanjs/devkit/commandDecorators";
7
+ import { type CodeAgentProfile, codeAgentPresets, isCodeAgentPresetName } from "akanjs/common";
8
+ import { akanCodeDefaultModel, type CodeAgentModelRef } from "../agent/akanCodeModel";
9
+ import { CodeAgentStreamPrinter } from "../agent/CodeAgentStreamPrinter";
10
+ import { WorkspaceTrust, type WorkspaceTrustKind } from "../agent/WorkspaceTrust";
11
+ import type { AkanToolCatalog } from "../tools/AkanToolPack";
12
+ import type { CodeTuiExit } from "../tui/CodeTui";
13
+ import { CodeTrustPrompt, type CodeTrustPromptStreams } from "./CodeTrustPrompt";
14
+
15
+ //? @akanjs/code must not depend on the CLI that loads it, so the CLI hands in what only it has.
16
+ export interface AkanCodeHost {
17
+ catalog: AkanToolCatalog;
18
+ openBrowser: (url: string) => void;
19
+ }
20
+
21
+ export interface AkanCodeStartOptions {
22
+ app: string | null;
23
+ profile: string;
24
+ model: string | null;
25
+ compactAt: number | null;
26
+ json: boolean;
27
+ thinking: boolean;
28
+ rpc: boolean;
29
+ rpcListen: string | null;
30
+ interactive: boolean;
31
+ resume: string | null;
32
+ trustWorkspace: boolean;
33
+ askNetwork: boolean;
34
+ askCommands: boolean;
35
+ ask: boolean;
36
+ rpcBindAny: boolean;
37
+ rpcToken: boolean;
38
+ }
39
+
40
+ export interface CodeRunOptions {
41
+ workspace: Workspace;
42
+ app?: string;
43
+ profile: string;
44
+ model?: string;
45
+ compactAt?: number;
46
+ json: boolean;
47
+ thinking: boolean;
48
+ resume?: string;
49
+ trustWorkspace?: boolean;
50
+ askNetwork?: boolean;
51
+ askCommands?: boolean;
52
+ ask?: boolean;
53
+ rpcBindAny?: boolean;
54
+ rpcToken?: boolean;
55
+ }
56
+
57
+ interface CodeStartMode {
58
+ hostAttached: boolean;
59
+ interactive: boolean;
60
+ ask: boolean;
61
+ }
62
+
63
+ export class AkanCodeRunner {
64
+ readonly #host: AkanCodeHost;
65
+
66
+ constructor(host: AkanCodeHost) {
67
+ this.#host = host;
68
+ }
69
+
70
+ async start(workspace: Workspace, prompt: string, options: AkanCodeStartOptions) {
71
+ const run = {
72
+ workspace,
73
+ ...(options.app ? { app: options.app } : {}),
74
+ profile: options.profile,
75
+ ...(options.model ? { model: options.model } : {}),
76
+ ...(options.compactAt !== null ? { compactAt: options.compactAt } : {}),
77
+ json: options.json,
78
+ thinking: options.thinking,
79
+ ...(options.resume ? { resume: options.resume } : {}),
80
+ trustWorkspace: options.trustWorkspace,
81
+ askNetwork: options.askNetwork,
82
+ askCommands: options.askCommands,
83
+ ask: options.ask,
84
+ rpcBindAny: options.rpcBindAny,
85
+ rpcToken: options.rpcToken,
86
+ };
87
+ if (options.rpcListen) return await this.serve(run, options.rpcListen);
88
+ if (options.rpc) return await this.serve(run);
89
+ const interactive = options.interactive || (!prompt.trim() && !options.json && !!process.stdout.isTTY);
90
+ if (interactive) return await this.tui(run, prompt);
91
+ if (!prompt.trim())
92
+ throw new Error('akan code needs a prompt when it has no terminal: akan code "add a comment module"');
93
+ await this.run(prompt, run);
94
+ }
95
+
96
+ async serve(options: CodeRunOptions, listen?: string) {
97
+ // Must run before the engine loads, or what it logs while loading corrupts the first stdout frame.
98
+ await import("../agent/consoleToStderr");
99
+ const [{ CodeAgent }, { CodeAgentRpcHost }, { CodeAgentRpcListener }] = await Promise.all([
100
+ import("../agent/CodeAgent"),
101
+ import("../agent/CodeAgentRpcHost"),
102
+ import("../agent/CodeAgentRpcListener"),
103
+ ]);
104
+ const address = listen ? CodeAgentRpcListener.parse(listen, { anyHost: !!options.rpcBindAny }) : null;
105
+ const tcp = !!address && !("unix" in address);
106
+ const tokenFile = tcp && options.rpcToken !== false ? AkanCodeEnv.get("AKAN_CODE_RPC_TOKEN_FILE") : undefined;
107
+ const token = !tcp || options.rpcToken === false ? null : AkanCodeRunner.#rpcTokenFrom(tokenFile);
108
+ const start = await this.#prepare(options, { hostAttached: true, interactive: false, ask: false });
109
+ for (const warning of start.warnings) process.stderr.write(`${warning}\n`);
110
+ const agent = await CodeAgent.create({ ...start.agent, mode: "rpc" });
111
+ if (!address) return await new CodeAgentRpcHost(agent).serve();
112
+ const listener = new CodeAgentRpcListener(new CodeAgentRpcHost(agent, null), address, { token }).listen();
113
+ const where = "unix" in address ? address.unix : `${address.hostname}:${listener.port}`;
114
+ const written = token && !tokenFile ? AkanCodeRunner.#writeRpcToken(listener.port ?? 0, token) : undefined;
115
+ const tokenAt = tokenFile ?? written;
116
+ process.stderr.write(
117
+ tokenAt
118
+ ? `akan code rpc listening on ${where}; open with {"auth":"<token>"}, the token is in ${tokenAt}\n`
119
+ : `akan code rpc listening on ${where}\n`,
120
+ );
121
+ if (tcp && !token)
122
+ process.stderr.write("No token is asked for, so any process on this machine can drive this agent.\n");
123
+ try {
124
+ await listener.serve();
125
+ } finally {
126
+ if (written) rmSync(written, { force: true });
127
+ }
128
+ }
129
+
130
+ async tui(options: CodeRunOptions, seed: string) {
131
+ const [{ CodeAgent }, { CodeTui }] = await Promise.all([import("../agent/CodeAgent"), import("../tui/CodeTui")]);
132
+ const start = await this.#prepare(options, { hostAttached: false, interactive: true, ask: true });
133
+ const agentOptions = start.agent;
134
+ let warnings: string[] = start.warnings;
135
+ let resume = options.resume;
136
+ let autoCompactAt = agentOptions.autoCompactAt;
137
+ let prompt = seed;
138
+ let notice: string | undefined;
139
+ // A session switch rebuilds the agent: the engine binds extensions, tools and context to it at construction.
140
+ for (;;) {
141
+ const agent = await CodeAgent.create({
142
+ ...agentOptions,
143
+ mode: "tui",
144
+ ...(resume ? { resume } : {}),
145
+ ...(autoCompactAt ? { autoCompactAt } : {}),
146
+ });
147
+ let next: CodeTuiExit | undefined;
148
+ try {
149
+ next = await new CodeTui(agent, {
150
+ thinking: options.thinking,
151
+ ...(notice ? { notice } : {}),
152
+ warnings,
153
+ openBrowser: this.#host.openBrowser,
154
+ }).run(prompt);
155
+ autoCompactAt = agent.info.autoCompactAt;
156
+ } finally {
157
+ agent.dispose();
158
+ }
159
+ if (!next) return;
160
+ resume = next.id;
161
+ notice = next.notice;
162
+ warnings = [];
163
+ prompt = "";
164
+ }
165
+ }
166
+
167
+ async run(prompt: string, options: CodeRunOptions) {
168
+ const { CodeAgent } = await import("../agent/CodeAgent");
169
+ const ask = !!process.stdin.isTTY && !!process.stderr.isTTY;
170
+ const start = await this.#prepare(options, { hostAttached: false, interactive: false, ask });
171
+ for (const warning of start.warnings) process.stderr.write(`${warning}\n`);
172
+ const agent = await CodeAgent.create(start.agent);
173
+ const printer = new CodeAgentStreamPrinter({ json: options.json, thinking: options.thinking });
174
+ agent.on((event) => printer.print(event));
175
+ agent.announce();
176
+ try {
177
+ await agent.prompt(prompt);
178
+ await agent.waitForIdle();
179
+ } finally {
180
+ printer.finish();
181
+ agent.dispose();
182
+ }
183
+ }
184
+
185
+ async #prepare(options: CodeRunOptions, mode: CodeStartMode) {
186
+ const profile = AkanCodeRunner.profileOf(options, mode);
187
+ const trust = await AkanCodeRunner.trust(options.workspace.workspaceRoot, profile, {
188
+ trustWorkspace: !!options.trustWorkspace,
189
+ ...(mode.ask && process.stdin.isTTY ? { streams: { input: process.stdin, output: process.stderr } } : {}),
190
+ });
191
+ const agent = {
192
+ workspace: options.workspace,
193
+ cwd: profile.paths.root,
194
+ profile,
195
+ apps: options.app ? [options.app] : await options.workspace.getApps(),
196
+ model: AkanCodeRunner.modelOf(options.model),
197
+ catalog: this.#host.catalog,
198
+ ...(options.compactAt !== undefined ? { autoCompactAt: options.compactAt } : {}),
199
+ };
200
+ return { agent, warnings: [...AkanCodeRunner.startWarnings(profile, options.ask === false), ...trust] };
201
+ }
202
+
203
+ static profileOf(
204
+ options: CodeRunOptions,
205
+ { hostAttached, interactive = true }: { hostAttached: boolean; interactive?: boolean },
206
+ ): CodeAgentProfile {
207
+ if (!isCodeAgentPresetName(options.profile))
208
+ throw new Error(`Unknown profile: ${options.profile}. Use local, pod, review, or web.`);
209
+ const root = options.app
210
+ ? `${options.workspace.workspaceRoot}/apps/${options.app}`
211
+ : options.workspace.workspaceRoot;
212
+ const profile = codeAgentPresets[options.profile](root);
213
+ const { askOutside: _ask, ...network } = profile.network;
214
+ const askNetwork = options.ask !== false && options.askNetwork !== false;
215
+ const askCommands = options.ask !== false && options.askCommands !== false;
216
+ return {
217
+ ...profile,
218
+ ...(askNetwork ? {} : { network }),
219
+ ...(!askCommands && profile.approval === "commands" ? { approval: "never" as const } : {}),
220
+ ui: { ...profile.ui, canPrompt: AkanCodeRunner.canPrompt(profile, hostAttached, interactive) },
221
+ };
222
+ }
223
+
224
+ //* A host on the RPC wire is someone to ask; a pod job or a one-shot run with none must never park a turn.
225
+ static canPrompt(profile: CodeAgentProfile, hostAttached: boolean, interactive = true) {
226
+ const forced = AkanCodeEnv.get("AKAN_CODE_CAN_PROMPT");
227
+ if (forced === "1") return true;
228
+ if (forced === "0") return false;
229
+ return hostAttached || (interactive && profile.ui.canPrompt);
230
+ }
231
+
232
+ static startWarnings(profile: CodeAgentProfile, unasked = false) {
233
+ return [
234
+ ...AkanCodeEnv.ignored(),
235
+ ...(profile.name === "local"
236
+ ? [
237
+ unasked
238
+ ? "--no-ask: this session runs shell commands and network requests without asking. The local profile is not a sandbox: it refuses known secret files, but a command can read anything you can. Use --profile pod inside a container to isolate it."
239
+ : "The local profile is not a sandbox: it refuses known secret files and asks before a shell command and an unlisted host, but a command you approve can read anything you can. Use --profile pod inside a container to isolate it.",
240
+ ]
241
+ : []),
242
+ ];
243
+ }
244
+
245
+ static async trust(
246
+ workspaceRoot: string,
247
+ profile: CodeAgentProfile,
248
+ { trustWorkspace, streams }: { trustWorkspace: boolean; streams?: CodeTrustPromptStreams },
249
+ ) {
250
+ const kinds: WorkspaceTrustKind[] = profile.tools.mcp === "off" ? ["extensions"] : ["mcp", "extensions"];
251
+ const pending = WorkspaceTrust.pending(workspaceRoot, kinds);
252
+ if (!pending.length) return [];
253
+ if (trustWorkspace) {
254
+ WorkspaceTrust.approve(workspaceRoot, pending, false);
255
+ return [];
256
+ }
257
+ if (streams && (await CodeTrustPrompt.ask(pending, streams))) {
258
+ WorkspaceTrust.approve(workspaceRoot, pending, true);
259
+ return [];
260
+ }
261
+ return [CodeTrustPrompt.skipped(pending)];
262
+ }
263
+
264
+ static #rpcTokenFrom(file: string | undefined) {
265
+ if (!file || !existsSync(file)) {
266
+ const token = randomBytes(32).toString("base64url");
267
+ if (file) AkanCodeRunner.#writePrivate(file, token);
268
+ return token;
269
+ }
270
+ const token = readFileSync(file, "utf8").trim();
271
+ if (!token) throw new Error(`AKAN_CODE_RPC_TOKEN_FILE names ${file}, which is empty.`);
272
+ return token;
273
+ }
274
+
275
+ static #writeRpcToken(port: number, token: string) {
276
+ const file = akanCodePaths.rpcTokenFile(port);
277
+ AkanCodeRunner.#writePrivate(file, token);
278
+ return file;
279
+ }
280
+
281
+ static #writePrivate(file: string, content: string) {
282
+ akanCodePaths.ensureGlobalDir();
283
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
284
+ writeFileSync(file, `${content}\n`, { mode: 0o600 });
285
+ chmodSync(file, 0o600);
286
+ }
287
+
288
+ static modelOf(model: string | undefined): CodeAgentModelRef | undefined {
289
+ if (!model) return undefined;
290
+ const [provider, ...rest] = model.split("/");
291
+ if (!provider || !rest.length)
292
+ throw new Error(
293
+ `Model must be "<provider>/<id>", e.g. ${akanCodeDefaultModel.provider}/${akanCodeDefaultModel.id}`,
294
+ );
295
+ return { provider, id: rest.join("/") };
296
+ }
297
+ }
@@ -0,0 +1,57 @@
1
+ import type { WorkspaceTrustItem } from "../agent/WorkspaceTrust";
2
+
3
+ export interface CodeTrustPromptStreams {
4
+ input: NodeJS.ReadableStream;
5
+ output: NodeJS.WritableStream;
6
+ }
7
+
8
+ const shown = 8;
9
+
10
+ export class CodeTrustPrompt {
11
+ static describe(items: WorkspaceTrustItem[]) {
12
+ const lines = ["This repo asks akan code to run its own code:"];
13
+ for (const item of items) {
14
+ lines.push(
15
+ item.kind === "mcp"
16
+ ? " MCP servers in .akan/code/mcp.json, which it would start or connect to:"
17
+ : " Extensions in .akan/code/extensions/, which it would load and run:",
18
+ );
19
+ lines.push(...item.lines.slice(0, shown).map((line) => ` ${line}`));
20
+ if (item.lines.length > shown) lines.push(` … and ${item.lines.length - shown} more`);
21
+ }
22
+ return lines.join("\n");
23
+ }
24
+
25
+ static skipped(items: WorkspaceTrustItem[]) {
26
+ const what = items.map((item) => (item.kind === "mcp" ? "MCP servers" : "extensions")).join(" and ");
27
+ return `This repo's ${what} were not started: they are not approved. Start akan code in a terminal to approve them, or pass --trust-workspace.`;
28
+ }
29
+
30
+ static async ask(items: WorkspaceTrustItem[], { input, output }: CodeTrustPromptStreams) {
31
+ output.write(`${CodeTrustPrompt.describe(items)}\n\nStart them, and remember this until they change? [y/N] `);
32
+ const answer = await CodeTrustPrompt.#line(input);
33
+ return /^\s*y(es)?\s*$/i.test(answer ?? "");
34
+ }
35
+
36
+ // Raw `data` events, not readline: the full-screen session takes stdin right after, and readline keeps its listener.
37
+ static #line(input: NodeJS.ReadableStream) {
38
+ return new Promise<string | undefined>((resolve) => {
39
+ let buffer = "";
40
+ const finish = (value: string | undefined) => {
41
+ input.off("data", onData);
42
+ input.off("end", onEnd);
43
+ input.pause();
44
+ resolve(value);
45
+ };
46
+ const onData = (chunk: Buffer | string) => {
47
+ buffer += chunk.toString();
48
+ const newline = buffer.search(/[\r\n]/);
49
+ if (newline >= 0) finish(buffer.slice(0, newline));
50
+ };
51
+ const onEnd = () => finish(undefined);
52
+ input.on("data", onData);
53
+ input.on("end", onEnd);
54
+ input.resume();
55
+ });
56
+ }
57
+ }