@cjhyy/code-shell 0.3.0 → 0.5.0-rc.2

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 (464) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/dist/cli.js +2 -0
  3. package/dist/index.d.ts +1 -68
  4. package/dist/index.js +1 -1
  5. package/package.json +25 -73
  6. package/dist/agent/coordinator.d.ts +0 -49
  7. package/dist/anthropic-DJXVKFMJ.js +0 -1
  8. package/dist/arena/arena.d.ts +0 -43
  9. package/dist/arena/context/context-tools.d.ts +0 -16
  10. package/dist/arena/detect-mode.d.ts +0 -20
  11. package/dist/arena/digest-builder.d.ts +0 -25
  12. package/dist/arena/index.d.ts +0 -29
  13. package/dist/arena/index.js +0 -1
  14. package/dist/arena/iterate/convergence.d.ts +0 -25
  15. package/dist/arena/iterate/formats/index.d.ts +0 -22
  16. package/dist/arena/iterate/index.d.ts +0 -11
  17. package/dist/arena/iterate/iterative-arena.d.ts +0 -23
  18. package/dist/arena/iterate/parse.d.ts +0 -42
  19. package/dist/arena/iterate/phases/argue.d.ts +0 -22
  20. package/dist/arena/iterate/phases/revise.d.ts +0 -16
  21. package/dist/arena/iterate/phases/tournament.d.ts +0 -34
  22. package/dist/arena/iterate/tools/web-tools.d.ts +0 -13
  23. package/dist/arena/iterate/types.d.ts +0 -152
  24. package/dist/arena/ledger.d.ts +0 -47
  25. package/dist/arena/lenses/architecture.d.ts +0 -5
  26. package/dist/arena/lenses/engineering.d.ts +0 -5
  27. package/dist/arena/lenses/general.d.ts +0 -5
  28. package/dist/arena/lenses/index.d.ts +0 -16
  29. package/dist/arena/lenses/product.d.ts +0 -5
  30. package/dist/arena/model-presets.d.ts +0 -23
  31. package/dist/arena/phases/adjudication.d.ts +0 -24
  32. package/dist/arena/phases/build-consensus.d.ts +0 -29
  33. package/dist/arena/phases/claim-registry.d.ts +0 -26
  34. package/dist/arena/phases/cross-review.d.ts +0 -45
  35. package/dist/arena/phases/debate-rounds.d.ts +0 -27
  36. package/dist/arena/phases/participant-research.d.ts +0 -38
  37. package/dist/arena/phases/planning-detail-expansion.d.ts +0 -38
  38. package/dist/arena/planner.d.ts +0 -27
  39. package/dist/arena/providers/docs.d.ts +0 -6
  40. package/dist/arena/providers/git.d.ts +0 -8
  41. package/dist/arena/providers/index.d.ts +0 -32
  42. package/dist/arena/providers/none.d.ts +0 -7
  43. package/dist/arena/providers/repo.d.ts +0 -6
  44. package/dist/arena/render/session.d.ts +0 -17
  45. package/dist/arena/render/terminal.d.ts +0 -33
  46. package/dist/arena/strategies/discussion.d.ts +0 -25
  47. package/dist/arena/strategies/index.d.ts +0 -15
  48. package/dist/arena/strategies/language-wrapper.d.ts +0 -17
  49. package/dist/arena/strategies/lens-wrapper.d.ts +0 -16
  50. package/dist/arena/strategies/planning.d.ts +0 -30
  51. package/dist/arena/strategies/review.d.ts +0 -26
  52. package/dist/arena/strategies/utils.d.ts +0 -39
  53. package/dist/arena/tools/selector.d.ts +0 -17
  54. package/dist/arena/transitions.d.ts +0 -48
  55. package/dist/arena/types.d.ts +0 -508
  56. package/dist/arena-MRBATZFD.js +0 -3
  57. package/dist/bootstrap/setup.d.ts +0 -14
  58. package/dist/bootstrap/state.d.ts +0 -160
  59. package/dist/bwrap-PVZMLHZR.js +0 -2
  60. package/dist/chunk-2OD6VR4N.js +0 -2
  61. package/dist/chunk-3QP5BQ3L.js +0 -1
  62. package/dist/chunk-5QIVXFCT.js +0 -1
  63. package/dist/chunk-AFMP73YP.js +0 -2
  64. package/dist/chunk-D3TVASD2.js +0 -4
  65. package/dist/chunk-DI26OUIU.js +0 -2
  66. package/dist/chunk-FU7AHZNN.js +0 -1
  67. package/dist/chunk-FZXY554D.js +0 -2
  68. package/dist/chunk-GGVAOPI7.js +0 -1
  69. package/dist/chunk-GKAQH2DG.js +0 -2
  70. package/dist/chunk-GYNO4R7R.js +0 -2
  71. package/dist/chunk-K4HILJ6G.js +0 -251
  72. package/dist/chunk-M7VU4YVY.js +0 -49
  73. package/dist/chunk-MLCTC53I.js +0 -1
  74. package/dist/chunk-O5HFCH2U.js +0 -1
  75. package/dist/chunk-OWBYLMDD.js +0 -1
  76. package/dist/chunk-P6JSTIFM.js +0 -1
  77. package/dist/chunk-QTWU7UNA.js +0 -5
  78. package/dist/chunk-SKIX2M5Z.js +0 -4
  79. package/dist/chunk-SNFAPSLA.js +0 -1
  80. package/dist/chunk-SV7H4FKT.js +0 -3
  81. package/dist/chunk-T222K6IV.js +0 -18
  82. package/dist/chunk-TKJA6W36.js +0 -3
  83. package/dist/chunk-WI6FSWGU.js +0 -1
  84. package/dist/chunk-WONQHE4P.js +0 -641
  85. package/dist/chunk-X2S7ASQ2.js +0 -1
  86. package/dist/chunk-Z5HKHAO7.js +0 -336
  87. package/dist/cli/commands/arena.d.ts +0 -29
  88. package/dist/cli/commands/builtin/advanced-commands.d.ts +0 -5
  89. package/dist/cli/commands/builtin/core-commands.d.ts +0 -5
  90. package/dist/cli/commands/builtin/export-md.d.ts +0 -19
  91. package/dist/cli/commands/builtin/extra-commands.d.ts +0 -6
  92. package/dist/cli/commands/builtin/git-commands.d.ts +0 -5
  93. package/dist/cli/commands/builtin/init/detect.d.ts +0 -25
  94. package/dist/cli/commands/builtin/init/index.d.ts +0 -19
  95. package/dist/cli/commands/builtin/more-commands.d.ts +0 -5
  96. package/dist/cli/commands/builtin/permissions-command.d.ts +0 -5
  97. package/dist/cli/commands/builtin/plugin-commands-registration.d.ts +0 -12
  98. package/dist/cli/commands/builtin/plugin-handler.d.ts +0 -6
  99. package/dist/cli/commands/builtin/utility-commands.d.ts +0 -5
  100. package/dist/cli/commands/registry.d.ts +0 -79
  101. package/dist/cli/commands/repl.d.ts +0 -21
  102. package/dist/cli/commands/run.d.ts +0 -21
  103. package/dist/cli/commands/runs.d.ts +0 -14
  104. package/dist/cli/cost-tracker.d.ts +0 -63
  105. package/dist/cli/exit.d.ts +0 -12
  106. package/dist/cli/input/ndjson-reader.d.ts +0 -31
  107. package/dist/cli/input-compiler.d.ts +0 -5
  108. package/dist/cli/main.d.ts +0 -5
  109. package/dist/cli/main.js +0 -415
  110. package/dist/cli/migrate-models.d.ts +0 -45
  111. package/dist/cli/onboarding.d.ts +0 -189
  112. package/dist/cli/output/renderer.d.ts +0 -28
  113. package/dist/cli/output/terminal-ui.d.ts +0 -50
  114. package/dist/cli/updater.d.ts +0 -65
  115. package/dist/client-base-GSFXPP2Y.js +0 -1
  116. package/dist/compaction-L3Y6NG4N.js +0 -1
  117. package/dist/context/compaction.d.ts +0 -116
  118. package/dist/context/manager.d.ts +0 -145
  119. package/dist/context/token-counter.d.ts +0 -27
  120. package/dist/context/tool-result-storage.d.ts +0 -96
  121. package/dist/cron/scheduler.d.ts +0 -34
  122. package/dist/data/openrouter-models.d.ts +0 -35
  123. package/dist/data/openrouter-sync.d.ts +0 -16
  124. package/dist/data/static-catalogs.d.ts +0 -25
  125. package/dist/devtools-FBX4HVVY.js +0 -1
  126. package/dist/engine/cost-store.d.ts +0 -22
  127. package/dist/engine/engine.d.ts +0 -236
  128. package/dist/engine/model-facade.d.ts +0 -24
  129. package/dist/engine/query.d.ts +0 -50
  130. package/dist/engine/streaming-tool-queue.d.ts +0 -34
  131. package/dist/engine/token-budget.d.ts +0 -22
  132. package/dist/engine/tool-summary.d.ts +0 -13
  133. package/dist/engine/turn-loop.d.ts +0 -122
  134. package/dist/engine/turn-state.d.ts +0 -20
  135. package/dist/exceptions.d.ts +0 -44
  136. package/dist/export-md-U72T7NW7.js +0 -22
  137. package/dist/file-history-7FQFEQOL.js +0 -1
  138. package/dist/git/utils.d.ts +0 -35
  139. package/dist/git/worktree.d.ts +0 -36
  140. package/dist/hooks/events.d.ts +0 -114
  141. package/dist/hooks/inject.d.ts +0 -19
  142. package/dist/hooks/registry.d.ts +0 -15
  143. package/dist/hooks/shell-runner.d.ts +0 -45
  144. package/dist/llm/api-key-sanitize.d.ts +0 -22
  145. package/dist/llm/capabilities/index.d.ts +0 -20
  146. package/dist/llm/capabilities/rules.d.ts +0 -26
  147. package/dist/llm/capabilities/types.d.ts +0 -108
  148. package/dist/llm/client-base.d.ts +0 -29
  149. package/dist/llm/client-factory.d.ts +0 -10
  150. package/dist/llm/model-cache.d.ts +0 -21
  151. package/dist/llm/model-fetcher.d.ts +0 -29
  152. package/dist/llm/model-pool.d.ts +0 -84
  153. package/dist/llm/provider-catalog.d.ts +0 -32
  154. package/dist/llm/provider-kinds.d.ts +0 -21
  155. package/dist/llm/providers/anthropic.d.ts +0 -19
  156. package/dist/llm/providers/openai.d.ts +0 -64
  157. package/dist/llm/retry.d.ts +0 -12
  158. package/dist/llm/stream-watchdog.d.ts +0 -42
  159. package/dist/llm/token-counter.d.ts +0 -17
  160. package/dist/llm/types.d.ts +0 -37
  161. package/dist/logging/logger.d.ts +0 -102
  162. package/dist/logging/session-recorder.d.ts +0 -90
  163. package/dist/lsp/client.d.ts +0 -41
  164. package/dist/lsp/manager.d.ts +0 -40
  165. package/dist/lsp/servers.d.ts +0 -16
  166. package/dist/manager-4XKLZHKE.js +0 -1
  167. package/dist/mcp-manager-3JGHEJO3.js +0 -1
  168. package/dist/memory-BNI4WEWL.js +0 -1
  169. package/dist/model-cache-HEDXI7UJ.js +0 -1
  170. package/dist/model-fetcher-X5W5EASG.js +0 -1
  171. package/dist/native-ts/yoga-layout/enums.d.ts +0 -117
  172. package/dist/native-ts/yoga-layout/index.d.ts +0 -270
  173. package/dist/off-7SDVMMXW.js +0 -1
  174. package/dist/openai-OQ6LLN5J.js +0 -1
  175. package/dist/openrouter-models-ZT4R2AE3.js +0 -1
  176. package/dist/openrouter-sync-ARMVWY7S.js +0 -1
  177. package/dist/plugin-handler-GJISMH5Q.js +0 -11
  178. package/dist/plugins/gitOps.d.ts +0 -23
  179. package/dist/plugins/installedPlugins.d.ts +0 -15
  180. package/dist/plugins/knownMarketplaces.d.ts +0 -10
  181. package/dist/plugins/loadPluginHooks.d.ts +0 -52
  182. package/dist/plugins/marketplaceManager.d.ts +0 -49
  183. package/dist/plugins/parseMarketplaceInput.d.ts +0 -16
  184. package/dist/plugins/pluginCommandHook.d.ts +0 -54
  185. package/dist/plugins/pluginCommandsLoader.d.ts +0 -25
  186. package/dist/plugins/pluginInstaller.d.ts +0 -36
  187. package/dist/plugins/schemas.d.ts +0 -9
  188. package/dist/plugins/types.d.ts +0 -75
  189. package/dist/plugins/varRewrite.d.ts +0 -42
  190. package/dist/preset/index.d.ts +0 -60
  191. package/dist/product/define.d.ts +0 -60
  192. package/dist/product/index.d.ts +0 -5
  193. package/dist/product/index.js +0 -1
  194. package/dist/product/types.d.ts +0 -111
  195. package/dist/prompt/composer.d.ts +0 -42
  196. package/dist/prompt/instruction-scanner.d.ts +0 -54
  197. package/dist/prompt/section-cache.d.ts +0 -15
  198. package/dist/prompt/section-loader.d.ts +0 -26
  199. package/dist/protocol/client.d.ts +0 -64
  200. package/dist/protocol/helpers.d.ts +0 -42
  201. package/dist/protocol/index.d.ts +0 -4
  202. package/dist/protocol/server.d.ts +0 -51
  203. package/dist/protocol/transport.d.ts +0 -36
  204. package/dist/protocol/types.d.ts +0 -192
  205. package/dist/react-compiler-runtime-shim.d.ts +0 -1
  206. package/dist/remote/bridge.d.ts +0 -37
  207. package/dist/render/Ansi.d.ts +0 -10
  208. package/dist/render/bidi.d.ts +0 -15
  209. package/dist/render/clearTerminal.d.ts +0 -19
  210. package/dist/render/colorize.d.ts +0 -16
  211. package/dist/render/components/AlternateScreen.d.ts +0 -21
  212. package/dist/render/components/App.d.ts +0 -71
  213. package/dist/render/components/AppContext.d.ts +0 -11
  214. package/dist/render/components/Box.d.ts +0 -49
  215. package/dist/render/components/Button.d.ts +0 -36
  216. package/dist/render/components/ClockContext.d.ts +0 -9
  217. package/dist/render/components/CursorDeclarationContext.d.ts +0 -22
  218. package/dist/render/components/ErrorOverview.d.ts +0 -5
  219. package/dist/render/components/Link.d.ts +0 -7
  220. package/dist/render/components/Newline.d.ts +0 -12
  221. package/dist/render/components/NoSelect.d.ts +0 -19
  222. package/dist/render/components/RawAnsi.d.ts +0 -16
  223. package/dist/render/components/ScrollBox.d.ts +0 -78
  224. package/dist/render/components/Spacer.d.ts +0 -5
  225. package/dist/render/components/Static.d.ts +0 -23
  226. package/dist/render/components/StdinContext.d.ts +0 -27
  227. package/dist/render/components/TerminalFocusContext.d.ts +0 -10
  228. package/dist/render/components/TerminalSizeContext.d.ts +0 -5
  229. package/dist/render/components/Text.d.ts +0 -55
  230. package/dist/render/constants.d.ts +0 -1
  231. package/dist/render/cursor.d.ts +0 -8
  232. package/dist/render/devtools.d.ts +0 -9
  233. package/dist/render/dom.d.ts +0 -77
  234. package/dist/render/events/click-event.d.ts +0 -31
  235. package/dist/render/events/dispatcher.d.ts +0 -40
  236. package/dist/render/events/emitter.d.ts +0 -5
  237. package/dist/render/events/event-handlers.d.ts +0 -46
  238. package/dist/render/events/event.d.ts +0 -5
  239. package/dist/render/events/focus-event.d.ts +0 -13
  240. package/dist/render/events/input-event.d.ts +0 -30
  241. package/dist/render/events/keyboard-event.d.ts +0 -19
  242. package/dist/render/events/paste-event.d.ts +0 -8
  243. package/dist/render/events/resize-event.d.ts +0 -9
  244. package/dist/render/events/terminal-event.d.ts +0 -54
  245. package/dist/render/events/terminal-focus-event.d.ts +0 -13
  246. package/dist/render/focus.d.ts +0 -43
  247. package/dist/render/frame.d.ts +0 -95
  248. package/dist/render/get-max-width.d.ts +0 -17
  249. package/dist/render/hit-test.d.ts +0 -33
  250. package/dist/render/hooks/use-animation-frame.d.ts +0 -26
  251. package/dist/render/hooks/use-app.d.ts +0 -5
  252. package/dist/render/hooks/use-declared-cursor.d.ts +0 -26
  253. package/dist/render/hooks/use-input.d.ts +0 -37
  254. package/dist/render/hooks/use-interval.d.ts +0 -18
  255. package/dist/render/hooks/use-search-highlight.d.ts +0 -30
  256. package/dist/render/hooks/use-selection.d.ts +0 -39
  257. package/dist/render/hooks/use-stdin.d.ts +0 -5
  258. package/dist/render/hooks/use-tab-status.d.ts +0 -13
  259. package/dist/render/hooks/use-terminal-focus.d.ts +0 -10
  260. package/dist/render/hooks/use-terminal-title.d.ts +0 -12
  261. package/dist/render/hooks/use-terminal-viewport.d.ts +0 -29
  262. package/dist/render/index.d.ts +0 -30
  263. package/dist/render/ink.d.ts +0 -391
  264. package/dist/render/instances.d.ts +0 -3
  265. package/dist/render/layout/engine.d.ts +0 -2
  266. package/dist/render/layout/geometry.d.ts +0 -30
  267. package/dist/render/layout/node.d.ts +0 -125
  268. package/dist/render/layout/yoga.d.ts +0 -56
  269. package/dist/render/line-width-cache.d.ts +0 -1
  270. package/dist/render/log-update.d.ts +0 -28
  271. package/dist/render/measure-element.d.ts +0 -16
  272. package/dist/render/measure-text.d.ts +0 -6
  273. package/dist/render/node-cache.d.ts +0 -20
  274. package/dist/render/optimizer.d.ts +0 -15
  275. package/dist/render/output.d.ts +0 -119
  276. package/dist/render/parse-keypress.d.ts +0 -111
  277. package/dist/render/reconciler.d.ts +0 -11
  278. package/dist/render/render-border.d.ts +0 -24
  279. package/dist/render/render-node-to-output.d.ts +0 -45
  280. package/dist/render/render-to-screen.d.ts +0 -46
  281. package/dist/render/renderer.d.ts +0 -14
  282. package/dist/render/root.d.ts +0 -74
  283. package/dist/render/screen.d.ts +0 -269
  284. package/dist/render/searchHighlight.d.ts +0 -20
  285. package/dist/render/selection.d.ts +0 -229
  286. package/dist/render/squash-text-nodes.d.ts +0 -22
  287. package/dist/render/stringWidth.d.ts +0 -1
  288. package/dist/render/styles.d.ts +0 -306
  289. package/dist/render/supports-hyperlinks.d.ts +0 -13
  290. package/dist/render/tabstops.d.ts +0 -1
  291. package/dist/render/terminal-focus-state.d.ts +0 -6
  292. package/dist/render/terminal-querier.d.ts +0 -129
  293. package/dist/render/terminal.d.ts +0 -46
  294. package/dist/render/termio/ansi.d.ts +0 -65
  295. package/dist/render/termio/csi.d.ts +0 -165
  296. package/dist/render/termio/dec.d.ts +0 -37
  297. package/dist/render/termio/esc.d.ts +0 -12
  298. package/dist/render/termio/osc.d.ts +0 -173
  299. package/dist/render/termio/parser.d.ts +0 -35
  300. package/dist/render/termio/sgr.d.ts +0 -8
  301. package/dist/render/termio/tokenize.d.ts +0 -45
  302. package/dist/render/termio/types.d.ts +0 -190
  303. package/dist/render/termio.d.ts +0 -24
  304. package/dist/render/useTerminalNotification.d.ts +0 -28
  305. package/dist/render/warn.d.ts +0 -1
  306. package/dist/render/widest-line.d.ts +0 -1
  307. package/dist/render/wrap-text.d.ts +0 -2
  308. package/dist/render/wrapAnsi.d.ts +0 -7
  309. package/dist/run/ArtifactTracker.d.ts +0 -38
  310. package/dist/run/CheckpointWriter.d.ts +0 -53
  311. package/dist/run/EngineRunner.d.ts +0 -72
  312. package/dist/run/Evaluator.d.ts +0 -56
  313. package/dist/run/FileRunStore.d.ts +0 -39
  314. package/dist/run/Heartbeat.d.ts +0 -54
  315. package/dist/run/RunApprovalBackend.d.ts +0 -53
  316. package/dist/run/RunLock.d.ts +0 -40
  317. package/dist/run/RunManager.d.ts +0 -82
  318. package/dist/run/RunQueue.d.ts +0 -27
  319. package/dist/run/RunStore.d.ts +0 -25
  320. package/dist/run/factory.d.ts +0 -63
  321. package/dist/run/index.d.ts +0 -17
  322. package/dist/run/index.js +0 -1
  323. package/dist/run/types.d.ts +0 -136
  324. package/dist/seatbelt-L54CNI2Y.js +0 -37
  325. package/dist/services/analytics.d.ts +0 -29
  326. package/dist/services/auto-dream.d.ts +0 -35
  327. package/dist/services/diagnostics.d.ts +0 -41
  328. package/dist/services/extract-memories.d.ts +0 -27
  329. package/dist/services/index.d.ts +0 -11
  330. package/dist/services/memory-orchestrator.d.ts +0 -39
  331. package/dist/services/notifier.d.ts +0 -25
  332. package/dist/services/oauth.d.ts +0 -27
  333. package/dist/services/session-memory.d.ts +0 -37
  334. package/dist/session/file-history.d.ts +0 -41
  335. package/dist/session/memory.d.ts +0 -65
  336. package/dist/session/session-manager.d.ts +0 -28
  337. package/dist/session/transcript.d.ts +0 -39
  338. package/dist/session-manager-AGWS5SMJ.js +0 -1
  339. package/dist/settings/manager.d.ts +0 -36
  340. package/dist/settings/schema.d.ts +0 -1123
  341. package/dist/skills/frontmatter.d.ts +0 -13
  342. package/dist/skills/index.d.ts +0 -7
  343. package/dist/skills/scanner.d.ts +0 -20
  344. package/dist/tool-summary-HJX6RHG4.js +0 -2
  345. package/dist/tool-system/builtin/agent-notifications.d.ts +0 -55
  346. package/dist/tool-system/builtin/agent-registry.d.ts +0 -67
  347. package/dist/tool-system/builtin/agent-transcript-translator.d.ts +0 -22
  348. package/dist/tool-system/builtin/agent.d.ts +0 -16
  349. package/dist/tool-system/builtin/apply-patch/applier.d.ts +0 -26
  350. package/dist/tool-system/builtin/apply-patch/index.d.ts +0 -19
  351. package/dist/tool-system/builtin/apply-patch/parser.d.ts +0 -17
  352. package/dist/tool-system/builtin/apply-patch/seek-sequence.d.ts +0 -18
  353. package/dist/tool-system/builtin/apply-patch/types.d.ts +0 -49
  354. package/dist/tool-system/builtin/arena.d.ts +0 -31
  355. package/dist/tool-system/builtin/ask-user.d.ts +0 -20
  356. package/dist/tool-system/builtin/bash.d.ts +0 -12
  357. package/dist/tool-system/builtin/brief.d.ts +0 -6
  358. package/dist/tool-system/builtin/config.d.ts +0 -6
  359. package/dist/tool-system/builtin/cron.d.ts +0 -10
  360. package/dist/tool-system/builtin/edit.d.ts +0 -6
  361. package/dist/tool-system/builtin/file-cache.d.ts +0 -11
  362. package/dist/tool-system/builtin/glob.d.ts +0 -6
  363. package/dist/tool-system/builtin/grep.d.ts +0 -6
  364. package/dist/tool-system/builtin/index.d.ts +0 -20
  365. package/dist/tool-system/builtin/lsp.d.ts +0 -6
  366. package/dist/tool-system/builtin/mcp-tools.d.ts +0 -10
  367. package/dist/tool-system/builtin/notebook-edit.d.ts +0 -6
  368. package/dist/tool-system/builtin/plan.d.ts +0 -18
  369. package/dist/tool-system/builtin/powershell.d.ts +0 -6
  370. package/dist/tool-system/builtin/read.d.ts +0 -6
  371. package/dist/tool-system/builtin/remote-trigger.d.ts +0 -6
  372. package/dist/tool-system/builtin/repl.d.ts +0 -6
  373. package/dist/tool-system/builtin/send-message.d.ts +0 -6
  374. package/dist/tool-system/builtin/skill-prompt.d.ts +0 -7
  375. package/dist/tool-system/builtin/skill.d.ts +0 -8
  376. package/dist/tool-system/builtin/sleep.d.ts +0 -6
  377. package/dist/tool-system/builtin/task.d.ts +0 -51
  378. package/dist/tool-system/builtin/tool-search.d.ts +0 -11
  379. package/dist/tool-system/builtin/web-fetch.d.ts +0 -6
  380. package/dist/tool-system/builtin/web-search.d.ts +0 -6
  381. package/dist/tool-system/builtin/worktree.d.ts +0 -10
  382. package/dist/tool-system/builtin/write.d.ts +0 -6
  383. package/dist/tool-system/context.d.ts +0 -133
  384. package/dist/tool-system/executor.d.ts +0 -49
  385. package/dist/tool-system/investigation-guard.d.ts +0 -46
  386. package/dist/tool-system/mcp-manager.d.ts +0 -50
  387. package/dist/tool-system/permission.d.ts +0 -104
  388. package/dist/tool-system/registry.d.ts +0 -32
  389. package/dist/tool-system/sandbox/bwrap.d.ts +0 -13
  390. package/dist/tool-system/sandbox/index.d.ts +0 -78
  391. package/dist/tool-system/sandbox/off.d.ts +0 -2
  392. package/dist/tool-system/sandbox/seatbelt.d.ts +0 -18
  393. package/dist/tool-system/task-guard.d.ts +0 -30
  394. package/dist/tool-system/validation.d.ts +0 -5
  395. package/dist/types.d.ts +0 -356
  396. package/dist/ui/App.d.ts +0 -14
  397. package/dist/ui/components/AgentBlock.d.ts +0 -35
  398. package/dist/ui/components/AgentDock.d.ts +0 -36
  399. package/dist/ui/components/AskUserPrompt.d.ts +0 -14
  400. package/dist/ui/components/BabyHand.d.ts +0 -1
  401. package/dist/ui/components/Banner.d.ts +0 -8
  402. package/dist/ui/components/CodeBlock.d.ts +0 -7
  403. package/dist/ui/components/CommandInput.d.ts +0 -24
  404. package/dist/ui/components/ContextUsageBar.d.ts +0 -7
  405. package/dist/ui/components/DiffLine.d.ts +0 -33
  406. package/dist/ui/components/DiffView.d.ts +0 -6
  407. package/dist/ui/components/DogLogo.d.ts +0 -1
  408. package/dist/ui/components/FullscreenLayout.d.ts +0 -51
  409. package/dist/ui/components/KunHead.d.ts +0 -1
  410. package/dist/ui/components/KunLogo.d.ts +0 -1
  411. package/dist/ui/components/MessageContent.d.ts +0 -26
  412. package/dist/ui/components/MessageRow.d.ts +0 -54
  413. package/dist/ui/components/ModelManager.d.ts +0 -68
  414. package/dist/ui/components/ModelSelector.d.ts +0 -10
  415. package/dist/ui/components/OnboardingPrompt.d.ts +0 -16
  416. package/dist/ui/components/PermissionDialog.d.ts +0 -8
  417. package/dist/ui/components/PermissionPrompt.d.ts +0 -11
  418. package/dist/ui/components/ProviderModelFlow.d.ts +0 -58
  419. package/dist/ui/components/ScrollView.d.ts +0 -34
  420. package/dist/ui/components/SessionPicker.d.ts +0 -16
  421. package/dist/ui/components/Spinner.d.ts +0 -8
  422. package/dist/ui/components/SpinnerWithVerb.d.ts +0 -19
  423. package/dist/ui/components/StatusLine.d.ts +0 -28
  424. package/dist/ui/components/StructuredDiff.d.ts +0 -8
  425. package/dist/ui/components/TaskList.d.ts +0 -6
  426. package/dist/ui/components/TextInput.d.ts +0 -17
  427. package/dist/ui/components/ThemedBox.d.ts +0 -19
  428. package/dist/ui/components/ThemedText.d.ts +0 -26
  429. package/dist/ui/components/ToolCall.d.ts +0 -28
  430. package/dist/ui/components/UpdateBanner.d.ts +0 -1
  431. package/dist/ui/components/VirtualMessageList.d.ts +0 -43
  432. package/dist/ui/components/WelcomeTips.d.ts +0 -5
  433. package/dist/ui/dev-seed.d.ts +0 -1
  434. package/dist/ui/fullscreen-mode.d.ts +0 -9
  435. package/dist/ui/hooks/useCostSummary.d.ts +0 -1
  436. package/dist/ui/hooks/useVirtualScroll.d.ts +0 -101
  437. package/dist/ui/index.d.ts +0 -12
  438. package/dist/ui/input-history.d.ts +0 -61
  439. package/dist/ui/onboarding-runner.d.ts +0 -2
  440. package/dist/ui/perf-probes.d.ts +0 -22
  441. package/dist/ui/query-guard.d.ts +0 -35
  442. package/dist/ui/slice-anchor.d.ts +0 -44
  443. package/dist/ui/store.d.ts +0 -108
  444. package/dist/ui/terminal-renderer.d.ts +0 -45
  445. package/dist/ui/theme.d.ts +0 -36
  446. package/dist/ui/vim-mode.d.ts +0 -25
  447. package/dist/updater-OCNU2K2Z.js +0 -1
  448. package/dist/utils/debug.d.ts +0 -41
  449. package/dist/utils/earlyInput.d.ts +0 -43
  450. package/dist/utils/env.d.ts +0 -24
  451. package/dist/utils/envUtils.d.ts +0 -51
  452. package/dist/utils/execFileNoThrow.d.ts +0 -39
  453. package/dist/utils/format.d.ts +0 -44
  454. package/dist/utils/fullscreen.d.ts +0 -47
  455. package/dist/utils/intl.d.ts +0 -22
  456. package/dist/utils/lockfile.d.ts +0 -15
  457. package/dist/utils/semver.d.ts +0 -6
  458. package/dist/utils/sliceAnsi.d.ts +0 -12
  459. package/dist/utils/systemTheme.d.ts +0 -40
  460. package/dist/utils/task-sanitizer.d.ts +0 -6
  461. package/dist/utils/theme.d.ts +0 -91
  462. package/dist/utils/toolDisplay.d.ts +0 -31
  463. package/dist/utils/truncate.d.ts +0 -40
  464. package/dist/voice/index.d.ts +0 -35
@@ -1,251 +0,0 @@
1
- import {b}from'./chunk-WONQHE4P.js';import {d}from'./chunk-DI26OUIU.js';import {h,a}from'./chunk-3QP5BQ3L.js';h();h();h();h();function x(n,e){if(n===e)return 0;if(!n||!e)return 1;let t=a(c=>{let u=new Set;for(let l=0;l<c.length-2;l++)u.add(c.slice(l,l+3));return u},"trigrams"),r=t(n),i=t(e),o=0;for(let c of r)i.has(c)&&o++;let a$1=r.size+i.size-o;return a$1===0?0:1-o/a$1}a(x,"diffRatio");function C(n){let{round:e,critiques:t,draft:r,previousDraft:i}=n,o=t.filter(u=>u.severity==="blocker").length,a=t.filter(u=>u.severity==="major").length,s=t.length,c=i?x(i.content,r.content):1;return e===1?{blockerCount:o,majorCount:a,totalCritiques:s,diffFromPrevious:c,shouldStop:false,reason:"running"}:s===0?{blockerCount:o,majorCount:a,totalCritiques:s,diffFromPrevious:c,shouldStop:false,reason:"running"}:o===0&&a===0&&s>=3?{blockerCount:o,majorCount:a,totalCritiques:s,diffFromPrevious:c,shouldStop:true,reason:"all_minor_or_praise"}:o===0&&c<.05?{blockerCount:o,majorCount:a,totalCritiques:s,diffFromPrevious:c,shouldStop:true,reason:"blockers_zero_and_stable"}:{blockerCount:o,majorCount:a,totalCritiques:s,diffFromPrevious:c,shouldStop:false,reason:"running"}}a(C,"defaultConvergence");h();var q=`
2
- Hard rules:
3
- - Output the FULL artifact, not a sketch or outline.
4
- - No "...", "(continued)", "see above", "TBD", or placeholders.
5
- - Don't pad with filler. Every section must carry information.
6
- - Length is a floor, not a target \u2014 go beyond it if the topic warrants.
7
-
8
- Factual discipline (CRITICAL \u2014 fabrication = blocker-level defect):
9
- - Do NOT invent specific numbers, percentages, dollar amounts, market sizes,
10
- user-research counts, or "industry averages" you cannot verify.
11
- - Do NOT invent URLs, report IDs, document numbers, citation references.
12
- - Do NOT invent named people, companies, or product code-names.
13
- - For unknowable specifics, write a placeholder with the exact form:
14
- [\u9700\u8C03\u7814: \u5177\u4F53\u8BF4\u660E] e.g. "[\u9700\u8C03\u7814: \u5B9E\u9645\u884C\u4E1A\u6D41\u5931\u7387\u57FA\u51C6]"
15
- [TBD: short reason] e.g. "[TBD: confirm Stripe rate limits]"
16
- These placeholders are EXPECTED. Reviewers will not fault you for them.
17
- - General qualitative claims are fine ("annual growth typically in the
18
- double digits"); specific numbers without a verifiable source are NOT.
19
- - If you have web-search tools available, USE them before stating any
20
- specific number or citing any source.
21
- `;function I(n){return n.map((e,t)=>`[${t+1}] id=${e.id} severity=${e.severity} category=${e.category} from=${e.critic}
22
- anchor: "${e.anchor}"
23
- comment: ${e.comment}`+(e.suggestion?`
24
- suggestion: ${e.suggestion}`:"")).join(`
25
-
26
- `)}a(I,"formatCritiquesForPrompt");var T={format:"code",draftPrompt(n,e){return `You are writing a complete code artifact for the following task.
27
-
28
- Task: ${n.label}
29
- Description: ${n.description}
30
- ${n.sources?.length?`Source files for context: ${n.sources.join(", ")}`:""}
31
-
32
- This draft will compete with drafts from other participants in a tournament round.
33
- A merger will then read all drafts (anonymously) and pick the strongest parts.
34
- Make your draft strong, distinct, complete, and self-contained.
35
-
36
- Output requirements:
37
- - Compile-ready code in the appropriate language (infer from sources / description).
38
- - Include tests if behavior is non-trivial.
39
- - Inline comments only where the WHY is non-obvious \u2014 names should explain WHAT.
40
- - At least ${e} characters of substantive code (filler will be cut by the merger).
41
- ${q}`},mergePrompt(n,e,t){let r=e.map(i=>`--- ${i.anonymousLabel} ---
42
- ${i.content}
43
- --- end ${i.anonymousLabel} ---`).join(`
44
-
45
- `);return `Below are ${e.length} draft solutions for the same task, presented anonymously.
46
- Your job: produce a single v1 by merging the strongest parts of each.
47
-
48
- Task: ${n.label}
49
- Description: ${n.description}
50
-
51
- ${r}
52
-
53
- Merging rules:
54
- - For each section / function / module, pick the strongest version OR write a new one inspired by the best ideas.
55
- - Inline EVERYTHING. Do not write "see Draft B for the auth helper" \u2014 copy the auth helper in.
56
- - v1 must be COMPLETE and at least ${t} characters of substantive code.
57
- - After the code, output a 'mergeRationale' section: one short paragraph per major decision, "From Draft X I took ____, because ____. I rejected ____ because ____."
58
-
59
- Output format (literally \u2014 these markers will be parsed):
60
-
61
- <v1_content>
62
- {full code goes here}
63
- </v1_content>
64
-
65
- <merge_rationale>
66
- {your rationale here}
67
- </merge_rationale>`},argueSystem(){return `You are reviewing a code artifact. Find every meaningful issue.
68
-
69
- You may have access to a web_search tool \u2014 USE IT to verify any specific
70
- claim, library version, API behavior, or external reference made in the
71
- draft before deciding whether it's a fabrication.
72
-
73
- For each issue:
74
- - "anchor": quote 5-15 words verbatim from the draft to locate the issue.
75
- - "severity": "blocker" (must fix), "major" (should fix), "minor" (nice to fix), "nit" (style), or "praise" (good \u2014 don't gut this).
76
- - "category": "correctness" | "completeness" | "clarity" | "evidence" | "structure" | "style" | "fabrication" | "other".
77
- - "comment": what's wrong and what you'd do. If you used web_search, cite the URL.
78
- - "suggestion": optional concrete fix.
79
- - "evidence": optional array of {url, snippet} pairs supporting your critique.
80
-
81
- FABRICATION DETECTION (top priority):
82
- Any specific number, citation, URL, version string, API endpoint, library
83
- function, or named entity that you cannot verify is a "fabrication"
84
- critique with severity = "blocker". Be especially suspicious of:
85
- - "Industry average is X%" / "Surveys show N=..."
86
- - Documentation URLs with suspiciously generic paths
87
- - Library/API names that "sound right" but you can't confirm exist
88
-
89
- Aim for 8-20 critiques. Include PRAISE for parts that are genuinely good \u2014 this prevents the author from accidentally gutting them in the next revision.
90
-
91
- Output strictly as JSON: {"critiques": [{...}, ...]}`},argueUser(n,e,t){return `Task: ${n.label}
92
- ${t?`Review lens: ${t}
93
- `:""}
94
- Current draft (v${e.version}, by ${e.author}):
95
-
96
- ${e.content}
97
-
98
- Now produce your critiques as JSON.`},revisePrompt(n,e,t,r){return `You wrote v${e.version}. Critics raised ${t.length} points.
99
- Rewrite the artifact as v${e.version+1}.
100
-
101
- Task: ${n.label}
102
- Description: ${n.description}
103
-
104
- Current draft (v${e.version}):
105
- ${e.content}
106
-
107
- Critiques:
108
- ${I(t)}
109
-
110
- Rules:
111
- - ADDRESS every blocker and major. You may disagree, but say why in changelog.
112
- - Preserve PRAISE-tagged parts unless a later critique contradicts.
113
- - Output the COMPLETE new artifact (at least ${r} chars), not a diff.
114
- - After the code, output a JSON block:
115
-
116
- <v_next_content>
117
- {full code goes here}
118
- </v_next_content>
119
-
120
- <v_next_meta>
121
- {
122
- "acceptedCritiques": ["id1", "id2", ...],
123
- "rejectedCritiques": [{"id": "id3", "reason": "..."}, ...],
124
- "changelog": "what changed and why, in 1-3 short paragraphs"
125
- }
126
- </v_next_meta>`}},D={format:"document",draftPrompt(n,e){return `You are writing a complete long-form document for the following subject.
127
-
128
- Subject: ${n.label}
129
- Description: ${n.description}
130
- ${n.sources?.length?`Reference materials: ${n.sources.join(", ")}`:""}
131
-
132
- This draft will compete with drafts from other participants in a tournament round.
133
- A merger will then read all drafts (anonymously) and pick the strongest parts.
134
- Make your draft strong, distinct, complete, and self-contained.
135
-
136
- Document requirements:
137
- - Use clear hierarchical structure (## sections, ### subsections).
138
- - Every section must carry concrete information: examples, comparisons, trade-offs, numbers.
139
- - Cite sources inline with [n] footnotes when you make factual claims.
140
- - At least ${e} characters of substantive prose (filler will be cut by the merger).
141
- ${q}`},mergePrompt(n,e,t){let r=e.map(i=>`--- ${i.anonymousLabel} ---
142
- ${i.content}
143
- --- end ${i.anonymousLabel} ---`).join(`
144
-
145
- `);return `Below are ${e.length} draft documents for the same subject, presented anonymously.
146
- Your job: produce a single v1 markdown document by merging the strongest parts.
147
-
148
- Subject: ${n.label}
149
- Description: ${n.description}
150
-
151
- ${r}
152
-
153
- Merging rules:
154
- - Pick the strongest section from each draft, OR write a new section that combines their best ideas.
155
- - DO NOT write "see Draft B for ____" \u2014 inline everything.
156
- - The final v1 must be COMPLETE and at least ${t} characters.
157
- - Maintain coherent voice and consistent structure across sections.
158
-
159
- Output format (literally \u2014 these markers will be parsed):
160
-
161
- <v1_content>
162
- {full markdown document}
163
- </v1_content>
164
-
165
- <merge_rationale>
166
- {1-3 short paragraphs: from which draft you took which section, why; what you rejected, why}
167
- </merge_rationale>`},argueSystem(){return `You are reviewing a long-form document. Find every meaningful issue.
168
-
169
- You may have access to a web_search tool \u2014 USE IT to verify any specific
170
- number, citation, market figure, named survey, or external reference
171
- before deciding whether it's a fabrication.
172
-
173
- For each issue:
174
- - "anchor": quote 5-15 words verbatim from the document to locate the issue.
175
- - "severity": "blocker" | "major" | "minor" | "nit" | "praise".
176
- - "category": "correctness" | "completeness" | "clarity" | "evidence" | "structure" | "style" | "fabrication" | "other".
177
- - "comment": what's wrong / missing / weak. If you used web_search, cite the URL.
178
- - "suggestion": optional concrete fix or content to add.
179
- - "evidence": optional array of {url, snippet} pairs supporting your critique.
180
-
181
- FABRICATION DETECTION (top priority):
182
- The document is far more likely to fail because of fabricated facts than
183
- because of missing sections. Treat every specific number / report ID /
184
- URL / dollar figure / "industry average" / named survey as suspect until
185
- verified. Mark as severity = "blocker" if:
186
- - The number cannot be found via web_search.
187
- - The cited URL doesn't resolve to the claimed source.
188
- - The "report ID" / "document number" appears made up.
189
- - The named survey / interviewee count cannot be traced.
190
- A draft full of citations that don't check out is worse than a draft
191
- that honestly writes "[\u9700\u8C03\u7814: ...]". Reward the latter.
192
-
193
- Aim for 8-20 critiques. Don't be polite \u2014 depth, missing sections, weak claims, and structural issues matter more than typos. Include PRAISE for genuinely strong parts so the author doesn't gut them on revision.
194
-
195
- Output strictly as JSON: {"critiques": [{...}, ...]}`},argueUser(n,e,t){return `Subject: ${n.label}
196
- ${t?`Review lens: ${t}
197
- `:""}
198
- Current document (v${e.version}, by ${e.author}):
199
-
200
- ${e.content}
201
-
202
- Now produce your critiques as JSON.`},revisePrompt(n,e,t,r){return `You wrote v${e.version}. Critics raised ${t.length} points.
203
- Rewrite the document as v${e.version+1}.
204
-
205
- Subject: ${n.label}
206
- Description: ${n.description}
207
-
208
- Current document (v${e.version}):
209
- ${e.content}
210
-
211
- Critiques:
212
- ${I(t)}
213
-
214
- Rules:
215
- - ADDRESS every blocker and major. You may disagree, but say why in changelog.
216
- - Preserve PRAISE-tagged parts.
217
- - Expand sections that were called out as thin / missing examples / lacking evidence.
218
- - Output the COMPLETE new document (at least ${r} chars).
219
-
220
- Output format (literally \u2014 these markers will be parsed):
221
-
222
- <v_next_content>
223
- {full markdown document}
224
- </v_next_content>
225
-
226
- <v_next_meta>
227
- {
228
- "acceptedCritiques": ["id1", "id2", ...],
229
- "rejectedCritiques": [{"id": "id3", "reason": "..."}, ...],
230
- "changelog": "what changed and why, in 1-3 short paragraphs"
231
- }
232
- </v_next_meta>`}};function R(n){return n==="code"?T:D}a(R,"getFormat");h();h();function _(n,e){let t=new RegExp(`<${e}>([\\s\\S]*?)<\\/${e}>`,"i"),r=n.match(t);if(r)return r[1].trim();let o=new RegExp(`<${e}>`,"i").exec(n);if(!o)return null;let a=n.slice(o.index+o[0].length),s=a.search(/<[a-z_][\w]*>/i);return (s>=0?a.slice(0,s):a).trim()}a(_,"extractTag");function $(n){let e=_(n,"v1_content"),t=_(n,"merge_rationale");return e?{content:e,rationale:t??void 0}:{content:n.trim(),rationale:"[merge markers not found; using full response]"}}a($,"parseMergeResponse");function L(n){let e=_(n,"v_next_content"),t=_(n,"v_next_meta"),r={};if(t){let i=t.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/,"").trim();try{r=JSON.parse(i);}catch{r={changelog:`[meta JSON parse failed; raw text below]
233
- ${t}`};}}return {content:e??n.trim(),meta:r}}a(L,"parseReviseResponse");function k(n,e,t){let r=n.replace(/^[^{[]*/,"").replace(/[^}\]]*$/,"").trim(),i;try{i=JSON.parse(r);}catch{let s=n.match(/\{[\s\S]*\}|\[[\s\S]*\]/);if(!s)return [];try{i=JSON.parse(s[0]);}catch{return []}}let o=Array.isArray(i)?i:i.critiques;if(!Array.isArray(o))return [];let a=[];for(let s=0;s<o.length;s++){let c=o[s];if(!c.anchor||!c.comment)continue;let u;Array.isArray(c.evidence)&&(u=c.evidence.filter(l=>typeof l!="object"||l===null?false:typeof l.url=="string").map(l=>({url:l.url,snippet:l.snippet})),u.length===0&&(u=void 0)),a.push({id:`${t}-${e}-${s+1}`,critic:e,anchor:String(c.anchor),severity:c.severity??"minor",category:c.category??"other",comment:String(c.comment),suggestion:c.suggestion?String(c.suggestion):void 0,evidence:u});}return a}a(k,"parseCritiquesResponse");h();h();var ye={name:"WebSearch",description:"Search the web for information. Returns a list of search results with titles, URLs, and snippets. Use this when you need up-to-date information or facts not in your training data.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The search query"},num_results:{type:"number",description:"Number of results to return (default: 10, max: 20)"}},required:["query"]}};async function F(n){let e=n.query;if(!e)return "Error: query is required";let t=Math.min(n.num_results||10,20),r=process.env.SERPER_API_KEY,i=process.env.TAVILY_API_KEY,o=process.env.SEARXNG_URL;try{let a;if(r)a=await V(e,t,r);else if(i)a=await X(e,t,i);else if(o)a=await H(e,t,o);else return "Error: No search API configured. Set one of: SERPER_API_KEY, TAVILY_API_KEY, or SEARXNG_URL";return a.length===0?"No results found.":a.map((s,c)=>`${c+1}. ${s.title}
234
- ${s.url}
235
- ${s.snippet}`).join(`
236
-
237
- `)}catch(a){return `Search error: ${a.message}`}}a(F,"webSearchTool");async function V(n,e,t){let r=await fetch("https://google.serper.dev/search",{method:"POST",headers:{"X-API-KEY":t,"Content-Type":"application/json"},body:JSON.stringify({q:n,num:e})});if(!r.ok)throw new Error(`Serper API error: ${r.status} ${r.statusText}`);return ((await r.json()).organic??[]).map(o=>({title:o.title??"",url:o.link??"",snippet:o.snippet??""}))}a(V,"searchSerper");async function X(n,e,t){let r=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,query:n,max_results:e,include_answer:false})});if(!r.ok)throw new Error(`Tavily API error: ${r.status} ${r.statusText}`);return ((await r.json()).results??[]).map(o=>({title:o.title??"",url:o.url??"",snippet:o.content??""}))}a(X,"searchTavily");async function H(n,e,t){let r=new URL("/search",t);r.searchParams.set("q",n),r.searchParams.set("format","json"),r.searchParams.set("pageno","1");let i=await fetch(r.toString(),{headers:{Accept:"application/json"}});if(!i.ok)throw new Error(`SearXNG error: ${i.status} ${i.statusText}`);return ((await i.json()).results??[]).slice(0,e).map(a=>({title:a.title??"",url:a.url??"",snippet:a.content??""}))}a(H,"searchSearXNG");h();var Se={name:"WebFetch",description:"Fetch a web page and return its text content. Strips HTML tags to return readable text. Use this to read articles, documentation, or any web page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"The URL to fetch"},max_length:{type:"number",description:"Maximum characters to return (default: 50000)"},headers:{type:"object",description:"Optional HTTP headers to send"}},required:["url"]}},J=1e5,G=5e4,Q=new Set(["host","authorization","cookie","proxy-authorization","x-forwarded-for","x-real-ip","x-forwarded-host"]),Z=[/^localhost$/i,/^127\./,/^0\.0\.0\.0$/,/^10\./,/^169\.254\./,/^192\.168\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^::1$/,/^fc00:/i,/^fd00:/i,/^fe80:/i];function ee(n){return Z.some(e=>e.test(n))}a(ee,"isBlockedHost");async function M(n){let e=n.url;if(!e)return "Error: url is required";let t;try{t=new URL(e);}catch{return `Error: invalid URL "${e}"`}if(t.protocol!=="http:"&&t.protocol!=="https:")return `Error: only http(s) URLs are allowed, got "${t.protocol}"`;if(ee(t.hostname))return `Error: refusing to fetch internal/loopback host "${t.hostname}"`;let r=Math.min(n.max_length||G,J),i=n.headers??{},o={};for(let[a,s]of Object.entries(i))Q.has(a.toLowerCase())||(o[a]=s);try{let a=await fetch(e,{headers:{"User-Agent":"Mozilla/5.0 (compatible; code-shell/0.1; +https://github.com/nicepkg/code-shell)",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7",...o},redirect:"follow",signal:AbortSignal.timeout(3e4)});if(!a.ok)return `Error: HTTP ${a.status} ${a.statusText}`;let s=a.headers.get("content-type")??"",c=await a.text(),u;return s.includes("text/html")||s.includes("application/xhtml")?u=te(c):u=c,u.length>r&&(u=u.slice(0,r)+`
238
-
239
- ... content truncated (${u.length} chars total)`),u||"(page returned empty content)"}catch(a){let s=a.message;return s.includes("abort")||s.includes("timeout")?"Error: request timed out after 30s":`Fetch error: ${s}`}}a(M,"webFetchTool");function te(n){let e=n;e=e.replace(/<script[\s\S]*?<\/script>/gi,""),e=e.replace(/<style[\s\S]*?<\/style>/gi,""),e=e.replace(/<noscript[\s\S]*?<\/noscript>/gi,"");let t=e.match(/<title[^>]*>([\s\S]*?)<\/title>/i),r=t?O(t[1].trim()):"",i=e.match(/<main[\s\S]*?<\/main>/i)??e.match(/<article[\s\S]*?<\/article>/i)??e.match(/<div[^>]*(?:role="main"|id="content"|class="[^"]*content[^"]*")[^>]*>[\s\S]*?<\/div>/i);if(i)e=i[0];else {let o=e.match(/<body[\s\S]*?<\/body>/i);o&&(e=o[0]);}return e=e.replace(/<(nav|header|footer|aside)[\s\S]*?<\/\1>/gi,""),e=e.replace(/<(p|div|h[1-6]|li|br|tr|blockquote)[^>]*>/gi,`
240
- `),e=e.replace(/<\/(p|div|h[1-6]|li|tr|blockquote)>/gi,`
241
- `),e=e.replace(/<hr[^>]*>/gi,`
242
- ---
243
- `),e=e.replace(/<[^>]+>/g,""),e=O(e),e=e.split(`
244
- `).map(o=>o.trim()).filter(o=>o.length>0).join(`
245
- `),e=e.replace(/\n{3,}/g,`
246
-
247
- `),r&&(e=`# ${r}
248
-
249
- ${e}`),e.trim()}a(te,"extractTextFromHTML");function O(n){return n.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&apos;/g,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(Number(t))).replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}a(O,"decodeEntities");var re={name:"web_search",description:"Search the web (Google via Serper / Tavily / SearXNG depending on env). Use this to verify any specific number, citation, URL, library version, API name, or external claim made in the draft you are reviewing. If a claim cannot be verified by web_search, mark it as a fabrication critique with severity = blocker.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (English usually works best)."},num_results:{type:"number",description:"Default 5, max 20."}},required:["query"]}},ne={name:"web_fetch",description:"Fetch a URL and return its text content (HTML stripped). Use after web_search to read the actual page content of a search result and confirm a specific claim, version number, or quoted figure.",inputSchema:{type:"object",properties:{url:{type:"string",description:"Full http(s) URL to fetch."},max_length:{type:"number",description:"Default 50000 characters."}},required:["url"]}},j=[re,ne];async function N(n,e){return n==="web_search"?F(e):n==="web_fetch"?M(e):`Error: unknown tool "${n}"`}a(N,"executeIterateWebTool");function E(){return !!(process.env.SERPER_API_KEY||process.env.TAVILY_API_KEY||process.env.SEARXNG_URL)}a(E,"hasWebSearchProvider");var oe=8;async function U(n){let{subject:e,format:t,draft:r,critics:i,round:o,enableWebSearch:a,maxToolRounds:s,signal:c,onProgress:u}=n;u?.({type:"argue_start",round:o,data:{criticCount:i.length}});let l=!!a,p=l&&E();l&&!p&&d.warn("arena.iterate.argue_web_unavailable",{reason:"No SERPER_API_KEY / TAVILY_API_KEY / SEARXNG_URL configured"});let f=`r${o}`,d$1=i.map(async y=>{c?.throwIfAborted();try{return p?await ie({critic:y,subject:e,format:t,draft:r,idPrefix:f,maxToolRounds:s??oe,signal:c}):await ae({critic:y,subject:e,format:t,draft:r,idPrefix:f,signal:c})}catch(K){return d.warn("arena.iterate.argue_failed",{round:o,critic:y.name,error:K.message}),[]}}),h=(await Promise.all(d$1)).flat();return u?.({type:"argue_done",round:o,data:{critiqueCount:h.length,webEnabled:p}}),h}a(U,"runArgueRound");async function ae(n){let{critic:e,subject:t,format:r,draft:i,idPrefix:o,signal:a}=n,c=await(await b({...e.llm,enableStreaming:false})).createMessage({systemPrompt:r.argueSystem(r.format),messages:[{role:"user",content:r.argueUser(t,i)}],tools:[],signal:a}),u=k(c.text,e.name,o);return d.info("arena.iterate.argue_singleshot",{critic:e.name,critiqueCount:u.length}),u}a(ae,"argueSingleShot");async function ie(n){let{critic:e,subject:t,format:r,draft:i,idPrefix:o,maxToolRounds:a,signal:s}=n,c=await b({...e.llm,enableStreaming:false}),u=[{role:"user",content:r.argueUser(t,i)}],l=0,p="";for(;l<a;){s?.throwIfAborted();let d=await c.createMessage({systemPrompt:r.argueSystem(r.format),messages:u,tools:j,signal:s});if(d.text&&(p=d.text),!d.toolCalls||d.toolCalls.length===0)break;u.push({role:"assistant",content:[...d.text?[{type:"text",text:d.text}]:[],...d.toolCalls.map(h=>({type:"tool_use",id:h.id,name:h.toolName,input:h.args}))]});let b=await Promise.all(d.toolCalls.map(async h=>{try{let y=await N(h.toolName,h.args);return {id:h.id,content:y}}catch(y){return {id:h.id,content:`Error: ${y.message}`}}}));u.push({role:"user",content:b.map(h=>({type:"tool_result",tool_use_id:h.id,content:h.content}))}),l++;}!p&&l>=a&&(p=(await c.createMessage({systemPrompt:r.argueSystem(r.format),messages:[...u,{role:"user",content:"You have used the maximum number of tool rounds. Produce your critiques JSON now, based on what you have already gathered. Do not request any more tools."}],tools:[],signal:s})).text);let f=k(p,e.name,o);return d.info("arena.iterate.argue_toolloop",{critic:e.name,critiqueCount:f.length,toolRounds:l}),f}a(ie,"argueWithToolLoop");h();async function Y(n){let{subject:e,format:t,previous:r,critiques:i,author:o,minDraftLength:a,signal:s,onProgress:c}=n;c?.({type:"revise_start",round:r.version+1,participant:o.name});let u=await b({...o.llm,enableStreaming:false}),l=t.revisePrompt(e,r,i,a),p=await u.createMessage({systemPrompt:l,messages:[{role:"user",content:`Produce v${r.version+1} now.`}],tools:[],maxTokens:32e3,signal:s}),{content:f,meta:d$1}=L(p.text),b$1=f,h=r.content.length>0?1-b$1.length/r.content.length:0;h>.3&&b$1.length<a&&(d.warn("arena.iterate.revise_too_short",{version:r.version+1,previousLength:r.content.length,newLength:b$1.length,minDraftLength:a}),d$1.changelog=`[WARNING: revision is ${Math.round(h*100)}% shorter than v${r.version}; the author may have summarized instead of rewriting]
250
-
251
- `+(d$1.changelog??""));let y={version:r.version+1,author:o.name,format:t.format,content:b$1,acceptedCritiques:d$1.acceptedCritiques,rejectedCritiques:d$1.rejectedCritiques,changelog:d$1.changelog};return c?.({type:"revise_done",round:y.version,participant:o.name,data:{length:b$1.length,accepted:d$1.acceptedCritiques?.length??0}}),d.info("arena.iterate.revise",{version:y.version,author:o.name,length:b$1.length,accepted:d$1.acceptedCritiques?.length??0,rejected:d$1.rejectedCritiques?.length??0}),y}a(Y,"runRevise");h();async function W(n){let{subject:e,format:t,participants:r,minDraftLength:i,signal:o,onProgress:a}=n;a?.({type:"v1_tournament_start",data:{count:r.length}});let s=r.map(async(l,p)=>{o?.throwIfAborted();let f=await b({...l.llm,enableStreaming:false}),d$1=t.draftPrompt(e,i),h=(await f.createMessage({systemPrompt:d$1,messages:[{role:"user",content:"Write your draft now."}],tools:[],maxTokens:32e3,signal:o})).text.trim(),y={author:l.name,anonymousLabel:`Draft ${String.fromCharCode(65+p)}`,content:h};return a?.({type:"v1_candidate_done",participant:l.name,data:{length:h.length,anonymousLabel:y.anonymousLabel}}),d.info("arena.iterate.v1_candidate",{participant:l.name,anonymousLabel:y.anonymousLabel,length:h.length}),y}),c=await Promise.allSettled(s),u=[];for(let l of c)l.status==="fulfilled"?u.push(l.value):d.warn("arena.iterate.v1_candidate_failed",{error:l.reason?.message});if(u.length===0)throw new Error("All v1 tournament candidates failed");for(let l=u.length-1;l>0;l--){let p=Math.floor(Math.random()*(l+1));[u[l],u[p]]=[u[p],u[l]],u[l].anonymousLabel=`Draft ${String.fromCharCode(65+l)}`;}return u[0].anonymousLabel="Draft A",u}a(W,"runTournamentCandidates");async function B(n){let{subject:e,format:t,author:r,candidates:i,minDraftLength:o,signal:a,onProgress:s}=n;s?.({type:"v1_merge_start",participant:r.name});let c=await b({...r.llm,enableStreaming:false}),u=t.mergePrompt(e,i,o),l=await c.createMessage({systemPrompt:u,messages:[{role:"user",content:"Produce v1 now."}],tools:[],maxTokens:32e3,signal:a}),{content:p,rationale:f}=$(l.text),d$1={version:1,author:r.name,format:t.format,content:p,draftCandidates:i,mergeRationale:f};return s?.({type:"v1_merge_done",participant:r.name,data:{length:p.length}}),d.info("arena.iterate.v1_merge",{author:r.name,candidateCount:i.length,length:p.length}),d$1}a(B,"mergeCandidatesToV1");async function z(n){let{subject:e,format:t,author:r,minDraftLength:i,signal:o}=n,a=await b({...r.llm,enableStreaming:false}),s=t.draftPrompt(e,i),c=await a.createMessage({systemPrompt:s,messages:[{role:"user",content:"Write your draft now."}],tools:[],maxTokens:32e3,signal:o});return {version:1,author:r.name,format:t.format,content:c.text.trim()}}a(z,"singleAuthorV1");var se=5,A=class{static{a(this,"IterativeArena");}config;constructor(e){if(!e.author)throw new Error("IterativeArena requires an `author` participant");if(!e.critics||e.critics.length===0)throw new Error("IterativeArena requires at least 1 critic");let t=[e.author.name,...e.critics.map(r=>r.name)];if(new Set(t).size!==t.length)throw new Error("Author and critics must have unique names");this.config=e;}async run(){let e=Date.now(),{config:t}=this,r=R(t.format),i=t.maxRounds??se,o=t.minDraftLength??(t.format==="code"?200:800),a=t.signal,s=[],c;try{if((t.v1Strategy??"tournament")==="tournament"){let f=await W({subject:t.subject,format:r,participants:[t.author,...t.critics],minDraftLength:o,signal:a,onProgress:t.onProgress});c=await B({subject:t.subject,format:r,author:t.author,candidates:f,minDraftLength:o,signal:a,onProgress:t.onProgress});}else c=await z({subject:t.subject,format:r,author:t.author,minDraftLength:o,signal:a});}catch(f){throw d.error("arena.iterate.v1_failed",{error:f.message}),f}let u=t.author,l=[t.author,...t.critics],p;for(let f=1;f<=i;f++){a?.throwIfAborted();let d=await U({subject:t.subject,format:r,draft:c,critics:this.criticsForRound(f),round:f,enableWebSearch:t.enableWebSearch,maxToolRounds:t.maxArgueToolRounds,signal:a,onProgress:t.onProgress}),b=this.checkConvergence({round:f,critiques:d,draft:c,previousDraft:p}),h={round:f,draft:c,critiques:d,convergence:b},y;if(t.humanCheckpoint&&(t.onProgress?.({type:"checkpoint_pause",round:f}),y=await t.humanCheckpoint({round:f,draft:c,critiques:d,convergence:b})),s.push(h),t.onProgress?.({type:"round_done",round:f,data:{critiques:d.length,shouldStop:b.shouldStop,userAction:y}}),y==="stop")return this.finalize(s,"user_stop",e);if(y!=="force-continue"&&b.shouldStop)return this.finalize(s,"converged",e);if(f===i)return this.finalize(s,"max_rounds",e);p=c,u=this.pickNextAuthor(u,d,l,f),c=await Y({subject:t.subject,format:r,previous:p,critiques:d,author:u,minDraftLength:o,signal:a,onProgress:t.onProgress});}return this.finalize(s,"max_rounds",e)}criticsForRound(e){return this.config.critics}checkConvergence(e){if(this.config.convergenceStrategy&&this.config.convergenceStrategy!=="default"){let t=this.config.convergenceStrategy(e),r=e.critiques.filter(a=>a.severity==="blocker").length,i=e.critiques.filter(a=>a.severity==="major").length,o=e.previousDraft?x(e.previousDraft.content,e.draft.content):1;return {blockerCount:r,majorCount:i,totalCritiques:e.critiques.length,diffFromPrevious:o,shouldStop:t,reason:t?"all_minor_or_praise":"running"}}return C(e)}pickNextAuthor(e,t,r,i){let o=this.config.authorRotation??"fixed";if(o==="fixed")return this.config.author;if(o==="round-robin"){let a=i%r.length;return r[a]}if(o==="best-critic"){let a={blocker:5,major:3,minor:1,nit:.5,praise:0},s=new Map;for(let p of t)s.set(p.critic,(s.get(p.critic)??0)+(a[p.severity]??0));let c=e.name,u=-1;for(let[p,f]of s)f>u&&(u=f,c=p);return r.find(p=>p.name===c)??e}return e}finalize(e,t,r){let i=e.at(-1).draft,o={subject:this.config.subject,format:this.config.format,rounds:e,finalDraft:i,stoppedAt:t,durationMs:Date.now()-r};return this.config.onProgress?.({type:"iterate_complete",data:{stoppedAt:t,rounds:e.length,finalLength:i.content.length}}),d.info("arena.iterate.complete",{stoppedAt:t,rounds:e.length,finalVersion:i.version,finalLength:i.content.length}),o}};export{ye as a,F as b,Se as c,M as d,x as e,C as f,T as g,D as h,R as i,A as j};
@@ -1,49 +0,0 @@
1
- import {c,h,a,d}from'./chunk-3QP5BQ3L.js';function M(e){if(!e)return 0;let n=(e.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g)??[]).length;if(n/e.length>.3){let s=n/y.cjk,h=(e.length-n)/y.english;return Math.ceil(s+h)}return ["{","}","(",")",";","=>","import ","function ","class ","const "].reduce((s,i)=>s+(e.includes(i)?1:0),0)>=3?Math.ceil(e.length/y.code):e.startsWith("{")||e.startsWith("[")?Math.ceil(e.length/y.json):Math.ceil(e.length/y.english)}function S(e){let n=0;for(let t of e)if(n+=4,typeof t.content=="string")n+=M(t.content);else if(Array.isArray(t.content))for(let o of t.content)n+=j(o);return n}function j(e){let n=2;return e.text&&(n+=M(e.text)),e.content&&typeof e.content=="string"&&(n+=M(e.content)),e.input&&(n+=M(JSON.stringify(e.input))),e.name&&(n+=M(e.name)),n}var y,T=c(()=>{h();y={english:4,code:3.2,json:3.5,mixed:3.6,cjk:1.5};a(M,"estimateStringTokens");a(S,"estimateMessagesTokens");a(j,"estimateBlockTokens");});var K={};d(K,{COMPACTABLE_TOOL_NAMES:()=>R,adjustIndexToPreserveAPIInvariants:()=>w,applySummaryCompaction:()=>D,applyToolResultBudget:()=>L,buildSummarizationPrompt:()=>G,dropOldestRounds:()=>J,estimateTokens:()=>N,extractAnchoredSummary:()=>q,extractReferencedFilePaths:()=>C,groupMessagesByApiRound:()=>k,microcompact:()=>U,snipCompact:()=>z,truncateToolResult:()=>F,windowCompact:()=>I});function N(e){return Math.ceil(S(e)*(4/3))}function w(e,n){let t=n,o=new Set;for(let r=t;r<e.length;r++){let s=e[r];if(Array.isArray(s.content))for(let i of s.content)i.type==="tool_result"&&i.tool_use_id&&o.add(i.tool_use_id);}for(let r=t;r<e.length;r++){let s=e[r];if(Array.isArray(s.content))for(let i of s.content)i.type==="tool_use"&&i.id&&o.delete(i.id);}if(o.size===0)return t;for(let r=t-1;r>=0&&o.size>0;r--){let s=e[r];if(!(s.role!=="assistant"||!Array.isArray(s.content)))for(let i of s.content)i.type==="tool_use"&&i.id&&o.has(i.id)&&(o.delete(i.id),r<t&&(t=r));}return t}function z(e,n=3,t=8){if(e.length<=n+t+1)return e;let o=e.length-t;if(o=w(e,o),o<=n)return e;let s={role:"user",content:`<system-reminder>[${o-n} messages snipped to save context. Use the transcript file to review details if needed.]</system-reminder>`};return [...e.slice(0,n),s,...e.slice(o)]}function I(e,n){if(e.length<=n+1)return e;let t=e.length-n;return t=w(e,t),t<=1?e:[e[0],...e.slice(t)]}function W(e){let n=new Map;for(let t of e)if(Array.isArray(t.content))for(let o of t.content)o.type==="tool_use"&&o.id&&o.name&&n.set(o.id,o.name);return n}function B(e,n){if(!n||typeof n!="object")return "";let t=a(o=>{let r=[];for(let s of o){let i=n[s];typeof i=="string"&&i.length>0&&r.push(`${s}=${i.length>80?i.slice(0,77)+"...":i}`);}return r.join(" ")},"pick");switch(e){case "Read":case "Write":case "Edit":case "NotebookEdit":return t(["file_path","path","notebook_path"]);case "Glob":case "Grep":return t(["pattern","path","glob"]);case "Bash":case "PowerShell":case "REPL":return t(["command"]);case "WebFetch":case "WebSearch":return t(["url","query"]);default:{let o=JSON.stringify(n);return o.length>100?o.slice(0,97)+"...":o}}}function U(e,n={}){let t=n.keepRecentN??5,o=n.compactableTools??R,r=W(e),s=new Map;for(let l of e)if(Array.isArray(l.content))for(let g of l.content)g.type==="tool_use"&&g.id&&s.set(g.id,g.input);let i=0,h=[];for(let l=e.length-1;l>=0;l--){let g=e[l];!Array.isArray(g.content)||!g.content.some(d=>d.type==="tool_result"&&d.tool_use_id!=null&&o.has(r.get(d.tool_use_id)??"")&&typeof d.content=="string"&&!d.content.startsWith("[Old tool result cleared"))||(i++,i>t&&h.push(l));}if(h.length===0)return e;let a=new Set(h),u=new Set,p=0,m=e.map((l,g)=>!a.has(g)||!Array.isArray(l.content)?l:{...l,content:l.content.map(f=>{if(f.type!=="tool_result"||!f.tool_use_id)return f;let d=r.get(f.tool_use_id);if(!d||!o.has(d)||typeof f.content!="string"||f.content.startsWith("[Old tool result cleared"))return f;let A=B(d,s.get(f.tool_use_id)),O=A?`[Old tool result cleared \u2014 ${d} ${A}]`:`[Old tool result cleared \u2014 ${d}]`;return u.add(d),p++,{...f,content:O}})});return p>0&&n.onClear?.({clearedRounds:h.length,toolNames:[...u].sort()}),m}function L(e,n=1e5){return e.map(t=>{if(!Array.isArray(t.content))return t;let o=[],r=0;for(let a=0;a<t.content.length;a++){let u=t.content[a];if(u.type==="tool_result"&&typeof u.content=="string"){let p=u.content.length;o.push({index:a,size:p}),r+=p;}}if(r<=n||o.length===0)return t;o.sort((a,u)=>u.size-a.size);let s=r,i=new Set;for(let a of o){if(s<=n)break;i.add(a.index),s-=a.size,s+=200;}if(i.size===0)return t;let h=t.content.map((a,u)=>{if(!i.has(u))return a;let p=typeof a.content=="string"?a.content.slice(0,500):"",m=(a.content.length/1e3).toFixed(0);return {...a,content:`Output too large (${m}KB) \u2014 truncated to fit the per-message budget. Re-run the originating tool if you need the full output.
2
-
3
- Preview (first 500 chars):
4
- ${p}`}});return {...t,content:h}})}function F(e,n=3e4){if(e.length<=n)return e;let t=Math.floor(n*.7),o=Math.floor(n*.2),r=e.slice(0,t),s=e.slice(-o);return r+`
5
-
6
- ... [${e.length-t-o} characters truncated] ...
7
-
8
- `+s}function G(e,n){let t=[];for(let r of e)if(typeof r.content=="string")t.push(`[${r.role}]: ${r.content.slice(0,3e3)}`);else for(let s of r.content)if(s.type==="text"&&s.text)t.push(`[${r.role}]: ${s.text.slice(0,3e3)}`);else if(s.type==="tool_use"){let i=JSON.stringify(s.input).slice(0,500);t.push(`[tool_use]: ${s.name}(${i})`);}else if(s.type==="tool_result"){let i=typeof s.content=="string"?s.content:"";t.push(`[tool_result]: ${i.slice(0,1500)}`);}let o=`1. **Primary Request**: What the user originally asked for
9
- 2. **Key Concepts**: Important technical terms, patterns, file paths
10
- 3. **Files Referenced**: List of files read/edited with key content
11
- 4. **Errors & Fixes**: Any errors encountered and how they were resolved
12
- 5. **Actions Taken**: Tools used and their outcomes
13
- 6. **User Messages**: All distinct user requests (verbatim if short)
14
- 7. **Pending Tasks**: Anything started but not finished
15
- 8. **Current State**: Where things stand right now
16
- 9. **Next Steps**: What should happen next
17
- `;return n?`You are updating an anchored conversation summary. A prior summary is shown first, followed by NEW conversation that occurred after that summary was produced. Produce an UPDATED summary that:
18
- - Preserves every critical fact from the prior summary (file paths, decisions, the user's original intent, errors that were fixed)
19
- - Merges in new facts from the new conversation
20
- - Resolves contradictions in favor of the newer information
21
- - Stays in the same 9-section structure below
22
- - Is factual; preserves file paths, function names, and error messages exactly
23
-
24
- `+o+`
25
- === Prior summary ===
26
- `+n+`
27
-
28
- === New conversation ===
29
-
30
- `+t.join(`
31
- `):`Summarize the following conversation into these sections. Be factual. Preserve file paths, function names, and error messages exactly.
32
-
33
- `+o+`
34
- Conversation:
35
-
36
- `+t.join(`
37
- `)}function q(e){for(let n=e.length-1;n>=0;n--){let t=e[n],o=typeof t.content=="string"?t.content:"";if(!o)continue;let r=o.indexOf(x);if(r<0)continue;let s=o.indexOf(v,r+x.length);if(!(s<=r))return o.slice(r+x.length,s).trim()}}function D(e,n,t,o){if(e.length<=t+2)return e;let r=e.length-t;if(r=w(e,r),r<=1)return e;let s=e[0],i=e.slice(1,r),h=e.slice(r),a=C(i),u=`This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.
38
-
39
- ${x}
40
- ${n}
41
- ${v}`;o&&(u+=`
42
-
43
- If you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: ${o}`),a.length>0&&(u+=`
44
-
45
- Files referenced before compaction (use Read tool if you need their current content):
46
- `+a.map(m=>`- ${m}`).join(`
47
- `)),u+=`
48
-
49
- Recent messages are preserved verbatim below. Continue from where you left off.`;let p={role:"user",content:`<system-reminder>${u}</system-reminder>`};return [s,p,...h]}function k(e){let n=[],t=[];for(let o of e)o.role==="assistant"&&t.length>0?(n.push(t),t=[o]):t.push(o);return t.length>0&&n.push(t),n}function J(e,n){let t=k(e);if(t.length<=n+1)return t[t.length-1];let o=t.slice(n).flat(),r=w(o,0),s=o.slice(r);return s.length>0&&s[0].role==="assistant"&&s.unshift({role:"user",content:"<system-reminder>Earlier conversation context was removed to fit within the context window. Continue from the assistant's response below.</system-reminder>"}),s}function C(e){let n=new Set,t=new Set(["Read","Edit","Write","Glob","Grep"]);for(let o of e)if(Array.isArray(o.content)){for(let r of o.content)if(r.type==="tool_use"&&r.name&&t.has(r.name)&&r.input){let s=r.input,i=s.file_path??s.path;i&&n.add(i);}}return [...n]}var R,x,v,H=c(()=>{h();T();a(N,"estimateTokens");a(w,"adjustIndexToPreserveAPIInvariants");a(z,"snipCompact");a(I,"windowCompact");R=new Set(["Read","Glob","Grep","Bash","PowerShell","NotebookEdit","WebFetch","WebSearch","REPL"]);a(W,"buildToolUseIdToNameMap");a(B,"summarizeToolCallArgs");a(U,"microcompact");a(L,"applyToolResultBudget");a(F,"truncateToolResult");a(G,"buildSummarizationPrompt");x="<anchored-summary>",v="</anchored-summary>";a(q,"extractAnchoredSummary");a(D,"applySummaryCompaction");a(k,"groupMessagesByApiRound");a(J,"dropOldestRounds");a(C,"extractReferencedFilePaths");});export{N as a,w as b,z as c,I as d,R as e,U as f,L as g,F as h,G as i,q as j,D as k,k as l,J as m,C as n,K as o,H as p};
@@ -1 +0,0 @@
1
- import {a as a$1}from'./chunk-P6JSTIFM.js';import {h,a}from'./chunk-3QP5BQ3L.js';h();var u=[[/^deepseek-v4(?:-|$)/i,1e6],[/(?:^|\/)deepseek-v4(?:-|$)/i,1e6]];function g(s){for(let[e,i]of u)if(e.test(s))return i}a(g,"lookupBuiltinContextWindow");var l=class{static{a(this,"ModelPool");}models=new Map;activeKey;providerCatalog;cacheDir;setProviderCatalog(e){this.providerCatalog=e;}setCacheDir(e){this.cacheDir=e;}reloadCachedContextWindows(){if(this.cacheDir)for(let[e,i]of this.models){if(i.maxContextTokens!=null||!i.providerKey)continue;let t=a$1(this.cacheDir,i.providerKey);if(!t)continue;let n=t.models.find(r=>r.id===i.model);n?.contextLength&&this.models.set(e,{...i,maxContextTokens:n.contextLength});}}constructor(e,i){if(e)for(let t of e)this.models.set(t.key,this.withBuiltinDefaults(t));i&&this.models.has(i)?this.activeKey=i:e?.length&&(this.activeKey=e[0].key);}register(e){this.models.set(e.key,this.withBuiltinDefaults(e)),this.activeKey||(this.activeKey=e.key);}withBuiltinDefaults(e){if(e.maxContextTokens!=null)return e;let i=g(e.model);return i==null?e:{...e,maxContextTokens:i}}switch(e){let i=this.models.get(e);if(!i){let t=[...this.models.keys()].join(", ");throw new Error(`Model "${e}" not found. Available: ${t}`)}return this.activeKey=e,i}get(e){if(e)return this.models.get(e);if(this.activeKey)return this.models.get(this.activeKey)}getActiveKey(){return this.activeKey}list(){return [...this.models.values()]}get size(){return this.models.size}has(e){return this.models.has(e)}toLLMConfig(e,i){let t=e.providerKey&&this.providerCatalog?this.providerCatalog.get(e.providerKey):void 0,n=a(r=>r&&r==="anthropic"?"anthropic":"openai","kindToClientProvider");return {provider:e.provider||n(t?.kind)||"openai",model:e.model,apiKey:e.apiKey??t?.apiKey??i?.apiKey,baseUrl:e.baseUrl??t?.baseUrl??i?.baseUrl,temperature:i?.temperature??.3,maxTokens:e.maxOutputTokens??i?.maxTokens??8192,enableStreaming:i?.enableStreaming??true,...e.thinking||t?.thinking||i?.thinking?{thinking:e.thinking??t?.thinking??i?.thinking}:{},...t?.kind?{providerKind:t.kind}:{}}}resolveLLMConfig(e,i){let t=this.get(e);if(t)return this.toLLMConfig(t,i)}};export{l as a};
@@ -1 +0,0 @@
1
- import {h,a}from'./chunk-3QP5BQ3L.js';h();var r=null;async function c(){return r||(r=import('gpt-tokenizer').then(n=>n.encode)),r}a(c,"getEncoder");var o=null;c().then(n=>{o=n;});function u(n){return n?o?o(n).length:Math.ceil(n.length/4):0}a(u,"countTokens");export{u as a};
@@ -1 +0,0 @@
1
- import {d,c as c$1,b}from'./chunk-FU7AHZNN.js';import {d as d$1}from'./chunk-DI26OUIU.js';import {h,a}from'./chunk-3QP5BQ3L.js';h();var c=class g{constructor(e){this.config=e;this.provider=e.provider,this.model=e.model,this.temperature=e.temperature??.3,this.maxTokens=e.maxTokens??8192,this.timeout=e.timeout??12e4,this.retryMaxAttempts=e.retryMaxAttempts??3,this.enableStreaming=e.enableStreaming??true,this.initClient();}static{a(this,"LLMClientBase");}provider;model;temperature;maxTokens;timeout;retryMaxAttempts;enableStreaming;static onUsage;usage={records:[],totalPromptTokens:0,totalCompletionTokens:0,totalTokens:0,requestCount:0};recordUsage(e,i){i?.recordUsage!==false&&(this.usage.records.push(e),this.usage.totalPromptTokens+=e.promptTokens,this.usage.totalCompletionTokens+=e.completionTokens,this.usage.totalTokens+=e.totalTokens,this.usage.requestCount++,g.onUsage?.(this.model,e));}getUsage(){return {...this.usage}}async withRetry(e,i){let o=i??this.retryMaxAttempts,n;for(let t=1;t<=o;t++)try{return await e()}catch(r){if(n=r,r instanceof d)throw r;if(r instanceof c$1){let s=(r.retryAfter??t*2)*1e3;d$1.warn("llm.retry",{cat:"llm",provider:this.provider,model:this.model,attempt:t,of:o,reason:"rate_limit",waitMs:s}),await new Promise(T=>setTimeout(T,s));continue}if(t===o){d$1.error("llm.exhausted",{cat:"llm",provider:this.provider,model:this.model,attempts:o,error:r.message});break}let m=Math.min(1e3*Math.pow(2,t-1),3e4);d$1.warn("llm.retry",{cat:"llm",provider:this.provider,model:this.model,attempt:t,of:o,reason:"error",error:r.message,backoffMs:m}),await new Promise(s=>setTimeout(s,m));}throw n??new b("Unknown LLM error")}};export{c as a};
@@ -1 +0,0 @@
1
- import {h as h$1,a}from'./chunk-3QP5BQ3L.js';import {existsSync,readFileSync,mkdirSync,writeFileSync}from'fs';import {homedir}from'os';import {join}from'path';h$1();var h=168*3600*1e3;function S(e,r){let t=join(e,`${r}.json`);if(existsSync(t))try{let i=readFileSync(t,"utf-8"),o=JSON.parse(i);return !o||!Array.isArray(o.models)?void 0:o}catch{return}}a(S,"readCache");function x(e,r,t){existsSync(e)||mkdirSync(e,{recursive:true});let i={fetchedAt:new Date().toISOString(),providerKey:r,models:t};return writeFileSync(join(e,`${r}.json`),JSON.stringify(i,null,2),"utf-8"),i}a(x,"writeCache");function y(e,r=Date.now()){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?r-t>h:true}a(y,"isStale");function F(){return join(homedir(),".code-shell","cache","models")}a(F,"defaultCacheDir");export{S as a,x as b,y as c,F as d};
@@ -1,5 +0,0 @@
1
- import {j}from'./chunk-FU7AHZNN.js';import {h,a}from'./chunk-3QP5BQ3L.js';import {mkdirSync,existsSync,writeFileSync,appendFileSync,readFileSync,renameSync,readdirSync,statSync}from'fs';import {dirname,join}from'path';import {homedir}from'os';import {nanoid}from'nanoid';h();h();var l=class c{static{a(this,"Transcript");}events=[];filePath;currentTurn=0;getFilePath(){return this.filePath}constructor(t){this.filePath=t,mkdirSync(dirname(t),{recursive:true}),existsSync(t)||writeFileSync(t,"","utf-8");}append(t,s){let e={id:nanoid(12),type:t,timestamp:Date.now(),turnNumber:this.currentTurn,data:s};return this.events.push(e),this.flush(e),e}appendMessage(t,s){return this.append("message",{role:t,content:s})}appendToolUse(t,s,e){return this.append("tool_use",{toolName:t,toolCallId:s,args:e})}appendToolResult(t,s,e,n){return this.append("tool_result",{toolCallId:t,toolName:s,result:e,error:n})}appendTurnBoundary(){return this.currentTurn++,this.append("turn_boundary",{turnNumber:this.currentTurn})}appendSummary(t,s){return this.append("summary",{summary:t,trigger:"auto",compactedRange:s,preservedSegment:{headEventId:this.events[0]?.id,tailEventId:this.events[this.events.length-1]?.id}})}appendError(t,s){return this.append("error",{error:t,...s})}toMessages(){let t=[];for(let s of this.events)switch(s.type){case "message":{let{role:e,content:n}=s.data;t.push({role:e,content:n});break}case "tool_use":break;case "tool_result":{let{toolCallId:e,result:n,error:i}=s.data,r=t[t.length-1],o={type:"tool_result",tool_use_id:e,content:i?`Error: ${i}`:n??"(no output)"};r?.role==="user"&&Array.isArray(r.content)?r.content.push(o):t.push({role:"user",content:[o]});break}case "summary":{let{summary:e}=s.data;t.push({role:"user",content:`<system-reminder>Previous conversation was summarized:
2
- ${e}</system-reminder>`});break}}return t}getEvents(t){return t?this.events.filter(s=>s.type===t):[...this.events]}get turnNumber(){return this.currentTurn}get eventCount(){return this.events.length}flush(t){try{appendFileSync(this.filePath,JSON.stringify(t)+`
3
- `,"utf-8");}catch{}}repairToolResultPairs(){let t=new Set,s=new Set;for(let e of this.events)e.type==="tool_use"?t.add(e.data.toolCallId):e.type==="tool_result"&&s.add(e.data.toolCallId);for(let e of t)s.has(e)||this.append("tool_result",{toolCallId:e,toolName:"unknown",error:"[Tool result missing due to interrupted session]"});this.events=this.events.filter(e=>{if(e.type==="tool_result"){let n=e.data.toolCallId;return t.has(n)}return true});}static loadFromFile(t){let s=new c(t);if(!existsSync(t))return s;let n=readFileSync(t,"utf-8").split(`
4
- `).filter(i=>i.trim());for(let i of n)try{let r=JSON.parse(i);s.events.push(r),r.type==="turn_boundary"&&(s.currentTurn=r.data.turnNumber??s.currentTurn+1);}catch{}return s.repairToolResultPairs(),s}};var S=class{static{a(this,"SessionManager");}sessionsDir;constructor(t){this.sessionsDir=t??join(homedir(),".code-shell","sessions"),mkdirSync(this.sessionsDir,{recursive:true});}create(t,s,e){let n=nanoid(16),i=join(this.sessionsDir,n);mkdirSync(i,{recursive:true});let r={sessionId:n,cwd:t,startedAt:Date.now(),model:s,provider:e,tokenUsage:{promptTokens:0,completionTokens:0,totalTokens:0},turnCount:0,invokedSkills:[],status:"active"};writeFileSync(join(i,"state.json"),JSON.stringify(r,null,2),"utf-8");let o=new l(join(i,"transcript.jsonl"));return o.append("session_meta",{sessionId:n,cwd:t,model:s,provider:e,startedAt:r.startedAt}),{state:r,transcript:o}}resume(t){let s=join(this.sessionsDir,t);if(!existsSync(s))throw new j(`Session not found: ${t}`);let e=join(s,"state.json");if(!existsSync(e))throw new j(`Session state file not found: ${t}`);let n=JSON.parse(readFileSync(e,"utf-8")),i=join(s,"transcript.jsonl"),r=l.loadFromFile(i);return n.status="active",{state:n,transcript:r}}saveState(t){let s=join(this.sessionsDir,t.sessionId);mkdirSync(s,{recursive:true});let e=join(s,"state.json"),n=`${e}.${process.pid}.${Date.now()}.tmp`;writeFileSync(n,JSON.stringify(t,null,2),"utf-8"),renameSync(n,e);}fork(t,s){let e=this.resume(t),n=e.transcript.getEvents(),i=s??e.state.turnCount,r=this.create(e.state.cwd,e.state.model,e.state.provider);r.state.parentSessionId=t;for(let o of n){if(o.type==="turn_boundary"&&o.data.turnNumber>i)break;r.transcript.append(o.type,o.data);}return this.saveState(r.state),r}list(t=20){if(!existsSync(this.sessionsDir))return [];let s=readdirSync(this.sessionsDir,{withFileTypes:true}).filter(n=>n.isDirectory()).map(n=>n.name),e=[];for(let n of s){let i=join(this.sessionsDir,n,"state.json");if(existsSync(i))try{let r=JSON.parse(readFileSync(i,"utf-8")),o=join(this.sessionsDir,n,"transcript.jsonl"),m=I(o),T=existsSync(o)?statSync(o).mtimeMs:r.startedAt;e.push({...r,preview:m,lastActiveAt:T});}catch{}}return e.sort((n,i)=>i.lastActiveAt-n.lastActiveAt).slice(0,t)}};function I(c){if(!existsSync(c))return;let s=readFileSync(c,"utf-8").split(`
5
- `);for(let e=s.length-1;e>=0;e--){let n=s[e];if(!n)continue;let i;try{i=JSON.parse(n);}catch{continue}if(i.type!=="message"||i.data?.role!=="user")continue;let r=i.data.content,o=typeof r=="string"?r:Array.isArray(r)?r.find(m=>m.type==="text")?.text??"":"";if(o.trim())return o.replace(/\s+/g," ").trim()}}a(I,"readLastUserMessage");export{l as a,S as b};
@@ -1,4 +0,0 @@
1
- import {h as h$1,a}from'./chunk-3QP5BQ3L.js';import {existsSync,readFileSync,mkdirSync,writeFileSync,realpathSync,readdirSync,statSync}from'fs';import {join,dirname}from'path';import {homedir}from'os';import q from'lodash-es/memoize.js';import {parse}from'yaml';h$1();h$1();var A=/^---\s*\n([\s\S]*?)---\s*\n?/,M=/[{}[\]*&#!|>%@`]|: /;function I(n){let t=n.match(A);if(!t)return {frontmatter:{},body:n};let r=t[1]??"",s=n.slice(t[0].length),i;try{i=parse(r);}catch{try{i=parse(T(r));}catch{return {frontmatter:{},body:s}}}return i&&typeof i=="object"&&!Array.isArray(i)?{frontmatter:i,body:s}:{frontmatter:{},body:s}}a(I,"parseFrontmatter");function T(n){let t=n.split(`
2
- `),r=[];for(let s of t){let i=s.match(/^([a-zA-Z_-]+):\s+(.+)$/);if(!i){r.push(s);continue}let a=i[1],o=i[2];if(!a||!o){r.push(s);continue}if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")){r.push(s);continue}if(M.test(o)){let l=o.replace(/\\/g,"\\\\").replace(/"/g,'\\"');r.push(`${a}: "${l}"`);continue}r.push(s);}return r.join(`
3
- `)}a(T,"quoteProblematicValues");function $(n){return n==null?"":typeof n=="string"?n.trim():typeof n=="number"||typeof n=="boolean"?String(n):""}a($,"coerceDescription");h$1();function W(){return process.env.HOME??homedir()}a(W,"userHome");function m(){return join(W(),".code-shell","plugins","installed_plugins.json")}a(m,"installedPluginsPath");function y(){let n=m();if(!existsSync(n))return {version:2,plugins:{}};try{let t=JSON.parse(readFileSync(n,"utf-8"));if(t&&typeof t=="object"&&t.version===2&&t.plugins&&typeof t.plugins=="object")return t}catch{}return {version:2,plugins:{}}}a(y,"readInstalledPlugins");function x(n){let t=m();mkdirSync(dirname(t),{recursive:true}),writeFileSync(t,JSON.stringify(n,null,2)+`
4
- `,"utf-8");}a(x,"writeInstalledPlugins");function an(n,t){let r=y(),s=r.plugins[n]??[];s.push(t),r.plugins[n]=s,x(r);}a(an,"appendInstallEntry");function un(n){let t=y();return n in t.plugins?(delete t.plugins[n],x(t),true):false}a(un,"removeInstallEntries");function fn(n,t){return `${n}@${t}`}a(fn,"pluginInstallKey");function F(){return process.env.HOME??homedir()}a(F,"userHome");function G(n){return [{dir:join(n,".code-shell","skills"),source:"project"},{dir:join(F(),".code-shell","skills"),source:"user"}]}a(G,"bases");function X(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}a(X,"isENOENT");function h(n){if(typeof n!="object"||n===null||!("code"in n))return false;let t=n.code;return t==="EACCES"||t==="EPERM"||t==="EIO"}a(h,"isInaccessible");function O(n){try{return readFileSync(n,"utf-8")}catch(t){if(X(t))return null;if(h(t))return console.warn(`[skills] cannot read ${n}: ${t.message}`),null;throw t}}a(O,"readSkillFile");function v(n,t,r,s,i){let{frontmatter:a,body:o}=I(s),l=typeof a.name=="string"?a.name:void 0;l!==void 0&&l!==t&&console.warn(`[skills] frontmatter.name "${l}" in ${n} does not match directory name "${t}"; using directory name`);let c=$(a.description);return {name:i?`${i}:${t}`:t,description:c,content:o,filePath:n,source:r}}a(v,"buildSkillFromFile");function Z(n,t,r,s){for(let{dir:i,source:a}of n){if(!existsSync(i))continue;let o;try{o=realpathSync(i);}catch{continue}if(s.has(o))continue;s.add(o);let l;try{l=readdirSync(i,{withFileTypes:!0});}catch(c){if(h(c)){console.warn(`[skills] cannot read ${i}: ${c.message}`);continue}throw c}for(let c of l){if(!c.isDirectory()&&!c.isSymbolicLink()||r.has(c.name))continue;let f=join(i,c.name,"SKILL.md"),g=O(f);g!==null&&(t.push(v(f,c.name,a,g)),r.add(c.name));}}}a(Z,"scanDirBases");function Q(n){let t=y(),r=new Set,s=Object.keys(t.plugins).sort();for(let i of s){let a=t.plugins[i]??[],o=i.lastIndexOf("@"),l=o>0?i.slice(0,o):i;for(let c of a){let f=join(c.installPath,"skills");if(!existsSync(f))continue;let g;try{g=readdirSync(f,{withFileTypes:!0});}catch(u){if(h(u)){console.warn(`[skills] cannot read ${f}: ${u.message}`);continue}throw u}for(let u of g){if(!u.isDirectory()&&!u.isSymbolicLink())continue;let S=`${l}:${u.name}`;if(r.has(S))continue;let k=join(f,u.name,"SKILL.md"),b=O(k);b!==null&&(n.push(v(k,u.name,"plugin",b,l)),r.add(S));}}}}a(Q,"scanInstalledPlugins");function U(n){let t=[],r=new Set,s=new Set;return Z(G(n),t,r,s),Q(t),t}a(U,"scanOnce");function nn(){let n=m();try{return statSync(n).mtimeMs.toString()}catch{return "0"}}a(nn,"installedPluginsMtime");var L=q(U,n=>`${n}\0${F()}\0${nn()}`);function En(n){return L(n)}a(En,"scanSkills");function Pn(){L.cache.clear?.();}a(Pn,"invalidateSkillCache");export{I as a,$ as b,m as c,y as d,an as e,un as f,fn as g,En as h,Pn as i};
@@ -1 +0,0 @@
1
- import {h,a}from'./chunk-3QP5BQ3L.js';h();function t(){return {name:"off",wrap(r,a){return {file:a.shell,args:["-c",r]}}}}a(t,"createOffBackend");export{t as a};
@@ -1,3 +0,0 @@
1
- import {a as a$2}from'./chunk-O5HFCH2U.js';import {a as a$1}from'./chunk-OWBYLMDD.js';import {b,c,d as d$1}from'./chunk-FU7AHZNN.js';import {d}from'./chunk-DI26OUIU.js';import {h,a}from'./chunk-3QP5BQ3L.js';import N from'openai';h();h();h();var U=[{kind:"openai",match:/^(?:o[1-9]\d*|gpt-[5-9])(?:[-.]|$)/i,capability:{tokenLimitField:"max_completion_tokens",rejectedParams:new Set(["temperature","top_p","presence_penalty","frequency_penalty","logit_bias","logprobs","top_logprobs"]),reasoning:{kind:"openai-effort"},echoReasoning:"optional"},why:"OpenAI o-series + gpt-5+ reject classic sampling params; use max_completion_tokens + reasoning_effort."},{kind:"deepseek",match:/^deepseek-v4(?:[-.]|$)/i,capability:{reasoning:{kind:"deepseek-thinking"},echoReasoning:"when-tools"},why:"DeepSeek V4 thinking mode \u2014 top-level thinking:{type}; echo reasoning_content when tools are present."},{kind:"deepseek",match:/^deepseek-reasoner(?:[-.]|$)/i,capability:{reasoning:{kind:"none"},echoReasoning:"never"},why:"deepseek-reasoner refuses prior reasoning_content in input; always-on reasoning, no toggle."},{kind:"zai",match:/^glm-[4-9](?:[-.]|$)/i,capability:{reasoning:{kind:"deepseek-thinking"},echoReasoning:"optional"},why:"Z.AI GLM-4.5+ thinking shape is identical to DeepSeek V4; default is enabled."},{kind:"anthropic",match:/^claude-(?:opus|sonnet|haiku)-4-[6-9](?:[-.]|$)/i,capability:{reasoning:{kind:"anthropic-adaptive"},echoReasoning:"when-tools",parallelToolCalls:"anthropic-disable-flag",streamUsage:"auto"},why:"Claude 4.6+ thinking is adaptive \u2014 no opt-in field. Echo thinking blocks on tool turns."},{kind:"anthropic",match:/^claude-(?:opus|sonnet|haiku)-4(?:[-.]|$)/i,capability:{reasoning:{kind:"anthropic-budget",minBudgetTokens:1024},echoReasoning:"when-tools",parallelToolCalls:"anthropic-disable-flag",streamUsage:"auto"},why:"Claude 4.x \u22644.5 supports explicit thinking:{type:enabled, budget_tokens\u22651024}."},{kind:"anthropic",match:/^claude-/i,capability:{parallelToolCalls:"anthropic-disable-flag",streamUsage:"auto"},why:"Pre-Claude-4 \u2014 no extended thinking; keep Anthropic tool_choice/stream shape."},{kind:"google",match:/^gemini-(?:[2-9]\.\d|[2-9])/i,capability:{reasoning:{kind:"openai-effort"},echoReasoning:"optional"},why:"Gemini 2.5+ via OpenAI-compat \u2014 reasoning_effort is auto-mapped to thinking_level."},{kind:"openrouter",match:/./,capability:{reasoning:{kind:"openrouter-reasoning"},echoReasoning:"optional"},why:"OpenRouter exposes a unified reasoning:{effort,max_tokens,exclude,enabled} field for every backend."},{kind:"xai",match:/^grok-4\.3(?:[-.]|$)/i,capability:{reasoning:{kind:"openai-effort",disabledEffort:"low"}},why:"xAI grok-4.3 supports reasoning_effort none|low|medium|high \u2014 no `minimal`."},{kind:"mistral",match:/^magistral/i,capability:{reasoning:{kind:"openai-effort",disabledEffort:"none"}},why:"Mistral magistral models accept only reasoning_effort `high` or `none`."},{kind:"groq",match:/^(?:gpt-oss-(?:20b|120b)|qwen3-)/i,capability:{reasoning:{kind:"openai-effort"},tokenLimitField:"max_completion_tokens"},why:"Groq reasoning-capable models use max_completion_tokens + reasoning_effort."}];h();var C={tokenLimitField:"max_tokens",rejectedParams:new Set,reasoning:{kind:"none"},echoReasoning:"optional",parallelToolCalls:"openai-flag",streamUsage:"include-usage-flag"};function j(h,e){for(let t of U)if(t.kind===h&&t.match.test(e))return {...C,...t.capability,rejectedParams:t.capability.rejectedParams?new Set(t.capability.rejectedParams):new Set(C.rejectedParams)};return {...C,rejectedParams:new Set(C.rejectedParams)}}a(j,"capabilitiesFor");h();var v=class extends Error{constructor(t,c){super(`Stream idle for ${t}ms \u2014 aborted`);this.idleMs=t;this.requestId=c;this.name="StreamIdleTimeoutError";}static{a(this,"StreamIdleTimeoutError");}kind="stream-idle-timeout"};var T={enabled:process.env.CODESHELL_ENABLE_STREAM_WATCHDOG==="1",idleTimeoutMs:parseInt(process.env.CODESHELL_STREAM_IDLE_TIMEOUT_MS||"",10)||9e4,retries:parseInt(process.env.CODESHELL_STREAM_WATCHDOG_RETRIES||"",10)||2};async function W(h,e={}){let t=T.enabled||e.idleTimeoutMs!==void 0,c=e.idleTimeoutMs??T.idleTimeoutMs,o="";if(!t){for await(let n of h)e.onChunk?o+=e.onChunk(n)??"":o+=n?.choices?.[0]?.delta?.content??"";return o}let i=h[Symbol.asyncIterator]();try{for(;;){let n=i.next(),p=null,f=new Promise((r,l)=>{p=setTimeout(()=>{l(new v(c,e.requestId));},c);}),a;try{a=await Promise.race([n,f]);}finally{p!==null&&clearTimeout(p);}if(a.done)break;let s=a.value;e.onChunk?o+=e.onChunk(s)??"":o+=s?.choices?.[0]?.delta?.content??"";}}finally{i.return?.();}return o}a(W,"runStreamWithWatchdog");var D=class extends a$1{static{a(this,"OpenAIClient");}_client=null;_forceMaxCompletionTokens=false;constructor(e){super(e);}initClient(){}get client(){return this._client||(this._client=new N({apiKey:this.config.apiKey??process.env.OPENAI_API_KEY,...this.config.baseUrl?{baseURL:this.config.baseUrl}:{},timeout:this.timeout})),this._client}_capability=null;get capability(){if(!this._capability){let e=this.config.providerKind??"openai";this._capability=j(e,this.model);}return this._capability}async createMessage(e){return this.withRetry(async()=>{let t=e.thinking??this.config.thinking,c=this.buildMessages(e.systemPrompt,e.messages,t),o=e.tools?.length?this.convertTools(e.tools):void 0,i=d.span("llm.request",{cat:"llm",provider:this.provider,model:this.model,stream:!!(e.stream&&e.onChunk),messageCount:c.length,toolCount:o?.length??0});try{let n=e.stream&&e.onChunk?await this.streamMessage(e,c,o,t):await this.nonStreamMessage(e,c,o,t);return i.end({stopReason:n.stopReason,promptTokens:n.usage?.promptTokens,completionTokens:n.usage?.completionTokens,cacheReadTokens:n.usage?.cacheReadTokens,cacheCreationTokens:n.usage?.cacheCreationTokens}),n}catch(n){throw i.fail(n),n}})}buildRequestBody(e,t,c,o,i){let n=this.capability,p=e.maxTokens??this.maxTokens,a=this._forceMaxCompletionTokens||n.tokenLimitField==="max_completion_tokens"?{max_completion_tokens:p}:{max_tokens:p},s={};n.rejectedParams.has("temperature")||(s.temperature=e.temperature!==void 0?e.temperature:this.temperature);let r={};if(o)switch(n.reasoning.kind){case "deepseek-thinking":r.thinking={type:o};break;case "openai-effort":r.reasoning_effort=o==="disabled"?n.reasoning.disabledEffort??"minimal":"medium";break;case "openrouter-reasoning":r.reasoning=o==="disabled"?{effort:"minimal",exclude:true}:{effort:"medium"};break;}return {model:this.model,messages:t,...a,...s,...r,...c?{tools:c}:{},...i?{stream:true,stream_options:{include_usage:true}}:{}}}async nonStreamMessage(e,t,c,o){try{let i=await this.client.chat.completions.create(this.buildRequestBody(e,t,c,o,!1),{signal:e.signal}),n=i.choices[0];if(!n)throw new b("No response from OpenAI","openai");let p={promptTokens:i.usage?.prompt_tokens??0,completionTokens:i.usage?.completion_tokens??0,totalTokens:i.usage?.total_tokens??0};return this.recordUsage(p,e),this.processChoice(n,p)}catch(i){throw this.handleApiError(i),i}}async streamMessage(e,t,c,o){try{let i=await this.client.chat.completions.create(this.buildRequestBody(e,t,c,o,!0),{signal:e.signal}),n="",p="",f=new Map,a$1,s=Date.now(),r=!1,l=i.request_id,b=a(k=>{k.usage&&(a$1=k.usage);let m=k.choices[0]?.delta;if(!m)return "";let M=m.reasoning_content;if(typeof M=="string"&&M.length>0&&(p+=M),m.content&&(r||(r=!0,d.debug("llm.first_byte",{cat:"llm",provider:this.provider,model:this.model,ttft_ms:Date.now()-s})),n+=m.content,e.onChunk?.({type:"text",text:m.content,tokens:a$2(m.content)})),m.tool_calls)for(let u of m.tool_calls){let A=u.index;f.has(A)||(f.set(A,{id:u.id??"",name:u.function?.name??"",args:""}),e.onChunk?.({type:"tool_use_start",toolCall:{id:u.id,toolName:u.function?.name}}));let _=f.get(A);if(u.id&&(_.id=u.id),u.function?.name&&(_.name=u.function.name),u.function?.arguments&&(_.args+=u.function.arguments,_.id))try{let q=JSON.parse(_.args||"{}");e.onChunk?.({type:"tool_use_delta",toolCall:{id:_.id,toolName:_.name,args:q}});}catch{}}return k.choices[0]?.finish_reason&&e.onChunk?.({type:"stop",stopReason:k.choices[0].finish_reason}),m.content??""},"handleChunk");await W(i,{idleTimeoutMs:T.enabled?T.idleTimeoutMs:void 0,requestId:l,onChunk:b});let d$1=[];for(let[,k]of f){let m={};try{m=JSON.parse(k.args||"{}");}catch{}d$1.push({id:k.id,toolName:k.name,args:m});}let I={promptTokens:a$1?.prompt_tokens??0,completionTokens:a$1?.completion_tokens??0,totalTokens:a$1?.total_tokens??0};return this.recordUsage(I,e),{text:n,toolCalls:d$1,usage:I,stopReason:"stop",...p?{reasoningContent:p}:{}}}catch(i){throw this.handleApiError(i),i}}processChoice(e,t){let c=e.message.content??"",o=[];if(e.message.tool_calls)for(let n of e.message.tool_calls){let p={};try{p=JSON.parse(n.function.arguments||"{}");}catch{}o.push({id:n.id,toolName:n.function.name,args:p});}let i=B(e.message);return {text:c,toolCalls:o,usage:t,stopReason:e.finish_reason??void 0,...i?{reasoningContent:i}:{}}}buildMessages(e,t,c){let o=[{role:"system",content:e}],i=this.capability,n=t.some(a=>Array.isArray(a.content)&&a.content.some(s=>s.type==="tool_use"||s.type==="tool_result")),p=c!=="disabled"&&i.echoReasoning==="when-tools"&&n,f=i.echoReasoning==="never";for(let a of t)if(a.role!=="system")if(a.role==="assistant"){let s={role:"assistant"},r;if(typeof a.content=="string")s.content=a.content;else {let l=[],b=[];for(let d of a.content)d.type==="text"&&d.text?l.push(d.text):d.type==="tool_use"&&d.id&&d.name?b.push({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input??{})}}):d.type==="reasoning"&&d.reasoningContent&&(r=d.reasoningContent),!r&&d.reasoningContent&&(r=d.reasoningContent);l.length&&(s.content=l.join(`
2
- `)),b.length&&(s.tool_calls=b);}f?r=void 0:!r&&p&&(r=""),r!==void 0&&(s.reasoning_content=r),o.push(s);}else if(a.role==="tool")o.push({role:"tool",tool_call_id:a.tool_call_id??"",content:typeof a.content=="string"?a.content:""});else if(typeof a.content=="string")o.push({role:"user",content:a.content});else {let s=[],r=[];for(let l of a.content)l.type==="tool_result"&&l.tool_use_id?r.push({tool_use_id:l.tool_use_id,content:typeof l.content=="string"?l.content:""}):l.type==="text"&&l.text&&s.push(l.text);for(let l of r)o.push({role:"tool",tool_call_id:l.tool_use_id,content:l.content});s.length>0&&o.push({role:"user",content:s.join(`
3
- `)});}return o}convertTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}))}handleApiError(e){if(e instanceof N.APIError){if(e.status===429)throw new c("openai");let t=(e.message??"").toLowerCase();throw e.status===400&&t.includes("max_tokens")&&t.includes("max_completion_tokens")&&(this._forceMaxCompletionTokens=true),t.includes("context_length_exceeded")||t.includes("maximum context length")||t.includes("too many tokens")||t.includes("prompt is too long")?new d$1("openai"):e.status===401&&t.includes("provider returned error")?new b(`OpenAI-compatible endpoint returned 401 "Provider returned error". Two likely causes: (1) the API key is invalid/revoked, or (2) the upstream provider rejects tool calls for this model (common on OpenRouter's gpt-4o-mini route). Verify the key, then try a tool-capable model such as openai/gpt-4.1-mini or anthropic/claude-3.5-haiku.`,"openai",{status:e.status}):new b(`OpenAI API error: ${e.message}`,"openai",{status:e.status})}throw e}};function B(h){let e=h.reasoning_content??h.reasoning;return typeof e=="string"&&e.length>0?e:void 0}a(B,"extractReasoningContent");export{W as a,D as b};
@@ -1,18 +0,0 @@
1
- import {h,a}from'./chunk-3QP5BQ3L.js';import {mkdirSync,writeFileSync,existsSync,readdirSync,readFileSync,unlinkSync}from'fs';import {join}from'path';import {homedir}from'os';h();function v(o){if(o)return o;let e=process.env.CODE_SHELL_HOME;return e&&e.length>0?e:join(homedir(),".code-shell")}a(v,"resolveMemoryBaseDir");var p=class{static{a(this,"MemoryManager");}baseDir;memoryDir;indexPath;indexCache=null;constructor(e){let t=typeof e=="string"?{projectDir:e}:e??{};if(this.baseDir=v(t.baseDir),t.projectDir){let r=t.projectDir.replace(/[/\\:]/g,"-").replace(/^-/,"");this.memoryDir=join(this.baseDir,"projects",r,"memory");}else this.memoryDir=join(this.baseDir,"memory");this.indexPath=join(this.memoryDir,"MEMORY.md"),mkdirSync(this.memoryDir,{recursive:true});}getMemoryDir(){return this.memoryDir}save(e){let t=this.slugify(e.name)+".md",r=join(this.memoryDir,t),n=`---
2
- name: ${e.name}
3
- description: ${e.description}
4
- type: ${e.type}
5
- ---
6
-
7
- ${e.content}
8
- `;writeFileSync(r,n,"utf-8");let i=this.ensureIndexCache();return i.set(t,{name:e.name,description:e.description}),this.writeIndex(i),t}loadAll(){if(!existsSync(this.memoryDir))return [];let e=readdirSync(this.memoryDir).filter(r=>r.endsWith(".md")&&r!=="MEMORY.md"),t=[];for(let r of e){let n=this.loadFile(r);n&&t.push(n);}return t}loadFile(e){let t=join(this.memoryDir,e);if(!existsSync(t))return null;try{let n=readFileSync(t,"utf-8").match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!n)return null;let i=n[1],d=n[2].trim(),y=i.match(/name:\s*(.+)/)?.[1]?.trim()??e,f=i.match(/description:\s*(.+)/)?.[1]?.trim()??"",u=i.match(/type:\s*(.+)/)?.[1]?.trim()??"project";return {name:y,description:f,type:u,content:d,fileName:e}}catch{return null}}delete(e){let r=this.loadAll().find(n=>n.name===e||n.fileName===e);if(!r)return false;try{unlinkSync(join(this.memoryDir,r.fileName));let n=this.ensureIndexCache();return n.delete(r.fileName),this.writeIndex(n),!0}catch{return false}}getIndex(){return existsSync(this.indexPath)?readFileSync(this.indexPath,"utf-8"):""}buildMemoryContext(){let e=this.loadAll();return e.length===0?"":`# Persistent Memory
9
-
10
- The following memories from previous sessions may be relevant:
11
-
12
- `+e.map(r=>`- [${r.type}] ${r.name}: ${r.description}`).join(`
13
- `)+`
14
-
15
- To read a specific memory, check ${this.memoryDir}/`}ensureIndexCache(){if(this.indexCache!==null)return this.indexCache;let e=new Map;for(let t of this.loadAll())e.set(t.fileName,{name:t.name,description:t.description});return this.indexCache=e,e}writeIndex(e){let t=[];for(let[n,i]of e)t.push(`- [${i.name}](${n}) \u2014 ${i.description}`);let r=t.length>0?t.join(`
16
- `)+`
17
- `:`(no memories stored)
18
- `;writeFileSync(this.indexPath,r,"utf-8");}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,60)}};export{v as a,p as b};
@@ -1,3 +0,0 @@
1
- import {h,a,f,g,b as b$1}from'./chunk-3QP5BQ3L.js';import {execFile,spawn}from'child_process';import {readFileSync,constants}from'fs';import {access,stat,unlink,writeFile,mkdir,readFile}from'fs/promises';import {createRequire}from'module';import {homedir}from'os';import {dirname,resolve,join}from'path';import {fileURLToPath}from'url';import {promisify}from'util';import {gt}from'semver';h();h();function E(t,e){return gt(t,e)}a(E,"gt");var T=promisify(execFile),w="@cjhyy/code-shell",H=".update.lock",P=300*1e3,B=5e3,u,b=false,x=null;function kt(t=w){X(t);}a(kt,"checkForUpdate");function Et(){return u}a(Et,"getUpdateAvailable");function vt(){return x}a(vt,"getAutoUpdateDisabledReason");function St(){if(b)return;b=true;let t=a(()=>{let e=u;if(!(!e||!e.canAutoInstall))try{et(e.latestVersion);}catch{}},"fire");process.once("exit",t);}a(St,"scheduleAutoInstallOnExit");var y;function J(){if(y)return y;let t=W();return y=t,t}a(J,"getCurrentVersion");function W(){try{let e=typeof import.meta<"u"&&import.meta.url?dirname(fileURLToPath(import.meta.url)):f;for(let r=0;r<6;r++){try{let i=JSON.parse(readFileSync(resolve(e,"package.json"),"utf-8"));if(i&&typeof i.version=="string")return i.version}catch{}let o=dirname(e);if(o===e)break;e=o;}}catch{}try{let e=createRequire(import.meta.url??g)("../../package.json");if(e?.version)return e.version}catch{}return "0.0.0"}a(W,"resolveVersion");async function X(t){let e=nt();if(e){x=e;return}x=null;try{let r=J(),o=await z(t);if(!o)return;let i=!1;try{i=E(o,r);}catch{i=o!==r;}if(!i){u=void 0;return}let{hasPermissions:s,npmPrefix:a}=await Q();u={latestVersion:o,canAutoInstall:s,npmPrefix:a};}catch{}}a(X,"runCheck");async function z(t){try{let{stdout:e}=await T("npm",["view",`${t}@latest`,"version","--prefer-online"],{cwd:homedir(),timeout:B}),r=e.trim();return r.length>0?r:null}catch{return null}}a(z,"getLatestVersion");async function Q(){let t=null;try{let{stdout:e}=await T("npm",["-g","config","get","prefix"],{cwd:homedir(),timeout:5e3});t=e.trim();}catch{return {hasPermissions:false,npmPrefix:null}}if(!t)return {hasPermissions:false,npmPrefix:null};try{return await access(t,constants.W_OK),{hasPermissions:!0,npmPrefix:t}}catch{return {hasPermissions:false,npmPrefix:t}}}a(Q,"checkGlobalInstallPermissions");function D(){return process.env.HOME??homedir()}a(D,"userHome");function d(){return join(D(),".code-shell")}a(d,"configDir");function p(){return join(d(),H)}a(p,"getLockFilePath");function Y(){return join(d(),"update.log")}a(Y,"getUpdateLogPath");async function Z(){let t=p();try{let e=await stat(t);if(Date.now()-e.mtimeMs<P)return !1;try{let r=await stat(t);if(Date.now()-r.mtimeMs<P)return !1;await unlink(t);}catch(r){if(!U(r))return !1}}catch(e){if(!U(e))return false}try{return await writeFile(t,String(process.pid),{encoding:"utf8",flag:"wx"}),!0}catch(e){let r=k(e);if(r==="EEXIST")return false;if(r==="ENOENT")try{return await mkdir(d(),{recursive:!0}),await writeFile(t,String(process.pid),{encoding:"utf8",flag:"wx"}),!0}catch{return false}return false}}a(Z,"acquireLock");async function tt(){let t=p();try{await readFile(t,"utf8")===String(process.pid)&&await unlink(t);}catch{}}a(tt,"releaseLock");function et(t){let e=p();try{try{let s=b$1("fs");s.mkdirSync(d(),{recursive:!0}),s.writeFileSync(e,String(process.pid),{encoding:"utf8",flag:"wx"});}catch(s){if(k(s)==="EEXIST")try{let a=b$1("fs"),F=a.statSync(e);if(Date.now()-F.mtimeMs<P)return;a.unlinkSync(e),a.writeFileSync(e,String(process.pid),{encoding:"utf8",flag:"wx"});}catch{return}else return}}catch{return}let r=b$1("fs"),o=r.openSync(Y(),"a");try{r.writeSync(o,`
2
- [${new Date().toISOString()}] code-shell auto-update: installing ${w}@${t} (pid=${process.pid})
3
- `);}catch{}let i=[`npm install -g ${w}@${_(t)}`,`; rm -f ${_(e)}`].join(" ");try{spawn("sh",["-c",i],{detached:!0,stdio:["ignore",o,o],cwd:homedir()}).unref();}catch{try{r.unlinkSync(e);}catch{}}}a(et,"launchDetachedInstall");function nt(){return process.env.NODE_ENV==="development"?"development build":ot(process.env.DISABLE_AUTOUPDATER)?"DISABLE_AUTOUPDATER set":rt()===false?"settings.autoUpdates = false":null}a(nt,"isAutoUpdaterDisabled");function rt(){let t=join(D(),".code-shell","settings.json");try{let e=readFileSync(t,"utf8"),r=JSON.parse(e);if(typeof r.autoUpdates=="boolean")return r.autoUpdates}catch{}}a(rt,"readAutoUpdatesFlagFromDisk");function ot(t){if(!t)return false;let e=t.toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}a(ot,"isEnvTruthy");function k(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}a(k,"errnoCode");function U(t){return k(t)==="ENOENT"}a(U,"isENOENT");function _(t){return `'${t.replace(/'/g,"'\\''")}'`}a(_,"shellEscape");var It={acquireLock:Z,releaseLock:tt,getLockFilePath:p};export{kt as a,Et as b,vt as c,St as d,J as e,It as f};
@@ -1 +0,0 @@
1
- import {h,a}from'./chunk-3QP5BQ3L.js';import {mkdirSync,existsSync,readFileSync,copyFileSync,writeFileSync}from'fs';import {join,resolve}from'path';import {createHash}from'crypto';h();var g=class S{static{a(this,"FileHistory");}historyDir;snapshots=[];constructor(t){this.historyDir=join(t,"file-history"),mkdirSync(this.historyDir,{recursive:true});}saveSnapshot(t){let s=resolve(t);if(!existsSync(s))return null;try{let e=readFileSync(s),i=createHash("md5").update(e).digest("hex"),a=this.snapshots.find(l=>l.filePath===s&&l.hash===i);if(a)return a;let h=Date.now(),d=s.replace(/[/\\:]/g,"_").slice(-100),o=join(this.historyDir,`${h}_${d}`);copyFileSync(s,o);let c={filePath:s,timestamp:h,backupPath:o,hash:i,size:e.length};return this.snapshots.push(c),this.saveIndex(),c}catch{return null}}getSnapshots(t){let s=resolve(t);return this.snapshots.filter(e=>e.filePath===s).sort((e,i)=>i.timestamp-e.timestamp)}restore(t){try{return existsSync(t.backupPath)?(this.saveSnapshot(t.filePath),copyFileSync(t.backupPath,t.filePath),!0):!1}catch{return false}}restoreLatest(t){let s=this.getSnapshots(t);return s.length===0?false:this.restore(s[0])}getTrackedFiles(){return [...new Set(this.snapshots.map(t=>t.filePath))]}saveIndex(){try{let t=join(this.historyDir,"index.json");writeFileSync(t,JSON.stringify(this.snapshots,null,2),"utf-8");}catch{}}static loadFromDir(t){let s=new S(t),e=join(s.historyDir,"index.json");if(existsSync(e))try{s.snapshots=JSON.parse(readFileSync(e,"utf-8"));}catch{}return s}};export{g as a};