@akanjs/code 0.0.0 → 3.3.0-rc.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.ko.md +31 -0
  2. package/README.md +26 -4
  3. package/agent/AkanCodeCompaction.ts +49 -0
  4. package/agent/AkanCodeServices.ts +122 -0
  5. package/agent/AkanContextFiles.ts +94 -0
  6. package/agent/CodeAgent.ts +598 -0
  7. package/agent/CodeAgentAllowed.ts +35 -0
  8. package/agent/CodeAgentAsks.ts +66 -0
  9. package/agent/CodeAgentCommandLine.ts +372 -0
  10. package/agent/CodeAgentEventMapper.ts +225 -0
  11. package/agent/CodeAgentFrames.ts +57 -0
  12. package/agent/CodeAgentGate.ts +258 -0
  13. package/agent/CodeAgentProxy.ts +83 -0
  14. package/agent/CodeAgentRpcHost.ts +109 -0
  15. package/agent/CodeAgentRpcListener.ts +195 -0
  16. package/agent/CodeAgentStreamPrinter.ts +86 -0
  17. package/agent/CodeAgentSuspended.ts +85 -0
  18. package/agent/CodeAgentUi.ts +47 -0
  19. package/agent/CodeMailbox.ts +148 -0
  20. package/agent/CodeSessionFork.ts +56 -0
  21. package/agent/CodeSessionIndex.ts +78 -0
  22. package/agent/SubagentPool.ts +222 -0
  23. package/agent/WorkspaceTrust.ts +200 -0
  24. package/agent/akanCodeCompaction.test.ts +36 -0
  25. package/agent/akanCodeModel.ts +47 -0
  26. package/agent/akanCodeServices.test.ts +54 -0
  27. package/agent/akanContextFiles.test.ts +116 -0
  28. package/agent/akanSystemPrompt.ts +50 -0
  29. package/agent/codeAgent.test.ts +337 -0
  30. package/agent/codeAgentCommandLine.test.ts +212 -0
  31. package/agent/codeAgentContract.test.ts +757 -0
  32. package/agent/codeAgentHosts.ts +30 -0
  33. package/agent/codeAgentProxy.test.ts +125 -0
  34. package/agent/codeAgentRpcListener.test.ts +215 -0
  35. package/agent/codeAgentSuspended.test.ts +47 -0
  36. package/agent/codeMailbox.test.ts +76 -0
  37. package/agent/codeSessionFork.test.ts +58 -0
  38. package/agent/codeSessionIndex.test.ts +77 -0
  39. package/agent/consoleToStderr.ts +8 -0
  40. package/agent/jsonLines.ts +29 -0
  41. package/agent/stringArg.ts +5 -0
  42. package/bunfig.toml +2 -0
  43. package/feedback/DevLogFeedback.ts +82 -0
  44. package/feedback/PreviewFeedback.ts +46 -0
  45. package/feedback/TurnFeedback.ts +98 -0
  46. package/feedback/VerifyFeedback.ts +39 -0
  47. package/host/AkanCodeRunner.ts +297 -0
  48. package/host/CodeTrustPrompt.ts +57 -0
  49. package/host/codeRunnerPrompt.test.ts +181 -0
  50. package/host/hostGraph.test.ts +33 -0
  51. package/host/index.ts +2 -0
  52. package/index.ts +49 -0
  53. package/package.json +43 -9
  54. package/piDependencyPins.test.ts +45 -0
  55. package/test/preload.ts +3 -0
  56. package/tools/AkanCli.ts +56 -0
  57. package/tools/AkanCodePlugins.ts +145 -0
  58. package/tools/AkanEditScope.ts +53 -0
  59. package/tools/AkanEnvKeys.ts +50 -0
  60. package/tools/AkanToolPack.ts +87 -0
  61. package/tools/AkanVerifier.ts +30 -0
  62. package/tools/AskToolPack.ts +99 -0
  63. package/tools/DeepSeekWeb.ts +127 -0
  64. package/tools/MailToolPack.ts +76 -0
  65. package/tools/McpClient.ts +209 -0
  66. package/tools/McpOAuth.ts +233 -0
  67. package/tools/McpOAuthLoopback.ts +64 -0
  68. package/tools/McpServerConfig.ts +131 -0
  69. package/tools/McpSignIn.ts +158 -0
  70. package/tools/McpTokenStore.ts +128 -0
  71. package/tools/McpToolPack.ts +206 -0
  72. package/tools/SessionToolPack.ts +91 -0
  73. package/tools/WebToolPack.ts +315 -0
  74. package/tools/akanCodePlugins.test.ts +954 -0
  75. package/tools/askToolPack.test.ts +116 -0
  76. package/tools/deepSeekWeb.test.ts +113 -0
  77. package/tools/mcpOAuth.test.ts +648 -0
  78. package/tools/mcpServerConfig.test.ts +341 -0
  79. package/tsconfig.json +29 -0
  80. package/tui/CodeTui.tsx +394 -0
  81. package/tui/CodeTuiAgents.ts +65 -0
  82. package/tui/CodeTuiApp.test.tsx +251 -0
  83. package/tui/CodeTuiApp.tsx +312 -0
  84. package/tui/CodeTuiAutoCompact.ts +33 -0
  85. package/tui/CodeTuiClipboard.ts +94 -0
  86. package/tui/CodeTuiCommandRunner.ts +242 -0
  87. package/tui/CodeTuiCommands.ts +59 -0
  88. package/tui/CodeTuiEditor.ts +168 -0
  89. package/tui/CodeTuiFiles.ts +45 -0
  90. package/tui/CodeTuiFrame.ts +133 -0
  91. package/tui/CodeTuiLines.ts +117 -0
  92. package/tui/CodeTuiMarkdown.ts +159 -0
  93. package/tui/CodeTuiMcp.ts +111 -0
  94. package/tui/CodeTuiModels.ts +82 -0
  95. package/tui/CodeTuiMouse.ts +39 -0
  96. package/tui/CodeTuiOverlay.ts +148 -0
  97. package/tui/CodeTuiParts.ts +168 -0
  98. package/tui/CodeTuiPrompt.ts +271 -0
  99. package/tui/CodeTuiQuestion.ts +170 -0
  100. package/tui/codeTranscript.test.ts +445 -0
  101. package/tui/codeTui.test.tsx +1104 -0
  102. package/tui/codeTuiAgents.test.ts +61 -0
  103. package/tui/codeTuiClipboard.test.ts +16 -0
  104. package/tui/codeTuiCommands.test.ts +38 -0
  105. package/tui/codeTuiEditor.test.ts +122 -0
  106. package/tui/codeTuiFiles.test.ts +43 -0
  107. package/tui/codeTuiMarkdown.test.ts +91 -0
  108. package/tui/codeTuiMcp.test.ts +160 -0
  109. package/tui/codeTuiMouse.test.ts +61 -0
@@ -0,0 +1,181 @@
1
+ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { PassThrough } from "node:stream";
6
+ import type { Workspace } from "@akanjs/devkit/commandDecorators";
7
+ import { codeAgentPresets } from "akanjs/common";
8
+ import { WorkspaceTrust } from "../agent/WorkspaceTrust";
9
+ import { AkanCodeRunner, type CodeRunOptions } from "./AkanCodeRunner";
10
+ import { CodeTrustPrompt } from "./CodeTrustPrompt";
11
+
12
+ let codeHome: string;
13
+ let realCodeHome: string | undefined;
14
+
15
+ beforeAll(() => {
16
+ realCodeHome = process.env.AKAN_CODE_HOME;
17
+ codeHome = mkdtempSync(path.join(tmpdir(), "akan-code-runner-"));
18
+ process.env.AKAN_CODE_HOME = codeHome;
19
+ });
20
+
21
+ afterAll(() => {
22
+ if (realCodeHome === undefined) delete process.env.AKAN_CODE_HOME;
23
+ else process.env.AKAN_CODE_HOME = realCodeHome;
24
+ rmSync(codeHome, { recursive: true, force: true });
25
+ });
26
+
27
+ afterEach(() => {
28
+ delete process.env.AKAN_CODE_CAN_PROMPT;
29
+ });
30
+
31
+ const runOptions = (patch: Partial<CodeRunOptions> = {}): CodeRunOptions => ({
32
+ workspace: { workspaceRoot: "/w" } as unknown as Workspace,
33
+ profile: "local",
34
+ json: false,
35
+ thinking: false,
36
+ ...patch,
37
+ });
38
+
39
+ describe("AkanCodeRunner.canPrompt", () => {
40
+ test("a pod prompts only when a host is on the wire, and the env overrides either way", () => {
41
+ const pod = codeAgentPresets.pod("/w");
42
+ expect(AkanCodeRunner.canPrompt(pod, false)).toBe(false);
43
+ expect(AkanCodeRunner.canPrompt(pod, true)).toBe(true);
44
+ process.env.AKAN_CODE_CAN_PROMPT = "0";
45
+ expect(AkanCodeRunner.canPrompt(pod, true)).toBe(false);
46
+ process.env.AKAN_CODE_CAN_PROMPT = "1";
47
+ expect(AkanCodeRunner.canPrompt(pod, false)).toBe(true);
48
+ });
49
+
50
+ test("a one-shot run has nobody to answer, so it never prompts unless the env says to", () => {
51
+ const local = codeAgentPresets.local("/w");
52
+ expect(AkanCodeRunner.canPrompt(local, false, true)).toBe(true);
53
+ expect(AkanCodeRunner.canPrompt(local, false, false)).toBe(false);
54
+ process.env.AKAN_CODE_CAN_PROMPT = "1";
55
+ expect(AkanCodeRunner.canPrompt(local, false, false)).toBe(true);
56
+ });
57
+ });
58
+
59
+ describe("AkanCodeRunner.profileOf", () => {
60
+ test("the local profile asks before an unlisted host unless told not to", () => {
61
+ expect(AkanCodeRunner.profileOf(runOptions(), { hostAttached: false }).network.askOutside).toContain("github.com");
62
+ const quiet = AkanCodeRunner.profileOf(runOptions({ askNetwork: false }), { hostAttached: false });
63
+ expect(quiet.network.askOutside).toBeUndefined();
64
+ });
65
+
66
+ test("the local profile asks before a shell command unless told not to, and no flag makes another profile ask", () => {
67
+ expect(AkanCodeRunner.profileOf(runOptions(), { hostAttached: false }).approval).toBe("commands");
68
+ expect(AkanCodeRunner.profileOf(runOptions({ askCommands: false }), { hostAttached: false }).approval).toBe(
69
+ "never",
70
+ );
71
+ const web = AkanCodeRunner.profileOf(runOptions({ profile: "web", askCommands: false }), { hostAttached: true });
72
+ expect(web.approval).toBe("writes");
73
+ });
74
+
75
+ test("--no-ask stops the local profile asking about a shell command and an unlisted host, and changes nothing else", () => {
76
+ const asking = AkanCodeRunner.profileOf(runOptions(), { hostAttached: false });
77
+ const quiet = AkanCodeRunner.profileOf(runOptions({ ask: false }), { hostAttached: false });
78
+ expect(quiet.approval).toBe("never");
79
+ expect(quiet.network.askOutside).toBeUndefined();
80
+ expect({ ...quiet, approval: asking.approval, network: asking.network }).toEqual(asking);
81
+ expect(AkanCodeRunner.profileOf(runOptions({ ask: true }), { hostAttached: false })).toEqual(asking);
82
+ });
83
+
84
+ test("--no-ask leaves a profile other than local as it is", () => {
85
+ for (const profile of ["pod", "review", "web"] as const) {
86
+ const plain = AkanCodeRunner.profileOf(runOptions({ profile }), { hostAttached: true });
87
+ expect(AkanCodeRunner.profileOf(runOptions({ profile, ask: false }), { hostAttached: true })).toEqual(plain);
88
+ }
89
+ });
90
+
91
+ test("a session started with --no-ask says once that it runs commands and network requests without asking", () => {
92
+ const local = codeAgentPresets.local("/w");
93
+ const lines = AkanCodeRunner.startWarnings(local, true).filter((line) => line.includes("not a sandbox"));
94
+ expect(lines).toHaveLength(1);
95
+ expect(lines[0]).toStartWith("--no-ask: this session runs shell commands and network requests without asking.");
96
+ expect(AkanCodeRunner.startWarnings(local).join(" ")).not.toContain("--no-ask");
97
+ expect(AkanCodeRunner.startWarnings(codeAgentPresets.pod("/w"), true)).toEqual(
98
+ AkanCodeRunner.startWarnings(codeAgentPresets.pod("/w")),
99
+ );
100
+ });
101
+
102
+ test("the local profile warns at start that it is not a sandbox, and a pod does not", () => {
103
+ expect(AkanCodeRunner.startWarnings(codeAgentPresets.local("/w")).join(" ")).toContain("not a sandbox");
104
+ expect(AkanCodeRunner.startWarnings(codeAgentPresets.pod("/w"))).toEqual([]);
105
+ });
106
+ });
107
+
108
+ describe("AkanCodeRunner.trust", () => {
109
+ const repo = () => {
110
+ const root = mkdtempSync(path.join(tmpdir(), "akan-code-trust-"));
111
+ mkdirSync(path.join(root, ".akan", "code"), { recursive: true });
112
+ writeFileSync(
113
+ path.join(root, ".akan", "code", "mcp.json"),
114
+ JSON.stringify({ mcpServers: { tool: { command: "node", args: ["x.js"] } } }),
115
+ );
116
+ return root;
117
+ };
118
+
119
+ const terminal = (answer: string | null) => {
120
+ const input = new PassThrough();
121
+ const output = new PassThrough();
122
+ let shown = "";
123
+ output.on("data", (chunk: Buffer) => {
124
+ shown += chunk.toString();
125
+ });
126
+ if (answer === null) input.end();
127
+ else input.write(answer);
128
+ return { streams: { input, output }, shown: () => shown };
129
+ };
130
+
131
+ test("a yes at the terminal is remembered until the content changes", async () => {
132
+ const root = repo();
133
+ try {
134
+ const { streams, shown } = terminal("y\n");
135
+ expect(
136
+ await AkanCodeRunner.trust(root, codeAgentPresets.local(root), { trustWorkspace: false, streams }),
137
+ ).toEqual([]);
138
+ expect(shown()).toContain("tool: node x.js");
139
+ expect(WorkspaceTrust.pending(root)).toEqual([]);
140
+ } finally {
141
+ rmSync(root, { recursive: true, force: true });
142
+ }
143
+ });
144
+
145
+ test("a no, a closed input or no terminal at all leaves them unstarted and says how to start them", async () => {
146
+ const root = repo();
147
+ try {
148
+ const profile = codeAgentPresets.local(root);
149
+ for (const answer of ["n\n", "\n", null]) {
150
+ const { streams } = terminal(answer);
151
+ expect(await AkanCodeRunner.trust(root, profile, { trustWorkspace: false, streams })).toEqual([
152
+ CodeTrustPrompt.skipped(WorkspaceTrust.pending(root)),
153
+ ]);
154
+ }
155
+ const [warning] = await AkanCodeRunner.trust(root, profile, { trustWorkspace: false });
156
+ expect(warning).toContain("--trust-workspace");
157
+ expect(WorkspaceTrust.isTrusted(root, "mcp")).toBe(false);
158
+ } finally {
159
+ rmSync(root, { recursive: true, force: true });
160
+ }
161
+ });
162
+
163
+ test("--trust-workspace starts them for this run without writing anything down", async () => {
164
+ const root = repo();
165
+ try {
166
+ expect(await AkanCodeRunner.trust(root, codeAgentPresets.local(root), { trustWorkspace: true })).toEqual([]);
167
+ expect(WorkspaceTrust.isTrusted(root, "mcp")).toBe(true);
168
+ } finally {
169
+ rmSync(root, { recursive: true, force: true });
170
+ }
171
+ });
172
+
173
+ test("a profile with MCP off is not asked about servers it would never start", async () => {
174
+ const root = repo();
175
+ try {
176
+ expect(await AkanCodeRunner.trust(root, codeAgentPresets.pod(root), { trustWorkspace: false })).toEqual([]);
177
+ } finally {
178
+ rmSync(root, { recursive: true, force: true });
179
+ }
180
+ });
181
+ });
@@ -0,0 +1,33 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const engineFiles = ["agent/CodeAgent", "agent/CodeAgentRpcHost", "agent/CodeAgentRpcListener", "tui/CodeTui"];
6
+
7
+ describe("host module graph", () => {
8
+ // `serve` swaps the console out before the engine loads, so the entry the CLI imports reaches no engine module.
9
+ test("nothing statically reachable from the host entry imports the engine", async () => {
10
+ const root = path.resolve(import.meta.dir, "..");
11
+ const seen = new Set<string>();
12
+ const offenders: string[] = [];
13
+ const visit = async (file: string) => {
14
+ if (seen.has(file)) return;
15
+ seen.add(file);
16
+ const source = await Bun.file(file).text();
17
+ // `import type` is erased before the module ever loads, so only value imports count as a static path.
18
+ const specifiers = [
19
+ ...source.matchAll(/^\s*(?:import|export)\s+(?!type[\s{])(?:[^"';]*?\bfrom\s*)?["']([^"']+)["']/gm),
20
+ ].map((m) => m[1] ?? "");
21
+ const relative = path.relative(root, file).replace(/\.tsx?$/, "");
22
+ if (engineFiles.includes(relative) || specifiers.some((s) => s.startsWith("@earendil-works/")))
23
+ offenders.push(relative);
24
+ for (const specifier of specifiers.filter((s) => s.startsWith("."))) {
25
+ const base = path.resolve(path.dirname(file), specifier);
26
+ await visit([`${base}.ts`, `${base}.tsx`].find((candidate) => existsSync(candidate)) ?? `${base}.ts`);
27
+ }
28
+ };
29
+ await visit(path.join(import.meta.dir, "index.ts"));
30
+ expect(offenders).toEqual([]);
31
+ expect(seen.size).toBeGreaterThan(3);
32
+ });
33
+ });
package/host/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type { AkanCatalogTool, AkanToolCatalog, AkanToolMode } from "../tools/AkanToolPack";
2
+ export * from "./AkanCodeRunner";
package/index.ts ADDED
@@ -0,0 +1,49 @@
1
+ // Importing this barrel loads the engine (~122MiB resident); a host needing cheap pieces imports the owning module.
2
+ // agent/consoleToStderr is deliberately absent: it takes over globalThis.console, so an RPC entry imports it first.
3
+ // `CodeTui` is left out on purpose: it pulls in Ink and React, which an embedder of the core should not pay for.
4
+ export { akanCodePaths } from "@akanjs/devkit/codeAgent";
5
+ export * from "@akanjs/devkit/preview";
6
+ export * from "./agent/AkanCodeCompaction";
7
+ export * from "./agent/AkanCodeServices";
8
+ export * from "./agent/akanCodeModel";
9
+ export * from "./agent/akanSystemPrompt";
10
+ export * from "./agent/CodeAgent";
11
+ export * from "./agent/CodeAgentAsks";
12
+ export * from "./agent/CodeAgentEventMapper";
13
+ export * from "./agent/CodeAgentGate";
14
+ export * from "./agent/CodeAgentRpcHost";
15
+ export * from "./agent/CodeAgentStreamPrinter";
16
+ export * from "./agent/CodeAgentUi";
17
+ export * from "./agent/CodeMailbox";
18
+ export * from "./agent/CodeSessionFork";
19
+ export * from "./agent/CodeSessionIndex";
20
+ export * from "./agent/SubagentPool";
21
+ export * from "./feedback/DevLogFeedback";
22
+ export * from "./feedback/PreviewFeedback";
23
+ export * from "./feedback/TurnFeedback";
24
+ export * from "./feedback/VerifyFeedback";
25
+ export * from "./tools/AkanCli";
26
+ export * from "./tools/AkanCodePlugins";
27
+ export * from "./tools/AkanEditScope";
28
+ export * from "./tools/AkanEnvKeys";
29
+ export * from "./tools/AkanToolPack";
30
+ export * from "./tools/AkanVerifier";
31
+ export * from "./tools/MailToolPack";
32
+ export * from "./tools/McpClient";
33
+ export * from "./tools/McpToolPack";
34
+ export * from "./tools/SessionToolPack";
35
+ export * from "./tools/WebToolPack";
36
+ export { CodeTuiAgents } from "./tui/CodeTuiAgents";
37
+ export { CodeTuiClipboard } from "./tui/CodeTuiClipboard";
38
+ export { type CodeTuiCommand, CodeTuiCommands } from "./tui/CodeTuiCommands";
39
+ export { CodeTuiEditor, type CodeTuiEditorLayout, type CodeTuiEditorRow } from "./tui/CodeTuiEditor";
40
+ export { CodeTuiFiles } from "./tui/CodeTuiFiles";
41
+ export {
42
+ type CodeTuiLine,
43
+ CodeTuiLines,
44
+ type CodeTuiRow,
45
+ type CodeTuiSpan,
46
+ type CodeTuiStyle,
47
+ } from "./tui/CodeTuiLines";
48
+ export { CodeTuiMarkdown } from "./tui/CodeTuiMarkdown";
49
+ export { CodeTuiParts, type CodeTuiPartsOptions } from "./tui/CodeTuiParts";
package/package.json CHANGED
@@ -1,18 +1,52 @@
1
1
  {
2
2
  "name": "@akanjs/code",
3
- "version": "0.0.0",
4
- "description": "Placeholder that reserves the name. The coding agent behind `akan code` ships from 3.3.0-rc.70; install it at the version of @akanjs/cli.",
3
+ "version": "3.3.0-rc.71",
4
+ "sourceType": "module",
5
+ "type": "module",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "description": "The coding agent behind `akan code`: its engine, tools and terminal UI. Install it at the version of @akanjs/cli.",
10
+ "homepage": "https://akanjs.com",
5
11
  "license": "MIT",
6
12
  "repository": {
7
13
  "type": "git",
8
14
  "url": "https://github.com/akan-team/akanjs.git",
9
15
  "directory": "pkgs/@akanjs/code"
10
16
  },
11
- "homepage": "https://akanjs.com",
12
- "publishConfig": {
13
- "access": "public"
17
+ "engines": {
18
+ "bun": ">=1.4.4"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "import": "./index.ts",
23
+ "types": "./index.ts",
24
+ "default": "./index.ts"
25
+ },
26
+ "./host": {
27
+ "import": "./host/index.ts",
28
+ "types": "./host/index.ts",
29
+ "default": "./host/index.ts"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "dependencies": {
34
+ "@akanjs/devkit": "3.3.0-rc.71",
35
+ "@earendil-works/pi-agent-core": "1.5.2",
36
+ "@earendil-works/pi-ai": "1.5.2",
37
+ "@earendil-works/pi-codemode": "1.5.2",
38
+ "@earendil-works/pi-coding-agent": "1.5.2",
39
+ "@earendil-works/pi-mcp": "1.5.2",
40
+ "@earendil-works/pi-tui": "1.5.2",
41
+ "akanjs": "3.3.0-rc.71",
42
+ "chalk": "^6.0.1",
43
+ "ink": "^6.8.0",
44
+ "react": "19.3.1",
45
+ "string-width": "^8.3.0",
46
+ "typebox": "1.3.37"
14
47
  },
15
- "files": [
16
- "README.md"
17
- ]
18
- }
48
+ "devDependencies": {},
49
+ "bun": {
50
+ "platform": "bun"
51
+ }
52
+ }
@@ -0,0 +1,45 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import type { PackageJson } from "@akanjs/devkit/workspace/types";
4
+
5
+ //? PackageRunner re-declares pi's sibling pins because neither our `overrides` nor pi's own ranges reach a
6
+ //? consumer's install. The source of truth is pi's `dependencies`: since 1.3.0 it pins every sibling exactly, where
7
+ //? 0.86.1 floated `^0.86.1` and only the (now removed) `npm-shrinkwrap.json` held the resolved version.
8
+
9
+ const repoRoot = path.resolve(import.meta.dir, "../../..");
10
+ const piName = "@earendil-works/pi-coding-agent";
11
+ const piDir = `${repoRoot}/node_modules/${piName}`;
12
+ const publishedPackages = ["pkgs/@akanjs/code/package.json"];
13
+
14
+ const readJson = async <T>(file: string) => (await Bun.file(file).json()) as T;
15
+
16
+ const siblingEntries = async () => {
17
+ const { dependencies = {} } = await readJson<PackageJson>(`${piDir}/package.json`);
18
+ return Object.entries(dependencies).filter(([name]) => /^@earendil-works\/[^/]+$/.test(name));
19
+ };
20
+
21
+ describe("pi dependency pins", () => {
22
+ test("the package read here belongs to the coding agent we publish", async () => {
23
+ const installed = await readJson<PackageJson>(`${piDir}/package.json`);
24
+ for (const file of publishedPackages) {
25
+ const { dependencies = {} } = await readJson<PackageJson>(`${repoRoot}/${file}`);
26
+ expect({ file, [piName]: dependencies[piName] }).toEqual({ file, [piName]: installed.version });
27
+ }
28
+ });
29
+
30
+ test("the coding agent pins each sibling exactly", async () => {
31
+ const siblings = await siblingEntries();
32
+ expect(siblings.length).toBeGreaterThan(0);
33
+ const floating = siblings.filter(([, version]) => !/^\d+\.\d+\.\d+/.test(version));
34
+ expect(floating).toEqual([]);
35
+ });
36
+
37
+ test("every sibling pi package is published at the version the coding agent pins", async () => {
38
+ const siblings = await siblingEntries();
39
+ for (const file of publishedPackages) {
40
+ const { dependencies = {} } = await readJson<PackageJson>(`${repoRoot}/${file}`);
41
+ const declared = Object.fromEntries(siblings.map(([name]) => [name, dependencies[name]]));
42
+ expect({ file, ...declared }).toEqual({ file, ...Object.fromEntries(siblings) });
43
+ }
44
+ });
45
+ });
@@ -0,0 +1,3 @@
1
+ // Ink reads CI once at import and then writes no frame until unmount, so the terminal suites would read empty frames.
2
+ delete process.env.CI;
3
+ delete process.env.CONTINUOUS_INTEGRATION;
@@ -0,0 +1,56 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { stripAnsi } from "@akanjs/devkit/util/stripAnsi";
4
+
5
+ export interface AkanCliResult {
6
+ command: string;
7
+ ok: boolean;
8
+ exitCode: number;
9
+ output: string;
10
+ }
11
+
12
+ // A subprocess: the akan runners print to inherited stdio and return nothing; it also isolates their crashes.
13
+ export class AkanCli {
14
+ readonly #cwd: string;
15
+ readonly #entry: string;
16
+
17
+ constructor(cwd: string) {
18
+ this.#cwd = cwd;
19
+ this.#entry = AkanCli.#resolveEntry(cwd);
20
+ }
21
+
22
+ async run(args: string[], { timeoutMs = 300_000 }: { timeoutMs?: number } = {}): Promise<AkanCliResult> {
23
+ const proc = Bun.spawn([process.execPath, this.#entry, ...args], {
24
+ cwd: this.#cwd,
25
+ stdout: "pipe",
26
+ stderr: "pipe",
27
+ //? A workspace .env's AKAN_PUBLIC_LOG_LEVEL=verbose reaches the child too, and buried its error under 90 lines.
28
+ env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1", AKAN_LOG_STDOUT_LEVEL: "warn" },
29
+ });
30
+ const timer = setTimeout(() => proc.kill(), timeoutMs);
31
+ const [stdout, stderr, exitCode] = await Promise.all([
32
+ new Response(proc.stdout).text(),
33
+ new Response(proc.stderr).text(),
34
+ proc.exited,
35
+ ]);
36
+ clearTimeout(timer);
37
+ // tsgo colours regardless of NO_COLOR, and escape sequences are tokens the model pays for and cannot read.
38
+ const output = stripAnsi(`${stdout}${stderr}`).trim();
39
+ return { command: `akan ${args.join(" ")}`, ok: exitCode === 0, exitCode, output };
40
+ }
41
+
42
+ //? Bun.main is the akan that started this agent; a host embedding the engine is not one, so it gets the workspace's.
43
+ static #resolveEntry(cwd: string) {
44
+ const manifest = path.join(path.dirname(Bun.main), "package.json");
45
+ if (
46
+ existsSync(manifest) &&
47
+ (JSON.parse(readFileSync(manifest, "utf8")) as { name?: string }).name === "@akanjs/cli"
48
+ )
49
+ return Bun.main;
50
+ try {
51
+ return Bun.resolveSync("@akanjs/cli", cwd);
52
+ } catch {
53
+ return Bun.main;
54
+ }
55
+ }
56
+ }
@@ -0,0 +1,145 @@
1
+ import type { Workspace } from "@akanjs/devkit/commandDecorators";
2
+ import { PreviewView } from "@akanjs/devkit/preview";
3
+ import type { InlineExtension } from "@earendil-works/pi-coding-agent";
4
+ import type { CodeAgentMcpStatus, CodeAgentProfile, CodeAgentQuestion, CodeAgentSubagent } from "akanjs/common";
5
+ import type { CodeAgentModelRef } from "../agent/akanCodeModel";
6
+ import type { CodeMailbox } from "../agent/CodeMailbox";
7
+ import { SubagentPool, type SubagentSpend } from "../agent/SubagentPool";
8
+ import { DevLogFeedback } from "../feedback/DevLogFeedback";
9
+ import { PreviewFeedback } from "../feedback/PreviewFeedback";
10
+ import { TurnFeedback, type TurnFeedbackSource } from "../feedback/TurnFeedback";
11
+ import { VerifyFeedback } from "../feedback/VerifyFeedback";
12
+ import { type AkanToolCatalog, AkanToolPack } from "./AkanToolPack";
13
+ import { AskToolPack } from "./AskToolPack";
14
+ import type { DeepSeekWeb } from "./DeepSeekWeb";
15
+ import { MailToolPack } from "./MailToolPack";
16
+ import { McpToolPack } from "./McpToolPack";
17
+ import { SessionToolPack } from "./SessionToolPack";
18
+ import { WebToolPack } from "./WebToolPack";
19
+
20
+ export interface AkanCodePluginsOptions {
21
+ workspace: Workspace;
22
+ cwd: string;
23
+ profile: CodeAgentProfile;
24
+ /** Apps whose dev server should be watched, and whose page should be probed. */
25
+ apps: string[];
26
+ catalog?: AkanToolCatalog;
27
+ canSeeImages: boolean;
28
+ /** The owning agent's model as it is now; a `task` child runs on it. */
29
+ model?: () => CodeAgentModelRef | undefined;
30
+ deepseek?: DeepSeekWeb | undefined;
31
+ /** How many `task` levels deep the owning agent is. */
32
+ depth: number;
33
+ /** The tally of the sub-agent tree the owning agent belongs to, when a `task` opened it. */
34
+ subagentSpend?: SubagentSpend;
35
+ /** Reading the current session back would spend its own window twice, so it is excluded from search. */
36
+ currentSessionId: () => string;
37
+ /** Late, because the session this announces to its peers does not exist yet when the pack is built. */
38
+ mailbox: () => CodeMailbox | undefined;
39
+ onNotice?: (message: string) => void;
40
+ onAgents?: (agents: CodeAgentSubagent[]) => void;
41
+ /** How `ask_user` reaches the person. Absent on a host that has nobody to reach. */
42
+ onAsk?: (question: Omit<CodeAgentQuestion, "questionId">) => Promise<string | undefined>;
43
+ }
44
+
45
+ export interface AkanCodePluginsResult {
46
+ extensions: InlineExtension[];
47
+ /** Names the session's tool allowlist has to carry, or the model is told these tools do not exist. */
48
+ toolNames: string[];
49
+ /** Every declared MCP server and what it published, including the ones that published nothing. */
50
+ mcp: CodeAgentMcpStatus[];
51
+ /** Closes anything the pack holds open — currently the MCP server connections. */
52
+ dispose: () => void;
53
+ }
54
+
55
+ // Gated at assembly, not at call time: a capability the profile excludes is never built and costs no prompt tokens.
56
+ export class AkanCodePlugins {
57
+ static async build(options: AkanCodePluginsOptions): Promise<AkanCodePluginsResult> {
58
+ const mcp = await McpToolPack.connect({
59
+ workspaceRoot: options.workspace.workspaceRoot,
60
+ profile: options.profile,
61
+ ...(options.onNotice ? { onNotice: options.onNotice } : {}),
62
+ });
63
+ const dispose = () => mcp?.close();
64
+ const mcpStatus = mcp?.status ?? [];
65
+ const web = new WebToolPack({ profile: options.profile, deepseek: options.deepseek });
66
+ const sessions = new SessionToolPack({
67
+ workspaceRoot: options.workspace.workspaceRoot,
68
+ cwd: options.cwd,
69
+ profile: options.profile,
70
+ currentSessionId: options.currentSessionId,
71
+ });
72
+ const mail = new MailToolPack({ profile: options.profile, mailbox: options.mailbox });
73
+ const onAsk = options.onAsk;
74
+ const ask = onAsk ? new AskToolPack({ profile: options.profile, ask: onAsk }) : undefined;
75
+ const shared = {
76
+ extensions: [mcp?.extension(), web.extension(), sessions.extension(), mail.extension(), ask?.extension()].filter(
77
+ (entry) => !!entry,
78
+ ),
79
+ toolNames: [
80
+ ...(mcp?.toolNames ?? []),
81
+ ...web.names(),
82
+ ...sessions.names(),
83
+ ...mail.names(),
84
+ ...(ask?.names() ?? []),
85
+ ],
86
+ };
87
+ if (!options.profile.tools.akan) return { ...shared, mcp: mcpStatus, dispose };
88
+ const readOnly = !options.profile.tools.builtin.includes("write");
89
+ const pack = new AkanToolPack({
90
+ workspace: options.workspace,
91
+ cwd: options.cwd,
92
+ mode: readOnly ? "readonly" : "apply",
93
+ ...(options.catalog ? { catalog: options.catalog } : {}),
94
+ });
95
+ const extensions: InlineExtension[] = [pack.extension()];
96
+ const subagent = SubagentPool.extensionFor({
97
+ workspace: options.workspace,
98
+ cwd: options.cwd,
99
+ parent: options.profile,
100
+ ...(options.model ? { model: options.model } : {}),
101
+ ...(options.catalog ? { catalog: options.catalog } : {}),
102
+ depth: options.depth,
103
+ ...(options.subagentSpend ? { spend: options.subagentSpend } : {}),
104
+ ...(options.onNotice ? { onNotice: options.onNotice } : {}),
105
+ ...(options.onAgents ? { onAgents: options.onAgents } : {}),
106
+ });
107
+ if (subagent) extensions.push(subagent);
108
+ const sources = await AkanCodePlugins.#sources(options, readOnly);
109
+ if (sources.length)
110
+ extensions.push(
111
+ new TurnFeedback(sources, {
112
+ budget: options.profile.limits.feedback,
113
+ ...(options.onNotice ? { onNotice: options.onNotice } : {}),
114
+ }).extension(),
115
+ );
116
+ return {
117
+ extensions: [...extensions, ...shared.extensions],
118
+ toolNames: [...(await pack.names()), ...(subagent ? [SubagentPool.toolName] : []), ...shared.toolNames],
119
+ mcp: mcpStatus,
120
+ dispose,
121
+ };
122
+ }
123
+
124
+ static async #sources(options: AkanCodePluginsOptions, readOnly: boolean): Promise<TurnFeedbackSource[]> {
125
+ const sources: TurnFeedbackSource[] = [
126
+ new VerifyFeedback({ cwd: options.cwd, readOnly }),
127
+ new DevLogFeedback({ workspaceRoot: options.workspace.workspaceRoot, cwd: options.cwd, apps: options.apps }),
128
+ ];
129
+ const previewUrl = await AkanCodePlugins.#previewUrl(options);
130
+ if (!previewUrl) return sources;
131
+ // Said once here, or a UI turn silently skips its only visual check and reads as a clean run.
132
+ const reason = PreviewView.unavailableReason();
133
+ if (reason) options.onNotice?.(reason);
134
+ else sources.push(new PreviewFeedback({ cwd: options.cwd, previewUrl, canSeeImages: options.canSeeImages }));
135
+ return sources;
136
+ }
137
+
138
+ static async #previewUrl(options: AkanCodePluginsOptions) {
139
+ for (const app of options.apps) {
140
+ const url = await DevLogFeedback.previewUrl(options.workspace.workspaceRoot, app);
141
+ if (url) return url;
142
+ }
143
+ return undefined;
144
+ }
145
+ }
@@ -0,0 +1,53 @@
1
+ export interface AkanEditScopeResult {
2
+ paths: string[];
3
+ apps: string[];
4
+ libs: string[];
5
+ pkgs: string[];
6
+ /** A created, deleted or renamed file under `apps/**` or `libs/**` — the only kind a barrel has to catch up with. */
7
+ needsSync: boolean;
8
+ touchesTsx: boolean;
9
+ }
10
+
11
+ const empty: AkanEditScopeResult = { paths: [], apps: [], libs: [], pkgs: [], needsSync: false, touchesTsx: false };
12
+
13
+ // Read from git, not tool events: an edit made through `bash` (a heredoc, sed, a codemod) produces no write tool call.
14
+ export class AkanEditScope {
15
+ static async since(cwd: string, baseline: ReadonlySet<string>): Promise<AkanEditScopeResult> {
16
+ const current = await AkanEditScope.baseline(cwd);
17
+ const changed = [...current].filter((line) => !baseline.has(line));
18
+ if (!changed.length) return empty;
19
+ const entries = changed.map((line) => ({ code: line.slice(0, 2), file: line.slice(3).split(" -> ").at(-1) ?? "" }));
20
+ const paths = entries.map((entry) => entry.file).filter(Boolean);
21
+ return {
22
+ paths,
23
+ apps: AkanEditScope.#targets(paths, "apps"),
24
+ libs: AkanEditScope.#targets(paths, "libs"),
25
+ pkgs: AkanEditScope.#targets(paths, "pkgs"),
26
+ needsSync: entries.some((entry) => /[ARD?]/.test(entry.code) && /^(apps|libs)\//.test(entry.file)),
27
+ touchesTsx: paths.some((file) => file.endsWith(".tsx")),
28
+ };
29
+ }
30
+
31
+ /** The porcelain lines before a turn, so the turn is judged on what it changed rather than on a dirty tree. */
32
+ static async baseline(cwd: string) {
33
+ const proc = Bun.spawn(["git", "status", "--porcelain=v1", "--untracked-files=all"], {
34
+ cwd,
35
+ stdout: "pipe",
36
+ stderr: "ignore",
37
+ });
38
+ const text = await new Response(proc.stdout).text();
39
+ await proc.exited;
40
+ return new Set(text.split("\n").filter((line) => line.trim().length > 3));
41
+ }
42
+
43
+ static #targets(paths: string[], root: "apps" | "libs" | "pkgs") {
44
+ const names = paths
45
+ .filter((file) => file.startsWith(`${root}/`))
46
+ .map((file) => {
47
+ const [, first = "", second = ""] = file.split("/");
48
+ return first.startsWith("@") && second ? `${first}/${second}` : first;
49
+ })
50
+ .filter(Boolean);
51
+ return [...new Set(names)];
52
+ }
53
+ }