@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,268 @@
1
+ /**
2
+ * SafeSpawn — unified subprocess lifecycle wrapper.
3
+ *
4
+ * Responsibilities:
5
+ * 1. Optional sandbox wrap (Seatbelt / bubblewrap) via {@link SandboxBackend}.
6
+ * 2. UTF-8 IO drain via {@link StringDecoder} (no half-character corruption
7
+ * when a multi-byte sequence spans two `data` events).
8
+ * 3. Per-stream byte cap with a `truncated` flag (no unbounded buffer fill).
9
+ * 4. `ctx.signal` abort cascade — SIGTERM, then SIGKILL after
10
+ * `ioDrainGraceMs` (default 100ms). This is the snappy path because
11
+ * the user is waiting on the cancel.
12
+ * 5. Hard timeout — SIGTERM, then SIGKILL after 2s. Longer grace because
13
+ * we expect the child to be wedged.
14
+ * 6. Listener cleanup on every exit path (no MaxListeners leak across a
15
+ * long session that reuses one AbortSignal across many spawns).
16
+ *
17
+ * Explicit non-goals:
18
+ *
19
+ * - Permission classification. {@link ToolExecutor} already classifies
20
+ * builtin tools BEFORE the tool function runs; re-classifying here
21
+ * would double-prompt. Install/marketplace paths (gitOps) are consented
22
+ * at user-initiated install time; see docs/architecture/17.
23
+ * - Retries. The caller decides retry policy if any.
24
+ * - Output formatting. SafeSpawn returns structured fields and lets the
25
+ * caller compose its own user-facing string (Bash's "STDERR:\n…" /
26
+ * "Exit code: N" / "Killed by signal: X" formatting lives in bash.ts;
27
+ * REPL/PowerShell have their own messages).
28
+ *
29
+ * Two entry points, both share the same internal lifecycle:
30
+ * - {@link safeSpawn}(file, args, opts) — direct argv spawn. Use from
31
+ * REPL, PowerShell, gitOps where the binary + args are known.
32
+ * - {@link safeSpawnShell}(command, opts) — runs `command` through the
33
+ * sandbox backend (or a plain shell if no sandbox). Use from Bash
34
+ * where the LLM provides a free-form shell string.
35
+ */
36
+ import { spawn } from "node:child_process";
37
+ import { StringDecoder } from "node:string_decoder";
38
+ export const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
39
+ export const DEFAULT_IO_DRAIN_GRACE_MS = 100;
40
+ const TIMEOUT_SIGKILL_GRACE_MS = 2000;
41
+ /**
42
+ * Spawn `(file, args)` directly under the unified lifecycle policy. Use this
43
+ * when you know the binary and args (REPL, PowerShell, gitOps). For shell-
44
+ * string spawning under a sandbox, see {@link safeSpawnShell}.
45
+ */
46
+ export function safeSpawn(file, args, opts) {
47
+ return runLifecycle({
48
+ file,
49
+ args,
50
+ opts,
51
+ cleanup: undefined,
52
+ });
53
+ }
54
+ /**
55
+ * Spawn a shell `command` string under an optional sandbox. The sandbox
56
+ * backend decides the actual `(file, args)` (e.g. Seatbelt becomes
57
+ * `/usr/bin/sandbox-exec -f profile shell -c command`). The backend's
58
+ * `cleanup` callback is invoked on every exit path — close, error,
59
+ * abort, timeout, pre-spawn-abort. Used by the Bash tool.
60
+ */
61
+ export function safeSpawnShell(command, opts) {
62
+ const shell = opts.shell ?? "/bin/bash";
63
+ let file;
64
+ let args;
65
+ let cleanup;
66
+ if (opts.sandbox) {
67
+ const wrapped = opts.sandbox.wrap(command, { cwd: opts.cwd, shell });
68
+ file = wrapped.file;
69
+ args = wrapped.args;
70
+ cleanup = wrapped.cleanup;
71
+ }
72
+ else {
73
+ file = shell;
74
+ args = ["-c", command];
75
+ }
76
+ return runLifecycle({ file, args, opts, cleanup });
77
+ }
78
+ function runLifecycle({ file, args, opts, cleanup }) {
79
+ const maxBytes = opts.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
80
+ const abortGrace = opts.ioDrainGraceMs ?? DEFAULT_IO_DRAIN_GRACE_MS;
81
+ // Pre-spawn abort: don't pay spawn cost.
82
+ if (opts.signal?.aborted) {
83
+ safeCleanup(cleanup);
84
+ return Promise.resolve(emptyResult({ reason: "aborted", aborted: true }));
85
+ }
86
+ return new Promise((resolve) => {
87
+ let settled = false;
88
+ const finish = (result) => {
89
+ if (settled)
90
+ return;
91
+ settled = true;
92
+ // Always release backend-allocated resources, regardless of exit path.
93
+ // cleanup is best-effort — see seatbelt backend for rationale.
94
+ safeCleanup(cleanup);
95
+ // Remove abort listener so a long-lived AbortSignal (multi-turn
96
+ // session reusing the same controller) doesn't accumulate listeners.
97
+ if (opts.signal && onAbort) {
98
+ opts.signal.removeEventListener("abort", onAbort);
99
+ }
100
+ resolve(result);
101
+ };
102
+ let child;
103
+ try {
104
+ child = spawn(file, args, { cwd: opts.cwd, env: opts.env });
105
+ }
106
+ catch (err) {
107
+ finish(emptyResult({ reason: "spawn_failed", spawnFailed: true, error: err.message }));
108
+ return;
109
+ }
110
+ const stdoutDec = new StringDecoder("utf-8");
111
+ const stderrDec = new StringDecoder("utf-8");
112
+ let stdout = "";
113
+ let stderr = "";
114
+ let stdoutTruncated = false;
115
+ let stderrTruncated = false;
116
+ let timedOut = false;
117
+ let aborted = false;
118
+ const timer = setTimeout(() => {
119
+ timedOut = true;
120
+ try {
121
+ child.kill("SIGTERM");
122
+ }
123
+ catch { /* may already be dead */ }
124
+ setTimeout(() => {
125
+ try {
126
+ child.kill("SIGKILL");
127
+ }
128
+ catch { /* ignore */ }
129
+ }, TIMEOUT_SIGKILL_GRACE_MS).unref();
130
+ }, opts.timeoutMs);
131
+ let onAbort;
132
+ if (opts.signal) {
133
+ onAbort = () => {
134
+ aborted = true;
135
+ try {
136
+ child.kill("SIGTERM");
137
+ }
138
+ catch { /* may already be dead */ }
139
+ setTimeout(() => {
140
+ try {
141
+ child.kill("SIGKILL");
142
+ }
143
+ catch { /* ignore */ }
144
+ }, abortGrace).unref();
145
+ };
146
+ opts.signal.addEventListener("abort", onAbort, { once: true });
147
+ }
148
+ child.stdout?.on("data", (chunk) => {
149
+ if (stdoutTruncated)
150
+ return;
151
+ const piece = stdoutDec.write(chunk);
152
+ if (stdout.length + piece.length > maxBytes) {
153
+ stdoutTruncated = true;
154
+ stdout += piece.slice(0, maxBytes - stdout.length);
155
+ }
156
+ else {
157
+ stdout += piece;
158
+ }
159
+ });
160
+ child.stderr?.on("data", (chunk) => {
161
+ if (stderrTruncated)
162
+ return;
163
+ const piece = stderrDec.write(chunk);
164
+ if (stderr.length + piece.length > maxBytes) {
165
+ stderrTruncated = true;
166
+ stderr += piece.slice(0, maxBytes - stderr.length);
167
+ }
168
+ else {
169
+ stderr += piece;
170
+ }
171
+ });
172
+ child.on("error", (err) => {
173
+ clearTimeout(timer);
174
+ // Mid-stream child error (e.g. spawn race where the exec fails after
175
+ // the parent got the ChildProcess handle). SDK-wise this maps to the
176
+ // same "never got a clean lifecycle" meaning as the synchronous spawn
177
+ // throw above, so we surface the same reason. If timeout or abort
178
+ // fired concurrently, give those precedence — the user-facing cause
179
+ // is the cancel/timeout, not the resulting process death.
180
+ const reason = timedOut
181
+ ? "timeout"
182
+ : aborted
183
+ ? "aborted"
184
+ : "spawn_failed";
185
+ finish({
186
+ reason,
187
+ stdout,
188
+ stderr,
189
+ exitCode: null,
190
+ signal: null,
191
+ stdoutTruncated,
192
+ stderrTruncated,
193
+ timedOut,
194
+ aborted,
195
+ spawnFailed: true,
196
+ error: err.message,
197
+ });
198
+ });
199
+ child.on("close", (code, sig) => {
200
+ clearTimeout(timer);
201
+ // Flush trailing incomplete utf-8 (returns "" when last write completed
202
+ // a sequence). Skip when already truncated — preserves the cap exactly.
203
+ const tailOut = stdoutDec.end();
204
+ const tailErr = stderrDec.end();
205
+ if (tailOut && !stdoutTruncated) {
206
+ if (stdout.length + tailOut.length > maxBytes) {
207
+ stdoutTruncated = true;
208
+ stdout += tailOut.slice(0, maxBytes - stdout.length);
209
+ }
210
+ else {
211
+ stdout += tailOut;
212
+ }
213
+ }
214
+ if (tailErr && !stderrTruncated) {
215
+ if (stderr.length + tailErr.length > maxBytes) {
216
+ stderrTruncated = true;
217
+ stderr += tailErr.slice(0, maxBytes - stderr.length);
218
+ }
219
+ else {
220
+ stderr += tailErr;
221
+ }
222
+ }
223
+ const reason = timedOut
224
+ ? "timeout"
225
+ : aborted
226
+ ? "aborted"
227
+ : "ok";
228
+ finish({
229
+ reason,
230
+ stdout,
231
+ stderr,
232
+ exitCode: code,
233
+ signal: sig,
234
+ stdoutTruncated,
235
+ stderrTruncated,
236
+ timedOut,
237
+ aborted,
238
+ spawnFailed: false,
239
+ });
240
+ });
241
+ });
242
+ }
243
+ function safeCleanup(cleanup) {
244
+ if (!cleanup)
245
+ return;
246
+ try {
247
+ cleanup();
248
+ }
249
+ catch { /* best-effort */ }
250
+ }
251
+ function emptyResult(overrides) {
252
+ return {
253
+ // Callers always supply `reason` via overrides; the "ok" default is just
254
+ // a placeholder for the shape — it's never observed because every
255
+ // emptyResult() callsite sets reason explicitly.
256
+ reason: "ok",
257
+ stdout: "",
258
+ stderr: "",
259
+ exitCode: null,
260
+ signal: null,
261
+ stdoutTruncated: false,
262
+ stderrTruncated: false,
263
+ timedOut: false,
264
+ aborted: false,
265
+ spawnFailed: false,
266
+ ...overrides,
267
+ };
268
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Analytics service — event tracking and telemetry.
3
+ *
4
+ * Provides a lightweight analytics pipeline that queues events
5
+ * and flushes them to configured sinks (file, console, or remote).
6
+ */
7
+ export interface AnalyticsEvent {
8
+ name: string;
9
+ properties?: Record<string, unknown>;
10
+ timestamp?: string;
11
+ }
12
+ type AnalyticsSink = (events: AnalyticsEvent[]) => void;
13
+ declare class AnalyticsService {
14
+ private queue;
15
+ private sinks;
16
+ private flushTimer;
17
+ private initialized;
18
+ /**
19
+ * Initialize the analytics service with default file sink.
20
+ */
21
+ init(): void;
22
+ addSink(sink: AnalyticsSink): void;
23
+ track(name: string, properties?: Record<string, unknown>): void;
24
+ flush(): void;
25
+ shutdown(): void;
26
+ }
27
+ export declare const analytics: AnalyticsService;
28
+ export declare function trackEvent(name: string, properties?: Record<string, unknown>): void;
29
+ export {};
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Analytics service — event tracking and telemetry.
3
+ *
4
+ * Provides a lightweight analytics pipeline that queues events
5
+ * and flushes them to configured sinks (file, console, or remote).
6
+ */
7
+ import { appendFileSync, mkdirSync, existsSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { homedir } from "node:os";
10
+ class AnalyticsService {
11
+ queue = [];
12
+ sinks = [];
13
+ flushTimer = null;
14
+ initialized = false;
15
+ /**
16
+ * Initialize the analytics service with default file sink.
17
+ */
18
+ init() {
19
+ if (this.initialized)
20
+ return;
21
+ this.initialized = true;
22
+ // Default: file-based sink
23
+ this.addSink(fileAnalyticsSink());
24
+ // Flush every 30 seconds
25
+ this.flushTimer = setInterval(() => this.flush(), 30_000);
26
+ // Flush on exit
27
+ process.on("beforeExit", () => this.flush());
28
+ }
29
+ addSink(sink) {
30
+ this.sinks.push(sink);
31
+ }
32
+ track(name, properties) {
33
+ this.queue.push({
34
+ name,
35
+ properties,
36
+ timestamp: new Date().toISOString(),
37
+ });
38
+ // Auto-flush if queue gets large
39
+ if (this.queue.length >= 100) {
40
+ this.flush();
41
+ }
42
+ }
43
+ flush() {
44
+ if (this.queue.length === 0)
45
+ return;
46
+ const events = [...this.queue];
47
+ this.queue = [];
48
+ for (const sink of this.sinks) {
49
+ try {
50
+ sink(events);
51
+ }
52
+ catch {
53
+ // Silently ignore sink errors
54
+ }
55
+ }
56
+ }
57
+ shutdown() {
58
+ this.flush();
59
+ if (this.flushTimer) {
60
+ clearInterval(this.flushTimer);
61
+ this.flushTimer = null;
62
+ }
63
+ }
64
+ }
65
+ function fileAnalyticsSink() {
66
+ const logDir = join(homedir(), ".code-shell", "analytics");
67
+ return (events) => {
68
+ if (!existsSync(logDir)) {
69
+ mkdirSync(logDir, { recursive: true });
70
+ }
71
+ const dateStr = new Date().toISOString().split("T")[0];
72
+ const logFile = join(logDir, `${dateStr}.jsonl`);
73
+ const lines = events
74
+ .map((e) => JSON.stringify({ ...e, ...e.properties, properties: undefined }))
75
+ .join("\n") + "\n";
76
+ appendFileSync(logFile, lines, "utf-8");
77
+ };
78
+ }
79
+ // Singleton
80
+ export const analytics = new AnalyticsService();
81
+ // Convenience
82
+ export function trackEvent(name, properties) {
83
+ analytics.track(name, properties);
84
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * AutoDream service — background memory consolidation.
3
+ *
4
+ * Periodically consolidates and organizes memories using the LLM,
5
+ * similar to the /dream command but running automatically.
6
+ */
7
+ export interface AutoDreamConfig {
8
+ /** Minimum sessions between dream runs */
9
+ minSessionsBetween: number;
10
+ /** Minimum time between dream runs (ms) */
11
+ minTimeBetween: number;
12
+ /** Whether auto-dream is enabled */
13
+ enabled: boolean;
14
+ }
15
+ /**
16
+ * Check if auto-dream should run.
17
+ */
18
+ export declare function shouldAutoDream(config?: AutoDreamConfig): boolean;
19
+ /**
20
+ * Record that a session was completed (increment counter).
21
+ */
22
+ export declare function recordSession(): void;
23
+ /**
24
+ * Record that a dream run completed.
25
+ */
26
+ export declare function recordDreamComplete(): void;
27
+ /**
28
+ * System prompt for the auto-dream tool-call loop.
29
+ *
30
+ * Drives the LLM as a "memory consolidation assistant" that operates ONLY in
31
+ * the dream scope via the MemorySave/MemoryDelete tools. The user scope is
32
+ * read-only context — modifying it would need permission, which a background
33
+ * dream pass cannot obtain (no UI on the call path).
34
+ */
35
+ export declare function buildDreamSystemPrompt(): string;
36
+ /**
37
+ * Initial user prompt for the dream loop — gives the LLM the lay of the land
38
+ * (entries in both scopes, by name + description) without dumping every entry
39
+ * body. The LLM uses MemoryRead to fetch bodies for entries it wants to act on.
40
+ */
41
+ export declare function buildDreamUserPrompt(userMemories: Array<{
42
+ name: string;
43
+ type: string;
44
+ description: string;
45
+ }>, dreamMemories: Array<{
46
+ name: string;
47
+ type: string;
48
+ description: string;
49
+ }>): string;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * AutoDream service — background memory consolidation.
3
+ *
4
+ * Periodically consolidates and organizes memories using the LLM,
5
+ * similar to the /dream command but running automatically.
6
+ */
7
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { homedir } from "node:os";
10
+ const DEFAULT_CONFIG = {
11
+ minSessionsBetween: 5,
12
+ minTimeBetween: 24 * 60 * 60 * 1000, // 24 hours
13
+ enabled: true,
14
+ };
15
+ function getStateFile() {
16
+ return join(homedir(), ".code-shell", "auto-dream-state.json");
17
+ }
18
+ function loadState() {
19
+ const stateFile = getStateFile();
20
+ if (existsSync(stateFile)) {
21
+ try {
22
+ return JSON.parse(readFileSync(stateFile, "utf-8"));
23
+ }
24
+ catch { }
25
+ }
26
+ return { lastDreamAt: null, sessionsSinceLastDream: 0 };
27
+ }
28
+ function saveState(state) {
29
+ const stateFile = getStateFile();
30
+ mkdirSync(join(homedir(), ".code-shell"), { recursive: true });
31
+ writeFileSync(stateFile, JSON.stringify(state, null, 2), "utf-8");
32
+ }
33
+ /**
34
+ * Check if auto-dream should run.
35
+ */
36
+ export function shouldAutoDream(config = DEFAULT_CONFIG) {
37
+ if (!config.enabled)
38
+ return false;
39
+ const state = loadState();
40
+ // Check session count
41
+ if (state.sessionsSinceLastDream < config.minSessionsBetween)
42
+ return false;
43
+ // Check time
44
+ if (state.lastDreamAt) {
45
+ const elapsed = Date.now() - new Date(state.lastDreamAt).getTime();
46
+ if (elapsed < config.minTimeBetween)
47
+ return false;
48
+ }
49
+ return true;
50
+ }
51
+ /**
52
+ * Record that a session was completed (increment counter).
53
+ */
54
+ export function recordSession() {
55
+ const state = loadState();
56
+ state.sessionsSinceLastDream++;
57
+ saveState(state);
58
+ }
59
+ /**
60
+ * Record that a dream run completed.
61
+ */
62
+ export function recordDreamComplete() {
63
+ const state = loadState();
64
+ state.lastDreamAt = new Date().toISOString();
65
+ state.sessionsSinceLastDream = 0;
66
+ saveState(state);
67
+ }
68
+ /**
69
+ * System prompt for the auto-dream tool-call loop.
70
+ *
71
+ * Drives the LLM as a "memory consolidation assistant" that operates ONLY in
72
+ * the dream scope via the MemorySave/MemoryDelete tools. The user scope is
73
+ * read-only context — modifying it would need permission, which a background
74
+ * dream pass cannot obtain (no UI on the call path).
75
+ */
76
+ export function buildDreamSystemPrompt() {
77
+ return [
78
+ "You are a memory consolidation assistant for the CodeShell memory system.",
79
+ "",
80
+ "Your job: clean up the `dream` scope by deduplicating, merging, removing stale, and improving descriptions.",
81
+ "",
82
+ "Tools available:",
83
+ "- MemoryList({ scope }): list memories in a scope",
84
+ "- MemoryRead({ scope, name }): read full content of an entry",
85
+ "- MemorySave({ scope: 'dream', ... }): create or overwrite a dream entry (auto-approved)",
86
+ "- MemoryDelete({ scope: 'dream', name }): soft-delete a dream entry (auto-approved, recoverable from trash)",
87
+ "",
88
+ "Rules — read carefully:",
89
+ "1. You may freely Save/Delete in the `dream` scope. These operations DO NOT prompt the user.",
90
+ "2. You may NOT Save/Delete in the `user` scope from this loop — those operations require interactive permission which is not available here. Treat user-scope entries as read-only context.",
91
+ "3. If you find user-scope entries that look stale, surface them in your final summary text — don't try to delete them.",
92
+ "4. Prefer fewer, higher-quality merged entries over many similar fragments.",
93
+ "5. When an entry has versioned variants (e.g. `*-v1`, `*-v2`, `*-v3`), keep only the latest.",
94
+ "6. Be conservative: if uncertain whether two entries are truly duplicates, leave them alone.",
95
+ "7. When you're done, stop calling tools and respond with a one-paragraph summary of what you changed.",
96
+ ].join("\n");
97
+ }
98
+ /**
99
+ * Initial user prompt for the dream loop — gives the LLM the lay of the land
100
+ * (entries in both scopes, by name + description) without dumping every entry
101
+ * body. The LLM uses MemoryRead to fetch bodies for entries it wants to act on.
102
+ */
103
+ export function buildDreamUserPrompt(userMemories, dreamMemories) {
104
+ const fmt = (m) => ` - [${m.type}] ${m.name}: ${m.description}`;
105
+ const sections = [];
106
+ sections.push(`User-scope memories (READ-ONLY context, ${userMemories.length} entries):`);
107
+ if (userMemories.length === 0) {
108
+ sections.push(" (none)");
109
+ }
110
+ else {
111
+ sections.push(userMemories.map(fmt).join("\n"));
112
+ }
113
+ sections.push("");
114
+ sections.push(`Dream-scope memories (YOUR WORKSPACE, ${dreamMemories.length} entries):`);
115
+ if (dreamMemories.length === 0) {
116
+ sections.push(" (none — you may consolidate from user-scope by re-saving curated entries into dream)");
117
+ }
118
+ else {
119
+ sections.push(dreamMemories.map(fmt).join("\n"));
120
+ }
121
+ sections.push("");
122
+ sections.push("Begin consolidation. Use MemoryRead to inspect any entries whose names suggest duplication or staleness, then MemorySave/MemoryDelete in dream scope to clean up.");
123
+ return sections.join("\n");
124
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Diagnostics service — error tracking and system health monitoring.
3
+ *
4
+ * Collects and reports diagnostic information for debugging.
5
+ */
6
+ export interface DiagnosticEntry {
7
+ timestamp: string;
8
+ level: "error" | "warn" | "info";
9
+ category: string;
10
+ message: string;
11
+ metadata?: Record<string, unknown>;
12
+ stack?: string;
13
+ }
14
+ declare class DiagnosticsTracker {
15
+ private logDir;
16
+ private entries;
17
+ constructor();
18
+ /**
19
+ * Record a diagnostic event.
20
+ */
21
+ record(level: DiagnosticEntry["level"], category: string, message: string, metadata?: Record<string, unknown>): void;
22
+ /**
23
+ * Record an error with stack trace.
24
+ */
25
+ recordError(category: string, error: Error, metadata?: Record<string, unknown>): void;
26
+ /**
27
+ * Get recent diagnostic entries.
28
+ */
29
+ getRecent(count?: number): DiagnosticEntry[];
30
+ /**
31
+ * Get entries by category.
32
+ */
33
+ getByCategory(category: string): DiagnosticEntry[];
34
+ /**
35
+ * Generate a diagnostic report for troubleshooting.
36
+ */
37
+ generateReport(): string;
38
+ private persist;
39
+ }
40
+ export declare const diagnostics: DiagnosticsTracker;
41
+ export {};
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Diagnostics service — error tracking and system health monitoring.
3
+ *
4
+ * Collects and reports diagnostic information for debugging.
5
+ */
6
+ import { appendFileSync, mkdirSync, existsSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { homedir } from "node:os";
9
+ class DiagnosticsTracker {
10
+ logDir;
11
+ entries = [];
12
+ constructor() {
13
+ this.logDir = join(homedir(), ".code-shell", "diagnostics");
14
+ }
15
+ /**
16
+ * Record a diagnostic event.
17
+ */
18
+ record(level, category, message, metadata) {
19
+ const entry = {
20
+ timestamp: new Date().toISOString(),
21
+ level,
22
+ category,
23
+ message,
24
+ metadata,
25
+ };
26
+ this.entries.push(entry);
27
+ this.persist(entry);
28
+ }
29
+ /**
30
+ * Record an error with stack trace.
31
+ */
32
+ recordError(category, error, metadata) {
33
+ const entry = {
34
+ timestamp: new Date().toISOString(),
35
+ level: "error",
36
+ category,
37
+ message: error.message,
38
+ stack: error.stack,
39
+ metadata,
40
+ };
41
+ this.entries.push(entry);
42
+ this.persist(entry);
43
+ }
44
+ /**
45
+ * Get recent diagnostic entries.
46
+ */
47
+ getRecent(count = 50) {
48
+ return this.entries.slice(-count);
49
+ }
50
+ /**
51
+ * Get entries by category.
52
+ */
53
+ getByCategory(category) {
54
+ return this.entries.filter((e) => e.category === category);
55
+ }
56
+ /**
57
+ * Generate a diagnostic report for troubleshooting.
58
+ */
59
+ generateReport() {
60
+ const lines = [
61
+ "=== Code Shell Diagnostic Report ===",
62
+ `Generated: ${new Date().toISOString()}`,
63
+ `Platform: ${process.platform} ${process.arch}`,
64
+ `Node: ${process.version}`,
65
+ `Memory: ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB`,
66
+ "",
67
+ ];
68
+ const errors = this.entries.filter((e) => e.level === "error");
69
+ const warnings = this.entries.filter((e) => e.level === "warn");
70
+ lines.push(`Errors: ${errors.length}`);
71
+ lines.push(`Warnings: ${warnings.length}`);
72
+ lines.push(`Total events: ${this.entries.length}`);
73
+ lines.push("");
74
+ if (errors.length > 0) {
75
+ lines.push("Recent Errors:");
76
+ for (const err of errors.slice(-10)) {
77
+ lines.push(` [${err.timestamp}] ${err.category}: ${err.message}`);
78
+ if (err.stack) {
79
+ lines.push(` ${err.stack.split("\n")[1]?.trim() ?? ""}`);
80
+ }
81
+ }
82
+ }
83
+ return lines.join("\n");
84
+ }
85
+ persist(entry) {
86
+ try {
87
+ if (!existsSync(this.logDir)) {
88
+ mkdirSync(this.logDir, { recursive: true });
89
+ }
90
+ const dateStr = entry.timestamp.split("T")[0];
91
+ const logFile = join(this.logDir, `${dateStr}.jsonl`);
92
+ appendFileSync(logFile, JSON.stringify(entry) + "\n", "utf-8");
93
+ }
94
+ catch {
95
+ // Best-effort persistence
96
+ }
97
+ }
98
+ }
99
+ export const diagnostics = new DiagnosticsTracker();