@akanjs/devkit 3.3.0-rc.8 → 4.0.0-rc.0

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 (347) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +7 -1
  3. package/README.md +7 -1
  4. package/akanApp/akanApp.host.test.ts +3 -1
  5. package/akanApp/akanApp.host.ts +26 -2
  6. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  7. package/akanApp/devHostPolicy.ts +5 -0
  8. package/akanApp/devMetadataRestart.ts +93 -0
  9. package/akanApp/devRecycler.test.ts +2 -0
  10. package/akanApp/devRecycler.ts +9 -0
  11. package/akanConfig/akanBin.ts +4 -0
  12. package/akanConfig/akanConfig.test.ts +269 -18
  13. package/akanConfig/akanConfig.ts +104 -210
  14. package/akanConfig/akanPreview.test.ts +28 -0
  15. package/akanConfig/akanPreview.ts +24 -0
  16. package/akanConfig/akanWorkers.test.ts +73 -0
  17. package/akanConfig/akanWorkers.ts +61 -0
  18. package/akanConfig/desktopServerConfig.ts +96 -0
  19. package/akanConfig/dockerImage.ts +212 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/types.ts +4 -0
  23. package/app/appBin.test.ts +63 -0
  24. package/app/appBin.ts +50 -0
  25. package/app/applicationBuildReporter.test.ts +51 -1
  26. package/app/applicationBuildReporter.ts +6 -1
  27. package/app/applicationBuildRunner.test.ts +358 -5
  28. package/app/applicationBuildRunner.ts +221 -31
  29. package/app/clientServerBoundary.test.ts +115 -0
  30. package/app/clientServerBoundary.ts +89 -0
  31. package/app/dictionarySizes.test.ts +40 -0
  32. package/app/dictionarySizes.ts +95 -0
  33. package/app/routeFilesReport.test.ts +59 -0
  34. package/app/routeFilesReport.ts +46 -0
  35. package/app/routeJsBudget.ts +18 -4
  36. package/artifact/implicitRootLayout.test.ts +19 -0
  37. package/artifact/implicitRootLayout.ts +16 -2
  38. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  39. package/artifact/storeBootstrap.test.ts +28 -0
  40. package/artifact/storeBootstrap.ts +64 -8
  41. package/biome.base.json +7 -5
  42. package/codeAgent/index.ts +1 -34
  43. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  44. package/codeAgent/skills/akan-debug/SKILL.md +8 -3
  45. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  46. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  47. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  48. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  49. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  50. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  51. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  52. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  56. package/commandDecorators/command.ts +28 -12
  57. package/commandDecorators/commandBuilder.ts +8 -1
  58. package/commandDecorators/commandDecorators.test.ts +70 -3
  59. package/commandDecorators/helpFormatter.ts +14 -12
  60. package/context/akanContext.ts +2 -0
  61. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  62. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  63. package/docs/apiReference.test.ts +25 -0
  64. package/docs/apiReference.ts +38 -5
  65. package/docs/declarationReader.ts +30 -0
  66. package/executors/appExecutor.ts +26 -12
  67. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  68. package/executors/clientRuntimeKeys.fixture.json +393 -0
  69. package/executors/clientRuntimeKeys.test.ts +1690 -0
  70. package/executors/executor.ts +14 -6
  71. package/executors/executors.test.ts +155 -1
  72. package/executors/pkgExecutor.ts +2 -1
  73. package/executors/sysExecutor.ts +112 -8
  74. package/executors/workspaceExecutor.ts +7 -4
  75. package/frontendBuild/allRoutesBuilder.ts +99 -7
  76. package/frontendBuild/autoImportSync.ts +3 -2
  77. package/frontendBuild/buildRouteClient.test.ts +684 -6
  78. package/frontendBuild/clientBuildTypes.ts +26 -0
  79. package/frontendBuild/clientEntriesBundler.ts +49 -1
  80. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  81. package/frontendBuild/clientEntryDiscovery.ts +134 -12
  82. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  83. package/frontendBuild/clientEntryGroups.ts +61 -0
  84. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  85. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  86. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  87. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  88. package/frontendBuild/csrDevPatcher.ts +37 -11
  89. package/frontendBuild/csrDevTypes.ts +9 -0
  90. package/frontendBuild/devBarrelImports.test.ts +124 -0
  91. package/frontendBuild/devBarrelImports.ts +81 -21
  92. package/frontendBuild/devChangePlanner.ts +0 -1
  93. package/frontendBuild/devRegistryBundler.ts +4 -2
  94. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  95. package/frontendBuild/devRouteRuntime.ts +167 -0
  96. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  97. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  98. package/frontendBuild/dictionaryConstants.ts +136 -0
  99. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  100. package/frontendBuild/dictionaryPackState.ts +131 -0
  101. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  102. package/frontendBuild/dictionaryPacking.ts +160 -0
  103. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  104. package/frontendBuild/dictionaryRoutes.ts +227 -0
  105. package/frontendBuild/frontendBuild.test.ts +5 -3
  106. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  107. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  108. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  109. package/frontendBuild/precompressArtifacts.ts +34 -8
  110. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  111. package/frontendBuild/renderedEntries.ts +144 -0
  112. package/frontendBuild/routeClientBuilder.ts +407 -43
  113. package/frontendBuild/routeHandoffs.test.ts +155 -0
  114. package/frontendBuild/routeHandoffs.ts +117 -0
  115. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  116. package/frontendBuild/routeModulePreloads.ts +20 -11
  117. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  118. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  119. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  120. package/frontendBuild/routeRuntimePays.ts +117 -0
  121. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  122. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  123. package/frontendBuild/ssrDevBundler.ts +66 -11
  124. package/frontendBuild/vendorFileImports.test.ts +254 -0
  125. package/frontendBuild/vendorFileImports.ts +163 -0
  126. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  127. package/frontendBuild/vendorNarrowing.ts +38 -2
  128. package/frontendBuild/vendorSpecifiers.ts +2 -0
  129. package/guideline/agentAssets.ts +1 -1
  130. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  131. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  132. package/incrementalBuilder/builderWatch.ts +11 -1
  133. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  134. package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
  135. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  136. package/incrementalBuilder/pendingMetadata.ts +19 -0
  137. package/integration/devStability.integration.test.ts +46 -21
  138. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  139. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  140. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  141. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  142. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  143. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  144. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  145. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  146. package/lint/biomeBase.test.ts +50 -3
  147. package/lint/biomeBase.ts +1 -1
  148. package/lint/biomeCheck.test.ts +162 -0
  149. package/lint/biomeCheck.ts +131 -0
  150. package/lint/linter.test.ts +16 -11
  151. package/lint/no-arbitrary-color.grit +5 -0
  152. package/lint/no-conditional-st-hook.grit +5 -1
  153. package/lint/no-daisyui-legacy-class.grit +8 -0
  154. package/lint/no-document-cookie.grit +3 -0
  155. package/lint/no-inline-color.grit +10 -2
  156. package/lint/no-oversized-list-limit.grit +2 -0
  157. package/lint/no-raw-palette-class.grit +7 -0
  158. package/lint/no-unpublished-form-setter.grit +2 -0
  159. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  160. package/lint/no-web-storage.grit +3 -0
  161. package/lint/withheldEnvFile.ts +17 -0
  162. package/mobile/desktopBin.ts +2 -2
  163. package/mobile/desktopServerStage.test.ts +18 -3
  164. package/mobile/desktopServerStage.ts +7 -2
  165. package/mobile/nativeApp.test.ts +7 -5
  166. package/mobile/nativeApp.ts +2 -2
  167. package/mobile/nativeConfig.test.ts +17 -1
  168. package/mobile/nativeConfig.ts +11 -6
  169. package/mobile/nativePublicEnv.ts +1 -1
  170. package/mobile/serverBundleSecrets.ts +43 -0
  171. package/package.json +11 -12
  172. package/packageExports.test.ts +3 -2
  173. package/preview/PreviewView.ts +25 -3
  174. package/quality/dictionaryKeys.test.ts +356 -0
  175. package/quality/dictionaryKeys.ts +488 -0
  176. package/quality/objectImportReport.test.ts +36 -0
  177. package/quality/objectImportReport.ts +105 -0
  178. package/quality/qualityScanner.ts +1 -1
  179. package/quality/routeRuntimeReport.test.ts +91 -0
  180. package/quality/routeRuntimeReport.ts +121 -0
  181. package/quality/runtimeConstantFacts.ts +71 -0
  182. package/quality/runtimeConstantGraph.ts +123 -0
  183. package/quality/runtimeConstantReads.ts +116 -0
  184. package/quality/runtimeImports.test.ts +190 -0
  185. package/quality/runtimeImports.ts +233 -0
  186. package/quality/runtimeKeyNames.ts +46 -0
  187. package/quality/runtimeLexicalScope.ts +132 -0
  188. package/quality/runtimeMarkerReach.test.ts +84 -0
  189. package/quality/runtimeMarkerReach.ts +255 -0
  190. package/quality/runtimeModuleFacts.ts +290 -0
  191. package/quality/runtimeNameTable.test.ts +172 -0
  192. package/quality/runtimeNameTable.ts +477 -0
  193. package/quality/runtimeScopeReport.test.ts +123 -0
  194. package/quality/runtimeScopeReport.ts +167 -0
  195. package/quality/runtimeSliceKey.ts +269 -0
  196. package/quality/runtimeSyntax.ts +133 -0
  197. package/quality/runtimeTable.fixture.ts +189 -0
  198. package/quality/runtimeUse.test.ts +737 -0
  199. package/quality/runtimeUse.ts +696 -0
  200. package/quality/runtimeUseReadable.test.ts +393 -0
  201. package/quality/ssrScanner.test.ts +13 -0
  202. package/quality/ssrScanner.ts +1 -1
  203. package/quality/translatorBindings.ts +187 -0
  204. package/test/fakeTerminal.ts +45 -0
  205. package/test/secretEnvFixture.ts +134 -0
  206. package/test/testHelpers.ts +11 -0
  207. package/transforms/barrelAnalyzer.ts +24 -2
  208. package/transforms/barrelImportsPlugin.ts +121 -32
  209. package/transforms/exportReach.test.ts +162 -0
  210. package/transforms/exportReach.ts +308 -0
  211. package/transforms/frameworkObjects.fixture.tsx +58 -0
  212. package/transforms/frameworkObjects.test.ts +54 -0
  213. package/transforms/modelReference.test.ts +196 -0
  214. package/transforms/modelReference.ts +39 -0
  215. package/transforms/moduleParts.test.ts +225 -0
  216. package/transforms/moduleParts.ts +418 -0
  217. package/transforms/objectImportEdits.ts +150 -0
  218. package/transforms/objectMemberImports.test.ts +633 -0
  219. package/transforms/objectMemberImports.ts +571 -0
  220. package/transforms/objectMemberLookup.ts +150 -0
  221. package/transforms/objectModule.test.ts +307 -0
  222. package/transforms/objectModule.ts +482 -0
  223. package/transforms/objectModuleAnalyzer.ts +104 -0
  224. package/transforms/partImports.test.ts +76 -0
  225. package/transforms/partImports.ts +110 -0
  226. package/transforms/partModules.test.ts +187 -0
  227. package/transforms/partModules.ts +90 -0
  228. package/transforms/partPurity.ts +124 -0
  229. package/transforms/reactIconImports.test.ts +231 -0
  230. package/transforms/reactIconImports.ts +325 -0
  231. package/transforms/routeConstants.ts +122 -0
  232. package/transforms/routeRuntime.test.ts +835 -0
  233. package/transforms/routeRuntime.ts +703 -0
  234. package/transforms/routeRuntimeEdits.ts +92 -0
  235. package/transforms/routeRuntimeGraph.ts +66 -0
  236. package/transforms/routeRuntimePlan.ts +244 -0
  237. package/transforms/secretEnvDeclaration.test.ts +208 -0
  238. package/transforms/secretEnvDeclaration.ts +213 -0
  239. package/transforms/secretEnvFile.test.ts +117 -0
  240. package/transforms/secretEnvFile.ts +113 -0
  241. package/transforms/secretEnvName.test.ts +54 -0
  242. package/transforms/secretEnvName.ts +29 -0
  243. package/transforms/secretEnvSource.test.ts +148 -0
  244. package/transforms/secretEnvSource.ts +166 -0
  245. package/transforms/serverEnvEvaluationError.ts +11 -0
  246. package/transforms/serverEnvPlugin.test.ts +2 -1
  247. package/transforms/serverEnvPlugin.ts +13 -0
  248. package/transforms/serverEnvProfile.test.ts +129 -2
  249. package/transforms/serverEnvProfile.ts +126 -40
  250. package/transforms/serverEnvSecrets.test.ts +292 -0
  251. package/transforms/signalDescriptors.test.ts +280 -0
  252. package/transforms/signalDescriptors.ts +227 -0
  253. package/transforms/thisFreeExports.ts +87 -0
  254. package/transforms/transforms.test.ts +177 -0
  255. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  256. package/tunnel/createTunnel.ts +5 -1
  257. package/tunnel/ssh2Module.test.ts +37 -0
  258. package/tunnel/ssh2Module.ts +28 -0
  259. package/tunnel/sshTunnel.ts +4 -2
  260. package/typecheck/projectTypecheck.test.ts +32 -1
  261. package/typecheck/projectTypecheck.ts +3 -3
  262. package/typecheck/typeChecker.test.ts +49 -0
  263. package/typecheck/typeChecker.ts +9 -7
  264. package/typecheck/withheldDiagnostics.ts +41 -0
  265. package/util/devInstallCommand.ts +7 -0
  266. package/util/jsonFormatter.test.ts +13 -9
  267. package/workflow/executor.ts +6 -2
  268. package/workflow/index.ts +1 -0
  269. package/workflow/plan.ts +36 -7
  270. package/workflow/types.ts +1 -1
  271. package/workflow/uiTarget.ts +50 -0
  272. package/workspace/envSeed.test.ts +30 -1
  273. package/workspace/envSeed.ts +30 -1
  274. package/workspace/mainCheckout.test.ts +55 -0
  275. package/workspace/mainCheckout.ts +38 -0
  276. package/workspace/scanInfo.test.ts +39 -0
  277. package/workspace/scanInfo.ts +55 -6
  278. package/workspace/slicePlanner.ts +2 -1
  279. package/workspace/workspaceLayout.test.ts +22 -1
  280. package/workspace/workspaceLayout.ts +3 -3
  281. package/CHANGELOG.md +0 -2903
  282. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  283. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  284. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  285. package/codeAgent/agent/CodeAgent.ts +0 -626
  286. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  287. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  288. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  289. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  290. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  291. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  292. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  293. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  294. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  295. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  296. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  297. package/codeAgent/agent/CodeMailbox.ts +0 -148
  298. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  299. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  300. package/codeAgent/agent/SubagentPool.ts +0 -219
  301. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  302. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  303. package/codeAgent/agent/akanCodeModel.ts +0 -47
  304. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  305. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  306. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  307. package/codeAgent/agent/codeAgent.test.ts +0 -337
  308. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  309. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  310. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  311. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  312. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  313. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  314. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  315. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  316. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  317. package/codeAgent/agent/consoleToStderr.ts +0 -8
  318. package/codeAgent/agent/jsonLines.ts +0 -29
  319. package/codeAgent/agent/stringArg.ts +0 -5
  320. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  321. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  322. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  323. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  324. package/codeAgent/tools/AkanCli.ts +0 -51
  325. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  326. package/codeAgent/tools/AkanEditScope.ts +0 -53
  327. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  328. package/codeAgent/tools/AkanToolPack.ts +0 -86
  329. package/codeAgent/tools/AkanVerifier.ts +0 -30
  330. package/codeAgent/tools/AskToolPack.ts +0 -99
  331. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  332. package/codeAgent/tools/MailToolPack.ts +0 -76
  333. package/codeAgent/tools/McpClient.ts +0 -209
  334. package/codeAgent/tools/McpOAuth.ts +0 -233
  335. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  336. package/codeAgent/tools/McpServerConfig.ts +0 -131
  337. package/codeAgent/tools/McpSignIn.ts +0 -158
  338. package/codeAgent/tools/McpTokenStore.ts +0 -128
  339. package/codeAgent/tools/McpToolPack.ts +0 -206
  340. package/codeAgent/tools/SessionToolPack.ts +0 -91
  341. package/codeAgent/tools/WebToolPack.ts +0 -315
  342. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  343. package/codeAgent/tools/askToolPack.test.ts +0 -116
  344. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  345. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  346. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  347. package/piDependencyPins.test.ts +0 -45
@@ -1,626 +0,0 @@
1
- import {
2
- type AgentSession,
3
- createAgentSession,
4
- DefaultResourceLoader,
5
- type ExtensionAPI,
6
- type InlineExtension,
7
- type ToolDefinition,
8
- } from "@earendil-works/pi-coding-agent";
9
- import {
10
- type CodeAgentAnswer,
11
- type CodeAgentEffort,
12
- type CodeAgentEvent,
13
- type CodeAgentEventBody,
14
- type CodeAgentImage,
15
- type CodeAgentMcpStatus,
16
- type CodeAgentProfile,
17
- type CodeAgentProviderInfo,
18
- type CodeAgentQuestion,
19
- type CodeAgentSessionInfo,
20
- type CodeAgentState,
21
- codeAgentClip,
22
- codeAgentLabelChars,
23
- codeAgentRenderAnswer,
24
- codeAgentSessionName,
25
- } from "akanjs/common";
26
- import type { Workspace } from "../../commandDecorators";
27
- import { AkanCodePlugins } from "../tools/AkanCodePlugins";
28
- import { DeepSeekWeb } from "../tools/DeepSeekWeb";
29
- import { AkanCodeCompaction } from "./AkanCodeCompaction";
30
- import { AkanCodeServices } from "./AkanCodeServices";
31
- import {
32
- akanCodeModel,
33
- akanCodeModelSupportsImages,
34
- akanCodeModelWarnings,
35
- type CodeAgentModelRef,
36
- } from "./akanCodeModel";
37
- import { akanCodePaths } from "./akanCodePaths";
38
- import { CodeAgentAsks } from "./CodeAgentAsks";
39
- import { CodeAgentEventMapper } from "./CodeAgentEventMapper";
40
- import { CodeAgentGate } from "./CodeAgentGate";
41
- import { CodeAgentProxy } from "./CodeAgentProxy";
42
- import { CodeAgentSuspended } from "./CodeAgentSuspended";
43
- import { CodeAgentUi } from "./CodeAgentUi";
44
- import { CodeMailbox } from "./CodeMailbox";
45
- import { CodeSessionFork } from "./CodeSessionFork";
46
- import { CodeSessionIndex } from "./CodeSessionIndex";
47
- import type { SubagentSpend } from "./SubagentPool";
48
-
49
- // The engine's run-mode type is not re-exported from its package entry, so the literal set is restated.
50
- export type CodeAgentHostMode = "tui" | "rpc" | "json" | "print";
51
-
52
- export interface CodeAgentOptions {
53
- workspace: Workspace;
54
- cwd?: string;
55
- profile: CodeAgentProfile;
56
- model?: CodeAgentModelRef;
57
- /** Percent of the context window that starts a compaction, in steps of 10. */
58
- autoCompactAt?: number;
59
- /** Apps whose dev server and preview the turn-end feedback loop watches. */
60
- apps?: string[];
61
- extensions?: InlineExtension[];
62
- customTools?: ToolDefinition[];
63
- /** `print` for a one-shot stream, `rpc` when a host drives this process over stdio. */
64
- mode?: CodeAgentHostMode;
65
- /** How many `task` tools deep this agent already is. */
66
- depth?: number;
67
- /** The tally (tokens spent, sub-agents running) of the sub-agent tree whose `task` opened this agent. */
68
- subagentSpend?: SubagentSpend;
69
- /** Id of a stored session to continue instead of opening a new one. */
70
- resume?: string;
71
- }
72
-
73
- const textOf = (content: unknown) => {
74
- if (typeof content === "string") return content.trim();
75
- if (!Array.isArray(content)) return "";
76
- return content
77
- .map((part) => (typeof part === "object" && part && "text" in part ? String(part.text) : ""))
78
- .join("")
79
- .trim();
80
- };
81
-
82
- export class CodeAgent {
83
- readonly #profile: CodeAgentProfile;
84
- readonly #gate: CodeAgentGate;
85
- readonly #mapper = new CodeAgentEventMapper();
86
- readonly #asks = new CodeAgentAsks();
87
- #suspended = new CodeAgentSuspended(null);
88
- readonly #listeners = new Set<(event: CodeAgentEvent) => void>();
89
- #session: AgentSession | undefined;
90
- #disposePlugins: (() => void) | undefined;
91
- #seq = 0;
92
- #disposed = false;
93
- #sessionDir: string | undefined;
94
- #mailbox: CodeMailbox | undefined;
95
- #mcp: CodeAgentMcpStatus[] = [];
96
- #workspaceRoot = "";
97
- // Cleared at `idle`: an earlier turn is in the transcript; only the turn in flight exists nowhere else.
98
- readonly #replay: CodeAgentEvent[] = [];
99
- #replayFrom = 0;
100
- #lastContextTokens: number | undefined;
101
- #autoCompactAt: number | undefined;
102
-
103
- private constructor(profile: CodeAgentProfile) {
104
- this.#profile = profile;
105
- this.#gate = new CodeAgentGate(profile);
106
- }
107
-
108
- static async create(options: CodeAgentOptions) {
109
- const workspaceRoot = options.workspace.workspaceRoot;
110
- const cwd = options.cwd ?? workspaceRoot;
111
- const agent = new CodeAgent(options.profile);
112
- const autoCompactAt = AkanCodeCompaction.normalize(options.autoCompactAt);
113
- const settingsManager = AkanCodeServices.settings();
114
- const proxy = CodeAgentProxy.fromEnv(options.profile);
115
- const modelRuntime = await AkanCodeServices.runtime(workspaceRoot, proxy);
116
- const model = await akanCodeModel(modelRuntime, options.model);
117
- const compaction = settingsManager.getCompactionSettings(model);
118
- const modelWarnings = akanCodeModelWarnings(model, compaction.reserveTokens + compaction.keepRecentTokens);
119
-
120
- const akan = await AkanCodePlugins.build({
121
- workspace: options.workspace,
122
- cwd,
123
- profile: options.profile,
124
- apps: options.apps ?? [],
125
- canSeeImages: akanCodeModelSupportsImages(model),
126
- model: () => {
127
- const current = agent.#session?.model;
128
- return current ? { provider: current.provider, id: current.id } : undefined;
129
- },
130
- deepseek: await DeepSeekWeb.fromRuntime(modelRuntime, !!proxy),
131
- depth: options.depth ?? 0,
132
- ...(options.subagentSpend ? { subagentSpend: options.subagentSpend } : {}),
133
- currentSessionId: () => agent.sessionId,
134
- mailbox: () => agent.#mailbox,
135
- onNotice: (message) => agent.#emit({ type: "notice", level: "warning", message }),
136
- onAgents: (agents) => agent.#emit({ type: "subagent", agents }),
137
- onAsk: (question) => agent.ask(question),
138
- });
139
-
140
- const resourceLoader = new DefaultResourceLoader({
141
- cwd,
142
- agentDir: akanCodePaths.globalDir(),
143
- settingsManager,
144
- ...AkanCodeServices.resourceOptions({
145
- workspaceRoot,
146
- cwd,
147
- profile: options.profile,
148
- extensions: [agent.#gateExtension(), ...akan.extensions, ...(options.extensions ?? [])],
149
- }),
150
- });
151
- await resourceLoader.reload();
152
-
153
- const { session } = await createAgentSession({
154
- cwd,
155
- agentDir: akanCodePaths.globalDir(),
156
- modelRuntime,
157
- settingsManager,
158
- resourceLoader,
159
- model,
160
- sessionManager: AkanCodeServices.sessions(workspaceRoot, cwd, options.profile, options.resume),
161
- noTools: "builtin",
162
- tools: [...options.profile.tools.builtin, ...akan.toolNames],
163
- customTools: options.customTools,
164
- });
165
- agent.#disposePlugins = akan.dispose;
166
- agent.#mcp = akan.mcp;
167
- agent.#workspaceRoot = workspaceRoot;
168
- if (options.profile.session.store !== "memory") agent.#sessionDir = akanCodePaths.sessionsDir(workspaceRoot);
169
- await agent.#attach(session, options.mode ?? "print");
170
- const autoCompactWarning = agent.#fitAutoCompact(autoCompactAt);
171
- agent.#suspended = new CodeAgentSuspended(CodeAgentSuspended.fileOf(agent.#sessionDir, agent.sessionId));
172
- if (agent.#sessionDir && options.profile.session.store === "file")
173
- agent.#openMail(akanCodePaths.mailDir(workspaceRoot), cwd);
174
- for (const message of [...modelWarnings, ...autoCompactWarning])
175
- agent.#emit({ type: "notice", level: "warning", message });
176
- return agent;
177
- }
178
-
179
- get profile() {
180
- return this.#profile;
181
- }
182
-
183
- get allowed() {
184
- return this.#gate.allowed;
185
- }
186
-
187
- get canSeeImages() {
188
- const model = this.#session?.model;
189
- return model ? akanCodeModelSupportsImages(model) : false;
190
- }
191
-
192
- /** The workspace's stored sessions, newest first. Empty on a profile that keeps none. */
193
- sessions() {
194
- return this.#sessionDir ? CodeSessionIndex.list(this.#sessionDir) : [];
195
- }
196
-
197
- /** The repo, which is not `profile.paths.root` — that one is narrowed to an app by `akan code --app`. */
198
- get workspaceRoot() {
199
- return this.#workspaceRoot;
200
- }
201
-
202
- /**
203
- * As assembled at creation: the tool allowlist is fixed then, so a server declared later is unreachable. A
204
- * server's `auth` still turns `required` when a call's token cannot be renewed, until a reload.
205
- */
206
- mcpServers(): CodeAgentMcpStatus[] {
207
- return this.#mcp;
208
- }
209
-
210
- /** The other `akan code` sessions running in this workspace right now. */
211
- peers() {
212
- return this.#mailbox?.peers() ?? [];
213
- }
214
-
215
- /** The peer receives the text as a prompt of its own, queued as a follow-up when it is mid-turn. */
216
- send(target: string, text: string) {
217
- const mailbox = this.#mailbox;
218
- if (!mailbox) throw new Error("This profile keeps no shared mailbox, so it has no peers.");
219
- const peer = mailbox.find(target);
220
- if (!peer) throw new Error(`No live session matches "${target}". Ask for the list first.`);
221
- mailbox.send(peer.id, text);
222
- return peer;
223
- }
224
-
225
- #openMail(dir: string, cwd: string) {
226
- const session = this.#session;
227
- if (!session) return;
228
- this.#mailbox = new CodeMailbox(dir, session.sessionId, session.sessionName ?? session.sessionId.slice(0, 8));
229
- this.#mailbox.open(cwd, (mail) => {
230
- const from = `${mail.fromName} (${mail.from.slice(0, 8)})`;
231
- this.#emit({ type: "notice", level: "info", message: `message from ${from}` });
232
- void this.#prompt(`Message from another session — ${from}:\n${mail.text}`).catch((error: unknown) =>
233
- this.#emit({ type: "notice", level: "error", message: String(error) }),
234
- );
235
- });
236
- }
237
-
238
- get sessionId() {
239
- return this.#session?.sessionId ?? "";
240
- }
241
-
242
- get isStreaming() {
243
- return this.#session?.isStreaming ?? false;
244
- }
245
-
246
- get tokensUsed() {
247
- return this.#session?.getSessionStats().tokens.total ?? 0;
248
- }
249
-
250
- get info(): CodeAgentSessionInfo {
251
- const session = this.#require();
252
- const model = session.model;
253
- return {
254
- sessionId: session.sessionId,
255
- cwd: this.#profile.paths.root,
256
- profile: this.#profile.name,
257
- model: model ? { provider: model.provider, id: model.id, name: model.name } : undefined,
258
- tools: session.getActiveToolNames(),
259
- contextTokens: model?.contextWindow,
260
- // Not `off`: that is a setting of a reasoning model, not the absence of reasoning.
261
- effort: session.supportsThinking() ? session.thinkingLevel : undefined,
262
- autoCompactAt: this.#autoCompactAt,
263
- name: session.sessionName,
264
- interaction: this.#profile.interaction,
265
- };
266
- }
267
-
268
- /** A `session` frame minted outside this counter would carry `seq: 0`, which every client drops. */
269
- announce() {
270
- this.#emit({ type: "session", info: this.info });
271
- this.#restore();
272
- //* A resumed worker says again what it is still waiting on, or a host that reattached has no card to answer.
273
- const { question, approvals } = this.#suspended;
274
- if (question) this.#emit({ type: "question", question });
275
- for (const request of approvals) this.#emit({ type: "approval", request });
276
- }
277
-
278
- // Prose only: a past turn's tool calls would redraw rows nobody waits on, against a tree that has moved since.
279
- #restore() {
280
- const session = this.#session;
281
- if (!session) return;
282
- const turnId = `restored:${session.sessionId}`;
283
- for (const message of session.messages) {
284
- if (message.role !== "user" && message.role !== "assistant") continue;
285
- const text = textOf(message.content);
286
- if (text) this.#emit({ type: "message", turnId, role: message.role, text });
287
- }
288
- this.#emitContextNow();
289
- }
290
-
291
- on(listener: (event: CodeAgentEvent) => void) {
292
- this.#listeners.add(listener);
293
- return () => this.#listeners.delete(listener);
294
- }
295
-
296
- /** One turn's worth of frames is kept for reconnection; a client further behind reloads the transcript. */
297
- static readonly replayLimit = 2_000;
298
-
299
- /** `frames` only when `sinceSeq` is given; a client behind `replayFrom` has to reload the transcript. */
300
- async state({ sinceSeq }: { sinceSeq?: number } = {}): Promise<CodeAgentState> {
301
- const base = { info: this.info, streaming: this.isStreaming, replayFrom: this.#replayFrom };
302
- if (sinceSeq === undefined) return base;
303
- return { ...base, frames: this.#replay.filter((event) => event.seq > sinceSeq) };
304
- }
305
-
306
- async prompt(message: string, images?: CodeAgentImage[]) {
307
- this.#suspended.clear();
308
- await this.#prompt(message, images);
309
- }
310
-
311
- async #prompt(message: string, images?: CodeAgentImage[]) {
312
- const session = this.#require();
313
- // From the first prompt, not the answer, so the session is not nameless while it is worth watching.
314
- if (!session.sessionName && message.trim()) this.setName(codeAgentSessionName(message));
315
- const attachments = await CodeAgent.#attachments(images);
316
- const options = attachments.length ? { images: attachments } : {};
317
- if (session.isStreaming) return await session.prompt(message, { ...options, streamingBehavior: "followUp" });
318
- await session.prompt(message, { ...options, source: "extension" });
319
- }
320
-
321
- async abort() {
322
- // The engine finalizes an interrupted message as an ordinary stop, so the abort is noted here.
323
- this.#mapper.noteOutcome("aborted");
324
- this.#asks.clear();
325
- await this.#require().abort();
326
- }
327
-
328
- // Not via `prompt`: that opens a turn with the question slot still filled, which the engine does not stop.
329
- async answer(questionId: string, answer: CodeAgentAnswer) {
330
- const question = this.#asks.questionOf(questionId);
331
- const rendered = question ? codeAgentRenderAnswer(question, answer) : (answer.text ?? "");
332
- if (this.#asks.answer(questionId, rendered)) {
333
- this.#emit({ type: "question_resolved", questionId, answer, rendered });
334
- return true;
335
- }
336
- if (this.#profile.interaction.question !== "suspend") return false;
337
- const suspended = this.#suspended.takeQuestion(questionId);
338
- if (!suspended) return false;
339
- const suspendedRendered = codeAgentRenderAnswer(suspended, answer);
340
- this.#emit({ type: "question_resolved", questionId, answer, rendered: suspendedRendered });
341
- // As prose: compaction and the next turn read message content only, so a structured-only answer is lost.
342
- await this.#prompt(`The user answered: ${suspendedRendered}\nContinue the task.`);
343
- return true;
344
- }
345
-
346
- async approve(approvalId: string, approved: boolean, remember?: "session") {
347
- if (this.#asks.resolveApproval(approvalId, approved)) {
348
- const remembered = this.allowed.settle(approvalId, approved && remember === "session");
349
- this.#emit({ type: "approval_resolved", approvalId, approved, ...(remembered.length ? { remembered } : {}) });
350
- for (const covered of this.allowed.covered())
351
- if (this.#asks.resolveApproval(covered, true))
352
- this.#emit({ type: "approval_resolved", approvalId: covered, approved: true });
353
- return true;
354
- }
355
- if (this.#profile.interaction.approval !== "suspend") return false;
356
- if (!this.#suspended.takeApproval(approvalId)) return false;
357
- this.#emit({ type: "approval_resolved", approvalId, approved });
358
- if (approved) await this.#prompt("The user approved the pending action. Retry it and continue.");
359
- return true;
360
- }
361
-
362
- async compact(instructions?: string) {
363
- await this.#require().compact(instructions);
364
- }
365
-
366
- /** Renames the session and says so on the wire, because a host draws the name from the session frame. */
367
- setName(name: string) {
368
- const clean = name.trim();
369
- if (!clean) return;
370
- this.#require().setSessionName(clean);
371
- this.#mailbox?.rename(clean, this.#profile.paths.root);
372
- this.#emit({ type: "session", info: this.info });
373
- }
374
-
375
- /** Copies the session file, not memory, under a new id: the file is what a resume replays. */
376
- fork(name?: string) {
377
- if (!this.#sessionDir) throw new Error("This profile keeps no sessions on disk, so there is nothing to fork");
378
- return CodeSessionFork.fork(this.#sessionDir, this.sessionId, name);
379
- }
380
-
381
- /** The reasoning levels this model offers, clamped by the engine to what the provider actually serves. */
382
- efforts(): CodeAgentEffort[] {
383
- const session = this.#session;
384
- if (!session?.supportsThinking()) return [];
385
- return session.getAvailableThinkingLevels();
386
- }
387
-
388
- setEffort(effort: CodeAgentEffort) {
389
- const session = this.#require();
390
- if (!session.supportsThinking()) throw new Error(`${session.model?.id ?? "this model"} does no reasoning`);
391
- // The engine clamps rather than refuses, so the frame that follows is the level that took, not the one asked.
392
- session.setThinkingLevel(effort);
393
- this.#emit({ type: "session", info: this.info });
394
- }
395
-
396
- /** Every registered provider, keyed or not — `getAvailable()` would list only what is already reachable. */
397
- catalogue(): CodeAgentProviderInfo[] {
398
- const runtime = this.#session?.modelRuntime;
399
- if (!runtime) return [];
400
- const current = this.#session?.model;
401
- return runtime
402
- .getProviders()
403
- .map((provider) => ({
404
- id: provider.id,
405
- name: provider.name ?? provider.id,
406
- authorized: runtime.hasConfiguredAuth(provider.id),
407
- models: (runtime.getModels(provider.id) ?? []).map((model) => ({
408
- id: model.id,
409
- name: model.name,
410
- ...(model.contextWindow ? { contextWindow: model.contextWindow } : {}),
411
- current: model.provider === current?.provider && model.id === current?.id,
412
- })),
413
- }))
414
- .sort((a, b) => a.id.localeCompare(b.id));
415
- }
416
-
417
- async setModel(ref: CodeAgentModelRef) {
418
- const session = this.#require();
419
- const model = await akanCodeModel(session.modelRuntime, ref);
420
- if (!model) throw new Error(`Unknown model: ${ref.provider}/${ref.id}`);
421
- await session.setModel(model);
422
- for (const message of this.#fitAutoCompact(this.#autoCompactAt))
423
- this.#emit({ type: "notice", level: "warning", message });
424
- this.#emit({ type: "session", info: this.info });
425
- }
426
-
427
- setAutoCompactAt(percent: number | undefined) {
428
- const wanted = AkanCodeCompaction.normalize(percent);
429
- const problem = this.#autoCompactProblem(wanted);
430
- if (problem) throw new Error(problem);
431
- this.#autoCompactAt = wanted;
432
- this.#applyAutoCompact();
433
- this.#emit({ type: "session", info: this.info });
434
- }
435
-
436
- // A share that fit one window can fall under the kept turns of a smaller one, and would compact every turn.
437
- #fitAutoCompact(percent: number | undefined) {
438
- const problem = this.#autoCompactProblem(percent);
439
- this.#autoCompactAt = problem ? undefined : percent;
440
- this.#applyAutoCompact();
441
- return problem ? [`${problem} Autocompact is back to the default.`] : [];
442
- }
443
-
444
- #autoCompactProblem(percent: number | undefined) {
445
- const session = this.#require();
446
- const model = session.model;
447
- if (!model || !percent) return undefined;
448
- const { keepRecentTokens } = session.settingsManager.getCompactionSettings(model);
449
- return AkanCodeCompaction.problemOf(model, percent, keepRecentTokens);
450
- }
451
-
452
- // Never before `create` has built the session: `settingsManager.reload()` drops whatever `applyOverrides` set.
453
- #applyAutoCompact() {
454
- const session = this.#require();
455
- if (session.model) AkanCodeCompaction.apply(session.settingsManager, session.model, this.#autoCompactAt);
456
- }
457
-
458
- async waitForIdle() {
459
- await this.#require().waitForIdle();
460
- }
461
-
462
- dispose() {
463
- this.#mailbox?.close();
464
- if (this.#disposed) return;
465
- this.#disposed = true;
466
- this.#asks.clear();
467
- this.#listeners.clear();
468
- this.#disposePlugins?.();
469
- this.#session?.dispose();
470
- }
471
-
472
- async #attach(session: AgentSession, mode: CodeAgentHostMode) {
473
- this.#session = session;
474
- session.subscribe((event) => {
475
- for (const body of this.#mapper.map(event)) this.#emit(body);
476
- // Per turn, not per delta: the count only moves when a provider response lands.
477
- if (event.type === "agent_end" || event.type === "compaction_end") this.#emitContextNow();
478
- });
479
- await session.bindExtensions({
480
- mode,
481
- uiContext: this.#ui().context(),
482
- abortHandler: () => void session.abort(),
483
- onError: (error: unknown) => this.#emit({ type: "error", message: String(error), fatal: false }),
484
- });
485
- }
486
-
487
- /** A path is read here rather than by the host, so a browser and a terminal hand the core the same thing. */
488
- static async #attachments(images: CodeAgentImage[] | undefined) {
489
- if (!images?.length) return [];
490
- return await Promise.all(
491
- images.map(async (image) => {
492
- if ("data" in image) return { type: "image" as const, data: image.data, mimeType: image.mime };
493
- const file = Bun.file(image.path);
494
- return {
495
- type: "image" as const,
496
- data: Buffer.from(await file.arrayBuffer()).toString("base64"),
497
- mimeType: file.type || "image/png",
498
- };
499
- }),
500
- );
501
- }
502
-
503
- // Also on resume, or a session reopened at 80% shows no usage until its next turn ends.
504
- #emitContextNow() {
505
- const usage = this.#session?.getContextUsage();
506
- // `== null` on purpose: typed `number | null`, but `undefined` must not emit `used: undefined`.
507
- if (usage?.tokens == null) return;
508
- if (usage.tokens === this.#lastContextTokens) return;
509
- this.#lastContextTokens = usage.tokens;
510
- this.#emit({ type: "context", used: usage.tokens, max: usage.contextWindow || undefined });
511
- }
512
-
513
- #require() {
514
- if (!this.#session) throw new Error("CodeAgent is not started");
515
- return this.#session;
516
- }
517
-
518
- #emit(body: CodeAgentEventBody) {
519
- this.#seq += 1;
520
- const event = { ...body, seq: this.#seq } as CodeAgentEvent;
521
- this.#remember(event);
522
- for (const listener of this.#listeners) listener(event);
523
- }
524
-
525
- #remember(event: CodeAgentEvent) {
526
- if (event.type === "idle") {
527
- this.#replay.length = 0;
528
- this.#replayFrom = event.seq;
529
- return;
530
- }
531
- this.#replay.push(event);
532
- while (this.#replay.length > CodeAgent.replayLimit) {
533
- const dropped = this.#replay.shift();
534
- this.#replayFrom = dropped?.seq ?? this.#replayFrom;
535
- }
536
- }
537
-
538
- #gateExtension(): InlineExtension {
539
- return {
540
- name: "akan-profile-gate",
541
- factory: (pi: ExtensionAPI) => {
542
- pi.on("tool_call", async (event) => {
543
- const verdict = this.#gate.verdict(event.toolName, event.input);
544
- if (verdict.block) return this.#refuse(event.toolCallId, event.toolName, event.input, verdict.block);
545
- if (!verdict.approval) return undefined;
546
- if (verdict.strict && !this.#profile.ui.canPrompt)
547
- return this.#refuse(
548
- event.toolCallId,
549
- event.toolName,
550
- event.input,
551
- "This reaches a host outside the profile's list, which needs the user's approval, and nobody can be asked in this session. Use a listed host, or say what you need fetched.",
552
- );
553
- const approved = await this.#requestApproval(
554
- event.toolCallId,
555
- event.toolName,
556
- verdict.approval,
557
- verdict.remember,
558
- );
559
- if (approved) return undefined;
560
- return this.#refuse(event.toolCallId, event.toolName, event.input, "The user declined this action.");
561
- });
562
- },
563
- };
564
- }
565
-
566
- #refuse(toolCallId: string, toolName: string, args: unknown, reason: string) {
567
- for (const body of this.#mapper.markBlocked(toolCallId, toolName, args, reason)) this.#emit(body);
568
- return { block: true, reason };
569
- }
570
-
571
- async #requestApproval(toolCallId: string, name: string, summary: string, offered?: string[]) {
572
- // Nobody to ask means nobody to refuse: a pod would otherwise deny every write it was created to make.
573
- if (!this.#profile.ui.canPrompt) return true;
574
- const approvalId = this.#asks.nextId("a");
575
- const suspends = this.#profile.interaction.approval === "suspend";
576
- // A suspended approval ends its turn, and the retry is a new call, so there is no session answer to offer.
577
- const remember = suspends ? undefined : offered;
578
- const request = {
579
- approvalId,
580
- toolCallId,
581
- name,
582
- summary: codeAgentClip(summary, codeAgentLabelChars),
583
- policy: this.#profile.approval,
584
- ...(remember ? { remember } : {}),
585
- };
586
- this.#emit({ type: "approval", request });
587
- if (suspends) {
588
- this.#suspended.addApproval(request);
589
- this.#mapper.noteOutcome("awaiting");
590
- return false;
591
- }
592
- if (remember) this.allowed.offer(approvalId, remember);
593
- const approved = await this.#asks.openApproval(approvalId);
594
- this.allowed.settle(approvalId, false);
595
- return approved;
596
- }
597
-
598
- /** The rendered answer; `undefined` when skipped, suspended, or nobody can be prompted. */
599
- async ask(spec: Omit<CodeAgentQuestion, "questionId">) {
600
- const question: CodeAgentQuestion = { questionId: this.#asks.nextId("q"), ...spec };
601
- if (!this.#profile.ui.canPrompt) {
602
- this.#emit({ type: "question_skipped", question, reason: "no-host" });
603
- return undefined;
604
- }
605
- this.#emit({ type: "question", question });
606
- if (this.#profile.interaction.question === "suspend") {
607
- this.#suspended.setQuestion(question);
608
- this.#mapper.noteOutcome("awaiting");
609
- return undefined;
610
- }
611
- return (await this.#asks.openQuestion(question)) || undefined;
612
- }
613
-
614
- #ui() {
615
- return new CodeAgentUi({
616
- ask: async (prompt, kind, choices) =>
617
- await this.ask({
618
- prompt,
619
- kind,
620
- ...(choices ? { options: choices.map((label) => ({ key: label, label })) } : {}),
621
- freeText: kind === "text",
622
- }),
623
- notify: (level, message) => this.#emit({ type: "notice", level, message }),
624
- });
625
- }
626
- }
@@ -1,35 +0,0 @@
1
- // Kept in this process only: a resumed or reloaded session starts with nothing allowed.
2
- export class CodeAgentAllowed {
3
- readonly #names = new Set<string>();
4
- readonly #offers = new Map<string, string[]>();
5
-
6
- get names() {
7
- return [...this.#names].sort();
8
- }
9
-
10
- missing(names: string[]) {
11
- return names.filter((name) => !this.#names.has(name));
12
- }
13
-
14
- offer(approvalId: string, names: string[]) {
15
- this.#offers.set(approvalId, names);
16
- }
17
-
18
- settle(approvalId: string, remember: boolean) {
19
- const names = this.#offers.get(approvalId) ?? [];
20
- this.#offers.delete(approvalId);
21
- if (!remember) return [];
22
- for (const name of names) this.#names.add(name);
23
- return names;
24
- }
25
-
26
- covered() {
27
- return [...this.#offers].filter(([, names]) => !this.missing(names).length).map(([approvalId]) => approvalId);
28
- }
29
-
30
- clear() {
31
- const count = this.#names.size;
32
- this.#names.clear();
33
- return count;
34
- }
35
- }