@akanjs/devkit 3.3.0-rc.69 → 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 (101) hide show
  1. package/README.ko.md +2 -1
  2. package/README.md +2 -1
  3. package/akanApp/akanApp.host.ts +15 -2
  4. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  5. package/akanApp/devHostPolicy.ts +5 -0
  6. package/akanApp/devMetadataRestart.ts +93 -0
  7. package/akanApp/devRecycler.test.ts +2 -0
  8. package/akanApp/devRecycler.ts +9 -0
  9. package/codeAgent/index.ts +1 -34
  10. package/codeAgent/skills/akan-page/SKILL.md +9 -4
  11. package/codeAgent/skills/akan-service/SKILL.md +11 -9
  12. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  13. package/executors/executors.test.ts +15 -0
  14. package/executors/pkgExecutor.ts +2 -1
  15. package/frontendBuild/csrDevPatcher.test.ts +3 -4
  16. package/frontendBuild/csrDevPatcher.ts +4 -4
  17. package/frontendBuild/devChangePlanner.ts +0 -1
  18. package/frontendBuild/frontendBuild.test.ts +5 -3
  19. package/frontendBuild/ssrBaseArtifactBuilder.ts +12 -7
  20. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  21. package/frontendBuild/vendorNarrowing.ts +10 -2
  22. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  23. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  24. package/incrementalBuilder/builderWatch.ts +11 -1
  25. package/incrementalBuilder/incrementalBuilder.proc.test.ts +80 -0
  26. package/incrementalBuilder/incrementalBuilder.proc.ts +11 -2
  27. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  28. package/incrementalBuilder/pendingMetadata.ts +19 -0
  29. package/integration/devStability.integration.test.ts +46 -21
  30. package/package.json +5 -10
  31. package/packageExports.test.ts +3 -2
  32. package/test/fakeTerminal.ts +45 -0
  33. package/tunnel/ssh2Module.ts +2 -6
  34. package/util/devInstallCommand.ts +7 -0
  35. package/workspace/slicePlanner.ts +1 -0
  36. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  37. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  38. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  39. package/codeAgent/agent/CodeAgent.ts +0 -626
  40. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  41. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  42. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  43. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  44. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  45. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  46. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  47. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  48. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  49. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  50. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  51. package/codeAgent/agent/CodeMailbox.ts +0 -148
  52. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  53. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  54. package/codeAgent/agent/SubagentPool.ts +0 -219
  55. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  56. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  57. package/codeAgent/agent/akanCodeModel.ts +0 -47
  58. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  59. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  60. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  61. package/codeAgent/agent/codeAgent.test.ts +0 -337
  62. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  63. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  64. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  65. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  66. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  67. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  68. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  69. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  70. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  71. package/codeAgent/agent/consoleToStderr.ts +0 -8
  72. package/codeAgent/agent/jsonLines.ts +0 -29
  73. package/codeAgent/agent/stringArg.ts +0 -5
  74. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  75. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  76. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  77. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  78. package/codeAgent/tools/AkanCli.ts +0 -51
  79. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  80. package/codeAgent/tools/AkanEditScope.ts +0 -53
  81. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  82. package/codeAgent/tools/AkanToolPack.ts +0 -86
  83. package/codeAgent/tools/AkanVerifier.ts +0 -30
  84. package/codeAgent/tools/AskToolPack.ts +0 -99
  85. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  86. package/codeAgent/tools/MailToolPack.ts +0 -76
  87. package/codeAgent/tools/McpClient.ts +0 -209
  88. package/codeAgent/tools/McpOAuth.ts +0 -233
  89. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  90. package/codeAgent/tools/McpServerConfig.ts +0 -131
  91. package/codeAgent/tools/McpSignIn.ts +0 -158
  92. package/codeAgent/tools/McpTokenStore.ts +0 -128
  93. package/codeAgent/tools/McpToolPack.ts +0 -206
  94. package/codeAgent/tools/SessionToolPack.ts +0 -91
  95. package/codeAgent/tools/WebToolPack.ts +0 -315
  96. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  97. package/codeAgent/tools/askToolPack.test.ts +0 -116
  98. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  99. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  100. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  101. package/piDependencyPins.test.ts +0 -45
@@ -724,6 +724,86 @@ else {
724
724
  }
725
725
  }, 60_000);
726
726
 
727
+ test("a signal save rides every pages batch until one builds green, through the builder that saw it", async () => {
728
+ const { root } = track(await createTempApp("demo"));
729
+ const appDir = path.join(root, "apps/demo");
730
+ const ledger = path.join(root, "batches.log");
731
+ const tries = path.join(root, "metadata-tries");
732
+ // A stand-in batch: the first pages build carrying metadata fails, the second builds its pages but not its SSR
733
+ // registry, and every batch logs the metadata it carried.
734
+ await writeText(
735
+ path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
736
+ `import fs from "node:fs";
737
+ import path from "node:path";
738
+ const { generation, needs, metadata } = JSON.parse(process.argv[2]);
739
+ fs.appendFileSync(${JSON.stringify(ledger)}, needs.join(",") + " " + (metadata ?? []).map((file) => path.basename(file)).join(",") + "\\n");
740
+ const carried = needs.includes("pages") && !!metadata;
741
+ const tried = carried && fs.existsSync(${JSON.stringify(tries)}) ? fs.readFileSync(${JSON.stringify(tries)}, "utf8").length : 0;
742
+ if (carried) fs.appendFileSync(${JSON.stringify(tries)}, "x");
743
+ const errors = !carried ? {} : tried === 0 ? { pages: "the pages build is broken" } : tried === 1 ? { ssr: "the SSR registry is broken" } : {};
744
+ process.once("disconnect", () => {});
745
+ if (needs.includes("pages")) process.send({ type: "build-status", data: { generation, phase: "pages", ok: !errors.pages, files: [] } });
746
+ process.send({ type: "build-batch-result", data: { generation, errors, artifact: {}, optimizedFonts: { css: "", files: [] } } });
747
+ `,
748
+ );
749
+ const page = path.join(appDir, "page/_index.tsx");
750
+ const signal = path.join(appDir, "lib/demo/demo.signal.ts");
751
+ await writeText(page, "export default () => null;\n");
752
+ await writeText(signal, "export const signal = 0;\n");
753
+ await writeText(
754
+ path.join(appDir, "tsconfig.json"),
755
+ JSON.stringify({ compilerOptions: { target: "ESNext", paths: { "@apps/*": ["./apps/*"] } } }),
756
+ );
757
+ const messages: BuilderMessage[] = [];
758
+ const proc = Bun.spawn(["bun", path.join(import.meta.dir, "incrementalBuilder.proc.ts")], {
759
+ cwd: appDir,
760
+ env: {
761
+ ...process.env,
762
+ AKAN_WORKSPACE_ROOT: root,
763
+ AKAN_PUBLIC_APP_NAME: "demo",
764
+ AKAN_PUBLIC_REPO_NAME: "repo",
765
+ AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
766
+ AKAN_PUBLIC_ENV: "local",
767
+ AKAN_DEV_CSR_PATCHER: "off",
768
+ },
769
+ stdio: ["ignore", "ignore", "ignore"],
770
+ serialization: "advanced",
771
+ ipc: (message: BuilderMessage) => {
772
+ messages.push(message);
773
+ },
774
+ });
775
+ const pagesBatches = async () =>
776
+ (
777
+ await Bun.file(ledger)
778
+ .text()
779
+ .catch(() => "")
780
+ )
781
+ .split("\n")
782
+ .filter((line) => line.split(" ")[0]?.split(",").includes("pages"))
783
+ .map((line) => line.split(" ")[1] ?? "");
784
+ const pagesStatuses = () =>
785
+ messages.flatMap((message) =>
786
+ message.type === "build-status" && message.data.phase === "pages" ? [message.data.ok] : [],
787
+ );
788
+ try {
789
+ await until(proc, "boot-armed", () => messages.some((message) => message.type === "boot-armed"));
790
+ await writeText(signal, "export const signal = 1;\n");
791
+ await until(proc, "the signal save's pages status", () => pagesStatuses().length === 1);
792
+ await writeText(page, "export default () => 1;\n");
793
+ await until(proc, "the next save's pages status", () => pagesStatuses().length === 2);
794
+ await writeText(page, "export default () => 2;\n");
795
+ await until(proc, "the third save's pages status", () => pagesStatuses().length === 3);
796
+ await writeText(page, "export default () => 3;\n");
797
+ await until(proc, "the fourth save's pages status", () => pagesStatuses().length === 4);
798
+ } finally {
799
+ proc.kill();
800
+ await proc.exited;
801
+ }
802
+ expect(pagesStatuses()).toEqual([false, true, true, true]);
803
+ expect(await pagesBatches()).toEqual(["demo.signal.ts", "demo.signal.ts", "demo.signal.ts", ""]);
804
+ expect(messages.filter((message) => message.type === "builder-ready")).toHaveLength(1);
805
+ }, 60_000);
806
+
727
807
  test("a failed boot build waits for the save that fixes it, and the builder it recovers continues the generation and watches", async () => {
728
808
  const { root } = track(await createTempApp("demo"));
729
809
  const appDir = path.join(root, "apps/demo");
@@ -29,6 +29,7 @@ import { BuilderLanes } from "./builderLanes";
29
29
  import { BuilderWatch } from "./builderWatch";
30
30
  import type { BatchJob, DiscoveryJob } from "./builderWorkQueue";
31
31
  import { CsrRegistry } from "./csrRegistry";
32
+ import { PendingMetadata } from "./pendingMetadata";
32
33
  import { SsrRegistry } from "./ssrRegistry";
33
34
 
34
35
  class IncrementalBuilder {
@@ -47,6 +48,7 @@ class IncrementalBuilder {
47
48
  readonly #delegations = new Map<string, number>();
48
49
  //? A route build bundles only entries no earlier route built: the dictionary walk reads every build's graph.
49
50
  readonly #dictionaryGraph = new Map<string, readonly ClientModuleImport[]>();
51
+ readonly #metadata = new PendingMetadata();
50
52
  readonly #lanes: BuilderLanes;
51
53
  readonly #csr: CsrRegistry;
52
54
  readonly #ssr: SsrRegistry;
@@ -86,7 +88,7 @@ class IncrementalBuilder {
86
88
  );
87
89
  this.#watcher = new BuilderWatch(
88
90
  options.app,
89
- { logger, lanes, csr: this.#csr, ssr: this.#ssr, graphPayloads: this.#graphPayloads },
91
+ { logger, lanes, csr: this.#csr, ssr: this.#ssr, graphPayloads: this.#graphPayloads, metadata: this.#metadata },
90
92
  { nextGeneration: () => ++this.#generation, refreshDiscovery: (job) => this.#refreshDiscovery(job) },
91
93
  );
92
94
  }
@@ -248,7 +250,12 @@ class IncrementalBuilder {
248
250
  async #runBatch(work: BatchWork): Promise<BuildBatchResult> {
249
251
  const { generation, needs, changedFiles } = work;
250
252
  const started = Date.now();
251
- const result = await this.#batchRunner.run(await this.#batchRequest(work), (msg) => BuilderChannel.emit(msg));
253
+ const request = await this.#batchRequest(work);
254
+ const result = await this.#batchRunner.run(request, (msg) => BuilderChannel.emit(msg));
255
+ //? A registry this batch failed to rebuild keeps the dev host's restart for a later batch, which then rewrites the
256
+ //? base artifact around its own pages bundle.
257
+ const built = !result.crashed && !result.errors.pages && !result.errors.csr && !result.errors.ssr;
258
+ if (request.metadata && built) this.#metadata.settle(generation);
252
259
  if (result.optimizedFonts) this.#optimizedFonts = result.optimizedFonts;
253
260
  if (result.cssAssets) this.#artifact = { ...this.#artifact, cssAssets: result.cssAssets };
254
261
  // A need the worker died before reporting goes red here instead of looking silently successful.
@@ -272,6 +279,7 @@ class IncrementalBuilder {
272
279
  }
273
280
 
274
281
  async #batchRequest({ generation, needs, changedFiles, trace }: BatchWork): Promise<BuildBatchRequest> {
282
+ const metadata = needs.includes("pages") ? this.#metadata.files : [];
275
283
  return {
276
284
  appName: this.#app.name,
277
285
  workspaceRoot: this.#app.workspace.workspaceRoot,
@@ -284,6 +292,7 @@ class IncrementalBuilder {
284
292
  cssAssets: this.#artifact.cssAssets ?? null,
285
293
  artifactDir: path.resolve(this.#artifactDir),
286
294
  ...(trace ? { trace } : {}),
295
+ ...(metadata.length > 0 ? { metadata } : {}),
287
296
  };
288
297
  }
289
298
 
@@ -0,0 +1,27 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { PendingMetadata } from "./pendingMetadata";
3
+
4
+ describe("PendingMetadata", () => {
5
+ test("keeps a save until a green pages build at or past it, and a save after that build for the next one", () => {
6
+ const pending = new PendingMetadata();
7
+ pending.note(["/app/lib/b/b.dictionary.ts", "/app/lib/a/a.signal.ts"], 4);
8
+ pending.note([], 5);
9
+ pending.note(["/app/lib/c/c.signal.ts"], 6);
10
+
11
+ pending.settle(3);
12
+ expect(pending.files).toEqual(["/app/lib/a/a.signal.ts", "/app/lib/b/b.dictionary.ts", "/app/lib/c/c.signal.ts"]);
13
+
14
+ pending.settle(5);
15
+ expect(pending.files).toEqual(["/app/lib/c/c.signal.ts"]);
16
+ });
17
+
18
+ test("a file saved again after the build that took it in waits for the next one", () => {
19
+ const pending = new PendingMetadata();
20
+ pending.note(["/app/lib/a/a.signal.ts"], 4);
21
+ pending.note(["/app/lib/a/a.signal.ts"], 7);
22
+
23
+ pending.settle(4);
24
+
25
+ expect(pending.files).toEqual(["/app/lib/a/a.signal.ts"]);
26
+ });
27
+ });
@@ -0,0 +1,19 @@
1
+ //* Signal and dictionary saves no batch has built green yet. Noted when the save is planned, so one whose batch never
2
+ //* built (a barrel sync error) still rides the next pages build: each pages build carrying any rebuilds the dictionary
3
+ //* assets and rewrites the base artifact the restarted backend boots on.
4
+ export class PendingMetadata {
5
+ readonly #files = new Map<string, number>();
6
+
7
+ note(files: readonly string[], generation: number): void {
8
+ for (const file of files) this.#files.set(file, generation);
9
+ }
10
+
11
+ get files(): string[] {
12
+ return [...this.#files.keys()].sort();
13
+ }
14
+
15
+ /** After a green batch of `generation`: every save noted up to it was noted before that batch started. */
16
+ settle(generation: number): void {
17
+ for (const [file, noted] of this.#files) if (noted <= generation) this.#files.delete(file);
18
+ }
19
+ }
@@ -242,17 +242,30 @@ describe("dev stability integration harness", () => {
242
242
  hmr?.close();
243
243
  });
244
244
 
245
- integrationTest("dictionary edits recycle runtime metadata and replace stale snapshots", async () => {
246
- const harness = await createHarness();
247
- const host = await harness.startHost();
248
- const hmr = await harness.tryConnectHmrProbe();
249
- await harness.waitForHttpText("initial-shared-marker", WAIT_MS);
250
- const { mark } = await harness.editUntilSeen(
251
- host,
252
- (attempt) =>
253
- harness.writeFile(
254
- "lib/_fixture/fixture.dictionary.ts",
255
- `import { serviceDictionary } from "akanjs/dictionary";
245
+ integrationTest(
246
+ "dictionary edits restart only the backend, onto dictionary assets the running builder rebuilt",
247
+ async () => {
248
+ const harness = await createHarness();
249
+ const host = await harness.startHost();
250
+ const hmr = await harness.tryConnectHmrProbe();
251
+ await harness.waitForHttpText("initial-shared-marker", WAIT_MS);
252
+ const builderPids = (since: number) => [
253
+ ...new Set(
254
+ [
255
+ ...host.logs
256
+ .join("")
257
+ .slice(since)
258
+ .matchAll(/\[IncrementalBuilder\] (\d+)/g),
259
+ ].map(([, pid]) => pid),
260
+ ),
261
+ ];
262
+ const [builderPid] = builderPids(0);
263
+ const { mark, attempts } = await harness.editUntilSeen(
264
+ host,
265
+ (attempt) =>
266
+ harness.writeFile(
267
+ "lib/_fixture/fixture.dictionary.ts",
268
+ `import { serviceDictionary } from "akanjs/dictionary";
256
269
 
257
270
  import type { FixtureEndpoint } from "./fixture.signal";
258
271
 
@@ -262,17 +275,29 @@ export const dictionary = serviceDictionary(["en", "ko"])
262
275
  hello: ["Updated Dictionary ${attempt}", "업데이트 사전 ${attempt}"],
263
276
  });
264
277
  `,
265
- ),
266
- // Each attempt recycles the builder and the backend, so patience is cheaper than a retry.
267
- { evidence: /\[dev-plan\].*actions=.*restart-builder/, attempts: 2, evidenceTimeoutMs: 30_000 },
268
- );
278
+ ),
279
+ { evidence: /\[dev-host\] runtime metadata generation=\d+/, attempts: 2, evidenceTimeoutMs: 30_000 },
280
+ );
269
281
 
270
- await host.waitForLogSince(mark, /\[dev-host\] recycling builder\/backend for runtime metadata/);
271
- await host.waitForLogSince(mark, /backend ready pid=(\d+)|AkanApp gateway is running on port/);
272
- await harness.waitForHttpText("initial-shared-marker");
273
- expect(host.proc.killed).toBe(false);
274
- hmr?.close();
275
- });
282
+ await host.waitForLogSince(mark, /\[dev-host\] runtime metadata generation=\d+ built at generation=\d+/);
283
+ await host.waitForLogSince(mark, /backend ready pid=(\d+)|AkanApp gateway is running on port/);
284
+ await harness.waitForHttpText("initial-shared-marker");
285
+ const artifact = (await Bun.file(path.join(harness.appDir, ".akan/artifact/base-artifact.json")).json()) as {
286
+ dictAssets: Record<string, { url: string; parts?: Record<string, { url: string }> }>;
287
+ };
288
+ const english = artifact.dictAssets.en;
289
+ const urls = [english?.url, ...Object.values(english?.parts ?? {}).map(({ url }) => url)].filter(Boolean);
290
+ const origin = `http://localhost:${await harness.resolvePort()}`;
291
+ const served = await Promise.all(
292
+ urls.map(async (url) => await fetch(`${origin}${url}`).then((res) => res.text())),
293
+ );
294
+ expect(served.some((text) => text.includes(`Updated Dictionary ${attempts}`))).toBe(true);
295
+ expect(host.logs.join("").slice(mark)).not.toMatch(/recycling builder\/backend/);
296
+ expect(builderPids(mark).every((pid) => pid === builderPid)).toBe(true);
297
+ expect(host.proc.killed).toBe(false);
298
+ hmr?.close();
299
+ },
300
+ );
276
301
 
277
302
  integrationTest("config edits restart the dev host and keep serving", async () => {
278
303
  const harness = await createHarness();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.69",
3
+ "version": "3.3.0-rc.70",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -41,25 +41,21 @@
41
41
  "./app/applicationBuildRunner": "./app/applicationBuildRunner.ts",
42
42
  "./cloud/cloudApi": "./cloud/cloudApi.ts",
43
43
  "./cloud/cloudUpdates": "./cloud/cloudUpdates.ts",
44
+ "./cloud/configLock": "./cloud/configLock.ts",
44
45
  "./commandDecorators/exitCodeError": "./commandDecorators/exitCodeError.ts",
45
46
  "./mobile/desktopRelease": "./mobile/desktopRelease.ts",
46
47
  "./mobile/serverBundleSecrets": "./mobile/serverBundleSecrets.ts",
47
48
  "./transforms/serverEnvProfile": "./transforms/serverEnvProfile.ts",
48
49
  "./util/fileEditor": "./util/fileEditor.ts",
49
50
  "./util/selectModel": "./util/selectModel.ts",
51
+ "./util/stripAnsi": "./util/stripAnsi.ts",
50
52
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
51
53
  },
52
54
  "dependencies": {
53
- "@akanjs/language": "3.3.0-rc.69",
54
- "@earendil-works/pi-agent-core": "1.5.2",
55
- "@earendil-works/pi-ai": "1.5.2",
56
- "@earendil-works/pi-codemode": "1.5.2",
57
- "@earendil-works/pi-coding-agent": "1.5.2",
58
- "@earendil-works/pi-mcp": "1.5.2",
59
- "@earendil-works/pi-tui": "1.5.2",
55
+ "@akanjs/language": "3.3.0-rc.70",
60
56
  "@inquirer/prompts": "^8.7.3",
61
57
  "@tailwindcss/node": "^4.3.3",
62
- "akanjs": "3.3.0-rc.69",
58
+ "akanjs": "3.3.0-rc.70",
63
59
  "chalk": "^6.0.1",
64
60
  "commander": "^15.0.0",
65
61
  "dayjs": "^1.11.23",
@@ -71,7 +67,6 @@
71
67
  "subset-font": "^2.9.0",
72
68
  "tailwind-scrollbar": "^4.0.2",
73
69
  "tailwindcss": "^4.3.3",
74
- "typebox": "1.3.37",
75
70
  "typescript": "^6.0.3"
76
71
  },
77
72
  "peerDependencies": {
@@ -14,13 +14,14 @@ const barrelFacets = async (): Promise<string[]> => {
14
14
  return [...barrel.matchAll(/^export (?:type )?\* from "\.\/([^"]+)";$/gm)].map((match) => `./${match[1]}`);
15
15
  };
16
16
 
17
- //? The CLI's dist inlines devkit: once installed, only devkit's own sources, the CLI's templates and the README
18
- //? examples a tool author copies import a subpath.
17
+ //? The CLI's dist inlines devkit: once installed, only devkit's and @akanjs/code's sources, the CLI's templates and the
18
+ //? README examples a tool author copies import a subpath.
19
19
  const importedSubpaths = async (): Promise<string[]> => {
20
20
  const repoRoot = path.resolve(packageDir, "../../..");
21
21
  const found = new Set<string>();
22
22
  const sources = [
23
23
  ...new Bun.Glob("pkgs/@akanjs/devkit/**/*.{ts,tsx}").scanSync({ cwd: repoRoot }),
24
+ ...new Bun.Glob("pkgs/@akanjs/code/**/*.{ts,tsx}").scanSync({ cwd: repoRoot }),
24
25
  ...new Bun.Glob("pkgs/@akanjs/devkit/README*.md").scanSync({ cwd: repoRoot }),
25
26
  ...new Bun.Glob("pkgs/@akanjs/cli/templates/**/*").scanSync({ cwd: repoRoot }),
26
27
  ];
@@ -0,0 +1,45 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { PassThrough } from "node:stream";
3
+
4
+ export const esc = String.fromCharCode(27);
5
+ export const csi = new RegExp(`${esc}\\[[0-9;?]*[a-zA-Z]`, "g");
6
+
7
+ export class FakeStdout extends EventEmitter {
8
+ readonly frames: string[] = [];
9
+ constructor(
10
+ readonly columns: number,
11
+ readonly rows: number,
12
+ readonly isTTY = false,
13
+ ) {
14
+ super();
15
+ }
16
+ write = (frame: string) => {
17
+ this.frames.push(frame);
18
+ return true;
19
+ };
20
+ // With a cursor position set, Ink follows each content frame with a cursor-only write.
21
+ get lastFrame() {
22
+ for (let at = this.frames.length - 1; at >= 0; at -= 1) {
23
+ const text = (this.frames[at] ?? "").replace(csi, "");
24
+ if (text.trim()) return text;
25
+ }
26
+ return "";
27
+ }
28
+ }
29
+
30
+ export const makeStdin = () => {
31
+ const stdin = new PassThrough() as PassThrough & {
32
+ isTTY: boolean;
33
+ setRawMode: (raw: boolean) => void;
34
+ ref: () => void;
35
+ unref: () => void;
36
+ };
37
+ stdin.isTTY = true;
38
+ stdin.setRawMode = () => undefined;
39
+ stdin.ref = () => undefined;
40
+ stdin.unref = () => undefined;
41
+ return stdin;
42
+ };
43
+
44
+ // Ink throttles frame writes to `maxFps: 30`; anything shorter reads the previous frame.
45
+ export const nextFrame = () => Bun.sleep(80);
@@ -1,5 +1,4 @@
1
- import { existsSync } from "node:fs";
2
- import path from "node:path";
1
+ import { devInstallCommand } from "../util/devInstallCommand";
3
2
 
4
3
  export type Ssh2 = typeof import("ssh2");
5
4
 
@@ -11,10 +10,7 @@ const resolveFrom = (dir: string) => {
11
10
  }
12
11
  };
13
12
 
14
- export const ssh2InstallCommand = (workspaceRoot: string) =>
15
- existsSync(path.join(workspaceRoot, "package-lock.json")) && !existsSync(path.join(workspaceRoot, "bun.lock"))
16
- ? "npm install -D ssh2"
17
- : "bun add -d ssh2";
13
+ export const ssh2InstallCommand = (workspaceRoot: string) => devInstallCommand(workspaceRoot, "ssh2").join(" ");
18
14
 
19
15
  //? A global akan resolves packages from its own install, so the workspace root is searched as well.
20
16
  export const loadSsh2 = async (
@@ -0,0 +1,7 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export const devInstallCommand = (workspaceRoot: string, spec: string) =>
5
+ existsSync(path.join(workspaceRoot, "package-lock.json")) && !existsSync(path.join(workspaceRoot, "bun.lock"))
6
+ ? ["npm", "install", "-D", spec]
7
+ : ["bun", "add", "-d", spec];
@@ -24,6 +24,7 @@ export class SlicePlanner {
24
24
  /** Never pruned: the toolchain a workspace runs on, which no source file imports. */
25
25
  static readonly toolchainDependencies = [
26
26
  "@akanjs/cli",
27
+ "@akanjs/code",
27
28
  "@akanjs/devkit",
28
29
  "@biomejs/biome",
29
30
  "@types/bun",
@@ -1,49 +0,0 @@
1
- import type { SettingsManager } from "@earendil-works/pi-coding-agent";
2
- import type { CodeAgentModel } from "./akanCodeModel";
3
-
4
- type CompactedModel = Pick<CodeAgentModel, "provider" | "id" | "contextWindow">;
5
-
6
- // The engine compacts above `contextWindow - reserveTokens`, so a share of the window becomes a reserve per model.
7
- export class AkanCodeCompaction {
8
- // Twice the engine's 16,384: at 16k a reasoning model stops mid-thought at the compaction threshold,
9
- // and the recovery re-sends a near-full window to retry the turn.
10
- static readonly reserveFloor = 32_768;
11
- static readonly steps = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] as const;
12
-
13
- static isStep(percent: number) {
14
- return AkanCodeCompaction.steps.some((step) => step === percent);
15
- }
16
-
17
- /** `100` is the default itself, so it is stored as no choice at all. */
18
- static normalize(percent: number | undefined) {
19
- if (percent === undefined) return undefined;
20
- if (!AkanCodeCompaction.isStep(percent))
21
- throw new Error(`Autocompact takes a percent in steps of 10: ${AkanCodeCompaction.steps.join(", ")}.`);
22
- return percent === 100 ? undefined : percent;
23
- }
24
-
25
- static thresholdOf(contextWindow: number, percent: number | undefined) {
26
- const share = percent ? Math.floor((contextWindow * percent) / 100) : contextWindow;
27
- return Math.min(share, contextWindow - AkanCodeCompaction.reserveFloor);
28
- }
29
-
30
- static apply(settings: SettingsManager, model: CompactedModel, percent: number | undefined) {
31
- const threshold = AkanCodeCompaction.thresholdOf(model.contextWindow, percent);
32
- // Keyed by model, so the next model is never checked against a reserve sized for this one's window.
33
- settings.applyOverrides({
34
- compaction: {
35
- modelOverrides: { [`${model.provider}/${model.id}`]: { reserveTokens: model.contextWindow - threshold } },
36
- },
37
- });
38
- }
39
-
40
- /** Why `percent` cannot work on `model`, or undefined when it can. */
41
- static problemOf(model: CompactedModel, percent: number, keepRecentTokens: number) {
42
- const name = `${model.provider}/${model.id}`;
43
- if (model.contextWindow <= 0) return `${name} declares no context window, so it has no share to compact at.`;
44
- const threshold = AkanCodeCompaction.thresholdOf(model.contextWindow, percent);
45
- if (threshold >= keepRecentTokens) return undefined;
46
- const k = (tokens: number) => `${Math.round(tokens / 1000)}k`;
47
- return `Compacting at ${percent}% of the ${k(model.contextWindow)} window of ${name} starts at ${k(threshold)}, under the ${k(keepRecentTokens)} of recent turns every compaction keeps, so every turn would compact again.`;
48
- }
49
- }
@@ -1,122 +0,0 @@
1
- import { existsSync, mkdirSync, mkdtempSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import path from "node:path";
4
- import { type InlineExtension, ModelRuntime, SessionManager, SettingsManager } from "@earendil-works/pi-coding-agent";
5
- import type { CodeAgentProfile } from "akanjs/common";
6
- import { AkanEnvKeys } from "../tools/AkanEnvKeys";
7
- import { AkanCodeCompaction } from "./AkanCodeCompaction";
8
- import { type AkanContextFile, AkanContextFiles } from "./AkanContextFiles";
9
- import { akanCodePaths } from "./akanCodePaths";
10
- import { akanSystemPrompt } from "./akanSystemPrompt";
11
- import type { CodeAgentProxy } from "./CodeAgentProxy";
12
- import { CodeSessionIndex } from "./CodeSessionIndex";
13
- import { WorkspaceTrust } from "./WorkspaceTrust";
14
-
15
- type PrepareRequest = (
16
- model: unknown,
17
- options?: Record<string, unknown>,
18
- ) => Promise<{ model: { compat?: Record<string, unknown> } }>;
19
-
20
- export interface AkanCodeServicesOptions {
21
- workspaceRoot: string;
22
- cwd: string;
23
- profile: CodeAgentProfile;
24
- extensions: InlineExtension[];
25
- sessionId?: string;
26
- }
27
-
28
- // All four engine services are injected explicitly: any one left out makes the engine fall back to `~/.pi/`.
29
- export class AkanCodeServices {
30
- static settings() {
31
- // In memory on purpose: file settings would be a second configuration surface beside the profile.
32
- // `enableInstallTelemetry` defaults to true and adds pi-branded headers to OpenRouter/NVIDIA/Cloudflare calls.
33
- return SettingsManager.inMemory({
34
- enableInstallTelemetry: false,
35
- enableAnalytics: false,
36
- quietStartup: true,
37
- compaction: { reserveTokens: AkanCodeCompaction.reserveFloor },
38
- // pi 1.5 defaults to "idle", which sends billed cache refreshes for up to 30 minutes between turns.
39
- cacheWarming: "streaming",
40
- });
41
- }
42
-
43
- // The engine locks and rewrites `authPath` itself, so two `akan code` refreshing a token at once cannot clobber it.
44
- static async runtime(workspaceRoot: string, proxy: CodeAgentProxy | null = null) {
45
- akanCodePaths.ensureGlobalDir();
46
- const runtime = await ModelRuntime.create({
47
- //* Behind a proxy no real key may reach a request, so credentials live in a throwaway file.
48
- authPath: proxy
49
- ? path.join(mkdtempSync(path.join(tmpdir(), "akan-code-proxy-")), "auth.json")
50
- : akanCodePaths.authFile(),
51
- modelsPath: akanCodePaths.modelsFile(),
52
- });
53
- AkanCodeServices.#holdMessageThreadsOff(runtime);
54
- if (proxy) await proxy.apply(runtime);
55
- else await AkanEnvKeys.apply(runtime, workspaceRoot);
56
- return runtime;
57
- }
58
-
59
- // pi 1.5 turned Anthropic message threads on for api.anthropic.com; a models.json `compat` that names it still wins.
60
- static #holdMessageThreadsOff(runtime: ModelRuntime) {
61
- const target = runtime as unknown as { prepareRequest?: PrepareRequest };
62
- const original = target.prepareRequest?.bind(runtime);
63
- if (!original) throw new Error("The model runtime no longer exposes prepareRequest; update AkanCodeServices");
64
- target.prepareRequest = async (model, options) => {
65
- const prepared = await original(model, options);
66
- if (prepared.model.compat?.supportsMessageThreads !== undefined) return prepared;
67
- return {
68
- ...prepared,
69
- model: { ...prepared.model, compat: { ...prepared.model.compat, supportsMessageThreads: false } },
70
- };
71
- };
72
- }
73
-
74
- static sessions(workspaceRoot: string, cwd: string, profile: CodeAgentProfile, resume?: string) {
75
- //* `remote` has no store of its own yet, so it keeps a file session: a pod worker's suspended asks need it.
76
- if (profile.session.store === "memory") return SessionManager.inMemory(cwd);
77
- const dir = akanCodePaths.sessionsDir(workspaceRoot);
78
- mkdirSync(dir, { recursive: true });
79
- const manager = SessionManager.create(cwd, dir);
80
- if (!resume) return manager;
81
- const file = CodeSessionIndex.fileOf(dir, resume);
82
- // A mistyped id that quietly opened a new session would look like a session that lost its history.
83
- if (!file) throw new Error(`No stored session ${resume} in ${dir}`);
84
- manager.setSessionFile(file);
85
- return manager;
86
- }
87
-
88
- // Skills are text, never code that runs, so unlike extensions they may come from the home directory too.
89
- static #skillPaths(profile: CodeAgentProfile, workspaceRoot: string) {
90
- if (!profile.context.skills) return [];
91
- const dirs = [
92
- akanCodePaths.builtinSkillsDir(),
93
- akanCodePaths.globalSkillsDir(),
94
- akanCodePaths.skillsDir(workspaceRoot),
95
- ];
96
- return dirs.filter((dir): dir is string => !!dir && existsSync(dir));
97
- }
98
-
99
- static resourceOptions(options: AkanCodeServicesOptions) {
100
- // A path that does not exist is reported as a load error rather than skipped, and these two are optional.
101
- const present = (dir: string) => (existsSync(dir) ? [dir] : []);
102
- return {
103
- noExtensions: true,
104
- // Disables only the engine's default skill locations (`~/.pi/skills`, `.pi/`); `additionalSkillPaths` merge.
105
- noSkills: true,
106
- noPromptTemplates: true,
107
- noThemes: true,
108
- noContextFiles: !options.profile.context.projectFiles,
109
- agentsFilesOverride: ({ agentsFiles }: { agentsFiles: AkanContextFile[] }) => ({
110
- agentsFiles: options.profile.context.projectFiles
111
- ? AkanContextFiles.extend(agentsFiles, { workspaceRoot: options.workspaceRoot, cwd: options.cwd })
112
- : agentsFiles,
113
- }),
114
- appendSystemPrompt: [akanSystemPrompt(options.profile)],
115
- additionalExtensionPaths: WorkspaceTrust.isTrusted(options.workspaceRoot, "extensions")
116
- ? present(akanCodePaths.extensionsDir(options.workspaceRoot))
117
- : [],
118
- additionalSkillPaths: AkanCodeServices.#skillPaths(options.profile, options.workspaceRoot),
119
- extensionFactories: options.extensions,
120
- };
121
- }
122
- }