@cjhyy/code-shell 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (441) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/LICENSE +21 -0
  3. package/README.md +177 -0
  4. package/dist/agent/coordinator.d.ts +49 -0
  5. package/dist/anthropic-NENYS535.js +9 -0
  6. package/dist/anthropic-XMTTVNSH.cjs +9 -0
  7. package/dist/arena/arena.d.ts +43 -0
  8. package/dist/arena/context/context-tools.d.ts +16 -0
  9. package/dist/arena/detect-mode.d.ts +20 -0
  10. package/dist/arena/digest-builder.d.ts +25 -0
  11. package/dist/arena/index.cjs +103 -0
  12. package/dist/arena/index.d.ts +29 -0
  13. package/dist/arena/index.js +103 -0
  14. package/dist/arena/iterate/convergence.d.ts +25 -0
  15. package/dist/arena/iterate/formats/index.d.ts +22 -0
  16. package/dist/arena/iterate/index.d.ts +11 -0
  17. package/dist/arena/iterate/iterative-arena.d.ts +23 -0
  18. package/dist/arena/iterate/parse.d.ts +42 -0
  19. package/dist/arena/iterate/phases/argue.d.ts +22 -0
  20. package/dist/arena/iterate/phases/revise.d.ts +16 -0
  21. package/dist/arena/iterate/phases/tournament.d.ts +34 -0
  22. package/dist/arena/iterate/tools/web-tools.d.ts +13 -0
  23. package/dist/arena/iterate/types.d.ts +152 -0
  24. package/dist/arena/ledger.d.ts +47 -0
  25. package/dist/arena/lenses/architecture.d.ts +5 -0
  26. package/dist/arena/lenses/engineering.d.ts +5 -0
  27. package/dist/arena/lenses/general.d.ts +5 -0
  28. package/dist/arena/lenses/index.d.ts +16 -0
  29. package/dist/arena/lenses/product.d.ts +5 -0
  30. package/dist/arena/model-presets.d.ts +14 -0
  31. package/dist/arena/phases/adjudication.d.ts +24 -0
  32. package/dist/arena/phases/build-consensus.d.ts +29 -0
  33. package/dist/arena/phases/claim-registry.d.ts +26 -0
  34. package/dist/arena/phases/cross-review.d.ts +45 -0
  35. package/dist/arena/phases/debate-rounds.d.ts +27 -0
  36. package/dist/arena/phases/participant-research.d.ts +38 -0
  37. package/dist/arena/phases/planning-detail-expansion.d.ts +38 -0
  38. package/dist/arena/planner.d.ts +27 -0
  39. package/dist/arena/providers/docs.d.ts +6 -0
  40. package/dist/arena/providers/git.d.ts +8 -0
  41. package/dist/arena/providers/index.d.ts +16 -0
  42. package/dist/arena/providers/none.d.ts +7 -0
  43. package/dist/arena/providers/repo.d.ts +6 -0
  44. package/dist/arena/render/session.d.ts +17 -0
  45. package/dist/arena/render/terminal.d.ts +33 -0
  46. package/dist/arena/strategies/discussion.d.ts +25 -0
  47. package/dist/arena/strategies/index.d.ts +15 -0
  48. package/dist/arena/strategies/language-wrapper.d.ts +17 -0
  49. package/dist/arena/strategies/lens-wrapper.d.ts +16 -0
  50. package/dist/arena/strategies/planning.d.ts +30 -0
  51. package/dist/arena/strategies/review.d.ts +26 -0
  52. package/dist/arena/strategies/utils.d.ts +34 -0
  53. package/dist/arena/tools/selector.d.ts +17 -0
  54. package/dist/arena/transitions.d.ts +48 -0
  55. package/dist/arena/types.d.ts +499 -0
  56. package/dist/arena-46QQ6BZQ.js +261 -0
  57. package/dist/arena-HZZZ2GJH.cjs +261 -0
  58. package/dist/bootstrap/setup.d.ts +14 -0
  59. package/dist/bootstrap/state.d.ts +160 -0
  60. package/dist/bridge-4ZRXVWBN.js +98 -0
  61. package/dist/bridge-W476QDFH.cjs +98 -0
  62. package/dist/chunk-3EAEC566.cjs +136 -0
  63. package/dist/chunk-3EUDE77E.cjs +1252 -0
  64. package/dist/chunk-3QR52LL5.cjs +105 -0
  65. package/dist/chunk-4PKZPFCD.js +136 -0
  66. package/dist/chunk-4RRUP4MM.js +86 -0
  67. package/dist/chunk-4SFPFHMG.js +132 -0
  68. package/dist/chunk-5LHVI777.cjs +246 -0
  69. package/dist/chunk-6JOOLG6F.js +104 -0
  70. package/dist/chunk-6ZIROYXX.js +207 -0
  71. package/dist/chunk-7RMAR2Y3.js +6511 -0
  72. package/dist/chunk-BE6IPRDM.js +224 -0
  73. package/dist/chunk-BHGIJ2DJ.js +41 -0
  74. package/dist/chunk-BMH65OVB.cjs +224 -0
  75. package/dist/chunk-C7JBCO5V.js +80 -0
  76. package/dist/chunk-CSO5EOEP.cjs +132 -0
  77. package/dist/chunk-DI7RDLOS.js +47 -0
  78. package/dist/chunk-DICG4AB7.cjs +73 -0
  79. package/dist/chunk-EL2RL5DG.cjs +101 -0
  80. package/dist/chunk-FGZGCFJX.cjs +207 -0
  81. package/dist/chunk-FUOKLKR2.js +101 -0
  82. package/dist/chunk-FVP7XJGS.cjs +4577 -0
  83. package/dist/chunk-HD7MT5XU.cjs +86 -0
  84. package/dist/chunk-IJSHQGMP.cjs +45 -0
  85. package/dist/chunk-IMMTBZ33.cjs +63 -0
  86. package/dist/chunk-J5XW6UYL.js +291 -0
  87. package/dist/chunk-JT2WSQSR.cjs +335 -0
  88. package/dist/chunk-KO2FPF7G.js +93 -0
  89. package/dist/chunk-LRAY5IYC.cjs +291 -0
  90. package/dist/chunk-NG73UR3L.cjs +285 -0
  91. package/dist/chunk-NZ4DQ72D.cjs +664 -0
  92. package/dist/chunk-O6F2EF2Z.js +73 -0
  93. package/dist/chunk-OG4MIQJ6.js +335 -0
  94. package/dist/chunk-QHDYFC5U.cjs +6511 -0
  95. package/dist/chunk-R32DJSJE.cjs +41 -0
  96. package/dist/chunk-S74VVJBF.js +285 -0
  97. package/dist/chunk-SK62UVS6.js +105 -0
  98. package/dist/chunk-SQZHPD3S.js +4577 -0
  99. package/dist/chunk-UK2SU23S.cjs +93 -0
  100. package/dist/chunk-VKGNCYRL.js +258 -0
  101. package/dist/chunk-WFQF3RT4.cjs +104 -0
  102. package/dist/chunk-WHRTARDJ.cjs +258 -0
  103. package/dist/chunk-WRZJUQ5Z.js +664 -0
  104. package/dist/chunk-X4HAERTQ.js +63 -0
  105. package/dist/chunk-XHC2JMEC.cjs +80 -0
  106. package/dist/chunk-YZ25SSWJ.js +222 -0
  107. package/dist/chunk-ZJV3YSY3.cjs +222 -0
  108. package/dist/chunk-ZRSSGYA5.js +246 -0
  109. package/dist/chunk-ZXYDDJEJ.js +1252 -0
  110. package/dist/cli/commands/arena.d.ts +29 -0
  111. package/dist/cli/commands/builtin/advanced-commands.d.ts +5 -0
  112. package/dist/cli/commands/builtin/core-commands.d.ts +5 -0
  113. package/dist/cli/commands/builtin/extra-commands.d.ts +6 -0
  114. package/dist/cli/commands/builtin/git-commands.d.ts +5 -0
  115. package/dist/cli/commands/builtin/more-commands.d.ts +7 -0
  116. package/dist/cli/commands/builtin/permissions-command.d.ts +5 -0
  117. package/dist/cli/commands/builtin/utility-commands.d.ts +5 -0
  118. package/dist/cli/commands/registry.d.ts +64 -0
  119. package/dist/cli/commands/repl.d.ts +21 -0
  120. package/dist/cli/commands/run.d.ts +21 -0
  121. package/dist/cli/commands/runs.d.ts +14 -0
  122. package/dist/cli/cost-tracker.d.ts +57 -0
  123. package/dist/cli/exit.d.ts +12 -0
  124. package/dist/cli/input/ndjson-reader.d.ts +31 -0
  125. package/dist/cli/input-compiler.d.ts +5 -0
  126. package/dist/cli/main.cjs +19674 -0
  127. package/dist/cli/main.d.ts +5 -0
  128. package/dist/cli/main.js +19674 -0
  129. package/dist/cli/onboarding.d.ts +26 -0
  130. package/dist/cli/output/renderer.d.ts +28 -0
  131. package/dist/cli/output/terminal-ui.d.ts +50 -0
  132. package/dist/cli/updater.d.ts +10 -0
  133. package/dist/compaction-44I55TLI.cjs +32 -0
  134. package/dist/compaction-CCHWA4G6.js +32 -0
  135. package/dist/context/compaction.d.ts +83 -0
  136. package/dist/context/manager.d.ts +99 -0
  137. package/dist/context/token-counter.d.ts +27 -0
  138. package/dist/coordinator-5HY7ALO2.js +7 -0
  139. package/dist/coordinator-INDLPVMF.cjs +7 -0
  140. package/dist/cost-tracker-IWYAUPXH.js +9 -0
  141. package/dist/cost-tracker-JXTJQQWE.cjs +9 -0
  142. package/dist/cron/scheduler.d.ts +34 -0
  143. package/dist/devtools-KIY3LWQJ.js +6 -0
  144. package/dist/devtools-LRP47DDV.cjs +6 -0
  145. package/dist/engine/cost-store.d.ts +22 -0
  146. package/dist/engine/engine.d.ts +101 -0
  147. package/dist/engine/model-facade.d.ts +24 -0
  148. package/dist/engine/query.d.ts +50 -0
  149. package/dist/engine/streaming-tool-queue.d.ts +34 -0
  150. package/dist/engine/token-budget.d.ts +22 -0
  151. package/dist/engine/tool-summary.d.ts +13 -0
  152. package/dist/engine/turn-loop.d.ts +62 -0
  153. package/dist/engine/turn-state.d.ts +14 -0
  154. package/dist/exceptions.d.ts +44 -0
  155. package/dist/file-history-HZWO2WQ5.js +7 -0
  156. package/dist/file-history-UQQILIY7.cjs +7 -0
  157. package/dist/git/utils.d.ts +35 -0
  158. package/dist/git/worktree.d.ts +36 -0
  159. package/dist/hooks/events.d.ts +35 -0
  160. package/dist/hooks/registry.d.ts +15 -0
  161. package/dist/index.cjs +336 -0
  162. package/dist/index.d.ts +64 -0
  163. package/dist/index.js +336 -0
  164. package/dist/ink/Ansi.d.ts +10 -0
  165. package/dist/ink/bidi.d.ts +15 -0
  166. package/dist/ink/clearTerminal.d.ts +13 -0
  167. package/dist/ink/colorize.d.ts +16 -0
  168. package/dist/ink/components/AlternateScreen.d.ts +21 -0
  169. package/dist/ink/components/App.d.ts +70 -0
  170. package/dist/ink/components/AppContext.d.ts +11 -0
  171. package/dist/ink/components/Box.d.ts +49 -0
  172. package/dist/ink/components/Button.d.ts +36 -0
  173. package/dist/ink/components/ClockContext.d.ts +9 -0
  174. package/dist/ink/components/CursorDeclarationContext.d.ts +22 -0
  175. package/dist/ink/components/ErrorOverview.d.ts +5 -0
  176. package/dist/ink/components/Link.d.ts +7 -0
  177. package/dist/ink/components/Newline.d.ts +12 -0
  178. package/dist/ink/components/NoSelect.d.ts +19 -0
  179. package/dist/ink/components/RawAnsi.d.ts +16 -0
  180. package/dist/ink/components/ScrollBox.d.ts +78 -0
  181. package/dist/ink/components/Spacer.d.ts +5 -0
  182. package/dist/ink/components/StdinContext.d.ts +27 -0
  183. package/dist/ink/components/TerminalFocusContext.d.ts +10 -0
  184. package/dist/ink/components/TerminalSizeContext.d.ts +5 -0
  185. package/dist/ink/components/Text.d.ts +55 -0
  186. package/dist/ink/constants.d.ts +1 -0
  187. package/dist/ink/cursor.d.ts +8 -0
  188. package/dist/ink/devtools.d.ts +5 -0
  189. package/dist/ink/dom.d.ts +76 -0
  190. package/dist/ink/events/click-event.d.ts +31 -0
  191. package/dist/ink/events/dispatcher.d.ts +40 -0
  192. package/dist/ink/events/emitter.d.ts +5 -0
  193. package/dist/ink/events/event-handlers.d.ts +46 -0
  194. package/dist/ink/events/event.d.ts +5 -0
  195. package/dist/ink/events/focus-event.d.ts +13 -0
  196. package/dist/ink/events/input-event.d.ts +30 -0
  197. package/dist/ink/events/keyboard-event.d.ts +19 -0
  198. package/dist/ink/events/paste-event.d.ts +8 -0
  199. package/dist/ink/events/resize-event.d.ts +9 -0
  200. package/dist/ink/events/terminal-event.d.ts +54 -0
  201. package/dist/ink/events/terminal-focus-event.d.ts +13 -0
  202. package/dist/ink/focus.d.ts +43 -0
  203. package/dist/ink/frame.d.ts +94 -0
  204. package/dist/ink/get-max-width.d.ts +17 -0
  205. package/dist/ink/hit-test.d.ts +33 -0
  206. package/dist/ink/hooks/use-animation-frame.d.ts +26 -0
  207. package/dist/ink/hooks/use-app.d.ts +5 -0
  208. package/dist/ink/hooks/use-declared-cursor.d.ts +26 -0
  209. package/dist/ink/hooks/use-input.d.ts +37 -0
  210. package/dist/ink/hooks/use-interval.d.ts +18 -0
  211. package/dist/ink/hooks/use-search-highlight.d.ts +30 -0
  212. package/dist/ink/hooks/use-selection.d.ts +39 -0
  213. package/dist/ink/hooks/use-stdin.d.ts +5 -0
  214. package/dist/ink/hooks/use-tab-status.d.ts +13 -0
  215. package/dist/ink/hooks/use-terminal-focus.d.ts +10 -0
  216. package/dist/ink/hooks/use-terminal-title.d.ts +12 -0
  217. package/dist/ink/hooks/use-terminal-viewport.d.ts +29 -0
  218. package/dist/ink/index.d.ts +20 -0
  219. package/dist/ink/ink.d.ts +369 -0
  220. package/dist/ink/instances.d.ts +3 -0
  221. package/dist/ink/layout/engine.d.ts +2 -0
  222. package/dist/ink/layout/geometry.d.ts +30 -0
  223. package/dist/ink/layout/node.d.ts +125 -0
  224. package/dist/ink/layout/yoga.d.ts +56 -0
  225. package/dist/ink/line-width-cache.d.ts +1 -0
  226. package/dist/ink/log-update.d.ts +17 -0
  227. package/dist/ink/measure-element.d.ts +16 -0
  228. package/dist/ink/measure-text.d.ts +6 -0
  229. package/dist/ink/node-cache.d.ts +20 -0
  230. package/dist/ink/optimizer.d.ts +15 -0
  231. package/dist/ink/output.d.ts +119 -0
  232. package/dist/ink/parse-keypress.d.ts +111 -0
  233. package/dist/ink/reconciler.d.ts +11 -0
  234. package/dist/ink/render-border.d.ts +24 -0
  235. package/dist/ink/render-node-to-output.d.ts +45 -0
  236. package/dist/ink/render-to-screen.d.ts +46 -0
  237. package/dist/ink/renderer.d.ts +14 -0
  238. package/dist/ink/root.d.ts +74 -0
  239. package/dist/ink/screen.d.ts +269 -0
  240. package/dist/ink/searchHighlight.d.ts +20 -0
  241. package/dist/ink/selection.d.ts +229 -0
  242. package/dist/ink/squash-text-nodes.d.ts +22 -0
  243. package/dist/ink/stringWidth.d.ts +1 -0
  244. package/dist/ink/styles.d.ts +306 -0
  245. package/dist/ink/supports-hyperlinks.d.ts +13 -0
  246. package/dist/ink/tabstops.d.ts +1 -0
  247. package/dist/ink/terminal-focus-state.d.ts +6 -0
  248. package/dist/ink/terminal-querier.d.ts +129 -0
  249. package/dist/ink/terminal.d.ts +46 -0
  250. package/dist/ink/termio/ansi.d.ts +65 -0
  251. package/dist/ink/termio/csi.d.ts +165 -0
  252. package/dist/ink/termio/dec.d.ts +37 -0
  253. package/dist/ink/termio/esc.d.ts +12 -0
  254. package/dist/ink/termio/osc.d.ts +173 -0
  255. package/dist/ink/termio/parser.d.ts +35 -0
  256. package/dist/ink/termio/sgr.d.ts +8 -0
  257. package/dist/ink/termio/tokenize.d.ts +45 -0
  258. package/dist/ink/termio/types.d.ts +190 -0
  259. package/dist/ink/termio.d.ts +24 -0
  260. package/dist/ink/useTerminalNotification.d.ts +28 -0
  261. package/dist/ink/warn.d.ts +1 -0
  262. package/dist/ink/widest-line.d.ts +1 -0
  263. package/dist/ink/wrap-text.d.ts +2 -0
  264. package/dist/ink/wrapAnsi.d.ts +7 -0
  265. package/dist/llm/client-base.d.ts +22 -0
  266. package/dist/llm/client-factory.d.ts +10 -0
  267. package/dist/llm/model-pool.d.ts +60 -0
  268. package/dist/llm/providers/anthropic.d.ts +19 -0
  269. package/dist/llm/providers/openai.d.ts +19 -0
  270. package/dist/llm/types.d.ts +21 -0
  271. package/dist/loader-DXFSUB4R.cjs +91 -0
  272. package/dist/loader-J5UID6CV.js +91 -0
  273. package/dist/logging/logger.d.ts +19 -0
  274. package/dist/lsp/client.d.ts +41 -0
  275. package/dist/lsp/manager.d.ts +40 -0
  276. package/dist/lsp/servers.d.ts +16 -0
  277. package/dist/manager-ETWDOCHN.cjs +9 -0
  278. package/dist/manager-HGMQNEJB.cjs +11 -0
  279. package/dist/manager-HUAQOORS.js +9 -0
  280. package/dist/manager-VJIZ2CQC.js +11 -0
  281. package/dist/mcp-manager-G4G2QASE.cjs +8 -0
  282. package/dist/mcp-manager-OKXHHWYR.js +8 -0
  283. package/dist/memory-AP747G5H.js +7 -0
  284. package/dist/memory-BH3BYUN5.cjs +7 -0
  285. package/dist/native-ts/yoga-layout/enums.d.ts +117 -0
  286. package/dist/native-ts/yoga-layout/index.d.ts +270 -0
  287. package/dist/onboarding-6WEPV7C2.js +11 -0
  288. package/dist/onboarding-QM5DY2TU.cjs +11 -0
  289. package/dist/openai-5HQGBL4L.js +9 -0
  290. package/dist/openai-656VWUQW.cjs +9 -0
  291. package/dist/plugins/loader.d.ts +72 -0
  292. package/dist/plugins/types.d.ts +4 -0
  293. package/dist/preset/index.d.ts +60 -0
  294. package/dist/product/define.d.ts +60 -0
  295. package/dist/product/index.cjs +23 -0
  296. package/dist/product/index.d.ts +5 -0
  297. package/dist/product/index.js +23 -0
  298. package/dist/product/types.d.ts +116 -0
  299. package/dist/prompt/composer.d.ts +42 -0
  300. package/dist/prompt/instruction-scanner.d.ts +54 -0
  301. package/dist/prompt/section-cache.d.ts +15 -0
  302. package/dist/prompt/section-loader.d.ts +26 -0
  303. package/dist/protocol/client.d.ts +64 -0
  304. package/dist/protocol/index.d.ts +4 -0
  305. package/dist/protocol/server.d.ts +49 -0
  306. package/dist/protocol/transport.d.ts +36 -0
  307. package/dist/protocol/types.d.ts +150 -0
  308. package/dist/react-compiler-runtime-shim.d.ts +1 -0
  309. package/dist/remote/bridge.d.ts +37 -0
  310. package/dist/run/ArtifactTracker.d.ts +38 -0
  311. package/dist/run/CheckpointWriter.d.ts +53 -0
  312. package/dist/run/EngineRunner.d.ts +70 -0
  313. package/dist/run/Evaluator.d.ts +56 -0
  314. package/dist/run/FileRunStore.d.ts +39 -0
  315. package/dist/run/Heartbeat.d.ts +54 -0
  316. package/dist/run/RunApprovalBackend.d.ts +53 -0
  317. package/dist/run/RunLock.d.ts +40 -0
  318. package/dist/run/RunManager.d.ts +76 -0
  319. package/dist/run/RunQueue.d.ts +27 -0
  320. package/dist/run/RunStore.d.ts +25 -0
  321. package/dist/run/factory.d.ts +57 -0
  322. package/dist/run/index.cjs +50 -0
  323. package/dist/run/index.d.ts +17 -0
  324. package/dist/run/index.js +50 -0
  325. package/dist/run/types.d.ts +136 -0
  326. package/dist/services/analytics.d.ts +29 -0
  327. package/dist/services/auto-dream.d.ts +35 -0
  328. package/dist/services/compact.d.ts +56 -0
  329. package/dist/services/diagnostics.d.ts +41 -0
  330. package/dist/services/extract-memories.d.ts +27 -0
  331. package/dist/services/index.d.ts +11 -0
  332. package/dist/services/notifier.d.ts +25 -0
  333. package/dist/services/oauth.d.ts +27 -0
  334. package/dist/services/session-memory.d.ts +37 -0
  335. package/dist/session/file-history.d.ts +41 -0
  336. package/dist/session/memory.d.ts +45 -0
  337. package/dist/session/session-manager.d.ts +23 -0
  338. package/dist/session/transcript.d.ts +39 -0
  339. package/dist/session-manager-JIIBCFTC.js +8 -0
  340. package/dist/session-manager-UQKB564H.cjs +8 -0
  341. package/dist/settings/manager.d.ts +27 -0
  342. package/dist/settings/schema.d.ts +676 -0
  343. package/dist/skills/index.d.ts +7 -0
  344. package/dist/skills/matcher.d.ts +21 -0
  345. package/dist/skills/scanner.d.ts +30 -0
  346. package/dist/skills-63RBYQRX.js +13 -0
  347. package/dist/skills-V3BPLW3D.cjs +13 -0
  348. package/dist/token-counter-CHAXW5O7.cjs +13 -0
  349. package/dist/token-counter-DSOZGZ5Q.js +13 -0
  350. package/dist/tool-summary-5P2GKRA4.cjs +31 -0
  351. package/dist/tool-summary-J2ICNMWP.js +31 -0
  352. package/dist/tool-system/builtin/agent.d.ts +35 -0
  353. package/dist/tool-system/builtin/arena.d.ts +18 -0
  354. package/dist/tool-system/builtin/ask-user.d.ts +12 -0
  355. package/dist/tool-system/builtin/bash.d.ts +6 -0
  356. package/dist/tool-system/builtin/brief.d.ts +6 -0
  357. package/dist/tool-system/builtin/config.d.ts +6 -0
  358. package/dist/tool-system/builtin/cron.d.ts +10 -0
  359. package/dist/tool-system/builtin/edit.d.ts +6 -0
  360. package/dist/tool-system/builtin/file-cache.d.ts +11 -0
  361. package/dist/tool-system/builtin/glob.d.ts +6 -0
  362. package/dist/tool-system/builtin/grep.d.ts +6 -0
  363. package/dist/tool-system/builtin/index.d.ts +10 -0
  364. package/dist/tool-system/builtin/lsp.d.ts +6 -0
  365. package/dist/tool-system/builtin/mcp-tools.d.ts +10 -0
  366. package/dist/tool-system/builtin/notebook-edit.d.ts +6 -0
  367. package/dist/tool-system/builtin/plan.d.ts +18 -0
  368. package/dist/tool-system/builtin/powershell.d.ts +6 -0
  369. package/dist/tool-system/builtin/read.d.ts +6 -0
  370. package/dist/tool-system/builtin/remote-trigger.d.ts +6 -0
  371. package/dist/tool-system/builtin/repl.d.ts +6 -0
  372. package/dist/tool-system/builtin/send-message.d.ts +6 -0
  373. package/dist/tool-system/builtin/skill.d.ts +6 -0
  374. package/dist/tool-system/builtin/sleep.d.ts +6 -0
  375. package/dist/tool-system/builtin/task.d.ts +51 -0
  376. package/dist/tool-system/builtin/tool-search.d.ts +12 -0
  377. package/dist/tool-system/builtin/web-fetch.d.ts +6 -0
  378. package/dist/tool-system/builtin/web-search.d.ts +6 -0
  379. package/dist/tool-system/builtin/worktree.d.ts +10 -0
  380. package/dist/tool-system/builtin/write.d.ts +6 -0
  381. package/dist/tool-system/executor.d.ts +25 -0
  382. package/dist/tool-system/mcp-manager.d.ts +50 -0
  383. package/dist/tool-system/permission.d.ts +69 -0
  384. package/dist/tool-system/registry.d.ts +24 -0
  385. package/dist/tool-system/validation.d.ts +5 -0
  386. package/dist/types.d.ts +260 -0
  387. package/dist/ui/App.d.ts +14 -0
  388. package/dist/ui/components/AgentBlock.d.ts +32 -0
  389. package/dist/ui/components/BabyHand.d.ts +1 -0
  390. package/dist/ui/components/Banner.d.ts +8 -0
  391. package/dist/ui/components/CodeBlock.d.ts +7 -0
  392. package/dist/ui/components/CommandInput.d.ts +13 -0
  393. package/dist/ui/components/ContextUsageBar.d.ts +7 -0
  394. package/dist/ui/components/DiffView.d.ts +6 -0
  395. package/dist/ui/components/DogLogo.d.ts +1 -0
  396. package/dist/ui/components/FullscreenLayout.d.ts +51 -0
  397. package/dist/ui/components/KunHead.d.ts +1 -0
  398. package/dist/ui/components/KunLogo.d.ts +1 -0
  399. package/dist/ui/components/MessageContent.d.ts +22 -0
  400. package/dist/ui/components/PermissionDialog.d.ts +8 -0
  401. package/dist/ui/components/PermissionPrompt.d.ts +8 -0
  402. package/dist/ui/components/ScrollView.d.ts +34 -0
  403. package/dist/ui/components/Spinner.d.ts +8 -0
  404. package/dist/ui/components/SpinnerWithVerb.d.ts +13 -0
  405. package/dist/ui/components/StatusLine.d.ts +22 -0
  406. package/dist/ui/components/StructuredDiff.d.ts +8 -0
  407. package/dist/ui/components/TaskList.d.ts +6 -0
  408. package/dist/ui/components/TextInput.d.ts +9 -0
  409. package/dist/ui/components/ThemedBox.d.ts +19 -0
  410. package/dist/ui/components/ThemedText.d.ts +26 -0
  411. package/dist/ui/components/ToolCall.d.ts +21 -0
  412. package/dist/ui/components/VirtualMessageList.d.ts +24 -0
  413. package/dist/ui/hooks/useCostSummary.d.ts +1 -0
  414. package/dist/ui/index.d.ts +12 -0
  415. package/dist/ui/input-history.d.ts +61 -0
  416. package/dist/ui/store.d.ts +82 -0
  417. package/dist/ui/terminal-renderer.d.ts +45 -0
  418. package/dist/ui/theme.d.ts +36 -0
  419. package/dist/ui/vim-mode.d.ts +25 -0
  420. package/dist/updater-AVD4LKTQ.js +183 -0
  421. package/dist/updater-URVNPDPW.cjs +183 -0
  422. package/dist/utils/debug.d.ts +57 -0
  423. package/dist/utils/earlyInput.d.ts +43 -0
  424. package/dist/utils/env.d.ts +24 -0
  425. package/dist/utils/envUtils.d.ts +51 -0
  426. package/dist/utils/execFileNoThrow.d.ts +39 -0
  427. package/dist/utils/format.d.ts +44 -0
  428. package/dist/utils/fullscreen.d.ts +47 -0
  429. package/dist/utils/intl.d.ts +22 -0
  430. package/dist/utils/lockfile.d.ts +15 -0
  431. package/dist/utils/log.d.ts +56 -0
  432. package/dist/utils/semver.d.ts +5 -0
  433. package/dist/utils/sliceAnsi.d.ts +12 -0
  434. package/dist/utils/systemTheme.d.ts +40 -0
  435. package/dist/utils/theme.d.ts +91 -0
  436. package/dist/utils/toolDisplay.d.ts +31 -0
  437. package/dist/utils/truncate.d.ts +40 -0
  438. package/dist/voice/index.d.ts +35 -0
  439. package/dist/voice-KTZ7PAGO.js +80 -0
  440. package/dist/voice-KZE25GKB.cjs +80 -0
  441. package/package.json +130 -0
@@ -0,0 +1,1252 @@
1
+ import {
2
+ createLLMClient
3
+ } from "./chunk-SQZHPD3S.js";
4
+ import {
5
+ logger
6
+ } from "./chunk-X4HAERTQ.js";
7
+ import {
8
+ init_esm_shims
9
+ } from "./chunk-DI7RDLOS.js";
10
+
11
+ // src/arena/index.ts
12
+ init_esm_shims();
13
+
14
+ // src/arena/iterate/index.ts
15
+ init_esm_shims();
16
+
17
+ // src/arena/iterate/iterative-arena.ts
18
+ init_esm_shims();
19
+
20
+ // src/arena/iterate/convergence.ts
21
+ init_esm_shims();
22
+ function diffRatio(a, b) {
23
+ if (a === b) return 0;
24
+ if (!a || !b) return 1;
25
+ const trigrams = (s) => {
26
+ const out = /* @__PURE__ */ new Set();
27
+ for (let i = 0; i < s.length - 2; i++) out.add(s.slice(i, i + 3));
28
+ return out;
29
+ };
30
+ const A = trigrams(a);
31
+ const B = trigrams(b);
32
+ let inter = 0;
33
+ for (const t of A) if (B.has(t)) inter++;
34
+ const union = A.size + B.size - inter;
35
+ if (union === 0) return 0;
36
+ const jaccard = inter / union;
37
+ return 1 - jaccard;
38
+ }
39
+ function defaultConvergence(args) {
40
+ const { round, critiques, draft, previousDraft } = args;
41
+ const blockerCount = critiques.filter((c) => c.severity === "blocker").length;
42
+ const majorCount = critiques.filter((c) => c.severity === "major").length;
43
+ const totalCritiques = critiques.length;
44
+ const diffFromPrevious = previousDraft ? diffRatio(previousDraft.content, draft.content) : 1;
45
+ if (round === 1) {
46
+ return {
47
+ blockerCount,
48
+ majorCount,
49
+ totalCritiques,
50
+ diffFromPrevious,
51
+ shouldStop: false,
52
+ reason: "running"
53
+ };
54
+ }
55
+ if (totalCritiques === 0) {
56
+ return {
57
+ blockerCount,
58
+ majorCount,
59
+ totalCritiques,
60
+ diffFromPrevious,
61
+ shouldStop: false,
62
+ reason: "running"
63
+ };
64
+ }
65
+ if (blockerCount === 0 && majorCount === 0 && totalCritiques >= 3) {
66
+ return {
67
+ blockerCount,
68
+ majorCount,
69
+ totalCritiques,
70
+ diffFromPrevious,
71
+ shouldStop: true,
72
+ reason: "all_minor_or_praise"
73
+ };
74
+ }
75
+ if (blockerCount === 0 && diffFromPrevious < 0.05) {
76
+ return {
77
+ blockerCount,
78
+ majorCount,
79
+ totalCritiques,
80
+ diffFromPrevious,
81
+ shouldStop: true,
82
+ reason: "blockers_zero_and_stable"
83
+ };
84
+ }
85
+ return {
86
+ blockerCount,
87
+ majorCount,
88
+ totalCritiques,
89
+ diffFromPrevious,
90
+ shouldStop: false,
91
+ reason: "running"
92
+ };
93
+ }
94
+
95
+ // src/arena/iterate/formats/index.ts
96
+ init_esm_shims();
97
+ var COMMON_DRAFT_RULES = `
98
+ Hard rules:
99
+ - Output the FULL artifact, not a sketch or outline.
100
+ - No "...", "(continued)", "see above", "TBD", or placeholders.
101
+ - Don't pad with filler. Every section must carry information.
102
+ - Length is a floor, not a target \u2014 go beyond it if the topic warrants.
103
+
104
+ Factual discipline (CRITICAL \u2014 fabrication = blocker-level defect):
105
+ - Do NOT invent specific numbers, percentages, dollar amounts, market sizes,
106
+ user-research counts, or "industry averages" you cannot verify.
107
+ - Do NOT invent URLs, report IDs, document numbers, citation references.
108
+ - Do NOT invent named people, companies, or product code-names.
109
+ - For unknowable specifics, write a placeholder with the exact form:
110
+ [\u9700\u8C03\u7814: \u5177\u4F53\u8BF4\u660E] e.g. "[\u9700\u8C03\u7814: \u5B9E\u9645\u884C\u4E1A\u6D41\u5931\u7387\u57FA\u51C6]"
111
+ [TBD: short reason] e.g. "[TBD: confirm Stripe rate limits]"
112
+ These placeholders are EXPECTED. Reviewers will not fault you for them.
113
+ - General qualitative claims are fine ("annual growth typically in the
114
+ double digits"); specific numbers without a verifiable source are NOT.
115
+ - If you have web-search tools available, USE them before stating any
116
+ specific number or citing any source.
117
+ `;
118
+ function formatCritiquesForPrompt(critiques) {
119
+ return critiques.map(
120
+ (c, i) => `[${i + 1}] id=${c.id} severity=${c.severity} category=${c.category} from=${c.critic}
121
+ anchor: "${c.anchor}"
122
+ comment: ${c.comment}` + (c.suggestion ? `
123
+ suggestion: ${c.suggestion}` : "")
124
+ ).join("\n\n");
125
+ }
126
+ var codeFormat = {
127
+ format: "code",
128
+ draftPrompt(subject, minLength) {
129
+ return `You are writing a complete code artifact for the following task.
130
+
131
+ Task: ${subject.label}
132
+ Description: ${subject.description}
133
+ ${subject.sources?.length ? `Source files for context: ${subject.sources.join(", ")}` : ""}
134
+
135
+ This draft will compete with drafts from other participants in a tournament round.
136
+ A merger will then read all drafts (anonymously) and pick the strongest parts.
137
+ Make your draft strong, distinct, complete, and self-contained.
138
+
139
+ Output requirements:
140
+ - Compile-ready code in the appropriate language (infer from sources / description).
141
+ - Include tests if behavior is non-trivial.
142
+ - Inline comments only where the WHY is non-obvious \u2014 names should explain WHAT.
143
+ - At least ${minLength} characters of substantive code (filler will be cut by the merger).
144
+ ${COMMON_DRAFT_RULES}`;
145
+ },
146
+ mergePrompt(subject, candidates, minLength) {
147
+ const blocks = candidates.map((c) => `--- ${c.anonymousLabel} ---
148
+ ${c.content}
149
+ --- end ${c.anonymousLabel} ---`).join("\n\n");
150
+ return `Below are ${candidates.length} draft solutions for the same task, presented anonymously.
151
+ Your job: produce a single v1 by merging the strongest parts of each.
152
+
153
+ Task: ${subject.label}
154
+ Description: ${subject.description}
155
+
156
+ ${blocks}
157
+
158
+ Merging rules:
159
+ - For each section / function / module, pick the strongest version OR write a new one inspired by the best ideas.
160
+ - Inline EVERYTHING. Do not write "see Draft B for the auth helper" \u2014 copy the auth helper in.
161
+ - v1 must be COMPLETE and at least ${minLength} characters of substantive code.
162
+ - After the code, output a 'mergeRationale' section: one short paragraph per major decision, "From Draft X I took ____, because ____. I rejected ____ because ____."
163
+
164
+ Output format (literally \u2014 these markers will be parsed):
165
+
166
+ <v1_content>
167
+ {full code goes here}
168
+ </v1_content>
169
+
170
+ <merge_rationale>
171
+ {your rationale here}
172
+ </merge_rationale>`;
173
+ },
174
+ argueSystem() {
175
+ return `You are reviewing a code artifact. Find every meaningful issue.
176
+
177
+ You may have access to a web_search tool \u2014 USE IT to verify any specific
178
+ claim, library version, API behavior, or external reference made in the
179
+ draft before deciding whether it's a fabrication.
180
+
181
+ For each issue:
182
+ - "anchor": quote 5-15 words verbatim from the draft to locate the issue.
183
+ - "severity": "blocker" (must fix), "major" (should fix), "minor" (nice to fix), "nit" (style), or "praise" (good \u2014 don't gut this).
184
+ - "category": "correctness" | "completeness" | "clarity" | "evidence" | "structure" | "style" | "fabrication" | "other".
185
+ - "comment": what's wrong and what you'd do. If you used web_search, cite the URL.
186
+ - "suggestion": optional concrete fix.
187
+ - "evidence": optional array of {url, snippet} pairs supporting your critique.
188
+
189
+ FABRICATION DETECTION (top priority):
190
+ Any specific number, citation, URL, version string, API endpoint, library
191
+ function, or named entity that you cannot verify is a "fabrication"
192
+ critique with severity = "blocker". Be especially suspicious of:
193
+ - "Industry average is X%" / "Surveys show N=..."
194
+ - Documentation URLs with suspiciously generic paths
195
+ - Library/API names that "sound right" but you can't confirm exist
196
+
197
+ 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.
198
+
199
+ Output strictly as JSON: {"critiques": [{...}, ...]}`;
200
+ },
201
+ argueUser(subject, draft, lens) {
202
+ return `Task: ${subject.label}
203
+ ${lens ? `Review lens: ${lens}
204
+ ` : ""}
205
+ Current draft (v${draft.version}, by ${draft.author}):
206
+
207
+ ${draft.content}
208
+
209
+ Now produce your critiques as JSON.`;
210
+ },
211
+ revisePrompt(subject, previous, critiques, minLength) {
212
+ return `You wrote v${previous.version}. Critics raised ${critiques.length} points.
213
+ Rewrite the artifact as v${previous.version + 1}.
214
+
215
+ Task: ${subject.label}
216
+ Description: ${subject.description}
217
+
218
+ Current draft (v${previous.version}):
219
+ ${previous.content}
220
+
221
+ Critiques:
222
+ ${formatCritiquesForPrompt(critiques)}
223
+
224
+ Rules:
225
+ - ADDRESS every blocker and major. You may disagree, but say why in changelog.
226
+ - Preserve PRAISE-tagged parts unless a later critique contradicts.
227
+ - Output the COMPLETE new artifact (at least ${minLength} chars), not a diff.
228
+ - After the code, output a JSON block:
229
+
230
+ <v_next_content>
231
+ {full code goes here}
232
+ </v_next_content>
233
+
234
+ <v_next_meta>
235
+ {
236
+ "acceptedCritiques": ["id1", "id2", ...],
237
+ "rejectedCritiques": [{"id": "id3", "reason": "..."}, ...],
238
+ "changelog": "what changed and why, in 1-3 short paragraphs"
239
+ }
240
+ </v_next_meta>`;
241
+ }
242
+ };
243
+ var documentFormat = {
244
+ format: "document",
245
+ draftPrompt(subject, minLength) {
246
+ return `You are writing a complete long-form document for the following subject.
247
+
248
+ Subject: ${subject.label}
249
+ Description: ${subject.description}
250
+ ${subject.sources?.length ? `Reference materials: ${subject.sources.join(", ")}` : ""}
251
+
252
+ This draft will compete with drafts from other participants in a tournament round.
253
+ A merger will then read all drafts (anonymously) and pick the strongest parts.
254
+ Make your draft strong, distinct, complete, and self-contained.
255
+
256
+ Document requirements:
257
+ - Use clear hierarchical structure (## sections, ### subsections).
258
+ - Every section must carry concrete information: examples, comparisons, trade-offs, numbers.
259
+ - Cite sources inline with [n] footnotes when you make factual claims.
260
+ - At least ${minLength} characters of substantive prose (filler will be cut by the merger).
261
+ ${COMMON_DRAFT_RULES}`;
262
+ },
263
+ mergePrompt(subject, candidates, minLength) {
264
+ const blocks = candidates.map((c) => `--- ${c.anonymousLabel} ---
265
+ ${c.content}
266
+ --- end ${c.anonymousLabel} ---`).join("\n\n");
267
+ return `Below are ${candidates.length} draft documents for the same subject, presented anonymously.
268
+ Your job: produce a single v1 markdown document by merging the strongest parts.
269
+
270
+ Subject: ${subject.label}
271
+ Description: ${subject.description}
272
+
273
+ ${blocks}
274
+
275
+ Merging rules:
276
+ - Pick the strongest section from each draft, OR write a new section that combines their best ideas.
277
+ - DO NOT write "see Draft B for ____" \u2014 inline everything.
278
+ - The final v1 must be COMPLETE and at least ${minLength} characters.
279
+ - Maintain coherent voice and consistent structure across sections.
280
+
281
+ Output format (literally \u2014 these markers will be parsed):
282
+
283
+ <v1_content>
284
+ {full markdown document}
285
+ </v1_content>
286
+
287
+ <merge_rationale>
288
+ {1-3 short paragraphs: from which draft you took which section, why; what you rejected, why}
289
+ </merge_rationale>`;
290
+ },
291
+ argueSystem() {
292
+ return `You are reviewing a long-form document. Find every meaningful issue.
293
+
294
+ You may have access to a web_search tool \u2014 USE IT to verify any specific
295
+ number, citation, market figure, named survey, or external reference
296
+ before deciding whether it's a fabrication.
297
+
298
+ For each issue:
299
+ - "anchor": quote 5-15 words verbatim from the document to locate the issue.
300
+ - "severity": "blocker" | "major" | "minor" | "nit" | "praise".
301
+ - "category": "correctness" | "completeness" | "clarity" | "evidence" | "structure" | "style" | "fabrication" | "other".
302
+ - "comment": what's wrong / missing / weak. If you used web_search, cite the URL.
303
+ - "suggestion": optional concrete fix or content to add.
304
+ - "evidence": optional array of {url, snippet} pairs supporting your critique.
305
+
306
+ FABRICATION DETECTION (top priority):
307
+ The document is far more likely to fail because of fabricated facts than
308
+ because of missing sections. Treat every specific number / report ID /
309
+ URL / dollar figure / "industry average" / named survey as suspect until
310
+ verified. Mark as severity = "blocker" if:
311
+ - The number cannot be found via web_search.
312
+ - The cited URL doesn't resolve to the claimed source.
313
+ - The "report ID" / "document number" appears made up.
314
+ - The named survey / interviewee count cannot be traced.
315
+ A draft full of citations that don't check out is worse than a draft
316
+ that honestly writes "[\u9700\u8C03\u7814: ...]". Reward the latter.
317
+
318
+ 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.
319
+
320
+ Output strictly as JSON: {"critiques": [{...}, ...]}`;
321
+ },
322
+ argueUser(subject, draft, lens) {
323
+ return `Subject: ${subject.label}
324
+ ${lens ? `Review lens: ${lens}
325
+ ` : ""}
326
+ Current document (v${draft.version}, by ${draft.author}):
327
+
328
+ ${draft.content}
329
+
330
+ Now produce your critiques as JSON.`;
331
+ },
332
+ revisePrompt(subject, previous, critiques, minLength) {
333
+ return `You wrote v${previous.version}. Critics raised ${critiques.length} points.
334
+ Rewrite the document as v${previous.version + 1}.
335
+
336
+ Subject: ${subject.label}
337
+ Description: ${subject.description}
338
+
339
+ Current document (v${previous.version}):
340
+ ${previous.content}
341
+
342
+ Critiques:
343
+ ${formatCritiquesForPrompt(critiques)}
344
+
345
+ Rules:
346
+ - ADDRESS every blocker and major. You may disagree, but say why in changelog.
347
+ - Preserve PRAISE-tagged parts.
348
+ - Expand sections that were called out as thin / missing examples / lacking evidence.
349
+ - Output the COMPLETE new document (at least ${minLength} chars).
350
+
351
+ Output format (literally \u2014 these markers will be parsed):
352
+
353
+ <v_next_content>
354
+ {full markdown document}
355
+ </v_next_content>
356
+
357
+ <v_next_meta>
358
+ {
359
+ "acceptedCritiques": ["id1", "id2", ...],
360
+ "rejectedCritiques": [{"id": "id3", "reason": "..."}, ...],
361
+ "changelog": "what changed and why, in 1-3 short paragraphs"
362
+ }
363
+ </v_next_meta>`;
364
+ }
365
+ };
366
+ function getFormat(format) {
367
+ return format === "code" ? codeFormat : documentFormat;
368
+ }
369
+
370
+ // src/arena/iterate/phases/argue.ts
371
+ init_esm_shims();
372
+
373
+ // src/arena/iterate/parse.ts
374
+ init_esm_shims();
375
+ function extractTag(text, tag) {
376
+ const closed = new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`, "i");
377
+ const closedMatch = text.match(closed);
378
+ if (closedMatch) return closedMatch[1].trim();
379
+ const opener = new RegExp(`<${tag}>`, "i");
380
+ const openMatch = opener.exec(text);
381
+ if (!openMatch) return null;
382
+ const after = text.slice(openMatch.index + openMatch[0].length);
383
+ const nextTag = after.search(/<[a-z_][\w]*>/i);
384
+ const body = nextTag >= 0 ? after.slice(0, nextTag) : after;
385
+ return body.trim();
386
+ }
387
+ function parseMergeResponse(text) {
388
+ const content = extractTag(text, "v1_content");
389
+ const rationale = extractTag(text, "merge_rationale");
390
+ if (content) {
391
+ return { content, rationale: rationale ?? void 0 };
392
+ }
393
+ return { content: text.trim(), rationale: "[merge markers not found; using full response]" };
394
+ }
395
+ function parseReviseResponse(text) {
396
+ const content = extractTag(text, "v_next_content");
397
+ const metaRaw = extractTag(text, "v_next_meta");
398
+ let meta = {};
399
+ if (metaRaw) {
400
+ const cleaned = metaRaw.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "").trim();
401
+ try {
402
+ meta = JSON.parse(cleaned);
403
+ } catch {
404
+ meta = { changelog: `[meta JSON parse failed; raw text below]
405
+ ${metaRaw}` };
406
+ }
407
+ }
408
+ return {
409
+ content: content ?? text.trim(),
410
+ meta
411
+ };
412
+ }
413
+ function parseCritiquesResponse(text, criticName, idPrefix) {
414
+ const cleaned = text.replace(/^[^{[]*/, "").replace(/[^}\]]*$/, "").trim();
415
+ let parsed;
416
+ try {
417
+ parsed = JSON.parse(cleaned);
418
+ } catch {
419
+ const jsonMatch = text.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
420
+ if (!jsonMatch) return [];
421
+ try {
422
+ parsed = JSON.parse(jsonMatch[0]);
423
+ } catch {
424
+ return [];
425
+ }
426
+ }
427
+ const arr = Array.isArray(parsed) ? parsed : parsed.critiques;
428
+ if (!Array.isArray(arr)) return [];
429
+ const out = [];
430
+ for (let i = 0; i < arr.length; i++) {
431
+ const c = arr[i];
432
+ if (!c.anchor || !c.comment) continue;
433
+ let evidence;
434
+ if (Array.isArray(c.evidence)) {
435
+ evidence = c.evidence.filter((e) => {
436
+ if (typeof e !== "object" || e === null) return false;
437
+ const obj = e;
438
+ return typeof obj.url === "string";
439
+ }).map((e) => ({ url: e.url, snippet: e.snippet }));
440
+ if (evidence.length === 0) evidence = void 0;
441
+ }
442
+ out.push({
443
+ id: `${idPrefix}-${criticName}-${i + 1}`,
444
+ critic: criticName,
445
+ anchor: String(c.anchor),
446
+ severity: c.severity ?? "minor",
447
+ category: c.category ?? "other",
448
+ comment: String(c.comment),
449
+ suggestion: c.suggestion ? String(c.suggestion) : void 0,
450
+ evidence
451
+ });
452
+ }
453
+ return out;
454
+ }
455
+
456
+ // src/arena/iterate/tools/web-tools.ts
457
+ init_esm_shims();
458
+
459
+ // src/tool-system/builtin/web-search.ts
460
+ init_esm_shims();
461
+ var webSearchToolDef = {
462
+ name: "WebSearch",
463
+ 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.",
464
+ inputSchema: {
465
+ type: "object",
466
+ properties: {
467
+ query: { type: "string", description: "The search query" },
468
+ num_results: {
469
+ type: "number",
470
+ description: "Number of results to return (default: 10, max: 20)"
471
+ }
472
+ },
473
+ required: ["query"]
474
+ }
475
+ };
476
+ async function webSearchTool(args) {
477
+ const query = args.query;
478
+ if (!query) return "Error: query is required";
479
+ const numResults = Math.min(args.num_results || 10, 20);
480
+ const serperKey = process.env.SERPER_API_KEY;
481
+ const tavilyKey = process.env.TAVILY_API_KEY;
482
+ const searxngUrl = process.env.SEARXNG_URL;
483
+ try {
484
+ let results;
485
+ if (serperKey) {
486
+ results = await searchSerper(query, numResults, serperKey);
487
+ } else if (tavilyKey) {
488
+ results = await searchTavily(query, numResults, tavilyKey);
489
+ } else if (searxngUrl) {
490
+ results = await searchSearXNG(query, numResults, searxngUrl);
491
+ } else {
492
+ return "Error: No search API configured. Set one of: SERPER_API_KEY, TAVILY_API_KEY, or SEARXNG_URL";
493
+ }
494
+ if (results.length === 0) return "No results found.";
495
+ return results.map((r, i) => `${i + 1}. ${r.title}
496
+ ${r.url}
497
+ ${r.snippet}`).join("\n\n");
498
+ } catch (err) {
499
+ return `Search error: ${err.message}`;
500
+ }
501
+ }
502
+ async function searchSerper(query, num, apiKey) {
503
+ const res = await fetch("https://google.serper.dev/search", {
504
+ method: "POST",
505
+ headers: {
506
+ "X-API-KEY": apiKey,
507
+ "Content-Type": "application/json"
508
+ },
509
+ body: JSON.stringify({ q: query, num })
510
+ });
511
+ if (!res.ok) throw new Error(`Serper API error: ${res.status} ${res.statusText}`);
512
+ const data = await res.json();
513
+ return (data.organic ?? []).map((item) => ({
514
+ title: item.title ?? "",
515
+ url: item.link ?? "",
516
+ snippet: item.snippet ?? ""
517
+ }));
518
+ }
519
+ async function searchTavily(query, num, apiKey) {
520
+ const res = await fetch("https://api.tavily.com/search", {
521
+ method: "POST",
522
+ headers: { "Content-Type": "application/json" },
523
+ body: JSON.stringify({
524
+ api_key: apiKey,
525
+ query,
526
+ max_results: num,
527
+ include_answer: false
528
+ })
529
+ });
530
+ if (!res.ok) throw new Error(`Tavily API error: ${res.status} ${res.statusText}`);
531
+ const data = await res.json();
532
+ return (data.results ?? []).map((item) => ({
533
+ title: item.title ?? "",
534
+ url: item.url ?? "",
535
+ snippet: item.content ?? ""
536
+ }));
537
+ }
538
+ async function searchSearXNG(query, num, baseUrl) {
539
+ const url = new URL("/search", baseUrl);
540
+ url.searchParams.set("q", query);
541
+ url.searchParams.set("format", "json");
542
+ url.searchParams.set("pageno", "1");
543
+ const res = await fetch(url.toString(), {
544
+ headers: { Accept: "application/json" }
545
+ });
546
+ if (!res.ok) throw new Error(`SearXNG error: ${res.status} ${res.statusText}`);
547
+ const data = await res.json();
548
+ return (data.results ?? []).slice(0, num).map((item) => ({
549
+ title: item.title ?? "",
550
+ url: item.url ?? "",
551
+ snippet: item.content ?? ""
552
+ }));
553
+ }
554
+
555
+ // src/tool-system/builtin/web-fetch.ts
556
+ init_esm_shims();
557
+ var webFetchToolDef = {
558
+ name: "WebFetch",
559
+ 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.",
560
+ inputSchema: {
561
+ type: "object",
562
+ properties: {
563
+ url: { type: "string", description: "The URL to fetch" },
564
+ max_length: {
565
+ type: "number",
566
+ description: "Maximum characters to return (default: 50000)"
567
+ },
568
+ headers: {
569
+ type: "object",
570
+ description: "Optional HTTP headers to send"
571
+ }
572
+ },
573
+ required: ["url"]
574
+ }
575
+ };
576
+ var MAX_OUTPUT = 1e5;
577
+ var DEFAULT_MAX = 5e4;
578
+ var BLOCKED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
579
+ "host",
580
+ "authorization",
581
+ "cookie",
582
+ "proxy-authorization",
583
+ "x-forwarded-for",
584
+ "x-real-ip",
585
+ "x-forwarded-host"
586
+ ]);
587
+ var BLOCKED_HOST_PATTERNS = [
588
+ /^localhost$/i,
589
+ /^127\./,
590
+ /^0\.0\.0\.0$/,
591
+ /^10\./,
592
+ /^169\.254\./,
593
+ // link-local + AWS/GCP metadata (169.254.169.254)
594
+ /^192\.168\./,
595
+ /^172\.(1[6-9]|2[0-9]|3[01])\./,
596
+ // 172.16.0.0/12
597
+ /^::1$/,
598
+ /^fc00:/i,
599
+ /^fd00:/i,
600
+ // IPv6 ULA
601
+ /^fe80:/i
602
+ // IPv6 link-local
603
+ ];
604
+ function isBlockedHost(hostname) {
605
+ return BLOCKED_HOST_PATTERNS.some((re) => re.test(hostname));
606
+ }
607
+ async function webFetchTool(args) {
608
+ const url = args.url;
609
+ if (!url) return "Error: url is required";
610
+ let parsed;
611
+ try {
612
+ parsed = new URL(url);
613
+ } catch {
614
+ return `Error: invalid URL "${url}"`;
615
+ }
616
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
617
+ return `Error: only http(s) URLs are allowed, got "${parsed.protocol}"`;
618
+ }
619
+ if (isBlockedHost(parsed.hostname)) {
620
+ return `Error: refusing to fetch internal/loopback host "${parsed.hostname}"`;
621
+ }
622
+ const maxLength = Math.min(args.max_length || DEFAULT_MAX, MAX_OUTPUT);
623
+ const rawHeaders = args.headers ?? {};
624
+ const customHeaders = {};
625
+ for (const [k, v] of Object.entries(rawHeaders)) {
626
+ if (!BLOCKED_REQUEST_HEADERS.has(k.toLowerCase())) {
627
+ customHeaders[k] = v;
628
+ }
629
+ }
630
+ try {
631
+ const res = await fetch(url, {
632
+ headers: {
633
+ "User-Agent": "Mozilla/5.0 (compatible; code-shell/0.1; +https://github.com/nicepkg/code-shell)",
634
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7",
635
+ ...customHeaders
636
+ },
637
+ redirect: "follow",
638
+ signal: AbortSignal.timeout(3e4)
639
+ });
640
+ if (!res.ok) {
641
+ return `Error: HTTP ${res.status} ${res.statusText}`;
642
+ }
643
+ const contentType = res.headers.get("content-type") ?? "";
644
+ const body = await res.text();
645
+ let text;
646
+ if (contentType.includes("text/html") || contentType.includes("application/xhtml")) {
647
+ text = extractTextFromHTML(body);
648
+ } else {
649
+ text = body;
650
+ }
651
+ if (text.length > maxLength) {
652
+ text = text.slice(0, maxLength) + `
653
+
654
+ ... content truncated (${text.length} chars total)`;
655
+ }
656
+ return text || "(page returned empty content)";
657
+ } catch (err) {
658
+ const msg = err.message;
659
+ if (msg.includes("abort") || msg.includes("timeout")) {
660
+ return "Error: request timed out after 30s";
661
+ }
662
+ return `Fetch error: ${msg}`;
663
+ }
664
+ }
665
+ function extractTextFromHTML(html) {
666
+ let text = html;
667
+ text = text.replace(/<script[\s\S]*?<\/script>/gi, "");
668
+ text = text.replace(/<style[\s\S]*?<\/style>/gi, "");
669
+ text = text.replace(/<noscript[\s\S]*?<\/noscript>/gi, "");
670
+ const titleMatch = text.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
671
+ const title = titleMatch ? decodeEntities(titleMatch[1].trim()) : "";
672
+ const mainMatch = text.match(/<main[\s\S]*?<\/main>/i) ?? text.match(/<article[\s\S]*?<\/article>/i) ?? text.match(/<div[^>]*(?:role="main"|id="content"|class="[^"]*content[^"]*")[^>]*>[\s\S]*?<\/div>/i);
673
+ if (mainMatch) {
674
+ text = mainMatch[0];
675
+ } else {
676
+ const bodyMatch = text.match(/<body[\s\S]*?<\/body>/i);
677
+ if (bodyMatch) text = bodyMatch[0];
678
+ }
679
+ text = text.replace(/<(nav|header|footer|aside)[\s\S]*?<\/\1>/gi, "");
680
+ text = text.replace(/<(p|div|h[1-6]|li|br|tr|blockquote)[^>]*>/gi, "\n");
681
+ text = text.replace(/<\/(p|div|h[1-6]|li|tr|blockquote)>/gi, "\n");
682
+ text = text.replace(/<hr[^>]*>/gi, "\n---\n");
683
+ text = text.replace(/<[^>]+>/g, "");
684
+ text = decodeEntities(text);
685
+ text = text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).join("\n");
686
+ text = text.replace(/\n{3,}/g, "\n\n");
687
+ if (title) {
688
+ text = `# ${title}
689
+
690
+ ${text}`;
691
+ }
692
+ return text.trim();
693
+ }
694
+ function decodeEntities(text) {
695
+ return text.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&apos;/g, "'").replace(/&nbsp;/g, " ").replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n))).replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
696
+ }
697
+
698
+ // src/arena/iterate/tools/web-tools.ts
699
+ var webSearchToolDef2 = {
700
+ name: "web_search",
701
+ 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.",
702
+ inputSchema: {
703
+ type: "object",
704
+ properties: {
705
+ query: { type: "string", description: "Search query (English usually works best)." },
706
+ num_results: { type: "number", description: "Default 5, max 20." }
707
+ },
708
+ required: ["query"]
709
+ }
710
+ };
711
+ var webFetchToolDef2 = {
712
+ name: "web_fetch",
713
+ 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.",
714
+ inputSchema: {
715
+ type: "object",
716
+ properties: {
717
+ url: { type: "string", description: "Full http(s) URL to fetch." },
718
+ max_length: { type: "number", description: "Default 50000 characters." }
719
+ },
720
+ required: ["url"]
721
+ }
722
+ };
723
+ var ITERATE_WEB_TOOLS = [webSearchToolDef2, webFetchToolDef2];
724
+ async function executeIterateWebTool(toolName, args) {
725
+ if (toolName === "web_search") {
726
+ return webSearchTool(args);
727
+ }
728
+ if (toolName === "web_fetch") {
729
+ return webFetchTool(args);
730
+ }
731
+ return `Error: unknown tool "${toolName}"`;
732
+ }
733
+ function hasWebSearchProvider() {
734
+ return Boolean(
735
+ process.env.SERPER_API_KEY || process.env.TAVILY_API_KEY || process.env.SEARXNG_URL
736
+ );
737
+ }
738
+
739
+ // src/arena/iterate/phases/argue.ts
740
+ var DEFAULT_MAX_TOOL_ROUNDS = 8;
741
+ async function runArgueRound(args) {
742
+ const { subject, format, draft, critics, round, enableWebSearch, maxToolRounds, signal, onProgress } = args;
743
+ onProgress?.({ type: "argue_start", round, data: { criticCount: critics.length } });
744
+ const wantWeb = Boolean(enableWebSearch);
745
+ const webAvailable = wantWeb && hasWebSearchProvider();
746
+ if (wantWeb && !webAvailable) {
747
+ logger.warn("arena.iterate.argue_web_unavailable", {
748
+ reason: "No SERPER_API_KEY / TAVILY_API_KEY / SEARXNG_URL configured"
749
+ });
750
+ }
751
+ const idPrefix = `r${round}`;
752
+ const tasks = critics.map(async (c) => {
753
+ signal?.throwIfAborted();
754
+ try {
755
+ if (webAvailable) {
756
+ return await argueWithToolLoop({
757
+ critic: c,
758
+ subject,
759
+ format,
760
+ draft,
761
+ idPrefix,
762
+ maxToolRounds: maxToolRounds ?? DEFAULT_MAX_TOOL_ROUNDS,
763
+ signal
764
+ });
765
+ }
766
+ return await argueSingleShot({ critic: c, subject, format, draft, idPrefix, signal });
767
+ } catch (err) {
768
+ logger.warn("arena.iterate.argue_failed", {
769
+ round,
770
+ critic: c.name,
771
+ error: err.message
772
+ });
773
+ return [];
774
+ }
775
+ });
776
+ const results = await Promise.all(tasks);
777
+ const allCritiques = results.flat();
778
+ onProgress?.({
779
+ type: "argue_done",
780
+ round,
781
+ data: { critiqueCount: allCritiques.length, webEnabled: webAvailable }
782
+ });
783
+ return allCritiques;
784
+ }
785
+ async function argueSingleShot(args) {
786
+ const { critic, subject, format, draft, idPrefix, signal } = args;
787
+ const client = await createLLMClient({ ...critic.llm, enableStreaming: false });
788
+ const resp = await client.createMessage({
789
+ systemPrompt: format.argueSystem(format.format),
790
+ messages: [{ role: "user", content: format.argueUser(subject, draft) }],
791
+ tools: [],
792
+ signal
793
+ });
794
+ const critiques = parseCritiquesResponse(resp.text, critic.name, idPrefix);
795
+ logger.info("arena.iterate.argue_singleshot", {
796
+ critic: critic.name,
797
+ critiqueCount: critiques.length
798
+ });
799
+ return critiques;
800
+ }
801
+ async function argueWithToolLoop(args) {
802
+ const { critic, subject, format, draft, idPrefix, maxToolRounds, signal } = args;
803
+ const client = await createLLMClient({ ...critic.llm, enableStreaming: false });
804
+ const messages = [
805
+ { role: "user", content: format.argueUser(subject, draft) }
806
+ ];
807
+ let toolRounds = 0;
808
+ let finalText = "";
809
+ while (toolRounds < maxToolRounds) {
810
+ signal?.throwIfAborted();
811
+ const resp = await client.createMessage({
812
+ systemPrompt: format.argueSystem(format.format),
813
+ messages,
814
+ tools: ITERATE_WEB_TOOLS,
815
+ signal
816
+ });
817
+ if (resp.text) finalText = resp.text;
818
+ if (!resp.toolCalls || resp.toolCalls.length === 0) {
819
+ break;
820
+ }
821
+ messages.push({
822
+ role: "assistant",
823
+ content: [
824
+ ...resp.text ? [{ type: "text", text: resp.text }] : [],
825
+ ...resp.toolCalls.map((tc) => ({
826
+ type: "tool_use",
827
+ id: tc.id,
828
+ name: tc.toolName,
829
+ input: tc.args
830
+ }))
831
+ ]
832
+ });
833
+ const toolResults = await Promise.all(
834
+ resp.toolCalls.map(async (tc) => {
835
+ try {
836
+ const result = await executeIterateWebTool(tc.toolName, tc.args);
837
+ return { id: tc.id, content: result };
838
+ } catch (err) {
839
+ return { id: tc.id, content: `Error: ${err.message}` };
840
+ }
841
+ })
842
+ );
843
+ messages.push({
844
+ role: "user",
845
+ content: toolResults.map((tr) => ({
846
+ type: "tool_result",
847
+ tool_use_id: tr.id,
848
+ content: tr.content
849
+ }))
850
+ });
851
+ toolRounds++;
852
+ }
853
+ if (!finalText && toolRounds >= maxToolRounds) {
854
+ const resp = await client.createMessage({
855
+ systemPrompt: format.argueSystem(format.format),
856
+ messages: [
857
+ ...messages,
858
+ {
859
+ role: "user",
860
+ 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."
861
+ }
862
+ ],
863
+ tools: [],
864
+ signal
865
+ });
866
+ finalText = resp.text;
867
+ }
868
+ const critiques = parseCritiquesResponse(finalText, critic.name, idPrefix);
869
+ logger.info("arena.iterate.argue_toolloop", {
870
+ critic: critic.name,
871
+ critiqueCount: critiques.length,
872
+ toolRounds
873
+ });
874
+ return critiques;
875
+ }
876
+
877
+ // src/arena/iterate/phases/revise.ts
878
+ init_esm_shims();
879
+ async function runRevise(args) {
880
+ const { subject, format, previous, critiques, author, minDraftLength, signal, onProgress } = args;
881
+ onProgress?.({ type: "revise_start", round: previous.version + 1, participant: author.name });
882
+ const client = await createLLMClient({ ...author.llm, enableStreaming: false });
883
+ const prompt = format.revisePrompt(subject, previous, critiques, minDraftLength);
884
+ const resp = await client.createMessage({
885
+ systemPrompt: prompt,
886
+ messages: [{ role: "user", content: `Produce v${previous.version + 1} now.` }],
887
+ tools: [],
888
+ maxTokens: 32e3,
889
+ signal
890
+ });
891
+ const { content, meta } = parseReviseResponse(resp.text);
892
+ let acceptedContent = content;
893
+ const shrinkage = previous.content.length > 0 ? 1 - acceptedContent.length / previous.content.length : 0;
894
+ if (shrinkage > 0.3 && acceptedContent.length < minDraftLength) {
895
+ logger.warn("arena.iterate.revise_too_short", {
896
+ version: previous.version + 1,
897
+ previousLength: previous.content.length,
898
+ newLength: acceptedContent.length,
899
+ minDraftLength
900
+ });
901
+ meta.changelog = `[WARNING: revision is ${Math.round(shrinkage * 100)}% shorter than v${previous.version}; the author may have summarized instead of rewriting]
902
+
903
+ ` + (meta.changelog ?? "");
904
+ }
905
+ const next = {
906
+ version: previous.version + 1,
907
+ author: author.name,
908
+ format: format.format,
909
+ content: acceptedContent,
910
+ acceptedCritiques: meta.acceptedCritiques,
911
+ rejectedCritiques: meta.rejectedCritiques,
912
+ changelog: meta.changelog
913
+ };
914
+ onProgress?.({
915
+ type: "revise_done",
916
+ round: next.version,
917
+ participant: author.name,
918
+ data: { length: acceptedContent.length, accepted: meta.acceptedCritiques?.length ?? 0 }
919
+ });
920
+ logger.info("arena.iterate.revise", {
921
+ version: next.version,
922
+ author: author.name,
923
+ length: acceptedContent.length,
924
+ accepted: meta.acceptedCritiques?.length ?? 0,
925
+ rejected: meta.rejectedCritiques?.length ?? 0
926
+ });
927
+ return next;
928
+ }
929
+
930
+ // src/arena/iterate/phases/tournament.ts
931
+ init_esm_shims();
932
+ async function runTournamentCandidates(args) {
933
+ const { subject, format, participants, minDraftLength, signal, onProgress } = args;
934
+ onProgress?.({ type: "v1_tournament_start", data: { count: participants.length } });
935
+ const tasks = participants.map(async (p, idx) => {
936
+ signal?.throwIfAborted();
937
+ const client = await createLLMClient({ ...p.llm, enableStreaming: false });
938
+ const prompt = format.draftPrompt(subject, minDraftLength);
939
+ const resp = await client.createMessage({
940
+ systemPrompt: prompt,
941
+ messages: [{ role: "user", content: `Write your draft now.` }],
942
+ tools: [],
943
+ maxTokens: 32e3,
944
+ signal
945
+ });
946
+ const content = resp.text.trim();
947
+ const candidate = {
948
+ author: p.name,
949
+ anonymousLabel: `Draft ${String.fromCharCode(65 + idx)}`,
950
+ // A, B, C...
951
+ content
952
+ };
953
+ onProgress?.({
954
+ type: "v1_candidate_done",
955
+ participant: p.name,
956
+ data: { length: content.length, anonymousLabel: candidate.anonymousLabel }
957
+ });
958
+ logger.info("arena.iterate.v1_candidate", {
959
+ participant: p.name,
960
+ anonymousLabel: candidate.anonymousLabel,
961
+ length: content.length
962
+ });
963
+ return candidate;
964
+ });
965
+ const settled = await Promise.allSettled(tasks);
966
+ const candidates = [];
967
+ for (const s of settled) {
968
+ if (s.status === "fulfilled") candidates.push(s.value);
969
+ else logger.warn("arena.iterate.v1_candidate_failed", { error: s.reason?.message });
970
+ }
971
+ if (candidates.length === 0) {
972
+ throw new Error("All v1 tournament candidates failed");
973
+ }
974
+ for (let i = candidates.length - 1; i > 0; i--) {
975
+ const j = Math.floor(Math.random() * (i + 1));
976
+ [candidates[i], candidates[j]] = [candidates[j], candidates[i]];
977
+ candidates[i].anonymousLabel = `Draft ${String.fromCharCode(65 + i)}`;
978
+ }
979
+ candidates[0].anonymousLabel = `Draft A`;
980
+ return candidates;
981
+ }
982
+ async function mergeCandidatesToV1(args) {
983
+ const { subject, format, author, candidates, minDraftLength, signal, onProgress } = args;
984
+ onProgress?.({ type: "v1_merge_start", participant: author.name });
985
+ const client = await createLLMClient({ ...author.llm, enableStreaming: false });
986
+ const prompt = format.mergePrompt(subject, candidates, minDraftLength);
987
+ const resp = await client.createMessage({
988
+ systemPrompt: prompt,
989
+ messages: [{ role: "user", content: `Produce v1 now.` }],
990
+ tools: [],
991
+ maxTokens: 32e3,
992
+ signal
993
+ });
994
+ const { content, rationale } = parseMergeResponse(resp.text);
995
+ const draft = {
996
+ version: 1,
997
+ author: author.name,
998
+ format: format.format,
999
+ content,
1000
+ draftCandidates: candidates,
1001
+ mergeRationale: rationale
1002
+ };
1003
+ onProgress?.({ type: "v1_merge_done", participant: author.name, data: { length: content.length } });
1004
+ logger.info("arena.iterate.v1_merge", {
1005
+ author: author.name,
1006
+ candidateCount: candidates.length,
1007
+ length: content.length
1008
+ });
1009
+ return draft;
1010
+ }
1011
+ async function singleAuthorV1(args) {
1012
+ const { subject, format, author, minDraftLength, signal } = args;
1013
+ const client = await createLLMClient({ ...author.llm, enableStreaming: false });
1014
+ const prompt = format.draftPrompt(subject, minDraftLength);
1015
+ const resp = await client.createMessage({
1016
+ systemPrompt: prompt,
1017
+ messages: [{ role: "user", content: `Write your draft now.` }],
1018
+ tools: [],
1019
+ maxTokens: 32e3,
1020
+ signal
1021
+ });
1022
+ return {
1023
+ version: 1,
1024
+ author: author.name,
1025
+ format: format.format,
1026
+ content: resp.text.trim()
1027
+ };
1028
+ }
1029
+
1030
+ // src/arena/iterate/iterative-arena.ts
1031
+ var DEFAULT_MAX_ROUNDS = 5;
1032
+ var IterativeArena = class {
1033
+ config;
1034
+ constructor(config) {
1035
+ if (!config.author) {
1036
+ throw new Error("IterativeArena requires an `author` participant");
1037
+ }
1038
+ if (!config.critics || config.critics.length === 0) {
1039
+ throw new Error("IterativeArena requires at least 1 critic");
1040
+ }
1041
+ const allNames = [config.author.name, ...config.critics.map((c) => c.name)];
1042
+ if (new Set(allNames).size !== allNames.length) {
1043
+ throw new Error("Author and critics must have unique names");
1044
+ }
1045
+ this.config = config;
1046
+ }
1047
+ async run() {
1048
+ const start = Date.now();
1049
+ const { config } = this;
1050
+ const format = getFormat(config.format);
1051
+ const maxRounds = config.maxRounds ?? DEFAULT_MAX_ROUNDS;
1052
+ const minDraftLength = config.minDraftLength ?? (config.format === "code" ? 200 : 800);
1053
+ const signal = config.signal;
1054
+ const rounds = [];
1055
+ let currentDraft;
1056
+ try {
1057
+ if ((config.v1Strategy ?? "tournament") === "tournament") {
1058
+ const candidates = await runTournamentCandidates({
1059
+ subject: config.subject,
1060
+ format,
1061
+ participants: [config.author, ...config.critics],
1062
+ minDraftLength,
1063
+ signal,
1064
+ onProgress: config.onProgress
1065
+ });
1066
+ currentDraft = await mergeCandidatesToV1({
1067
+ subject: config.subject,
1068
+ format,
1069
+ author: config.author,
1070
+ candidates,
1071
+ minDraftLength,
1072
+ signal,
1073
+ onProgress: config.onProgress
1074
+ });
1075
+ } else {
1076
+ currentDraft = await singleAuthorV1({
1077
+ subject: config.subject,
1078
+ format,
1079
+ author: config.author,
1080
+ minDraftLength,
1081
+ signal
1082
+ });
1083
+ }
1084
+ } catch (err) {
1085
+ logger.error("arena.iterate.v1_failed", { error: err.message });
1086
+ throw err;
1087
+ }
1088
+ let currentAuthor = config.author;
1089
+ const pool = [config.author, ...config.critics];
1090
+ let previousDraft;
1091
+ for (let r = 1; r <= maxRounds; r++) {
1092
+ signal?.throwIfAborted();
1093
+ const critiques = await runArgueRound({
1094
+ subject: config.subject,
1095
+ format,
1096
+ draft: currentDraft,
1097
+ critics: this.criticsForRound(r),
1098
+ round: r,
1099
+ enableWebSearch: config.enableWebSearch,
1100
+ maxToolRounds: config.maxArgueToolRounds,
1101
+ signal,
1102
+ onProgress: config.onProgress
1103
+ });
1104
+ const convergence = this.checkConvergence({
1105
+ round: r,
1106
+ critiques,
1107
+ draft: currentDraft,
1108
+ previousDraft
1109
+ });
1110
+ const round = {
1111
+ round: r,
1112
+ draft: currentDraft,
1113
+ critiques,
1114
+ convergence
1115
+ };
1116
+ let userAction;
1117
+ if (config.humanCheckpoint) {
1118
+ config.onProgress?.({ type: "checkpoint_pause", round: r });
1119
+ userAction = await config.humanCheckpoint({
1120
+ round: r,
1121
+ draft: currentDraft,
1122
+ critiques,
1123
+ convergence
1124
+ });
1125
+ }
1126
+ rounds.push(round);
1127
+ config.onProgress?.({
1128
+ type: "round_done",
1129
+ round: r,
1130
+ data: {
1131
+ critiques: critiques.length,
1132
+ shouldStop: convergence.shouldStop,
1133
+ userAction
1134
+ }
1135
+ });
1136
+ if (userAction === "stop") {
1137
+ return this.finalize(rounds, "user_stop", start);
1138
+ }
1139
+ if (userAction !== "force-continue" && convergence.shouldStop) {
1140
+ return this.finalize(rounds, "converged", start);
1141
+ }
1142
+ if (r === maxRounds) {
1143
+ return this.finalize(rounds, "max_rounds", start);
1144
+ }
1145
+ previousDraft = currentDraft;
1146
+ currentAuthor = this.pickNextAuthor(currentAuthor, critiques, pool, r);
1147
+ currentDraft = await runRevise({
1148
+ subject: config.subject,
1149
+ format,
1150
+ previous: previousDraft,
1151
+ critiques,
1152
+ author: currentAuthor,
1153
+ minDraftLength,
1154
+ signal,
1155
+ onProgress: config.onProgress
1156
+ });
1157
+ }
1158
+ return this.finalize(rounds, "max_rounds", start);
1159
+ }
1160
+ /** Critics for a given round = pool minus current author (so author isn't critiquing self). */
1161
+ criticsForRound(_round) {
1162
+ return this.config.critics;
1163
+ }
1164
+ checkConvergence(args) {
1165
+ if (this.config.convergenceStrategy && this.config.convergenceStrategy !== "default") {
1166
+ const stop = this.config.convergenceStrategy(args);
1167
+ const blockerCount = args.critiques.filter((c) => c.severity === "blocker").length;
1168
+ const majorCount = args.critiques.filter((c) => c.severity === "major").length;
1169
+ const diffFromPrevious = args.previousDraft ? diffRatio(args.previousDraft.content, args.draft.content) : 1;
1170
+ return {
1171
+ blockerCount,
1172
+ majorCount,
1173
+ totalCritiques: args.critiques.length,
1174
+ diffFromPrevious,
1175
+ shouldStop: stop,
1176
+ reason: stop ? "all_minor_or_praise" : "running"
1177
+ };
1178
+ }
1179
+ return defaultConvergence(args);
1180
+ }
1181
+ pickNextAuthor(current, critiques, pool, round) {
1182
+ const policy = this.config.authorRotation ?? "fixed";
1183
+ if (policy === "fixed") return this.config.author;
1184
+ if (policy === "round-robin") {
1185
+ const idx = round % pool.length;
1186
+ return pool[idx];
1187
+ }
1188
+ if (policy === "best-critic") {
1189
+ const sevWeight = {
1190
+ blocker: 5,
1191
+ major: 3,
1192
+ minor: 1,
1193
+ nit: 0.5,
1194
+ praise: 0
1195
+ };
1196
+ const scores = /* @__PURE__ */ new Map();
1197
+ for (const c of critiques) {
1198
+ scores.set(c.critic, (scores.get(c.critic) ?? 0) + (sevWeight[c.severity] ?? 0));
1199
+ }
1200
+ let best = current.name;
1201
+ let bestScore = -1;
1202
+ for (const [name, score] of scores) {
1203
+ if (score > bestScore) {
1204
+ bestScore = score;
1205
+ best = name;
1206
+ }
1207
+ }
1208
+ const winner = pool.find((p) => p.name === best);
1209
+ return winner ?? current;
1210
+ }
1211
+ return current;
1212
+ }
1213
+ finalize(rounds, stoppedAt, start) {
1214
+ const finalDraft = rounds.at(-1).draft;
1215
+ const result = {
1216
+ subject: this.config.subject,
1217
+ format: this.config.format,
1218
+ rounds,
1219
+ finalDraft,
1220
+ stoppedAt,
1221
+ durationMs: Date.now() - start
1222
+ };
1223
+ this.config.onProgress?.({
1224
+ type: "iterate_complete",
1225
+ data: {
1226
+ stoppedAt,
1227
+ rounds: rounds.length,
1228
+ finalLength: finalDraft.content.length
1229
+ }
1230
+ });
1231
+ logger.info("arena.iterate.complete", {
1232
+ stoppedAt,
1233
+ rounds: rounds.length,
1234
+ finalVersion: finalDraft.version,
1235
+ finalLength: finalDraft.content.length
1236
+ });
1237
+ return result;
1238
+ }
1239
+ };
1240
+
1241
+ export {
1242
+ webSearchToolDef,
1243
+ webSearchTool,
1244
+ webFetchToolDef,
1245
+ webFetchTool,
1246
+ diffRatio,
1247
+ defaultConvergence,
1248
+ codeFormat,
1249
+ documentFormat,
1250
+ getFormat,
1251
+ IterativeArena
1252
+ };