@cjhyy/code-shell-core 0.5.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 (484) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -0
  3. package/dist/agent/coordinator.d.ts +49 -0
  4. package/dist/agent/coordinator.js +77 -0
  5. package/dist/arena/arena.d.ts +43 -0
  6. package/dist/arena/arena.js +334 -0
  7. package/dist/arena/context/context-tools.d.ts +16 -0
  8. package/dist/arena/context/context-tools.js +231 -0
  9. package/dist/arena/detect-mode.d.ts +20 -0
  10. package/dist/arena/detect-mode.js +78 -0
  11. package/dist/arena/digest-builder.d.ts +25 -0
  12. package/dist/arena/digest-builder.js +120 -0
  13. package/dist/arena/index.d.ts +29 -0
  14. package/dist/arena/index.js +29 -0
  15. package/dist/arena/iterate/convergence.d.ts +25 -0
  16. package/dist/arena/iterate/convergence.js +103 -0
  17. package/dist/arena/iterate/formats/index.d.ts +22 -0
  18. package/dist/arena/iterate/formats/index.js +283 -0
  19. package/dist/arena/iterate/index.d.ts +11 -0
  20. package/dist/arena/iterate/index.js +9 -0
  21. package/dist/arena/iterate/iterative-arena.d.ts +23 -0
  22. package/dist/arena/iterate/iterative-arena.js +237 -0
  23. package/dist/arena/iterate/parse.d.ts +42 -0
  24. package/dist/arena/iterate/parse.js +123 -0
  25. package/dist/arena/iterate/phases/argue.d.ts +22 -0
  26. package/dist/arena/iterate/phases/argue.js +159 -0
  27. package/dist/arena/iterate/phases/revise.d.ts +16 -0
  28. package/dist/arena/iterate/phases/revise.js +62 -0
  29. package/dist/arena/iterate/phases/tournament.d.ts +34 -0
  30. package/dist/arena/iterate/phases/tournament.js +113 -0
  31. package/dist/arena/iterate/tools/web-tools.d.ts +13 -0
  32. package/dist/arena/iterate/tools/web-tools.js +54 -0
  33. package/dist/arena/iterate/types.d.ts +152 -0
  34. package/dist/arena/iterate/types.js +8 -0
  35. package/dist/arena/ledger.d.ts +47 -0
  36. package/dist/arena/ledger.js +151 -0
  37. package/dist/arena/lenses/architecture.d.ts +5 -0
  38. package/dist/arena/lenses/architecture.js +22 -0
  39. package/dist/arena/lenses/engineering.d.ts +5 -0
  40. package/dist/arena/lenses/engineering.js +22 -0
  41. package/dist/arena/lenses/general.d.ts +5 -0
  42. package/dist/arena/lenses/general.js +20 -0
  43. package/dist/arena/lenses/index.d.ts +16 -0
  44. package/dist/arena/lenses/index.js +47 -0
  45. package/dist/arena/lenses/product.d.ts +5 -0
  46. package/dist/arena/lenses/product.js +22 -0
  47. package/dist/arena/model-presets.d.ts +23 -0
  48. package/dist/arena/model-presets.js +44 -0
  49. package/dist/arena/phases/adjudication.d.ts +24 -0
  50. package/dist/arena/phases/adjudication.js +144 -0
  51. package/dist/arena/phases/build-consensus.d.ts +29 -0
  52. package/dist/arena/phases/build-consensus.js +86 -0
  53. package/dist/arena/phases/claim-registry.d.ts +26 -0
  54. package/dist/arena/phases/claim-registry.js +60 -0
  55. package/dist/arena/phases/cross-review.d.ts +45 -0
  56. package/dist/arena/phases/cross-review.js +224 -0
  57. package/dist/arena/phases/debate-rounds.d.ts +27 -0
  58. package/dist/arena/phases/debate-rounds.js +162 -0
  59. package/dist/arena/phases/participant-research.d.ts +38 -0
  60. package/dist/arena/phases/participant-research.js +317 -0
  61. package/dist/arena/phases/planning-detail-expansion.d.ts +38 -0
  62. package/dist/arena/phases/planning-detail-expansion.js +121 -0
  63. package/dist/arena/planner.d.ts +27 -0
  64. package/dist/arena/planner.js +312 -0
  65. package/dist/arena/providers/docs.d.ts +6 -0
  66. package/dist/arena/providers/docs.js +108 -0
  67. package/dist/arena/providers/git.d.ts +8 -0
  68. package/dist/arena/providers/git.js +174 -0
  69. package/dist/arena/providers/index.d.ts +32 -0
  70. package/dist/arena/providers/index.js +132 -0
  71. package/dist/arena/providers/none.d.ts +7 -0
  72. package/dist/arena/providers/none.js +11 -0
  73. package/dist/arena/providers/repo.d.ts +6 -0
  74. package/dist/arena/providers/repo.js +255 -0
  75. package/dist/arena/render/session.d.ts +17 -0
  76. package/dist/arena/render/session.js +190 -0
  77. package/dist/arena/render/terminal.d.ts +34 -0
  78. package/dist/arena/render/terminal.js +286 -0
  79. package/dist/arena/strategies/discussion.d.ts +25 -0
  80. package/dist/arena/strategies/discussion.js +143 -0
  81. package/dist/arena/strategies/index.d.ts +15 -0
  82. package/dist/arena/strategies/index.js +28 -0
  83. package/dist/arena/strategies/language-wrapper.d.ts +17 -0
  84. package/dist/arena/strategies/language-wrapper.js +102 -0
  85. package/dist/arena/strategies/lens-wrapper.d.ts +16 -0
  86. package/dist/arena/strategies/lens-wrapper.js +236 -0
  87. package/dist/arena/strategies/planning.d.ts +30 -0
  88. package/dist/arena/strategies/planning.js +225 -0
  89. package/dist/arena/strategies/review.d.ts +26 -0
  90. package/dist/arena/strategies/review.js +168 -0
  91. package/dist/arena/strategies/utils.d.ts +39 -0
  92. package/dist/arena/strategies/utils.js +647 -0
  93. package/dist/arena/tools/selector.d.ts +17 -0
  94. package/dist/arena/tools/selector.js +61 -0
  95. package/dist/arena/transitions.d.ts +48 -0
  96. package/dist/arena/transitions.js +92 -0
  97. package/dist/arena/types.d.ts +508 -0
  98. package/dist/arena/types.js +27 -0
  99. package/dist/cli/agent-server-stdio.d.ts +32 -0
  100. package/dist/cli/agent-server-stdio.js +116 -0
  101. package/dist/colorizer.d.ts +23 -0
  102. package/dist/colorizer.js +12 -0
  103. package/dist/context/compaction.d.ts +116 -0
  104. package/dist/context/compaction.js +534 -0
  105. package/dist/context/manager.d.ts +145 -0
  106. package/dist/context/manager.js +423 -0
  107. package/dist/context/token-counter.d.ts +27 -0
  108. package/dist/context/token-counter.js +91 -0
  109. package/dist/context/tool-result-storage.d.ts +96 -0
  110. package/dist/context/tool-result-storage.js +296 -0
  111. package/dist/cost-tracker.d.ts +64 -0
  112. package/dist/cost-tracker.js +314 -0
  113. package/dist/cron/scheduler.d.ts +34 -0
  114. package/dist/cron/scheduler.js +115 -0
  115. package/dist/data/deepseek-models.json +46 -0
  116. package/dist/data/gemini-models.json +67 -0
  117. package/dist/data/openai-models.json +175 -0
  118. package/dist/data/openrouter-models.d.ts +35 -0
  119. package/dist/data/openrouter-models.js +36 -0
  120. package/dist/data/openrouter-models.json +4626 -0
  121. package/dist/data/openrouter-sync.d.ts +16 -0
  122. package/dist/data/openrouter-sync.js +53 -0
  123. package/dist/data/static-catalogs.d.ts +25 -0
  124. package/dist/data/static-catalogs.js +26 -0
  125. package/dist/data/zai-models.json +56 -0
  126. package/dist/engine/cost-store.d.ts +22 -0
  127. package/dist/engine/cost-store.js +15 -0
  128. package/dist/engine/engine.d.ts +295 -0
  129. package/dist/engine/engine.js +1467 -0
  130. package/dist/engine/model-facade.d.ts +24 -0
  131. package/dist/engine/model-facade.js +194 -0
  132. package/dist/engine/parse-task.d.ts +59 -0
  133. package/dist/engine/parse-task.js +135 -0
  134. package/dist/engine/patch-orphaned-tools.d.ts +52 -0
  135. package/dist/engine/patch-orphaned-tools.js +95 -0
  136. package/dist/engine/query.d.ts +50 -0
  137. package/dist/engine/query.js +107 -0
  138. package/dist/engine/runtime.d.ts +50 -0
  139. package/dist/engine/runtime.js +59 -0
  140. package/dist/engine/streaming-tool-queue.d.ts +34 -0
  141. package/dist/engine/streaming-tool-queue.js +61 -0
  142. package/dist/engine/token-budget.d.ts +22 -0
  143. package/dist/engine/token-budget.js +40 -0
  144. package/dist/engine/tool-summary.d.ts +13 -0
  145. package/dist/engine/tool-summary.js +35 -0
  146. package/dist/engine/turn-loop.d.ts +122 -0
  147. package/dist/engine/turn-loop.js +602 -0
  148. package/dist/engine/turn-state.d.ts +20 -0
  149. package/dist/engine/turn-state.js +17 -0
  150. package/dist/exceptions.d.ts +61 -0
  151. package/dist/exceptions.js +116 -0
  152. package/dist/git/utils.d.ts +35 -0
  153. package/dist/git/utils.js +98 -0
  154. package/dist/git/worktree.d.ts +36 -0
  155. package/dist/git/worktree.js +139 -0
  156. package/dist/hooks/events.d.ts +114 -0
  157. package/dist/hooks/events.js +4 -0
  158. package/dist/hooks/inject.d.ts +19 -0
  159. package/dist/hooks/inject.js +29 -0
  160. package/dist/hooks/registry.d.ts +15 -0
  161. package/dist/hooks/registry.js +84 -0
  162. package/dist/hooks/shell-runner.d.ts +45 -0
  163. package/dist/hooks/shell-runner.js +173 -0
  164. package/dist/index.d.ts +117 -0
  165. package/dist/index.js +145 -0
  166. package/dist/llm/api-key-sanitize.d.ts +22 -0
  167. package/dist/llm/api-key-sanitize.js +81 -0
  168. package/dist/llm/capabilities/index.d.ts +20 -0
  169. package/dist/llm/capabilities/index.js +39 -0
  170. package/dist/llm/capabilities/rules.d.ts +26 -0
  171. package/dist/llm/capabilities/rules.js +215 -0
  172. package/dist/llm/capabilities/types.d.ts +114 -0
  173. package/dist/llm/capabilities/types.js +24 -0
  174. package/dist/llm/client-base.d.ts +29 -0
  175. package/dist/llm/client-base.js +137 -0
  176. package/dist/llm/client-factory.d.ts +10 -0
  177. package/dist/llm/client-factory.js +29 -0
  178. package/dist/llm/model-cache.d.ts +21 -0
  179. package/dist/llm/model-cache.js +46 -0
  180. package/dist/llm/model-fetcher.d.ts +29 -0
  181. package/dist/llm/model-fetcher.js +282 -0
  182. package/dist/llm/model-pool.d.ts +95 -0
  183. package/dist/llm/model-pool.js +246 -0
  184. package/dist/llm/provider-catalog.d.ts +32 -0
  185. package/dist/llm/provider-catalog.js +50 -0
  186. package/dist/llm/provider-kinds.d.ts +21 -0
  187. package/dist/llm/provider-kinds.js +132 -0
  188. package/dist/llm/providers/anthropic.d.ts +19 -0
  189. package/dist/llm/providers/anthropic.js +267 -0
  190. package/dist/llm/providers/openai.d.ts +64 -0
  191. package/dist/llm/providers/openai.js +606 -0
  192. package/dist/llm/retry.d.ts +12 -0
  193. package/dist/llm/retry.js +17 -0
  194. package/dist/llm/stream-watchdog.d.ts +42 -0
  195. package/dist/llm/stream-watchdog.js +70 -0
  196. package/dist/llm/token-counter.d.ts +17 -0
  197. package/dist/llm/token-counter.js +36 -0
  198. package/dist/llm/types.d.ts +37 -0
  199. package/dist/llm/types.js +4 -0
  200. package/dist/logging/logger.d.ts +109 -0
  201. package/dist/logging/logger.js +390 -0
  202. package/dist/logging/sanitize-messages.d.ts +42 -0
  203. package/dist/logging/sanitize-messages.js +150 -0
  204. package/dist/logging/session-recorder.d.ts +90 -0
  205. package/dist/logging/session-recorder.js +304 -0
  206. package/dist/lsp/client.d.ts +41 -0
  207. package/dist/lsp/client.js +166 -0
  208. package/dist/lsp/manager.d.ts +40 -0
  209. package/dist/lsp/manager.js +124 -0
  210. package/dist/lsp/servers.d.ts +16 -0
  211. package/dist/lsp/servers.js +60 -0
  212. package/dist/migrate-models.d.ts +45 -0
  213. package/dist/migrate-models.js +179 -0
  214. package/dist/onboarding.d.ts +189 -0
  215. package/dist/onboarding.js +625 -0
  216. package/dist/plugins/gitOps.d.ts +32 -0
  217. package/dist/plugins/gitOps.js +62 -0
  218. package/dist/plugins/installedPlugins.d.ts +15 -0
  219. package/dist/plugins/installedPlugins.js +56 -0
  220. package/dist/plugins/knownMarketplaces.d.ts +10 -0
  221. package/dist/plugins/knownMarketplaces.js +46 -0
  222. package/dist/plugins/loadPluginHooks.d.ts +52 -0
  223. package/dist/plugins/loadPluginHooks.js +162 -0
  224. package/dist/plugins/marketplaceManager.d.ts +49 -0
  225. package/dist/plugins/marketplaceManager.js +142 -0
  226. package/dist/plugins/parseMarketplaceInput.d.ts +16 -0
  227. package/dist/plugins/parseMarketplaceInput.js +73 -0
  228. package/dist/plugins/pluginCommandHook.d.ts +54 -0
  229. package/dist/plugins/pluginCommandHook.js +180 -0
  230. package/dist/plugins/pluginCommandsLoader.d.ts +25 -0
  231. package/dist/plugins/pluginCommandsLoader.js +114 -0
  232. package/dist/plugins/pluginInstaller.d.ts +36 -0
  233. package/dist/plugins/pluginInstaller.js +228 -0
  234. package/dist/plugins/schemas.d.ts +9 -0
  235. package/dist/plugins/schemas.js +136 -0
  236. package/dist/plugins/types.d.ts +75 -0
  237. package/dist/plugins/types.js +7 -0
  238. package/dist/plugins/varRewrite.d.ts +42 -0
  239. package/dist/plugins/varRewrite.js +129 -0
  240. package/dist/preset/index.d.ts +60 -0
  241. package/dist/preset/index.js +159 -0
  242. package/dist/product/define.d.ts +60 -0
  243. package/dist/product/define.js +123 -0
  244. package/dist/product/index.d.ts +5 -0
  245. package/dist/product/index.js +4 -0
  246. package/dist/product/types.d.ts +111 -0
  247. package/dist/product/types.js +21 -0
  248. package/dist/prompt/composer.d.ts +49 -0
  249. package/dist/prompt/composer.js +168 -0
  250. package/dist/prompt/instruction-scanner.d.ts +54 -0
  251. package/dist/prompt/instruction-scanner.js +187 -0
  252. package/dist/prompt/section-cache.d.ts +15 -0
  253. package/dist/prompt/section-cache.js +31 -0
  254. package/dist/prompt/section-loader.d.ts +26 -0
  255. package/dist/prompt/section-loader.js +53 -0
  256. package/dist/prompt/sections/base.md +35 -0
  257. package/dist/prompt/sections/coding.md +31 -0
  258. package/dist/prompt/sections/orchestration.md +16 -0
  259. package/dist/prompt/sections/tone.md +9 -0
  260. package/dist/protocol/chat-session-manager.d.ts +33 -0
  261. package/dist/protocol/chat-session-manager.js +65 -0
  262. package/dist/protocol/chat-session.d.ts +49 -0
  263. package/dist/protocol/chat-session.js +86 -0
  264. package/dist/protocol/client.d.ts +104 -0
  265. package/dist/protocol/client.js +260 -0
  266. package/dist/protocol/factories.d.ts +93 -0
  267. package/dist/protocol/factories.js +64 -0
  268. package/dist/protocol/helpers.d.ts +42 -0
  269. package/dist/protocol/helpers.js +55 -0
  270. package/dist/protocol/index.d.ts +4 -0
  271. package/dist/protocol/index.js +4 -0
  272. package/dist/protocol/server.d.ts +80 -0
  273. package/dist/protocol/server.js +855 -0
  274. package/dist/protocol/transport.d.ts +37 -0
  275. package/dist/protocol/transport.js +85 -0
  276. package/dist/protocol/types.d.ts +221 -0
  277. package/dist/protocol/types.js +61 -0
  278. package/dist/remote/bridge.d.ts +37 -0
  279. package/dist/remote/bridge.js +103 -0
  280. package/dist/run/ArtifactTracker.d.ts +38 -0
  281. package/dist/run/ArtifactTracker.js +132 -0
  282. package/dist/run/CheckpointWriter.d.ts +53 -0
  283. package/dist/run/CheckpointWriter.js +135 -0
  284. package/dist/run/EngineRunner.d.ts +72 -0
  285. package/dist/run/EngineRunner.js +119 -0
  286. package/dist/run/Evaluator.d.ts +56 -0
  287. package/dist/run/Evaluator.js +62 -0
  288. package/dist/run/FileRunStore.d.ts +39 -0
  289. package/dist/run/FileRunStore.js +176 -0
  290. package/dist/run/Heartbeat.d.ts +54 -0
  291. package/dist/run/Heartbeat.js +123 -0
  292. package/dist/run/RunApprovalBackend.d.ts +53 -0
  293. package/dist/run/RunApprovalBackend.js +85 -0
  294. package/dist/run/RunLock.d.ts +40 -0
  295. package/dist/run/RunLock.js +98 -0
  296. package/dist/run/RunManager.d.ts +82 -0
  297. package/dist/run/RunManager.js +587 -0
  298. package/dist/run/RunQueue.d.ts +27 -0
  299. package/dist/run/RunQueue.js +73 -0
  300. package/dist/run/RunStore.d.ts +25 -0
  301. package/dist/run/RunStore.js +9 -0
  302. package/dist/run/factory.d.ts +63 -0
  303. package/dist/run/factory.js +51 -0
  304. package/dist/run/index.d.ts +17 -0
  305. package/dist/run/index.js +23 -0
  306. package/dist/run/types.d.ts +136 -0
  307. package/dist/run/types.js +28 -0
  308. package/dist/runtime/safe-spawn.d.ts +118 -0
  309. package/dist/runtime/safe-spawn.js +268 -0
  310. package/dist/services/analytics.d.ts +29 -0
  311. package/dist/services/analytics.js +84 -0
  312. package/dist/services/auto-dream.d.ts +49 -0
  313. package/dist/services/auto-dream.js +124 -0
  314. package/dist/services/diagnostics.d.ts +41 -0
  315. package/dist/services/diagnostics.js +99 -0
  316. package/dist/services/extract-memories.d.ts +31 -0
  317. package/dist/services/extract-memories.js +71 -0
  318. package/dist/services/index.d.ts +11 -0
  319. package/dist/services/index.js +17 -0
  320. package/dist/services/memory-orchestrator.d.ts +60 -0
  321. package/dist/services/memory-orchestrator.js +133 -0
  322. package/dist/services/notifier.d.ts +25 -0
  323. package/dist/services/notifier.js +69 -0
  324. package/dist/services/oauth.d.ts +27 -0
  325. package/dist/services/oauth.js +153 -0
  326. package/dist/services/session-memory.d.ts +37 -0
  327. package/dist/services/session-memory.js +81 -0
  328. package/dist/session/file-history.d.ts +41 -0
  329. package/dist/session/file-history.js +115 -0
  330. package/dist/session/memory.d.ts +104 -0
  331. package/dist/session/memory.js +310 -0
  332. package/dist/session/session-manager.d.ts +41 -0
  333. package/dist/session/session-manager.js +261 -0
  334. package/dist/session/transcript.d.ts +39 -0
  335. package/dist/session/transcript.js +186 -0
  336. package/dist/settings/manager.d.ts +36 -0
  337. package/dist/settings/manager.js +187 -0
  338. package/dist/settings/schema.d.ts +1219 -0
  339. package/dist/settings/schema.js +246 -0
  340. package/dist/skills/frontmatter.d.ts +13 -0
  341. package/dist/skills/frontmatter.js +70 -0
  342. package/dist/skills/index.d.ts +7 -0
  343. package/dist/skills/index.js +6 -0
  344. package/dist/skills/scanner.d.ts +31 -0
  345. package/dist/skills/scanner.js +171 -0
  346. package/dist/state.d.ts +160 -0
  347. package/dist/state.js +267 -0
  348. package/dist/tool-system/builtin/agent-notifications.d.ts +84 -0
  349. package/dist/tool-system/builtin/agent-notifications.js +197 -0
  350. package/dist/tool-system/builtin/agent-registry.d.ts +67 -0
  351. package/dist/tool-system/builtin/agent-registry.js +126 -0
  352. package/dist/tool-system/builtin/agent-transcript-translator.d.ts +22 -0
  353. package/dist/tool-system/builtin/agent-transcript-translator.js +160 -0
  354. package/dist/tool-system/builtin/agent.d.ts +16 -0
  355. package/dist/tool-system/builtin/agent.js +364 -0
  356. package/dist/tool-system/builtin/apply-patch/applier.d.ts +26 -0
  357. package/dist/tool-system/builtin/apply-patch/applier.js +250 -0
  358. package/dist/tool-system/builtin/apply-patch/index.d.ts +20 -0
  359. package/dist/tool-system/builtin/apply-patch/index.js +101 -0
  360. package/dist/tool-system/builtin/apply-patch/parser.d.ts +17 -0
  361. package/dist/tool-system/builtin/apply-patch/parser.js +212 -0
  362. package/dist/tool-system/builtin/apply-patch/seek-sequence.d.ts +18 -0
  363. package/dist/tool-system/builtin/apply-patch/seek-sequence.js +123 -0
  364. package/dist/tool-system/builtin/apply-patch/types.d.ts +49 -0
  365. package/dist/tool-system/builtin/apply-patch/types.js +13 -0
  366. package/dist/tool-system/builtin/arena.d.ts +31 -0
  367. package/dist/tool-system/builtin/arena.js +416 -0
  368. package/dist/tool-system/builtin/ask-user.d.ts +20 -0
  369. package/dist/tool-system/builtin/ask-user.js +99 -0
  370. package/dist/tool-system/builtin/bash.d.ts +21 -0
  371. package/dist/tool-system/builtin/bash.js +149 -0
  372. package/dist/tool-system/builtin/brief.d.ts +6 -0
  373. package/dist/tool-system/builtin/brief.js +41 -0
  374. package/dist/tool-system/builtin/config.d.ts +6 -0
  375. package/dist/tool-system/builtin/config.js +67 -0
  376. package/dist/tool-system/builtin/cron.d.ts +10 -0
  377. package/dist/tool-system/builtin/cron.js +61 -0
  378. package/dist/tool-system/builtin/edit.d.ts +6 -0
  379. package/dist/tool-system/builtin/edit.js +100 -0
  380. package/dist/tool-system/builtin/file-cache.d.ts +11 -0
  381. package/dist/tool-system/builtin/file-cache.js +39 -0
  382. package/dist/tool-system/builtin/glob.d.ts +7 -0
  383. package/dist/tool-system/builtin/glob.js +76 -0
  384. package/dist/tool-system/builtin/grep.d.ts +7 -0
  385. package/dist/tool-system/builtin/grep.js +150 -0
  386. package/dist/tool-system/builtin/index.d.ts +20 -0
  387. package/dist/tool-system/builtin/index.js +449 -0
  388. package/dist/tool-system/builtin/lsp.d.ts +6 -0
  389. package/dist/tool-system/builtin/lsp.js +141 -0
  390. package/dist/tool-system/builtin/mcp-tools.d.ts +10 -0
  391. package/dist/tool-system/builtin/mcp-tools.js +102 -0
  392. package/dist/tool-system/builtin/memory.d.ts +26 -0
  393. package/dist/tool-system/builtin/memory.js +226 -0
  394. package/dist/tool-system/builtin/notebook-edit.d.ts +6 -0
  395. package/dist/tool-system/builtin/notebook-edit.js +124 -0
  396. package/dist/tool-system/builtin/plan.d.ts +15 -0
  397. package/dist/tool-system/builtin/plan.js +55 -0
  398. package/dist/tool-system/builtin/powershell.d.ts +11 -0
  399. package/dist/tool-system/builtin/powershell.js +64 -0
  400. package/dist/tool-system/builtin/read.d.ts +6 -0
  401. package/dist/tool-system/builtin/read.js +70 -0
  402. package/dist/tool-system/builtin/remote-trigger.d.ts +6 -0
  403. package/dist/tool-system/builtin/remote-trigger.js +54 -0
  404. package/dist/tool-system/builtin/repl.d.ts +11 -0
  405. package/dist/tool-system/builtin/repl.js +82 -0
  406. package/dist/tool-system/builtin/send-message.d.ts +6 -0
  407. package/dist/tool-system/builtin/send-message.js +47 -0
  408. package/dist/tool-system/builtin/skill-prompt.d.ts +20 -0
  409. package/dist/tool-system/builtin/skill-prompt.js +52 -0
  410. package/dist/tool-system/builtin/skill.d.ts +9 -0
  411. package/dist/tool-system/builtin/skill.js +55 -0
  412. package/dist/tool-system/builtin/sleep.d.ts +6 -0
  413. package/dist/tool-system/builtin/sleep.js +33 -0
  414. package/dist/tool-system/builtin/task.d.ts +48 -0
  415. package/dist/tool-system/builtin/task.js +139 -0
  416. package/dist/tool-system/builtin/tool-search.d.ts +11 -0
  417. package/dist/tool-system/builtin/tool-search.js +90 -0
  418. package/dist/tool-system/builtin/web-fetch.d.ts +10 -0
  419. package/dist/tool-system/builtin/web-fetch.js +328 -0
  420. package/dist/tool-system/builtin/web-search.d.ts +25 -0
  421. package/dist/tool-system/builtin/web-search.js +174 -0
  422. package/dist/tool-system/builtin/worktree.d.ts +10 -0
  423. package/dist/tool-system/builtin/worktree.js +95 -0
  424. package/dist/tool-system/builtin/write.d.ts +6 -0
  425. package/dist/tool-system/builtin/write.js +36 -0
  426. package/dist/tool-system/context.d.ts +165 -0
  427. package/dist/tool-system/context.js +18 -0
  428. package/dist/tool-system/executor.d.ts +49 -0
  429. package/dist/tool-system/executor.js +495 -0
  430. package/dist/tool-system/investigation-guard.d.ts +46 -0
  431. package/dist/tool-system/investigation-guard.js +155 -0
  432. package/dist/tool-system/mcp-manager.d.ts +67 -0
  433. package/dist/tool-system/mcp-manager.js +249 -0
  434. package/dist/tool-system/permission.d.ts +111 -0
  435. package/dist/tool-system/permission.js +774 -0
  436. package/dist/tool-system/registry.d.ts +32 -0
  437. package/dist/tool-system/registry.js +131 -0
  438. package/dist/tool-system/sandbox/bwrap.d.ts +13 -0
  439. package/dist/tool-system/sandbox/bwrap.js +63 -0
  440. package/dist/tool-system/sandbox/index.d.ts +78 -0
  441. package/dist/tool-system/sandbox/index.js +222 -0
  442. package/dist/tool-system/sandbox/off.d.ts +2 -0
  443. package/dist/tool-system/sandbox/off.js +8 -0
  444. package/dist/tool-system/sandbox/seatbelt.d.ts +18 -0
  445. package/dist/tool-system/sandbox/seatbelt.js +109 -0
  446. package/dist/tool-system/task-guard.d.ts +29 -0
  447. package/dist/tool-system/task-guard.js +70 -0
  448. package/dist/tool-system/validation.d.ts +5 -0
  449. package/dist/tool-system/validation.js +39 -0
  450. package/dist/types.d.ts +376 -0
  451. package/dist/types.js +4 -0
  452. package/dist/updater.d.ts +65 -0
  453. package/dist/updater.js +405 -0
  454. package/dist/utils/debug.d.ts +41 -0
  455. package/dist/utils/debug.js +110 -0
  456. package/dist/utils/earlyInput.d.ts +43 -0
  457. package/dist/utils/earlyInput.js +166 -0
  458. package/dist/utils/env.d.ts +24 -0
  459. package/dist/utils/env.js +104 -0
  460. package/dist/utils/envUtils.d.ts +51 -0
  461. package/dist/utils/envUtils.js +135 -0
  462. package/dist/utils/execFileNoThrow.d.ts +39 -0
  463. package/dist/utils/execFileNoThrow.js +74 -0
  464. package/dist/utils/format.d.ts +44 -0
  465. package/dist/utils/format.js +236 -0
  466. package/dist/utils/intl.d.ts +22 -0
  467. package/dist/utils/intl.js +83 -0
  468. package/dist/utils/lockfile.d.ts +15 -0
  469. package/dist/utils/lockfile.js +30 -0
  470. package/dist/utils/memoize.d.ts +19 -0
  471. package/dist/utils/memoize.js +14 -0
  472. package/dist/utils/semver.d.ts +6 -0
  473. package/dist/utils/semver.js +13 -0
  474. package/dist/utils/sliceAnsi.d.ts +12 -0
  475. package/dist/utils/sliceAnsi.js +62 -0
  476. package/dist/utils/systemTheme.d.ts +40 -0
  477. package/dist/utils/systemTheme.js +108 -0
  478. package/dist/utils/task-sanitizer.d.ts +6 -0
  479. package/dist/utils/task-sanitizer.js +24 -0
  480. package/dist/utils/theme.d.ts +93 -0
  481. package/dist/utils/theme.js +544 -0
  482. package/dist/utils/toolDisplay.d.ts +31 -0
  483. package/dist/utils/toolDisplay.js +188 -0
  484. package/package.json +72 -0
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Stream Idle Watchdog — guarantees an upper bound on the time a streaming
3
+ * LLM call can spend with no bytes arriving. Without this, a wedged HTTP/2
4
+ * connection can hang the session indefinitely; the SDK's request timeout
5
+ * only covers the initial fetch, not the streaming body.
6
+ *
7
+ * Disabled by default. Enabled via env CODESHELL_ENABLE_STREAM_WATCHDOG=1.
8
+ */
9
+ export class StreamIdleTimeoutError extends Error {
10
+ idleMs;
11
+ requestId;
12
+ kind = "stream-idle-timeout";
13
+ constructor(idleMs, requestId) {
14
+ super(`Stream idle for ${idleMs}ms — aborted`);
15
+ this.idleMs = idleMs;
16
+ this.requestId = requestId;
17
+ this.name = "StreamIdleTimeoutError";
18
+ }
19
+ }
20
+ export function createStreamWatchdog(opts) {
21
+ const warnMs = opts.warningMs ?? Math.floor(opts.idleTimeoutMs / 2);
22
+ let idleTimer = null;
23
+ let warnTimer = null;
24
+ let disposed = false;
25
+ function arm() {
26
+ if (disposed)
27
+ return;
28
+ if (opts.onWarning) {
29
+ warnTimer = setTimeout(() => {
30
+ if (disposed)
31
+ return;
32
+ opts.onWarning?.(warnMs);
33
+ }, warnMs);
34
+ }
35
+ idleTimer = setTimeout(() => {
36
+ if (disposed)
37
+ return;
38
+ opts.onTimeout();
39
+ }, opts.idleTimeoutMs);
40
+ }
41
+ function clear() {
42
+ if (idleTimer !== null) {
43
+ clearTimeout(idleTimer);
44
+ idleTimer = null;
45
+ }
46
+ if (warnTimer !== null) {
47
+ clearTimeout(warnTimer);
48
+ warnTimer = null;
49
+ }
50
+ }
51
+ arm();
52
+ return {
53
+ reset() {
54
+ if (disposed)
55
+ return;
56
+ clear();
57
+ arm();
58
+ },
59
+ dispose() {
60
+ disposed = true;
61
+ clear();
62
+ },
63
+ };
64
+ }
65
+ /** Environment-driven defaults. Read once at import time is fine — these never change inside a process. */
66
+ export const STREAM_WATCHDOG_CONFIG = {
67
+ enabled: process.env.CODESHELL_ENABLE_STREAM_WATCHDOG === "1",
68
+ idleTimeoutMs: parseInt(process.env.CODESHELL_STREAM_IDLE_TIMEOUT_MS || "", 10) || 90_000,
69
+ retries: parseInt(process.env.CODESHELL_STREAM_WATCHDOG_RETRIES || "", 10) || 2,
70
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Token counter — best-effort live token count for streaming output.
3
+ *
4
+ * Uses gpt-tokenizer's cl100k_base encoding. It's exact for GPT-4 family and
5
+ * close enough (within ~10%) for Claude/DeepSeek/Qwen for the purpose of a
6
+ * live counter in the UI. The authoritative number is still the provider's
7
+ * `usage` field, captured at end-of-stream.
8
+ *
9
+ * The encoder is lazy-initialized on first use so we don't pay the cost on
10
+ * startup for sessions that never stream.
11
+ */
12
+ /**
13
+ * Count tokens in `text`. Synchronous. If the encoder isn't loaded yet,
14
+ * falls back to chars/4 — only happens for the very first stream chunk in a
15
+ * cold process.
16
+ */
17
+ export declare function countTokens(text: string): number;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Token counter — best-effort live token count for streaming output.
3
+ *
4
+ * Uses gpt-tokenizer's cl100k_base encoding. It's exact for GPT-4 family and
5
+ * close enough (within ~10%) for Claude/DeepSeek/Qwen for the purpose of a
6
+ * live counter in the UI. The authoritative number is still the provider's
7
+ * `usage` field, captured at end-of-stream.
8
+ *
9
+ * The encoder is lazy-initialized on first use so we don't pay the cost on
10
+ * startup for sessions that never stream.
11
+ */
12
+ let encoderPromise = null;
13
+ async function getEncoder() {
14
+ if (!encoderPromise) {
15
+ encoderPromise = import("gpt-tokenizer").then((mod) => mod.encode);
16
+ }
17
+ return encoderPromise;
18
+ }
19
+ let encoderSync = null;
20
+ // Kick off the import so synchronous callers can use it on the next tick.
21
+ // First call still falls back to a length estimate.
22
+ void getEncoder().then((fn) => {
23
+ encoderSync = fn;
24
+ });
25
+ /**
26
+ * Count tokens in `text`. Synchronous. If the encoder isn't loaded yet,
27
+ * falls back to chars/4 — only happens for the very first stream chunk in a
28
+ * cold process.
29
+ */
30
+ export function countTokens(text) {
31
+ if (!text)
32
+ return 0;
33
+ if (encoderSync)
34
+ return encoderSync(text).length;
35
+ return Math.ceil(text.length / 4);
36
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * LLM-specific internal types.
3
+ */
4
+ import type { Message, ToolDefinition, LLMStreamChunk, TokenUsage } from "../types.js";
5
+ export interface CreateMessageOptions {
6
+ systemPrompt: string;
7
+ messages: Message[];
8
+ tools?: ToolDefinition[];
9
+ temperature?: number;
10
+ maxTokens?: number;
11
+ stream?: boolean;
12
+ onChunk?: (chunk: LLMStreamChunk) => void;
13
+ signal?: AbortSignal;
14
+ /**
15
+ * If false, this call's usage is excluded from the client's usage tracker
16
+ * and from the process-wide onUsage hook. Used for auxiliary sub-calls
17
+ * (tool-summary, future helper prompts) that should not appear in
18
+ * session_end.cost or skew turn/requestCount semantics.
19
+ * @default true
20
+ */
21
+ recordUsage?: boolean;
22
+ /**
23
+ * DeepSeek V4 thinking-mode switch. "enabled" is the endpoint default;
24
+ * "disabled" turns reasoning off (faster, cheaper, no `reasoning_content`
25
+ * on the reply). Ignored by every provider except DeepSeek V4 — the OpenAI
26
+ * SDK forwards unknown top-level fields verbatim, so it's harmless on
27
+ * other compatible endpoints.
28
+ */
29
+ thinking?: "enabled" | "disabled";
30
+ }
31
+ export interface LLMUsageTracker {
32
+ records: TokenUsage[];
33
+ totalPromptTokens: number;
34
+ totalCompletionTokens: number;
35
+ totalTokens: number;
36
+ requestCount: number;
37
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * LLM-specific internal types.
3
+ */
4
+ export {};
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Unified file logger for code-shell.
3
+ *
4
+ * Sinks (JSON Lines), routed by `cat`:
5
+ * ~/.code-shell/logs/ui-ink-YYYY-MM-DD.log
6
+ * — UI/ink chatter: stream events, ctx render, ink screen diffs.
7
+ * ~/.code-shell/logs/engine-YYYY-MM-DD.log
8
+ * — everything else: engine, llm, tool, context, mcp, sandbox, ...
9
+ *
10
+ * Routing is by entry `cat`: cat ∈ {ui, ink, render, stream} → ui-ink bucket;
11
+ * anything else → engine bucket. Run scripts/logs.sh to query both at once
12
+ * (merge sorted by timestamp, filter by sid, etc).
13
+ *
14
+ * Level defaults:
15
+ * - Local dev (CODE_SHELL_DEV=1, or running from src/, or --debug) → "debug"
16
+ * - Otherwise → "info"
17
+ * - CODE_SHELL_LOG_LEVEL overrides everything.
18
+ *
19
+ * Category filter (--debug=mcp,api or CODE_SHELL_DEBUG=mcp,api):
20
+ * When set, only debug logs whose `cat` matches are written.
21
+ *
22
+ * Disable entirely: CODE_SHELL_LOG=0
23
+ */
24
+ export type LogLevel = "debug" | "info" | "warn" | "error";
25
+ /**
26
+ * Override the directory log files are written into. Pass `null` to
27
+ * revert to the default `~/.code-shell/logs`. Affects all future writes
28
+ * AND `getLogsDir()` / `getRecentLogs()` reads, so call this before any
29
+ * log activity if you want a clean redirected stream.
30
+ */
31
+ export declare function setLogsDir(dir: string | null): void;
32
+ export declare function setCurrentSid(sid: string): void;
33
+ export declare function getCurrentSid(): string;
34
+ /**
35
+ * Run `fn` inside an ALS scope tagged with `sid`. All log lines emitted
36
+ * synchronously or via `await` inside `fn` resolve `getCurrentSid()` to
37
+ * this `sid` — concurrent Engine.run invocations no longer race on a
38
+ * module global.
39
+ */
40
+ export declare function runWithSid<T>(sid: string, fn: () => T | Promise<T>): T | Promise<T>;
41
+ /**
42
+ * Bind `sid` to the *current* async context without needing a callback.
43
+ * The binding lasts until the current async stack unwinds; concurrent
44
+ * sibling async chains keep their own bindings. Engine.run uses this so
45
+ * we don't have to indent the entire (long) method body into a callback.
46
+ */
47
+ export declare function enterSid(sid: string): void;
48
+ export declare function getInMemoryErrors(): ReadonlyArray<{
49
+ msg: string;
50
+ t: string;
51
+ data?: unknown;
52
+ }>;
53
+ export type ErrorLogSink = {
54
+ logError: (error: Error) => void;
55
+ logMCPError: (serverName: string, error: unknown) => void;
56
+ logMCPDebug: (serverName: string, message: string) => void;
57
+ getErrorsPath: () => string;
58
+ getMCPLogsPath: (serverName: string) => string;
59
+ };
60
+ export declare function attachErrorLogSink(sink: ErrorLogSink): void;
61
+ export interface LogContext {
62
+ cat?: string;
63
+ sid?: string;
64
+ [key: string]: unknown;
65
+ }
66
+ declare class Logger {
67
+ private readonly context;
68
+ private readonly enabled;
69
+ private readonly minLevel;
70
+ private readonly categoryFilter;
71
+ private readonly stderrEcho;
72
+ private dirReady;
73
+ constructor(context?: LogContext);
74
+ child(extra: LogContext): Logger;
75
+ /**
76
+ * Set the session id stamped on every subsequent log entry written by
77
+ * any logger in the process. Called by Engine once a run's
78
+ * authoritative session id is known.
79
+ */
80
+ setSid(sid: string): void;
81
+ getSid(): string;
82
+ debug(msg: string, data?: Record<string, unknown>): void;
83
+ info(msg: string, data?: Record<string, unknown>): void;
84
+ warn(msg: string, data?: Record<string, unknown>): void;
85
+ error(msgOrErr: string | Error | unknown, data?: Record<string, unknown> | Error): void;
86
+ private recordError;
87
+ private write;
88
+ getMinLevel(): LogLevel;
89
+ isCategoryActive(cat: string): boolean;
90
+ /**
91
+ * Open a span: writes a `<name>.begin` debug entry now and returns a handle
92
+ * whose `end()` writes `<name>.end` with `duration_ms` populated. Use for
93
+ * any "I want begin → end + how long" pattern (tool exec, LLM request,
94
+ * permission ask, etc.) so the begin/end pair is grouped under one cat
95
+ * and the duration is computed once instead of by hand from timestamps.
96
+ */
97
+ span(name: string, data?: Record<string, unknown>): LogSpan;
98
+ }
99
+ export interface LogSpan {
100
+ end(extra?: Record<string, unknown>): void;
101
+ fail(err: unknown, extra?: Record<string, unknown>): void;
102
+ }
103
+ export declare const logger: Logger;
104
+ export declare function getLogsDir(): string;
105
+ export declare function getRecentLogs(n?: number): string[];
106
+ export declare function rotateLogs(): void;
107
+ /** @internal — for tests */
108
+ export declare function _resetLoggerStateForTesting(): void;
109
+ export {};
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Unified file logger for code-shell.
3
+ *
4
+ * Sinks (JSON Lines), routed by `cat`:
5
+ * ~/.code-shell/logs/ui-ink-YYYY-MM-DD.log
6
+ * — UI/ink chatter: stream events, ctx render, ink screen diffs.
7
+ * ~/.code-shell/logs/engine-YYYY-MM-DD.log
8
+ * — everything else: engine, llm, tool, context, mcp, sandbox, ...
9
+ *
10
+ * Routing is by entry `cat`: cat ∈ {ui, ink, render, stream} → ui-ink bucket;
11
+ * anything else → engine bucket. Run scripts/logs.sh to query both at once
12
+ * (merge sorted by timestamp, filter by sid, etc).
13
+ *
14
+ * Level defaults:
15
+ * - Local dev (CODE_SHELL_DEV=1, or running from src/, or --debug) → "debug"
16
+ * - Otherwise → "info"
17
+ * - CODE_SHELL_LOG_LEVEL overrides everything.
18
+ *
19
+ * Category filter (--debug=mcp,api or CODE_SHELL_DEBUG=mcp,api):
20
+ * When set, only debug logs whose `cat` matches are written.
21
+ *
22
+ * Disable entirely: CODE_SHELL_LOG=0
23
+ */
24
+ import { appendFileSync, mkdirSync, existsSync, readdirSync, unlinkSync, readFileSync, } from "node:fs";
25
+ import { join, dirname } from "node:path";
26
+ import { homedir } from "node:os";
27
+ import { AsyncLocalStorage } from "node:async_hooks";
28
+ const LEVEL_ORDER = {
29
+ debug: 0,
30
+ info: 1,
31
+ warn: 2,
32
+ error: 3,
33
+ };
34
+ function defaultLogsDir() {
35
+ return join(homedir(), ".code-shell", "logs");
36
+ }
37
+ // Mutable so non-CLI hosts (Electron renderer, headless containers, tests)
38
+ // can redirect writes without touching every callsite. Reads go through
39
+ // getLogsDir() so a single setLogsDir() call propagates everywhere.
40
+ let _logsDir = null;
41
+ function logsDir() {
42
+ return _logsDir ?? defaultLogsDir();
43
+ }
44
+ /**
45
+ * Override the directory log files are written into. Pass `null` to
46
+ * revert to the default `~/.code-shell/logs`. Affects all future writes
47
+ * AND `getLogsDir()` / `getRecentLogs()` reads, so call this before any
48
+ * log activity if you want a clean redirected stream.
49
+ */
50
+ export function setLogsDir(dir) {
51
+ _logsDir = dir;
52
+ }
53
+ const MAX_LOG_FILES = 7;
54
+ const MAX_IN_MEMORY_ERRORS = 100;
55
+ /**
56
+ * Map a log entry's `cat` to a file bucket: "ui-ink" for UI/render logs,
57
+ * "engine" for everything else (engine, llm, tool, context, mcp, ...).
58
+ * Buckets are date-suffixed: ui-ink-2026-05-14.log / engine-2026-05-14.log.
59
+ *
60
+ * UI/ink lives in its own file because it's the chattiest (200ms spinner
61
+ * ticks, every stream event) and was drowning out engine traces. Keeping
62
+ * both date-suffixed lets one `grep "sid":"<id>"` over both files
63
+ * reconstruct a full session timeline if needed.
64
+ */
65
+ const INK_CATS = new Set(["ui", "ink", "render", "stream"]);
66
+ function routeBucket(cat, fallbackCat) {
67
+ const c = (cat ?? fallbackCat ?? "").toLowerCase();
68
+ if (INK_CATS.has(c))
69
+ return "ui-ink";
70
+ return "engine";
71
+ }
72
+ // ─── Local-dev detection ───────────────────────────────────────────
73
+ function isLocalDev() {
74
+ if (process.env.CODE_SHELL_DEV === "1")
75
+ return true;
76
+ if (process.argv.includes("--debug") || process.argv.includes("-d"))
77
+ return true;
78
+ if (process.argv.some((a) => a.startsWith("--debug=")))
79
+ return true;
80
+ // Don't silently raise the level under tests — they have their own
81
+ // diagnostic story and shouldn't spam the daily log file.
82
+ if (process.env.NODE_ENV === "test" || process.env.BUN_TEST === "1")
83
+ return false;
84
+ if (process.argv.some((a) => a.includes("/tests/") || a.endsWith(".test.ts")))
85
+ return false;
86
+ // Running directly from src/ (bun run src/cli/main.ts) — not a packaged install.
87
+ const entry = process.argv[1] ?? "";
88
+ if (entry.includes(`${"/"}src${"/"}`))
89
+ return true;
90
+ return false;
91
+ }
92
+ function resolveDefaultLevel() {
93
+ const raw = process.env.CODE_SHELL_LOG_LEVEL?.toLowerCase().trim();
94
+ if (raw && Object.hasOwn(LEVEL_ORDER, raw))
95
+ return raw;
96
+ return isLocalDev() ? "debug" : "info";
97
+ }
98
+ // ─── Category filter (--debug=mcp,api) ─────────────────────────────
99
+ function resolveCategoryFilter() {
100
+ // CLI: --debug=a,b
101
+ const cliArg = process.argv.find((a) => a.startsWith("--debug="));
102
+ let raw;
103
+ if (cliArg)
104
+ raw = cliArg.slice("--debug=".length);
105
+ // Env: CODE_SHELL_DEBUG=a,b (but "1" / "true" mean "all on", not a filter)
106
+ else {
107
+ const env = process.env.CODE_SHELL_DEBUG;
108
+ if (env && env !== "1" && env !== "true")
109
+ raw = env;
110
+ }
111
+ if (!raw)
112
+ return null;
113
+ const set = new Set(raw
114
+ .split(",")
115
+ .map((s) => s.trim().toLowerCase())
116
+ .filter(Boolean));
117
+ return set.size > 0 ? set : null;
118
+ }
119
+ // ─── Session id resolution ─────────────────────────────────────────
120
+ //
121
+ // Two mechanisms, layered:
122
+ //
123
+ // 1. `runWithSid(sid, fn)` — preferred. Engine.run wraps its entire body
124
+ // in this AsyncLocalStorage scope, so every log line emitted inside the
125
+ // (possibly deeply async) call tree picks up the right sid. Concurrent
126
+ // parent + child Engines coexist because each `await` boundary preserves
127
+ // the ALS context — they don't trample each other like a single module
128
+ // global would.
129
+ //
130
+ // 2. `_currentSidFallback` — module-level mutable, written by `setCurrentSid`.
131
+ // Used only as a fallback when a code path runs outside any ALS scope
132
+ // (bootstrap, top-level CLI, sid-stamping for /sid command). Tools like
133
+ // `recordToolCall` reading `getCurrentSid()` inside an Engine.run will
134
+ // transparently get the ALS value first.
135
+ //
136
+ // Why both? Background sub-agents kick off detached via `void runSubAgent(...)`
137
+ // — they're still inside the parent's ALS scope at spawn time and inherit
138
+ // it correctly. But the *parent* Engine's later turns also need the parent
139
+ // sid, which ALS gives us automatically (the parent's scope outlives the
140
+ // child's). The module global is just a safety net for code that has no
141
+ // scope, like the initial setup before any Engine has started.
142
+ const _sidAls = new AsyncLocalStorage();
143
+ let _currentSidFallback = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
144
+ export function setCurrentSid(sid) {
145
+ _currentSidFallback = sid;
146
+ }
147
+ export function getCurrentSid() {
148
+ return _sidAls.getStore() ?? _currentSidFallback;
149
+ }
150
+ /**
151
+ * Run `fn` inside an ALS scope tagged with `sid`. All log lines emitted
152
+ * synchronously or via `await` inside `fn` resolve `getCurrentSid()` to
153
+ * this `sid` — concurrent Engine.run invocations no longer race on a
154
+ * module global.
155
+ */
156
+ export function runWithSid(sid, fn) {
157
+ return _sidAls.run(sid, fn);
158
+ }
159
+ /**
160
+ * Bind `sid` to the *current* async context without needing a callback.
161
+ * The binding lasts until the current async stack unwinds; concurrent
162
+ * sibling async chains keep their own bindings. Engine.run uses this so
163
+ * we don't have to indent the entire (long) method body into a callback.
164
+ */
165
+ export function enterSid(sid) {
166
+ _sidAls.enterWith(sid);
167
+ }
168
+ // ─── In-memory error ring (for bug reports) ─────────────────────────
169
+ const inMemoryErrors = [];
170
+ export function getInMemoryErrors() {
171
+ return inMemoryErrors;
172
+ }
173
+ let errorLogSink = null;
174
+ export function attachErrorLogSink(sink) {
175
+ if (errorLogSink !== null)
176
+ return;
177
+ errorLogSink = sink;
178
+ }
179
+ class Logger {
180
+ context;
181
+ enabled;
182
+ minLevel;
183
+ categoryFilter;
184
+ stderrEcho;
185
+ dirReady = false;
186
+ constructor(context = {}) {
187
+ this.context = context;
188
+ this.enabled = process.env.CODE_SHELL_LOG !== "0";
189
+ this.minLevel = resolveDefaultLevel();
190
+ this.categoryFilter = resolveCategoryFilter();
191
+ this.stderrEcho =
192
+ process.env.CODE_SHELL_DEBUG === "1" ||
193
+ process.argv.includes("--debug-to-stderr") ||
194
+ process.argv.includes("-d2e");
195
+ }
196
+ child(extra) {
197
+ return new Logger({ ...this.context, ...extra });
198
+ }
199
+ /**
200
+ * Set the session id stamped on every subsequent log entry written by
201
+ * any logger in the process. Called by Engine once a run's
202
+ * authoritative session id is known.
203
+ */
204
+ setSid(sid) {
205
+ setCurrentSid(sid);
206
+ }
207
+ getSid() {
208
+ return getCurrentSid();
209
+ }
210
+ debug(msg, data) {
211
+ this.write("debug", msg, data);
212
+ }
213
+ info(msg, data) {
214
+ this.write("info", msg, data);
215
+ }
216
+ warn(msg, data) {
217
+ this.write("warn", msg, data);
218
+ }
219
+ error(msgOrErr, data) {
220
+ let msg;
221
+ let entryData;
222
+ let errObj;
223
+ if (typeof msgOrErr === "string") {
224
+ msg = msgOrErr;
225
+ if (data instanceof Error) {
226
+ errObj = data;
227
+ entryData = { error: data.message, stack: data.stack };
228
+ }
229
+ else {
230
+ entryData = data;
231
+ }
232
+ }
233
+ else if (msgOrErr instanceof Error) {
234
+ msg = msgOrErr.message;
235
+ errObj = msgOrErr;
236
+ entryData = { stack: msgOrErr.stack };
237
+ }
238
+ else {
239
+ msg = String(msgOrErr);
240
+ }
241
+ this.recordError(msg, entryData);
242
+ this.write("error", msg, entryData);
243
+ if (errObj)
244
+ errorLogSink?.logError(errObj);
245
+ }
246
+ recordError(msg, data) {
247
+ if (inMemoryErrors.length >= MAX_IN_MEMORY_ERRORS)
248
+ inMemoryErrors.shift();
249
+ inMemoryErrors.push({ msg, t: new Date().toISOString(), data });
250
+ }
251
+ write(level, msg, data) {
252
+ if (!this.enabled)
253
+ return;
254
+ if (LEVEL_ORDER[level] < LEVEL_ORDER[this.minLevel])
255
+ return;
256
+ const cat = data?.cat ?? this.context.cat;
257
+ // Category filter narrows the *debug* firehose only — info/warn/error
258
+ // always go through so a `--debug=mcp` invocation doesn't accidentally
259
+ // swallow unrelated errors.
260
+ if (level === "debug" && this.categoryFilter) {
261
+ if (!cat || !this.categoryFilter.has(cat.toLowerCase()))
262
+ return;
263
+ }
264
+ const t = new Date().toISOString();
265
+ const entry = { t, l: level, msg, ...this.context };
266
+ if (cat && !entry.cat)
267
+ entry.cat = cat;
268
+ // Stamp the current process-wide session id unless this logger's
269
+ // own context overrode it (rare). Doing it at write time means
270
+ // children created before Engine.run() still pick up the real sid.
271
+ if (entry.sid === undefined)
272
+ entry.sid = getCurrentSid();
273
+ if (data)
274
+ entry.d = data;
275
+ const line = JSON.stringify(entry) + "\n";
276
+ if (this.stderrEcho) {
277
+ process.stderr.write(line);
278
+ return;
279
+ }
280
+ try {
281
+ const dir = logsDir();
282
+ if (!this.dirReady) {
283
+ if (!existsSync(dir))
284
+ mkdirSync(dir, { recursive: true });
285
+ this.dirReady = true;
286
+ }
287
+ const dateStr = t.slice(0, 10);
288
+ // Route to per-area file. UI / ink events go to ui-ink-*.log so the
289
+ // engine log isn't drowned by 200ms spinner ticks and per-event traces.
290
+ // Everything else lands in engine-*.log (engine, turn-loop, llm, tool,
291
+ // context, mcp, sandbox, settings, ...). One-line grep across both with
292
+ // scripts/logs.sh.
293
+ const bucket = routeBucket(cat, this.context.cat);
294
+ const file = join(dir, `${bucket}-${dateStr}.log`);
295
+ appendFileSync(file, line, "utf-8");
296
+ }
297
+ catch {
298
+ // Best-effort.
299
+ }
300
+ }
301
+ getMinLevel() {
302
+ return this.minLevel;
303
+ }
304
+ isCategoryActive(cat) {
305
+ return !this.categoryFilter || this.categoryFilter.has(cat.toLowerCase());
306
+ }
307
+ /**
308
+ * Open a span: writes a `<name>.begin` debug entry now and returns a handle
309
+ * whose `end()` writes `<name>.end` with `duration_ms` populated. Use for
310
+ * any "I want begin → end + how long" pattern (tool exec, LLM request,
311
+ * permission ask, etc.) so the begin/end pair is grouped under one cat
312
+ * and the duration is computed once instead of by hand from timestamps.
313
+ */
314
+ span(name, data) {
315
+ const startedAt = Date.now();
316
+ this.write("debug", `${name}.begin`, data);
317
+ return {
318
+ end: (extra) => {
319
+ const duration_ms = Date.now() - startedAt;
320
+ this.write("info", `${name}.end`, { ...data, ...extra, duration_ms });
321
+ },
322
+ fail: (err, extra) => {
323
+ const duration_ms = Date.now() - startedAt;
324
+ const message = err instanceof Error ? err.message : String(err);
325
+ this.write("error", `${name}.fail`, { ...data, ...extra, duration_ms, error: message });
326
+ },
327
+ };
328
+ }
329
+ }
330
+ export const logger = new Logger();
331
+ // ─── Maintenance helpers ───────────────────────────────────────────
332
+ export function getLogsDir() {
333
+ return logsDir();
334
+ }
335
+ export function getRecentLogs(n = 50) {
336
+ const dateStr = new Date().toISOString().slice(0, 10);
337
+ const dir = logsDir();
338
+ // Merge across all buckets (engine + ui-ink) for the day, sort by
339
+ // timestamp so the tail represents a real chronological tail.
340
+ const all = [];
341
+ for (const bucket of ["engine", "ui-ink"]) {
342
+ const file = join(dir, `${bucket}-${dateStr}.log`);
343
+ if (!existsSync(file))
344
+ continue;
345
+ try {
346
+ for (const line of readFileSync(file, "utf-8").split("\n")) {
347
+ if (!line)
348
+ continue;
349
+ // Cheap timestamp extraction: lines start with {"t":"<iso>",...
350
+ const m = line.match(/^\{"t":"([^"]+)"/);
351
+ all.push({ t: m?.[1] ?? "", line });
352
+ }
353
+ }
354
+ catch {
355
+ /* ignore */
356
+ }
357
+ }
358
+ all.sort((a, b) => a.t.localeCompare(b.t));
359
+ return all.slice(-n).map((x) => x.line);
360
+ }
361
+ export function rotateLogs() {
362
+ try {
363
+ const dir = logsDir();
364
+ if (!existsSync(dir))
365
+ return;
366
+ const files = readdirSync(dir)
367
+ .filter((f) => f.endsWith(".log"))
368
+ .sort();
369
+ if (files.length <= MAX_LOG_FILES)
370
+ return;
371
+ for (const f of files.slice(0, files.length - MAX_LOG_FILES)) {
372
+ try {
373
+ unlinkSync(join(dir, f));
374
+ }
375
+ catch {
376
+ /* ignore */
377
+ }
378
+ }
379
+ }
380
+ catch {
381
+ // Best-effort.
382
+ }
383
+ }
384
+ /** @internal — for tests */
385
+ export function _resetLoggerStateForTesting() {
386
+ inMemoryErrors.length = 0;
387
+ errorLogSink = null;
388
+ }
389
+ // dirname is exported only to satisfy unused-import rules if reorganized later.
390
+ void dirname;