odant-work 1.0.42 → 1.0.44

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 (367) hide show
  1. package/#system/certs/russian_trusted_root_ca.pem +32 -32
  2. package/#system/mail.json.example +9 -9
  3. package/#system/package-manifest.json +30 -30
  4. package/#system/settings.json.example +3 -3
  5. package/$server/$folder/$class/$device/class.js +2 -2
  6. package/$server/$folder/$class/$domain/class.js +4 -4
  7. package/$server/$folder/$class/$domain/readme.md +5 -5
  8. package/$server/$folder/$class/$handler/$task/class.js +2 -2
  9. package/$server/$folder/$class/$handler/$trigger/class.js +3 -3
  10. package/$server/$folder/$class/$handler/class.js +9 -9
  11. package/$server/$folder/$class/$handler/handlers/pages/editor/$handler/class.js +5 -5
  12. package/$server/$folder/$class/$handler/readme.md +23 -23
  13. package/$server/$folder/$class/$service/$class/$service/class.js +3 -3
  14. package/$server/$folder/$class/$structure/$base/class.js +9 -9
  15. package/$server/$folder/$class/$structure/$user/class.js +2 -2
  16. package/$server/$folder/$class/$structure/handlers/pages/explorer/$handler/class.js +4 -4
  17. package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/readme.md +40 -40
  18. package/$server/$folder/$class/$structure/handlers/pages/form/database/$handler/database.js +18 -43
  19. package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/search.js +21 -26
  20. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/readme.md +34 -34
  21. package/$server/$folder/$class/ai/config.js +19 -19
  22. package/$server/$folder/$class/ai/prompt/$method/class.js +41 -41
  23. package/$server/$folder/$class/ai/skills/approval-flow.md +14 -14
  24. package/$server/$folder/$class/ai/skills/backup-check.md +13 -13
  25. package/$server/$folder/$class/ai/skills/computer.md +27 -27
  26. package/$server/$folder/$class/ai/skills/delegate-task.md +15 -15
  27. package/$server/$folder/$class/ai/skills/external-signup.md +14 -14
  28. package/$server/$folder/$class/ai/skills/lan-inventory.md +16 -16
  29. package/$server/$folder/$class/ai/skills/onboarding.md +15 -15
  30. package/$server/$folder/$class/ai/skills/orchestration.md +41 -41
  31. package/$server/$folder/$class/handlers/pages/form/builder/$handler/builder.js +259 -259
  32. package/$server/$folder/$class/handlers/pages/form/editor/$handler/editor.js +19 -19
  33. package/$server/$folder/$class/handlers/pages/form/objects/$handler/objects.js +1 -1
  34. package/$server/$folder/$class/handlers/pages/storage/$handler/storage.js +20 -20
  35. package/$server/$folder/$file/$audio/handlers/preview/$handler/class.js +3 -3
  36. package/$server/$folder/$file/$audio/handlers/preview/$handler/preview.js +88 -88
  37. package/$server/$folder/$file/$call/class.js +10 -10
  38. package/$server/$folder/$file/$call/handlers/preview/$handler/class.js +4 -4
  39. package/$server/$folder/$file/$call/triggers/on_save/$trigger/class.js +48 -48
  40. package/$server/$folder/$file/$data/class.js +16 -16
  41. package/$server/$folder/$file/$data/handlers/pages/form/editor/$handler/class.js +5 -5
  42. package/$server/$folder/$file/$data/handlers/pages/form/editor/$handler/editor.js +26 -26
  43. package/$server/$folder/$file/$devs/$js/class.js +2 -2
  44. package/$server/$folder/$file/$devs/$json/class.js +2 -2
  45. package/$server/$folder/$file/$devs/$ts/class.js +2 -2
  46. package/$server/$folder/$file/$devs/handlers/pages/form/file/$handler/class.js +3 -3
  47. package/$server/$folder/$file/$devs/handlers/pages/form/file/$handler/file.js +30 -30
  48. package/$server/$folder/$file/$eml/class.js +17 -17
  49. package/$server/$folder/$file/$eml/triggers/on_save/$trigger/class.js +97 -97
  50. package/$server/$folder/$file/$ics/class.js +44 -44
  51. package/$server/$folder/$file/$ics/handlers/pages/form/file/$handler/class.js +3 -3
  52. package/$server/$folder/$file/$ics/handlers/pages/form/file/$handler/file.js +10 -10
  53. package/$server/$folder/$file/$ics/handlers/preview/$handler/class.js +3 -3
  54. package/$server/$folder/$file/$ics/handlers/preview/$handler/preview.js +67 -67
  55. package/$server/$folder/$file/$ics/readme.md +21 -21
  56. package/$server/$folder/$file/$image/$svg/class.js +11 -11
  57. package/$server/$folder/$file/$image/handlers/preview/$handler/class.js +3 -3
  58. package/$server/$folder/$file/$image/handlers/preview/$handler/preview.js +33 -33
  59. package/$server/$folder/$file/$ipynb/handlers/pages/form/file/$handler/class.js +3 -3
  60. package/$server/$folder/$file/$logs/class.js +39 -39
  61. package/$server/$folder/$file/$logs/handlers/methods/txt-test/$handler/class.js +4 -4
  62. package/$server/$folder/$file/$md/handlers/pages/form/file/$handler/class.js +3 -3
  63. package/$server/$folder/$file/$md/handlers/pages/form/file/$handler/file.js +63 -63
  64. package/$server/$folder/$file/$office/$outlook/$ics/class.js +227 -227
  65. package/$server/$folder/$file/$office/$word/$rtf/template.rtf +159 -159
  66. package/$server/$folder/$file/$office/handlers/pages/form/file/$handler/file.js +16 -8
  67. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +17 -26
  68. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/voice-ui.js +94 -94
  69. package/$server/$folder/$file/$task/handlers/preview/$handler/class.js +3 -3
  70. package/$server/$folder/$file/$task/progress.md +20 -20
  71. package/$server/$folder/$file/$task/readme.md +32 -32
  72. package/$server/$folder/$file/$txt/handlers/preview/$handler/class.js +3 -3
  73. package/$server/$folder/$file/$txt/handlers/preview/$handler/preview.js +41 -41
  74. package/$server/$folder/$file/$video/handlers/preview/$handler/class.js +4 -4
  75. package/$server/$folder/$file/$video/handlers/preview/$handler/preview.js +13 -13
  76. package/$server/$folder/$file/class.js +2 -2
  77. package/$server/$folder/$file/handlers/methods/download/$handler/class.js +2 -2
  78. package/$server/$folder/$file/handlers/methods/download/$handler/download.js +4 -4
  79. package/$server/$folder/$file/handlers/pages/form/$handler/class.js +2 -2
  80. package/$server/$folder/$file/handlers/pages/form/file/$handler/class.js +3 -3
  81. package/$server/$folder/$file/handlers/pages/form/file/$handler/file.js +28 -28
  82. package/$server/$folder/$file/readme.md +31 -31
  83. package/$server/$folder/class.js +11 -11
  84. package/$server/$folder/handlers/methods/create/progress.md +15 -15
  85. package/$server/$folder/handlers/pages/form/$handler/class.js +5 -5
  86. package/$server/$folder/handlers/pages/form/$handler/form.js +199 -129
  87. package/$server/$folder/handlers/readme.md +24 -24
  88. package/$server/$folder/lib/calendar-form/calendar-form.js +296 -296
  89. package/$server/$folder/lib/dialogs/confirm/confirm.js +30 -30
  90. package/$server/$folder/lib/dialogs/input/input.js +57 -57
  91. package/$server/$folder/lib/email/settings.js +82 -82
  92. package/$server/$folder/lib/explorer/explorer.js +104 -11
  93. package/$server/$folder/lib/file-viewer/file-viewer.js +8 -8
  94. package/$server/$folder/lib/icon/user/user.js +6 -6
  95. package/$server/$folder/lib/item-data-grid/item-data-grid.js +48 -48
  96. package/$server/$folder/lib/item-form/item-form.js +84 -84
  97. package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +17 -37
  98. package/$server/$folder/lib/menu/progress.md +13 -13
  99. package/$server/$folder/lib/menu/readme.md +29 -29
  100. package/$server/$folder/lib/node/progress.md +13 -13
  101. package/$server/$folder/lib/node/readme.md +29 -29
  102. package/$server/$folder/lib/pack/pack.js +4 -4
  103. package/$server/$folder/lib/prompt-bar/progress.md +13 -13
  104. package/$server/$folder/lib/security/admin/admin.js +30 -30
  105. package/$server/$folder/lib/site-loc/readme.md +16 -16
  106. package/$server/$folder/lib/site-loc/site-loc.js +80 -80
  107. package/$server/$folder/lib/tools/tools.js +24 -6
  108. package/$server/$folder/lib/tree/progress.md +16 -16
  109. package/$server/$folder/readme.md +18 -18
  110. package/$server/readme.md +13 -13
  111. package/.cursor/rules/work.mdc +8 -8
  112. package/.github/workflows/ci.yml +39 -39
  113. package/MODELS/$ai/$folder/$class/$ai/class.js +18 -8
  114. package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +70 -219
  115. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +19 -41
  116. package/MODELS/$ai/$folder/$class/$provider/readme.md +16 -16
  117. package/MODELS/GigaChat/$provider/readme.md +24 -24
  118. package/MODULES/Register/$module/$folder/$class/$register/class.js +4 -4
  119. package/MODULES/Register/$module/$folder/$class/$struct/class.js +4 -4
  120. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/$virtual/class.js +14 -14
  121. package/MODULES/Register/CATALOGS//320/241/321/203/320/261/321/212/320/265/320/272/321/202/321/213//320/244/320/270/320/267. /320/273/320/270/321/206/320/260/$catalog/class.js" +11 -11
  122. package/MODULES/Register/OPERATIONS//320/240/320/265/320/260/320/273/320/270/320/267/320/260/321/206/320/270/321/217//320/237/320/276/320/272/321/203/320/277/320/260/321/202/320/265/320/273/321/216/$operation/print//320/241/321/207/321/221/321/202 /320/275/320/260 /320/276/320/277/320/273/320/260/321/202/321/203.html" +40 -40
  123. package/MODULES/Register/OPERATIONS//320/240/320/265/320/260/320/273/320/270/320/267/320/260/321/206/320/270/321/217//320/237/320/276/320/272/321/203/320/277/320/260/321/202/320/265/320/273/321/216/$operation/print//320/242/320/276/320/262/320/260/321/200/320/275/320/260/321/217 /320/275/320/260/320/272/320/273/320/260/320/264/320/275/320/260/321/217.html" +56 -56
  124. package/MODULES/Register/REGISTER/$register/$folder/$class/$account/class.js +18 -18
  125. package/MODULES/Register/REGISTER/$register/$folder/$class/$register/class.js +11 -11
  126. package/MODULES/Register/REGISTER/68/01/$account/class.js +1 -1
  127. package/MODULES/Register/REGISTER/68/02/$account/class.js +1 -1
  128. package/MODULES/Register/REGISTER//320/232/320/260/320/264/321/200/320/276/320/262/321/213/320/271 /321/200/320/265/320/267/320/265/321/200/320/262/$account/class.js" +1 -1
  129. package/MODULES/Register/REGISTER//320/232/320/260/320/264/321/200/321/213//320/222 /320/276/321/202/320/277/321/203/321/201/320/272/320/265/$account/class.js" +1 -1
  130. package/MODULES/Register/REGISTER//320/232/320/260/320/264/321/200/321/213//320/240/320/260/320/261/320/276/321/202/320/260/321/216/321/202/$account/class.js +1 -1
  131. package/MODULES/Register/REGISTER//320/242/320/265/321/205/320/275/320/270/321/207/320/265/321/201/320/272/320/270/320/271/$account/class.js +1 -1
  132. package/MODULES/Register/STRUCTS/$struct/$folder/$class/$struct/class.js +4 -4
  133. package/MODULES/Register/STRUCTS/$struct/class.js +4 -4
  134. package/MODULES/Register/STRUCTS//320/220/320/264/321/200/320/265/321/201/$struct/class.js +11 -11
  135. package/MODULES/Register/STRUCTS//320/225/320/264/320/270/320/275/320/270/321/206/320/260 /320/270/320/267/320/274/320/265/321/200/320/265/320/275/320/270/321/217/$struct/class.js" +11 -11
  136. package/MODULES/Register/STRUCTS//320/237/320/260/321/201/320/277/320/276/321/200/321/202/$struct/class.js +11 -11
  137. package/NODES/$node/$folder/$class/$node/class.js +35 -35
  138. package/NODES/$node/class.js +5 -5
  139. package/NODES/$node/handlers/pages/form/network/$handler/class.js +5 -5
  140. package/NODES/$node/handlers/pages/form/network/$handler/network.js +110 -110
  141. package/NODES/teewtew/$node/class.js +2 -2
  142. package/NODES/work.odant.org/$node/class.js +3 -3
  143. package/ORGANIZATIONS/$domain/$folder/$class/$base/$folder/$class/$structure/$base/class.js +17 -17
  144. package/ORGANIZATIONS/$domain/$folder/$class/$base/class.js +4 -4
  145. package/SERVICES/$service/$folder/$storage/$service/class.js +8 -8
  146. package/SERVICES/$service/$folder/$storage/$service/handlers/pages/form/mcp/$handler/mcp.js +18 -43
  147. package/SERVICES/ArgoCD/$service/$folder/$class/$service/class.js +356 -356
  148. package/SERVICES/ArgoCD/$service/$folder/$class/$service/handlers/pages/form/orders/$handler/class.js +244 -244
  149. package/SERVICES/ArgoCD/$service/class.js +4 -4
  150. package/SERVICES/ArgoCD/$service/readme.md +63 -63
  151. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/class.js +10 -10
  152. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/checkDomain/$method/class.js +33 -33
  153. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/provision/$method/class.js +225 -225
  154. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/submitOrder/$method/class.js +77 -77
  155. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/readme.md +33 -33
  156. package/SERVICES/ArgoCD/PaaS/$service/class.js +347 -347
  157. package/SERVICES/ArgoCD/PaaS/$service/order/pass.order +8 -8
  158. package/SERVICES/DuckDuckGo/$service/class.js +367 -367
  159. package/SERVICES/SearXNG/$service/class.js +70 -70
  160. package/SERVICES/Telegram/$service/class.js +114 -114
  161. package/SERVICES/Weather/$service/class.js +76 -76
  162. package/SERVICES/Yandex/$service/class.js +120 -120
  163. package/SERVICES/readme.md +43 -43
  164. package/USERS/$users/class.js +2 -2
  165. package/eslint.config.js +51 -51
  166. package/jsconfig.json +37 -37
  167. package/oda/benchmarks/dbmon/lib/ENV.js +213 -213
  168. package/oda/benchmarks/dbmon/lib/ga.js +11 -11
  169. package/oda/benchmarks/dbmon/lib/memory-stats.js +105 -105
  170. package/oda/benchmarks/dbmon/lib/monitor.js +69 -69
  171. package/oda/benchmarks/sierpinski/sierpinski.js +149 -149
  172. package/oda/components/editors/code-editor/code-editor.js +387 -387
  173. package/oda/components/editors/code-editor/src/ace.js +16 -16
  174. package/oda/components/editors/code-editor/src/beautify-css.js +1625 -1625
  175. package/oda/components/editors/code-editor/src/beautify-html.js +3122 -3122
  176. package/oda/components/editors/code-editor/src/beautify.js +4005 -4005
  177. package/oda/components/editors/code-editor/src/ext-beautify.js +7 -7
  178. package/oda/components/editors/code-editor/src/ext-code_lens.js +7 -7
  179. package/oda/components/editors/code-editor/src/ext-elastic_tabstops_lite.js +7 -7
  180. package/oda/components/editors/code-editor/src/ext-emmet.js +7 -7
  181. package/oda/components/editors/code-editor/src/ext-error_marker.js +7 -7
  182. package/oda/components/editors/code-editor/src/ext-hardwrap.js +7 -7
  183. package/oda/components/editors/code-editor/src/ext-keybinding_menu.js +7 -7
  184. package/oda/components/editors/code-editor/src/ext-language_tools.js +7 -7
  185. package/oda/components/editors/code-editor/src/ext-linking.js +7 -7
  186. package/oda/components/editors/code-editor/src/ext-modelist.js +7 -7
  187. package/oda/components/editors/code-editor/src/ext-options.js +7 -7
  188. package/oda/components/editors/code-editor/src/ext-prompt.js +7 -7
  189. package/oda/components/editors/code-editor/src/ext-rtl.js +7 -7
  190. package/oda/components/editors/code-editor/src/ext-searchbox.js +7 -7
  191. package/oda/components/editors/code-editor/src/ext-settings_menu.js +7 -7
  192. package/oda/components/editors/code-editor/src/ext-spellcheck.js +7 -7
  193. package/oda/components/editors/code-editor/src/ext-split.js +7 -7
  194. package/oda/components/editors/code-editor/src/ext-static_highlight.js +7 -7
  195. package/oda/components/editors/code-editor/src/ext-statusbar.js +7 -7
  196. package/oda/components/editors/code-editor/src/ext-textarea.js +7 -7
  197. package/oda/components/editors/code-editor/src/ext-themelist.js +7 -7
  198. package/oda/components/editors/code-editor/src/ext-whitespace.js +7 -7
  199. package/oda/components/editors/code-editor/src/keybinding-emacs.js +7 -7
  200. package/oda/components/editors/code-editor/src/keybinding-sublime.js +7 -7
  201. package/oda/components/editors/code-editor/src/keybinding-vim.js +7 -7
  202. package/oda/components/editors/code-editor/src/keybinding-vscode.js +7 -7
  203. package/oda/components/editors/code-editor/src/mode-css.js +7 -7
  204. package/oda/components/editors/code-editor/src/mode-html.js +7 -7
  205. package/oda/components/editors/code-editor/src/mode-javascript.js +7 -7
  206. package/oda/components/editors/code-editor/src/mode-json.js +7 -7
  207. package/oda/components/editors/code-editor/src/mode-markdown.js +7 -7
  208. package/oda/components/editors/code-editor/src/mode-svg.js +7 -7
  209. package/oda/components/editors/code-editor/src/mode-text.js +7 -7
  210. package/oda/components/editors/code-editor/src/mode-xml.js +7 -7
  211. package/oda/components/editors/code-editor/src/mode-xquery.js +7 -7
  212. package/oda/components/editors/code-editor/src/snippets/css.js +7 -7
  213. package/oda/components/editors/code-editor/src/snippets/html.js +7 -7
  214. package/oda/components/editors/code-editor/src/snippets/javascript.js +7 -7
  215. package/oda/components/editors/code-editor/src/snippets/json.js +7 -7
  216. package/oda/components/editors/code-editor/src/snippets/markdown.js +7 -7
  217. package/oda/components/editors/code-editor/src/snippets/svg.js +7 -7
  218. package/oda/components/editors/code-editor/src/snippets/text.js +7 -7
  219. package/oda/components/editors/code-editor/src/snippets/xml.js +7 -7
  220. package/oda/components/editors/code-editor/src/snippets/xquery.js +7 -7
  221. package/oda/components/editors/code-editor/src/theme-solarized_dark.js +7 -7
  222. package/oda/components/editors/code-editor/src/theme-solarized_light.js +7 -7
  223. package/oda/components/editors/markdown/markdown-editor/lib/font-awesome.min.css +3 -3
  224. package/oda/components/editors/markdown/markdown-editor/lib/readme.md +332 -332
  225. package/oda/components/editors/markdown/markdown-editor/markdown-editor.js +78 -78
  226. package/oda/components/editors/markdown/markdown-viewer/test.md +239 -239
  227. package/oda/components/editors/markdown/markdown.js +76 -76
  228. package/oda/components/inputs/block/readme.md +39 -39
  229. package/oda/components/inputs/checkbox/checkbox.js +92 -92
  230. package/oda/components/inputs/color/color.js +83 -83
  231. package/oda/components/inputs/date/date.js +40 -40
  232. package/oda/components/inputs/input/input.js +219 -219
  233. package/oda/components/inputs/link/readme.md +42 -42
  234. package/oda/components/inputs/markdown-input/markdown-input.js +77 -77
  235. package/oda/components/inputs/numeric/numeric.js +141 -141
  236. package/oda/components/inputs/table-input/readme.md +39 -39
  237. package/oda/components/inputs/text/text.js +88 -88
  238. package/oda/components/inputs/toggle/toggle.js +101 -101
  239. package/oda/components/layouts/app-layout/app-layout.js +4 -1
  240. package/oda/components/layouts/hexagon-layout/hexagon-layout.js +218 -218
  241. package/oda/components/layouts/tabs/tabs.js +784 -395
  242. package/oda/components/menus/menu/index_old.html +140 -140
  243. package/oda/components/menus/menu/menu.js +238 -238
  244. package/oda/components/packets/packets.js +25 -20
  245. package/oda/components/structure/controls-map.js +56 -56
  246. package/oda/components/structure/controls.js +29 -29
  247. package/oda/components/structure/readme.md +31 -31
  248. package/oda/components/structure/structure.js +64 -64
  249. package/oda/components/table/index.html +210 -210
  250. package/oda/components/table/lib/coerce.js +68 -68
  251. package/oda/components/table/lib/column.js +568 -568
  252. package/oda/components/table/readme.md +120 -120
  253. package/oda/components/table/router.js +86 -86
  254. package/oda/components/table/row.js +6 -4
  255. package/oda/components/table/settings.js +89 -89
  256. package/oda/components/table/table.js +2 -2
  257. package/oda/index.html +159 -159
  258. package/oda/tools/icons/icons-set/icons-set.js +60 -60
  259. package/oda/tools/icons/lib/svg/_makeSVG.html +41 -41
  260. package/oda/tools/icons/lib/svg/aws.svg +2679 -2679
  261. package/oda/tools/icons/lib/svg/info.json +46 -46
  262. package/oda/tools/jupyter/demo.ipynb +160 -160
  263. package/oda/tools/jupyter/lib/print_elements.js +73 -73
  264. package/oda/tools/jupyter/test-2.ipynb +305 -305
  265. package/oda/tools/jupyter/test.ipynb +603 -603
  266. package/oda/tools/styles/adoptedStyleSheets.js +333 -333
  267. package/oda/tools/tester/device-preview/devices.json +9 -9
  268. package/opencode.json +9 -9
  269. package/package.json +1 -1
  270. package/publish.cmd +2 -2
  271. package/readme.md +164 -164
  272. package/rules/rules.md +445 -445
  273. package/scripts/SYNC-README.md +107 -107
  274. package/scripts/agent-eval.mjs +223 -223
  275. package/scripts/dump-svn-chat.mjs +9 -9
  276. package/scripts/extract-chat-day.mjs +21 -21
  277. package/scripts/rag-bench.mjs +166 -166
  278. package/scripts/restore-chat.mjs +166 -166
  279. package/scripts/sync-svn-git.bat +129 -129
  280. package/scripts/test-merge.mjs +75 -75
  281. package/scripts/work-desktop-bridge.mjs +101 -101
  282. package/sources/client/field.js +168 -168
  283. package/sources/client/index.js +32 -32
  284. package/sources/client/readme.md +16 -16
  285. package/sources/core.js +91 -91
  286. package/sources/data/choices.js +125 -125
  287. package/sources/data/progress.md +13 -0
  288. package/sources/host/auto-updater.js +12 -1
  289. package/sources/host/babel-merge.js +353 -353
  290. package/sources/host/config.js +48 -48
  291. package/sources/host/email-utils.js +269 -269
  292. package/sources/host/http-server.js +1 -1
  293. package/sources/host/index-db.js +94 -94
  294. package/sources/host/net-guard.js +228 -228
  295. package/sources/host/package-install.js +63 -63
  296. package/sources/host/progress.md +14 -14
  297. package/sources/host/push.js +86 -86
  298. package/sources/host/readme.md +41 -41
  299. package/sources/host/secret-box.js +93 -93
  300. package/sources/host/server-id.js +26 -26
  301. package/sources/host/stun.js +33 -33
  302. package/sources/host/tls-ca.js +60 -60
  303. package/sources/host/vapid.js +14 -14
  304. package/sources/index.html +49 -49
  305. package/sources/manifest.json +49 -49
  306. package/sources/modules/a2a/server.js +608 -608
  307. package/sources/modules/agent/connections.js +442 -442
  308. package/sources/modules/agent/diff.js +69 -69
  309. package/sources/modules/agent/eval.js +222 -222
  310. package/sources/modules/agent/hooks.js +131 -131
  311. package/sources/modules/agent/log.js +43 -43
  312. package/sources/modules/agent/mcp-pool.js +253 -253
  313. package/sources/modules/agent/plugins.js +343 -343
  314. package/sources/modules/agent/recovery.js +89 -89
  315. package/sources/modules/agent/taint.js +100 -100
  316. package/sources/modules/agent/tools/branch.js +311 -311
  317. package/sources/modules/agent/tools/browser.js +254 -254
  318. package/sources/modules/agent/tools/computer.js +120 -120
  319. package/sources/modules/agent/tools/connect.js +316 -316
  320. package/sources/modules/agent/tools/dev/lsp.js +334 -334
  321. package/sources/modules/agent/tools/dev/patch.js +564 -564
  322. package/sources/modules/agent/tools/memory.js +153 -153
  323. package/sources/modules/agent/tools/os-files.js +358 -358
  324. package/sources/modules/agent/tools/plugins.js +80 -80
  325. package/sources/modules/agent/tools/sandbox.js +268 -268
  326. package/sources/modules/agent/types.d.ts +183 -183
  327. package/sources/modules/agent/undo.js +254 -254
  328. package/sources/modules/agent/util.js +179 -179
  329. package/sources/modules/contacts/contacts.js +200 -200
  330. package/sources/modules/contacts/index.html +546 -546
  331. package/sources/modules/lan/discovery.js +192 -192
  332. package/sources/modules/lan/store.js +62 -62
  333. package/sources/modules/mcp/readme.md +70 -70
  334. package/sources/modules/mcp/server.js +525 -525
  335. package/sources/modules/mcp/tokens.js +140 -140
  336. package/sources/modules/nodes/identity.js +123 -123
  337. package/sources/modules/nodes/inbound.js +172 -172
  338. package/sources/modules/nodes/outbound.js +105 -105
  339. package/sources/modules/nodes/signing.js +71 -71
  340. package/sources/modules/rag/embed-worker.js +36 -36
  341. package/sources/modules/rag/readme.md +70 -70
  342. package/sources/modules/readme.md +21 -21
  343. package/sources/modules/sandbox/config.js +74 -74
  344. package/sources/modules/sandbox/driver.js +100 -100
  345. package/sources/modules/sandbox/images/work-computer/Dockerfile +34 -34
  346. package/sources/modules/sandbox/images/work-computer/entrypoint.sh +24 -24
  347. package/sources/modules/sandbox/manager.js +1089 -1089
  348. package/sources/modules/sandbox/readme.md +63 -63
  349. package/sources/modules/sandbox/vnc-proxy.js +296 -296
  350. package/sources/modules/trainer/halogen.js +354 -100
  351. package/sources/modules/trainer/huggingface.js +28 -2
  352. package/sources/modules/trainer/index.js +70 -9
  353. package/sources/modules/trainer/local-engine.js +400 -167
  354. package/sources/modules/trainer/worker/local_infer_worker.py +164 -21
  355. package/sources/readme.md +216 -216
  356. package/sources/server/access/audit.js +138 -138
  357. package/sources/server/access/refs.js +106 -106
  358. package/sources/server/assert-class-id.js +23 -23
  359. package/sources/server/external-source.js +90 -90
  360. package/sources/server/index.js +12 -12
  361. package/sources/server/memory-mark.js +34 -34
  362. package/sources/server/readme.md +110 -110
  363. package/sources/server/safe-node-name.js +67 -67
  364. package/sources/server/upload-mark.js +24 -24
  365. package/sources/server/zip-guard.js +81 -81
  366. package/sources/tester.html +54 -54
  367. package/whitepaper.md +568 -568
@@ -1,564 +1,564 @@
1
- /**
2
- * Инструменты разработчика (этап 6.3): apply_patch — многофайловый патч одним вызовом.
3
- *
4
- * Формат `*** Begin Patch` (Add/Update/Delete/Move File, ханки с контекстом — как у Codex CLI,
5
- * модели его знают). Атомарно: сначала проверяются ВСЕ куски патча против текущего содержимого
6
- * (несовпадение/неоднозначность — отказ, ничего не записано), затем запись.
7
- *
8
- * Арены (архитектура 6.1, инварианты 11–12 в rules/threats.md):
9
- * work — каждый файл через ядро: история (снимок при записи), `entry.undoList` на файл
10
- * (undo.js collectUndo), права роли при записи, файлы памяти ai/memory.md — отказ;
11
- * частичный сбой записи — откат уже записанных из журнала (всё или ничего);
12
- * sandbox — docker exec: чтение/вычисление без записи, затем коммит во временный файл + mv,
13
- * оригиналы хранятся в .ap-bak до конца вызова, сбой — восстановление из баков.
14
- *
15
- * Лимиты: ≤50 файлов, ≤1 МБ на файл, ≤4 МБ текста патча.
16
- */
17
- import { log } from '../../log.js';
18
- import { mustItem, callAs, absPath, fileAt, writeFile, realPathOf } from '../work/common.js';
19
- import { assertNotMemory } from '../work/fs.js';
20
- import { beforeWrite, recordWrite, recordDelete } from '../../undo.js';
21
- import { lineDiff } from '../../diff.js';
22
- import { ctxRun } from '../sandbox.js';
23
- import { useSandbox, markSandboxTaint } from './search.js';
24
- import { assertSandboxPath, execRaw, readText, writeText } from '../../../sandbox/manager.js';
25
- import { FS } from '../../../../server/index.js';
26
-
27
- const OPS_MAX = 50; // файлов в одном патче
28
- const FILE_MAX = 1024 * 1024; // размер файла/итогового содержимого
29
- const PATCH_MAX = 4 * 1024 * 1024; // размер текста патча
30
- const SBX_CMD_SEC = 30; // потолок cp/mv/rm в песочнице
31
-
32
- // ── разбор патча ─────────────────────────────────────────────────────────────
33
-
34
- const HEAD_RE = /^\*\*\* (Add|Update|Delete|Move)(?: File)?:[ \t]*(.+)$/;
35
- const MOVE_TO_RE = /^\*\*\* Move to:[ \t]*(.+)$/;
36
- const HUNK_LINE_RE = /^[ +-]/;
37
-
38
- /**
39
- * Разбор текста патча → список операций.
40
- * @returns {Array<{kind:'add'|'update'|'delete'|'move', path:string, to?:string, content?:string[], hunks?:Array<{lines:Array<{k:string,v:string}>}>}>}
41
- */
42
- export function parsePatch(raw) {
43
- const text = String(raw ?? '');
44
- if (text.length > PATCH_MAX)
45
- throw new Error('apply_patch: патч больше ' + Math.round(PATCH_MAX / 1048576) + ' МБ');
46
- const lines = text.replace(/\r\n/g, '\n').split('\n');
47
- let begin = 0;
48
- while (begin < lines.length && !lines[begin].trim())
49
- begin++;
50
- if (lines[begin] !== '*** Begin Patch')
51
- throw new Error('apply_patch: первая строка должна быть «*** Begin Patch»');
52
- let end = -1;
53
- for (let j = lines.length - 1; j > begin; j--) {
54
- if (lines[j].trim() === '*** End Patch') {
55
- end = j;
56
- break;
57
- }
58
- }
59
- if (end < 0)
60
- throw new Error('apply_patch: нет строки «*** End Patch»');
61
- const ops = [];
62
- let cur = null;
63
- const section = (kind, path) => {
64
- if (ops.length >= OPS_MAX)
65
- throw new Error('apply_patch: больше ' + OPS_MAX + ' файлов в одном патче');
66
- cur = { kind, path: String(path).trim(), content: [], hunks: [] };
67
- ops.push(cur);
68
- return cur;
69
- };
70
- for (let i = begin + 1; i < end; i++) {
71
- const l = lines[i];
72
- if (l === '*** ')
73
- continue;
74
- const head = HEAD_RE.exec(l);
75
- if (head) {
76
- section(head[1].toLowerCase(), head[2]);
77
- continue;
78
- }
79
- const moveTo = MOVE_TO_RE.exec(l);
80
- if (moveTo) {
81
- if (!cur || cur.kind !== 'move' || cur.to)
82
- throw new Error('apply_patch: «*** Move to:» без «*** Move File:» (строка ' + (i + 1) + ')');
83
- cur.to = String(moveTo[1]).trim();
84
- continue;
85
- }
86
- if (l.startsWith('***'))
87
- throw new Error('apply_patch: неизвестная секция: ' + l.slice(0, 80) + ' (строка ' + (i + 1) + ')');
88
- if (!cur)
89
- throw new Error('apply_patch: строка до первой секции: ' + l.slice(0, 80));
90
- if (cur.kind === 'add') {
91
- // содержимое нового файла: каждая строка с «+» (пустая строка — пустая строка файла)
92
- if (l.startsWith('+'))
93
- cur.content.push(l.slice(1));
94
- else if (l === '')
95
- cur.content.push('');
96
- else
97
- throw new Error('apply_patch: Add File ' + cur.path + ': строка без «+»: ' + l.slice(0, 60));
98
- continue;
99
- }
100
- if (cur.kind === 'update') {
101
- if (l.startsWith('@@')) {
102
- cur.hunks.push({ lines: [] });
103
- continue;
104
- }
105
- if (HUNK_LINE_RE.test(l) || l === '') {
106
- if (!cur.hunks.length)
107
- cur.hunks.push({ lines: [] });
108
- const k = l === '' || l.startsWith(' ') ? ' ' : l.charAt(0);
109
- cur.hunks.at(-1).lines.push({ k, v: l === '' ? '' : l.slice(1) });
110
- continue;
111
- }
112
- throw new Error('apply_patch: Update File ' + cur.path + ': строка ханка не с « »/«-»/«+»: ' + l.slice(0, 60));
113
- }
114
- throw new Error('apply_patch: после ' + cur.kind + ' не должно быть строк: ' + l.slice(0, 60));
115
- }
116
- for (const op of ops) {
117
- if (op.kind === 'add' && op.content.join('\n').length > FILE_MAX)
118
- throw new Error('apply_patch: Add File ' + op.path + ' больше ' + Math.round(FILE_MAX / 1048576) + ' МБ');
119
- if (op.kind === 'update' && !op.hunks.length)
120
- throw new Error('apply_patch: Update File ' + op.path + ': нет ханков');
121
- if (op.kind === 'update')
122
- for (const h of op.hunks)
123
- if (!h.lines.some(x => x.k === ' ' || x.k === '-'))
124
- throw new Error('apply_patch: Update File ' + op.path + ': ханк без строк для замены (нет контекста и «-») — добавь контекст');
125
- if (op.kind === 'move' && !op.to)
126
- throw new Error('apply_patch: Move File ' + op.path + ': нет «*** Move to:»');
127
- }
128
- if (!ops.length)
129
- throw new Error('apply_patch: пустой патч (нет секций)');
130
- const seen = new Set();
131
- for (const op of ops) {
132
- for (const p of [op.path, op.to].filter(Boolean)) {
133
- const a = absPath(p, null);
134
- if (seen.has(a))
135
- throw new Error('apply_patch: файл ' + a + ' в патче дважды');
136
- seen.add(a);
137
- }
138
- }
139
- return ops;
140
- }
141
-
142
- /**
143
- * Применить ханки к тексту (точное построчное совпадение).
144
- * Фрагмент должен встречаться ровно один раз: не найден/неоднозначен — ошибка, ничего не меняется.
145
- */
146
- export function applyHunks(text, hunks, label) {
147
- const crlf = String(text).includes('\r\n');
148
- let ls = String(text).replace(/\r\n/g, '\n').split('\n');
149
- hunks.forEach((h, hi) => {
150
- const oldL = [], newL = [];
151
- for (const l of h.lines) {
152
- if (l.k === ' ') {
153
- oldL.push(l.v);
154
- newL.push(l.v);
155
- }
156
- else if (l.k === '-')
157
- oldL.push(l.v);
158
- else
159
- newL.push(l.v);
160
- }
161
- if (!oldL.length)
162
- throw new Error('apply_patch: ' + label + ': ханк ' + (hi + 1) + ' без строк для замены — добавь контекст');
163
- const oldS = oldL.join('\n');
164
- let idx = -1, hits = 0;
165
- for (let i = 0; i + oldL.length <= ls.length; i++) {
166
- if (ls[i] !== oldL[0])
167
- continue;
168
- if (ls.slice(i, i + oldL.length).join('\n') !== oldS)
169
- continue;
170
- hits++;
171
- idx = i;
172
- if (hits > 1)
173
- break;
174
- }
175
- if (!hits)
176
- throw new Error('apply_patch: ' + label + ': ханк ' + (hi + 1) + ' не найден (файл изменился?) — прочитай файл и поправь контекст');
177
- if (hits > 1)
178
- throw new Error('apply_patch: ' + label + ': ханк ' + (hi + 1) + ' встречается ' + hits + ' раз — добавь контекста для однозначности');
179
- ls.splice(idx, oldL.length, ...newL);
180
- });
181
- const out = ls.join('\n');
182
- return crlf ? out.replace(/\n/g, '\r\n') : out;
183
- }
184
-
185
- // ── арена work ──────────────────────────────────────────────────────────────
186
-
187
- /** Пометка внешнего источника снимается: файл целиком переписан своим текстом (как write). */
188
- async function unmarkExternalOf(path) {
189
- try {
190
- const { unmarkExternal } = await import('../../../../server/external-source.js');
191
- unmarkExternal(String(path || ''));
192
- }
193
- catch (e) { log.debug('dev.unmark', e); }
194
- }
195
-
196
- /** ФАЗА A (work): проверить каждый кусок против текущего содержимого, ничего не записывая. */
197
- async function planWork(ops, ctx) {
198
- const plans = [];
199
- for (const op of ops) {
200
- assertNotMemory(absPath(op.path, ctx));
201
- if (op.to)
202
- assertNotMemory(absPath(op.to, ctx));
203
- if (op.kind === 'add') {
204
- const ex = await fileAt(op.path, ctx);
205
- if (ex)
206
- throw new Error('apply_patch: Add File: файл уже есть — ' + ex.path + ' (используй Update File)');
207
- const content = op.content.length ? op.content.join('\n') + '\n' : '';
208
- plans.push({ op, kind: 'add', path: absPath(op.path, ctx), content });
209
- }
210
- else if (op.kind === 'update') {
211
- const item = await mustItem(op.path, ctx);
212
- if (Array.isArray(item) || isContainer(item))
213
- throw new Error('apply_patch: Update File: не файл — ' + absPath(op.path, ctx));
214
- const before = await callAs(item, 'load', { encoding: 'utf-8' }, ctx);
215
- if (typeof before !== 'string')
216
- throw new Error('apply_patch: Update File ' + item.path + ': файл не текстовый');
217
- const after = applyHunks(before, op.hunks, item.path);
218
- if (after.length > FILE_MAX)
219
- throw new Error('apply_patch: Update File ' + item.path + ': результат больше ' + Math.round(FILE_MAX / 1048576) + ' МБ');
220
- plans.push({ op, kind: 'update', path: item.path, item, before, after });
221
- }
222
- else if (op.kind === 'delete') {
223
- const item = await mustItem(op.path, ctx);
224
- if (Array.isArray(item) || isContainer(item))
225
- throw new Error('apply_patch: Delete File: не файл — ' + absPath(op.path, ctx));
226
- plans.push({ op, kind: 'delete', path: item.path, item });
227
- }
228
- else {
229
- const from = await mustItem(op.path, ctx);
230
- if (Array.isArray(from) || isContainer(from))
231
- throw new Error('apply_patch: Move File: не файл — ' + absPath(op.path, ctx));
232
- const ex = await fileAt(op.to, ctx);
233
- if (ex)
234
- throw new Error('apply_patch: Move File: файл уже есть — ' + ex.path);
235
- // без кодировки: Buffer для бинарного, строка — для текстового (file.js load)
236
- const buf = await callAs(from, 'load', {}, ctx);
237
- plans.push({ op, kind: 'move', path: from.path, to: absPath(op.to, ctx), item: from, content: buf });
238
- }
239
- }
240
- return plans;
241
- }
242
-
243
- function isContainer(item) {
244
- return !(item instanceof FS.$file);
245
- }
246
-
247
- /** Откат одного уже записанного плана (лучшее усилие; ошибки собирает вызывающий). */
248
- async function rollbackPlan(plan, ctx, sbx) {
249
- if (plan.kind === 'add') {
250
- const made = await fileAt(plan.real ?? plan.path, ctx);
251
- if (made)
252
- await callAs(made, 'delete', {}, ctx);
253
- }
254
- else if (plan.kind === 'update') {
255
- await callAs(await fileAt(plan.path, ctx) ?? plan.item, 'save', { post: plan.before, mainContext: ctx?.task?.path }, ctx);
256
- }
257
- else if (plan.kind === 'delete') {
258
- const pre = plan.pre;
259
- if (pre?.before?.snapshot) {
260
- const snap = await mustItem(pre.before.snapshot, ctx).catch(() => null);
261
- if (snap && !Array.isArray(snap))
262
- await callAs(snap, 'restore_from_history', {}, ctx);
263
- }
264
- else if (pre?.before?.text != null)
265
- await writeFile(plan.path, pre.before.text, ctx);
266
- else if (!sbx)
267
- throw new Error('прежняя версия ' + plan.path + ' не сохранена — восстанови из истории вручную');
268
- }
269
- else { // move: удалить новый, вернуть старый
270
- const made = await fileAt(plan.realTo ?? plan.to, ctx);
271
- if (made)
272
- await callAs(made, 'delete', {}, ctx);
273
- await writeFile(plan.path, plan.content, ctx);
274
- }
275
- }
276
-
277
- /** ФАЗА B (work): запись через ядро + журнал отката; частичный сбой — откат записанного. */
278
- async function commitWork(plans, ctx) {
279
- const journal = [];
280
- const undoList = [];
281
- const lines = [];
282
- const diffs = [];
283
- const one = () => ({});
284
- try {
285
- for (const plan of plans) {
286
- if (plan.kind === 'add') {
287
- const pre = await beforeWrite(await fileAt(plan.path, ctx));
288
- const wlog = await writeFile(plan.path, plan.content, ctx);
289
- const real = realPathOf(wlog, plan.path);
290
- plan.real = real;
291
- await unmarkExternalOf(real);
292
- const e = one();
293
- await recordWrite(e, { realItem: await fileAt(real, ctx), pre });
294
- if (e.undo)
295
- undoList.push(e.undo);
296
- journal.push(plan);
297
- lines.push('+ создан ' + real + ' (' + plan.content.length + ' символов)');
298
- diffs.push('## ' + real + '\n' + lineDiff('', plan.content).text);
299
- }
300
- else if (plan.kind === 'update') {
301
- const pre = await beforeWrite(plan.item);
302
- const saveParams = { post: plan.after };
303
- if (ctx?.task?.path)
304
- saveParams.mainContext = ctx.task.path;
305
- await callAs(plan.item, 'save', saveParams, ctx);
306
- await unmarkExternalOf(plan.path);
307
- const e = one();
308
- await recordWrite(e, { realItem: await fileAt(plan.path, ctx), pre });
309
- if (e.undo)
310
- undoList.push(e.undo);
311
- journal.push(plan);
312
- const d = lineDiff(plan.before, plan.after);
313
- lines.push('~ изменён ' + plan.path + ' (+' + d.added + ' −' + d.removed + ')');
314
- diffs.push('## ' + plan.path + '\n' + d.text);
315
- }
316
- else if (plan.kind === 'delete') {
317
- const pre = await beforeWrite(plan.item);
318
- await callAs(plan.item, 'delete', {}, ctx);
319
- plan.pre = pre;
320
- const e = one();
321
- recordDelete(e, { item: plan.item, pre });
322
- if (e.undo)
323
- undoList.push(e.undo);
324
- journal.push(plan);
325
- lines.push('− удалён ' + plan.path);
326
- diffs.push('## ' + plan.path + '\n' + lineDiff(plan.before ?? '', '').text);
327
- }
328
- else { // move: сначала новый файл, затем удаление старого — сбой не теряет файл
329
- // прежнее состояние СТАРОГО файла (для записи удаления); НОВОМУ — create (его не было)
330
- const preOld = await beforeWrite(plan.item);
331
- // writeFile принимает и строку, и Buffer; карточку не трогает (запись отката — своя, на файл)
332
- const wlog = await writeFile(plan.to, plan.content, ctx);
333
- const realTo = realPathOf(wlog, plan.to);
334
- plan.realTo = realTo;
335
- const eNew = one();
336
- await recordWrite(eNew, { realItem: await fileAt(realTo, ctx), pre: { known: false, before: null } });
337
- if (eNew.undo)
338
- undoList.push(eNew.undo);
339
- await callAs(plan.item, 'delete', {}, ctx);
340
- const eOld = one();
341
- recordDelete(eOld, { item: plan.item, pre: preOld });
342
- if (eOld.undo)
343
- undoList.push(eOld.undo);
344
- journal.push(plan);
345
- lines.push('→ перемещён ' + plan.path + ' → ' + realTo);
346
- diffs.push('## ' + plan.path + ' → ' + realTo + '\n(имя изменено, содержимое прежнее)');
347
- }
348
- }
349
- }
350
- catch (fail) {
351
- // всё или ничего: откат записанного в обратном порядке
352
- const restoreErrors = [];
353
- for (const plan of [...journal].reverse()) {
354
- try {
355
- await rollbackPlan(plan, ctx, false);
356
- }
357
- catch (e) {
358
- restoreErrors.push(String(e?.message || e).slice(0, 120));
359
- }
360
- }
361
- throw new Error('apply_patch: сбой на «' + (fail?.message || fail) + '» — записанное откачено'
362
- + (restoreErrors.length ? '; не удалось: ' + restoreErrors.join('; ') + ' — восстанови из истории вручную' : ''), { cause: fail });
363
- }
364
- return { lines, diffs, undoList };
365
- }
366
-
367
- async function workPatch(args, ctx) {
368
- const ops = parsePatch(args?.patch);
369
- const plans = await planWork(ops, ctx);
370
- const { lines, diffs, undoList } = await commitWork(plans, ctx);
371
- if (ctx.entry) {
372
- ctx.entry.path = plans[0].real ?? plans[0].realTo ?? plans[0].path;
373
- ctx.entry.diff = diffs.join('\n\n');
374
- if (undoList.length)
375
- ctx.entry.undoList = undoList;
376
- }
377
- return 'применён патч: ' + lines.length + ' файлов\n' + lines.join('\n');
378
- }
379
-
380
- // ── арена sandbox ───────────────────────────────────────────────────────────
381
-
382
- async function sbxCmd(docker, id, cmd) {
383
- const r = await execRaw(docker, id, { cmd, timeoutSec: SBX_CMD_SEC, maxBytes: 4096 });
384
- if (r.code !== 0)
385
- throw new Error('команда «' + cmd[0] + '» в песочнице: код ' + r.code + ' ' + String(r.stderr || '').trim().slice(0, 120));
386
- return r;
387
- }
388
-
389
- /** ФАЗА A (sandbox): чтение и вычисление без записи. */
390
- async function planSandbox(ops, docker, pc, cfg) {
391
- const plans = [];
392
- for (const op of ops) {
393
- const p = assertSandboxPath(op.path, cfg.workdir);
394
- const to = op.to ? assertSandboxPath(op.to, cfg.workdir) : null;
395
- if (op.kind === 'add') {
396
- const ex = await readText(docker, pc.id, p, cfg).then(() => true).catch(() => false);
397
- if (ex)
398
- throw new Error('apply_patch: Add File: файл уже есть — ' + p + ' (используй Update File)');
399
- plans.push({ op, kind: 'add', path: p, content: op.content.length ? op.content.join('\n') + '\n' : '' });
400
- }
401
- else if (op.kind === 'update') {
402
- let before;
403
- try {
404
- before = await readText(docker, pc.id, p, cfg);
405
- }
406
- catch {
407
- throw new Error('apply_patch: Update File: файл не найден — ' + p);
408
- }
409
- const after = applyHunks(before, op.hunks, p);
410
- plans.push({ op, kind: 'update', path: p, before, after });
411
- }
412
- else if (op.kind === 'delete') {
413
- const ex = await readText(docker, pc.id, p, cfg).then(() => true).catch(() => false);
414
- if (!ex)
415
- throw new Error('apply_patch: Delete File: файл не найден — ' + p);
416
- plans.push({ op, kind: 'delete', path: p });
417
- }
418
- else {
419
- let content;
420
- try {
421
- content = await readText(docker, pc.id, p, cfg);
422
- }
423
- catch {
424
- throw new Error('apply_patch: Move File: файл не найден — ' + p);
425
- }
426
- const ex = to && await readText(docker, pc.id, to, cfg).then(() => true).catch(() => false);
427
- if (ex)
428
- throw new Error('apply_patch: Move File: файл уже есть — ' + to);
429
- plans.push({ op, kind: 'move', path: p, to, content });
430
- }
431
- }
432
- return plans;
433
- }
434
-
435
- /** ФАЗА B (sandbox): баки → временный файл → mv; сбой — восстановление из баков. */
436
- async function commitSandbox(plans, docker, pc, cfg, ctx) {
437
- const baks = []; // { bak, orig }
438
- const tmps = []; // временные файлы (убрать при сбое)
439
- const lines = [];
440
- const diffs = [];
441
- const done = [];
442
- const tmp = p => p + '.ap-tmp';
443
- try {
444
- for (const plan of plans) {
445
- if (plan.kind === 'add') {
446
- const t = tmp(plan.path);
447
- await writeText(docker, pc.id, t, plan.content, cfg);
448
- tmps.push(t);
449
- await sbxCmd(docker, pc.id, ['mv', '--', t, plan.path]);
450
- done.push({ undo: async () => sbxCmd(docker, pc.id, ['rm', '--', plan.path]) });
451
- lines.push('+ создан ' + plan.path);
452
- diffs.push('## ' + plan.path + '\n' + lineDiff('', plan.content).text);
453
- }
454
- else if (plan.kind === 'update') {
455
- const bak = plan.path + '.ap-bak';
456
- await sbxCmd(docker, pc.id, ['cp', '--', plan.path, bak]);
457
- baks.push({ bak, orig: plan.path });
458
- const t = tmp(plan.path);
459
- await writeText(docker, pc.id, t, plan.after, cfg);
460
- tmps.push(t);
461
- await sbxCmd(docker, pc.id, ['mv', '--', t, plan.path]);
462
- done.push({ undo: async () => sbxCmd(docker, pc.id, ['mv', '--', bak, plan.path]) });
463
- const d = lineDiff(plan.before, plan.after);
464
- lines.push('~ изменён ' + plan.path + ' (+' + d.added + ' −' + d.removed + ')');
465
- diffs.push('## ' + plan.path + '\n' + d.text);
466
- }
467
- else if (plan.kind === 'delete') {
468
- const bak = plan.path + '.ap-bak';
469
- await sbxCmd(docker, pc.id, ['cp', '--', plan.path, bak]);
470
- baks.push({ bak, orig: plan.path });
471
- await sbxCmd(docker, pc.id, ['rm', '--', plan.path]);
472
- done.push({ undo: async () => sbxCmd(docker, pc.id, ['mv', '--', bak, plan.path]) });
473
- lines.push('− удалён ' + plan.path);
474
- }
475
- else {
476
- const bak = plan.path + '.ap-bak';
477
- await sbxCmd(docker, pc.id, ['cp', '--', plan.path, bak]);
478
- baks.push({ bak, orig: plan.path });
479
- await sbxCmd(docker, pc.id, ['mv', '--', plan.path, plan.to]);
480
- done.push({ undo: async () => sbxCmd(docker, pc.id, ['mv', '--', plan.to, plan.path]) });
481
- lines.push('→ перемещён ' + plan.path + ' → ' + plan.to);
482
- }
483
- }
484
- }
485
- catch (fail) {
486
- const restoreErrors = [];
487
- for (const d of [...done].reverse()) {
488
- try {
489
- await d.undo();
490
- }
491
- catch (e) {
492
- restoreErrors.push(String(e?.message || e).slice(0, 120));
493
- }
494
- }
495
- for (const b of baks)
496
- await sbxCmd(docker, pc.id, ['rm', '--', b.bak]).catch(() => {});
497
- for (const t of tmps)
498
- await sbxCmd(docker, pc.id, ['rm', '--', t]).catch(() => {});
499
- throw new Error('apply_patch: сбой в песочнице на «' + (fail?.message || fail) + '» — записанное откачено'
500
- + (restoreErrors.length ? '; не удалось: ' + restoreErrors.join('; ') : ''), { cause: fail });
501
- }
502
- // оригиналы хранились до конца вызова — убираем баки
503
- for (const b of baks)
504
- await sbxCmd(docker, pc.id, ['rm', '--', b.bak]).catch(() => {});
505
- if (ctx?.entry) {
506
- ctx.entry.path = plans[0].to ?? plans[0].path;
507
- ctx.entry.diff = diffs.length ? diffs.join('\n\n') : undefined;
508
- }
509
- return { lines, diffs };
510
- }
511
-
512
- async function sandboxPatch(args, ctx) {
513
- const ops = parsePatch(args?.patch);
514
- const { cfg, docker, pc } = await useSandbox(args, ctx);
515
- await markSandboxTaint(docker, pc, cfg, ctx);
516
- const plans = await planSandbox(ops, docker, pc, cfg);
517
- const { lines } = await commitSandbox(plans, docker, pc, cfg, ctx);
518
- return 'применён патч: ' + lines.length + ' файлов\n' + lines.join('\n');
519
- }
520
-
521
- // ── инструмент ──────────────────────────────────────────────────────────────
522
-
523
- const WHERE_PROP = {
524
- where: {
525
- type: 'string',
526
- enum: ['work', 'sandbox'],
527
- description: 'Где применять: work — дерево WORK (права роли, история, откат ленты), sandbox — ваш компьютер (песочница, от /workspace)',
528
- },
529
- };
530
-
531
- /** Все пути патча (для decide: защищённая зона хотя бы в одном — подтверждение всего патча). */
532
- function patchTargets(args) {
533
- if (typeof args?.patch !== 'string')
534
- return null;
535
- const out = [];
536
- for (const m of args.patch.matchAll(/^\*\*\* (?:Add|Update|Delete|Move)(?: File)?:[ \t]*(.+)$/gm))
537
- out.push(absPath(m[1], null));
538
- for (const m of args.patch.matchAll(/^\*\*\* Move to:[ \t]*(.+)$/gm))
539
- out.push(absPath(m[1], null));
540
- return out.length ? out : null;
541
- }
542
-
543
- export const apply_patch = {
544
- name: 'apply_patch',
545
- risk: 'write',
546
- target: args => args?.where === 'sandbox' ? null : patchTargets(args),
547
- description: 'Многофайловый патч одним вызовом (формат Codex CLI): «*** Begin Patch», секции «*** Add File: путь» (строки с «+»), «*** Update File: путь» (ханки: строки «контекст», «-убрать», «+добавить», «@@» — разделитель), «*** Delete File: путь», «*** Move File: путь» + «*** Move to: путь», «*** End Patch». Атомарно: сначала проверяются все куски, потом запись (всё или ничего). Арена work — дерево WORK (история, откат ленты, права роли; изменение системного кода — с подтверждения человека); sandbox — ваш компьютер (баки оригиналов до конца вызова). До 50 файлов, файл ≤1 МБ, патч ≤4 МБ.',
548
- parameters: {
549
- type: 'object',
550
- properties: {
551
- ...WHERE_PROP,
552
- patch: { type: 'string', description: 'Текст патча (*** Begin Patch … *** End Patch)' },
553
- name: { type: 'string', description: 'Компьютер (только sandbox, по умолчанию main)' },
554
- },
555
- required: ['patch'],
556
- },
557
- async run(args, ctx) {
558
- return args?.where === 'sandbox'
559
- ? ctxRun('apply_patch_sandbox', sandboxPatch)(args, ctx)
560
- : workPatch(args, ctx);
561
- },
562
- };
563
-
564
- export const devPatchTools = [apply_patch];
1
+ /**
2
+ * Инструменты разработчика (этап 6.3): apply_patch — многофайловый патч одним вызовом.
3
+ *
4
+ * Формат `*** Begin Patch` (Add/Update/Delete/Move File, ханки с контекстом — как у Codex CLI,
5
+ * модели его знают). Атомарно: сначала проверяются ВСЕ куски патча против текущего содержимого
6
+ * (несовпадение/неоднозначность — отказ, ничего не записано), затем запись.
7
+ *
8
+ * Арены (архитектура 6.1, инварианты 11–12 в rules/threats.md):
9
+ * work — каждый файл через ядро: история (снимок при записи), `entry.undoList` на файл
10
+ * (undo.js collectUndo), права роли при записи, файлы памяти ai/memory.md — отказ;
11
+ * частичный сбой записи — откат уже записанных из журнала (всё или ничего);
12
+ * sandbox — docker exec: чтение/вычисление без записи, затем коммит во временный файл + mv,
13
+ * оригиналы хранятся в .ap-bak до конца вызова, сбой — восстановление из баков.
14
+ *
15
+ * Лимиты: ≤50 файлов, ≤1 МБ на файл, ≤4 МБ текста патча.
16
+ */
17
+ import { log } from '../../log.js';
18
+ import { mustItem, callAs, absPath, fileAt, writeFile, realPathOf } from '../work/common.js';
19
+ import { assertNotMemory } from '../work/fs.js';
20
+ import { beforeWrite, recordWrite, recordDelete } from '../../undo.js';
21
+ import { lineDiff } from '../../diff.js';
22
+ import { ctxRun } from '../sandbox.js';
23
+ import { useSandbox, markSandboxTaint } from './search.js';
24
+ import { assertSandboxPath, execRaw, readText, writeText } from '../../../sandbox/manager.js';
25
+ import { FS } from '../../../../server/index.js';
26
+
27
+ const OPS_MAX = 50; // файлов в одном патче
28
+ const FILE_MAX = 1024 * 1024; // размер файла/итогового содержимого
29
+ const PATCH_MAX = 4 * 1024 * 1024; // размер текста патча
30
+ const SBX_CMD_SEC = 30; // потолок cp/mv/rm в песочнице
31
+
32
+ // ── разбор патча ─────────────────────────────────────────────────────────────
33
+
34
+ const HEAD_RE = /^\*\*\* (Add|Update|Delete|Move)(?: File)?:[ \t]*(.+)$/;
35
+ const MOVE_TO_RE = /^\*\*\* Move to:[ \t]*(.+)$/;
36
+ const HUNK_LINE_RE = /^[ +-]/;
37
+
38
+ /**
39
+ * Разбор текста патча → список операций.
40
+ * @returns {Array<{kind:'add'|'update'|'delete'|'move', path:string, to?:string, content?:string[], hunks?:Array<{lines:Array<{k:string,v:string}>}>}>}
41
+ */
42
+ export function parsePatch(raw) {
43
+ const text = String(raw ?? '');
44
+ if (text.length > PATCH_MAX)
45
+ throw new Error('apply_patch: патч больше ' + Math.round(PATCH_MAX / 1048576) + ' МБ');
46
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
47
+ let begin = 0;
48
+ while (begin < lines.length && !lines[begin].trim())
49
+ begin++;
50
+ if (lines[begin] !== '*** Begin Patch')
51
+ throw new Error('apply_patch: первая строка должна быть «*** Begin Patch»');
52
+ let end = -1;
53
+ for (let j = lines.length - 1; j > begin; j--) {
54
+ if (lines[j].trim() === '*** End Patch') {
55
+ end = j;
56
+ break;
57
+ }
58
+ }
59
+ if (end < 0)
60
+ throw new Error('apply_patch: нет строки «*** End Patch»');
61
+ const ops = [];
62
+ let cur = null;
63
+ const section = (kind, path) => {
64
+ if (ops.length >= OPS_MAX)
65
+ throw new Error('apply_patch: больше ' + OPS_MAX + ' файлов в одном патче');
66
+ cur = { kind, path: String(path).trim(), content: [], hunks: [] };
67
+ ops.push(cur);
68
+ return cur;
69
+ };
70
+ for (let i = begin + 1; i < end; i++) {
71
+ const l = lines[i];
72
+ if (l === '*** ')
73
+ continue;
74
+ const head = HEAD_RE.exec(l);
75
+ if (head) {
76
+ section(head[1].toLowerCase(), head[2]);
77
+ continue;
78
+ }
79
+ const moveTo = MOVE_TO_RE.exec(l);
80
+ if (moveTo) {
81
+ if (!cur || cur.kind !== 'move' || cur.to)
82
+ throw new Error('apply_patch: «*** Move to:» без «*** Move File:» (строка ' + (i + 1) + ')');
83
+ cur.to = String(moveTo[1]).trim();
84
+ continue;
85
+ }
86
+ if (l.startsWith('***'))
87
+ throw new Error('apply_patch: неизвестная секция: ' + l.slice(0, 80) + ' (строка ' + (i + 1) + ')');
88
+ if (!cur)
89
+ throw new Error('apply_patch: строка до первой секции: ' + l.slice(0, 80));
90
+ if (cur.kind === 'add') {
91
+ // содержимое нового файла: каждая строка с «+» (пустая строка — пустая строка файла)
92
+ if (l.startsWith('+'))
93
+ cur.content.push(l.slice(1));
94
+ else if (l === '')
95
+ cur.content.push('');
96
+ else
97
+ throw new Error('apply_patch: Add File ' + cur.path + ': строка без «+»: ' + l.slice(0, 60));
98
+ continue;
99
+ }
100
+ if (cur.kind === 'update') {
101
+ if (l.startsWith('@@')) {
102
+ cur.hunks.push({ lines: [] });
103
+ continue;
104
+ }
105
+ if (HUNK_LINE_RE.test(l) || l === '') {
106
+ if (!cur.hunks.length)
107
+ cur.hunks.push({ lines: [] });
108
+ const k = l === '' || l.startsWith(' ') ? ' ' : l.charAt(0);
109
+ cur.hunks.at(-1).lines.push({ k, v: l === '' ? '' : l.slice(1) });
110
+ continue;
111
+ }
112
+ throw new Error('apply_patch: Update File ' + cur.path + ': строка ханка не с « »/«-»/«+»: ' + l.slice(0, 60));
113
+ }
114
+ throw new Error('apply_patch: после ' + cur.kind + ' не должно быть строк: ' + l.slice(0, 60));
115
+ }
116
+ for (const op of ops) {
117
+ if (op.kind === 'add' && op.content.join('\n').length > FILE_MAX)
118
+ throw new Error('apply_patch: Add File ' + op.path + ' больше ' + Math.round(FILE_MAX / 1048576) + ' МБ');
119
+ if (op.kind === 'update' && !op.hunks.length)
120
+ throw new Error('apply_patch: Update File ' + op.path + ': нет ханков');
121
+ if (op.kind === 'update')
122
+ for (const h of op.hunks)
123
+ if (!h.lines.some(x => x.k === ' ' || x.k === '-'))
124
+ throw new Error('apply_patch: Update File ' + op.path + ': ханк без строк для замены (нет контекста и «-») — добавь контекст');
125
+ if (op.kind === 'move' && !op.to)
126
+ throw new Error('apply_patch: Move File ' + op.path + ': нет «*** Move to:»');
127
+ }
128
+ if (!ops.length)
129
+ throw new Error('apply_patch: пустой патч (нет секций)');
130
+ const seen = new Set();
131
+ for (const op of ops) {
132
+ for (const p of [op.path, op.to].filter(Boolean)) {
133
+ const a = absPath(p, null);
134
+ if (seen.has(a))
135
+ throw new Error('apply_patch: файл ' + a + ' в патче дважды');
136
+ seen.add(a);
137
+ }
138
+ }
139
+ return ops;
140
+ }
141
+
142
+ /**
143
+ * Применить ханки к тексту (точное построчное совпадение).
144
+ * Фрагмент должен встречаться ровно один раз: не найден/неоднозначен — ошибка, ничего не меняется.
145
+ */
146
+ export function applyHunks(text, hunks, label) {
147
+ const crlf = String(text).includes('\r\n');
148
+ let ls = String(text).replace(/\r\n/g, '\n').split('\n');
149
+ hunks.forEach((h, hi) => {
150
+ const oldL = [], newL = [];
151
+ for (const l of h.lines) {
152
+ if (l.k === ' ') {
153
+ oldL.push(l.v);
154
+ newL.push(l.v);
155
+ }
156
+ else if (l.k === '-')
157
+ oldL.push(l.v);
158
+ else
159
+ newL.push(l.v);
160
+ }
161
+ if (!oldL.length)
162
+ throw new Error('apply_patch: ' + label + ': ханк ' + (hi + 1) + ' без строк для замены — добавь контекст');
163
+ const oldS = oldL.join('\n');
164
+ let idx = -1, hits = 0;
165
+ for (let i = 0; i + oldL.length <= ls.length; i++) {
166
+ if (ls[i] !== oldL[0])
167
+ continue;
168
+ if (ls.slice(i, i + oldL.length).join('\n') !== oldS)
169
+ continue;
170
+ hits++;
171
+ idx = i;
172
+ if (hits > 1)
173
+ break;
174
+ }
175
+ if (!hits)
176
+ throw new Error('apply_patch: ' + label + ': ханк ' + (hi + 1) + ' не найден (файл изменился?) — прочитай файл и поправь контекст');
177
+ if (hits > 1)
178
+ throw new Error('apply_patch: ' + label + ': ханк ' + (hi + 1) + ' встречается ' + hits + ' раз — добавь контекста для однозначности');
179
+ ls.splice(idx, oldL.length, ...newL);
180
+ });
181
+ const out = ls.join('\n');
182
+ return crlf ? out.replace(/\n/g, '\r\n') : out;
183
+ }
184
+
185
+ // ── арена work ──────────────────────────────────────────────────────────────
186
+
187
+ /** Пометка внешнего источника снимается: файл целиком переписан своим текстом (как write). */
188
+ async function unmarkExternalOf(path) {
189
+ try {
190
+ const { unmarkExternal } = await import('../../../../server/external-source.js');
191
+ unmarkExternal(String(path || ''));
192
+ }
193
+ catch (e) { log.debug('dev.unmark', e); }
194
+ }
195
+
196
+ /** ФАЗА A (work): проверить каждый кусок против текущего содержимого, ничего не записывая. */
197
+ async function planWork(ops, ctx) {
198
+ const plans = [];
199
+ for (const op of ops) {
200
+ assertNotMemory(absPath(op.path, ctx));
201
+ if (op.to)
202
+ assertNotMemory(absPath(op.to, ctx));
203
+ if (op.kind === 'add') {
204
+ const ex = await fileAt(op.path, ctx);
205
+ if (ex)
206
+ throw new Error('apply_patch: Add File: файл уже есть — ' + ex.path + ' (используй Update File)');
207
+ const content = op.content.length ? op.content.join('\n') + '\n' : '';
208
+ plans.push({ op, kind: 'add', path: absPath(op.path, ctx), content });
209
+ }
210
+ else if (op.kind === 'update') {
211
+ const item = await mustItem(op.path, ctx);
212
+ if (Array.isArray(item) || isContainer(item))
213
+ throw new Error('apply_patch: Update File: не файл — ' + absPath(op.path, ctx));
214
+ const before = await callAs(item, 'load', { encoding: 'utf-8' }, ctx);
215
+ if (typeof before !== 'string')
216
+ throw new Error('apply_patch: Update File ' + item.path + ': файл не текстовый');
217
+ const after = applyHunks(before, op.hunks, item.path);
218
+ if (after.length > FILE_MAX)
219
+ throw new Error('apply_patch: Update File ' + item.path + ': результат больше ' + Math.round(FILE_MAX / 1048576) + ' МБ');
220
+ plans.push({ op, kind: 'update', path: item.path, item, before, after });
221
+ }
222
+ else if (op.kind === 'delete') {
223
+ const item = await mustItem(op.path, ctx);
224
+ if (Array.isArray(item) || isContainer(item))
225
+ throw new Error('apply_patch: Delete File: не файл — ' + absPath(op.path, ctx));
226
+ plans.push({ op, kind: 'delete', path: item.path, item });
227
+ }
228
+ else {
229
+ const from = await mustItem(op.path, ctx);
230
+ if (Array.isArray(from) || isContainer(from))
231
+ throw new Error('apply_patch: Move File: не файл — ' + absPath(op.path, ctx));
232
+ const ex = await fileAt(op.to, ctx);
233
+ if (ex)
234
+ throw new Error('apply_patch: Move File: файл уже есть — ' + ex.path);
235
+ // без кодировки: Buffer для бинарного, строка — для текстового (file.js load)
236
+ const buf = await callAs(from, 'load', {}, ctx);
237
+ plans.push({ op, kind: 'move', path: from.path, to: absPath(op.to, ctx), item: from, content: buf });
238
+ }
239
+ }
240
+ return plans;
241
+ }
242
+
243
+ function isContainer(item) {
244
+ return !(item instanceof FS.$file);
245
+ }
246
+
247
+ /** Откат одного уже записанного плана (лучшее усилие; ошибки собирает вызывающий). */
248
+ async function rollbackPlan(plan, ctx, sbx) {
249
+ if (plan.kind === 'add') {
250
+ const made = await fileAt(plan.real ?? plan.path, ctx);
251
+ if (made)
252
+ await callAs(made, 'delete', {}, ctx);
253
+ }
254
+ else if (plan.kind === 'update') {
255
+ await callAs(await fileAt(plan.path, ctx) ?? plan.item, 'save', { post: plan.before, mainContext: ctx?.task?.path }, ctx);
256
+ }
257
+ else if (plan.kind === 'delete') {
258
+ const pre = plan.pre;
259
+ if (pre?.before?.snapshot) {
260
+ const snap = await mustItem(pre.before.snapshot, ctx).catch(() => null);
261
+ if (snap && !Array.isArray(snap))
262
+ await callAs(snap, 'restore_from_history', {}, ctx);
263
+ }
264
+ else if (pre?.before?.text != null)
265
+ await writeFile(plan.path, pre.before.text, ctx);
266
+ else if (!sbx)
267
+ throw new Error('прежняя версия ' + plan.path + ' не сохранена — восстанови из истории вручную');
268
+ }
269
+ else { // move: удалить новый, вернуть старый
270
+ const made = await fileAt(plan.realTo ?? plan.to, ctx);
271
+ if (made)
272
+ await callAs(made, 'delete', {}, ctx);
273
+ await writeFile(plan.path, plan.content, ctx);
274
+ }
275
+ }
276
+
277
+ /** ФАЗА B (work): запись через ядро + журнал отката; частичный сбой — откат записанного. */
278
+ async function commitWork(plans, ctx) {
279
+ const journal = [];
280
+ const undoList = [];
281
+ const lines = [];
282
+ const diffs = [];
283
+ const one = () => ({});
284
+ try {
285
+ for (const plan of plans) {
286
+ if (plan.kind === 'add') {
287
+ const pre = await beforeWrite(await fileAt(plan.path, ctx));
288
+ const wlog = await writeFile(plan.path, plan.content, ctx);
289
+ const real = realPathOf(wlog, plan.path);
290
+ plan.real = real;
291
+ await unmarkExternalOf(real);
292
+ const e = one();
293
+ await recordWrite(e, { realItem: await fileAt(real, ctx), pre });
294
+ if (e.undo)
295
+ undoList.push(e.undo);
296
+ journal.push(plan);
297
+ lines.push('+ создан ' + real + ' (' + plan.content.length + ' символов)');
298
+ diffs.push('## ' + real + '\n' + lineDiff('', plan.content).text);
299
+ }
300
+ else if (plan.kind === 'update') {
301
+ const pre = await beforeWrite(plan.item);
302
+ const saveParams = { post: plan.after };
303
+ if (ctx?.task?.path)
304
+ saveParams.mainContext = ctx.task.path;
305
+ await callAs(plan.item, 'save', saveParams, ctx);
306
+ await unmarkExternalOf(plan.path);
307
+ const e = one();
308
+ await recordWrite(e, { realItem: await fileAt(plan.path, ctx), pre });
309
+ if (e.undo)
310
+ undoList.push(e.undo);
311
+ journal.push(plan);
312
+ const d = lineDiff(plan.before, plan.after);
313
+ lines.push('~ изменён ' + plan.path + ' (+' + d.added + ' −' + d.removed + ')');
314
+ diffs.push('## ' + plan.path + '\n' + d.text);
315
+ }
316
+ else if (plan.kind === 'delete') {
317
+ const pre = await beforeWrite(plan.item);
318
+ await callAs(plan.item, 'delete', {}, ctx);
319
+ plan.pre = pre;
320
+ const e = one();
321
+ recordDelete(e, { item: plan.item, pre });
322
+ if (e.undo)
323
+ undoList.push(e.undo);
324
+ journal.push(plan);
325
+ lines.push('− удалён ' + plan.path);
326
+ diffs.push('## ' + plan.path + '\n' + lineDiff(plan.before ?? '', '').text);
327
+ }
328
+ else { // move: сначала новый файл, затем удаление старого — сбой не теряет файл
329
+ // прежнее состояние СТАРОГО файла (для записи удаления); НОВОМУ — create (его не было)
330
+ const preOld = await beforeWrite(plan.item);
331
+ // writeFile принимает и строку, и Buffer; карточку не трогает (запись отката — своя, на файл)
332
+ const wlog = await writeFile(plan.to, plan.content, ctx);
333
+ const realTo = realPathOf(wlog, plan.to);
334
+ plan.realTo = realTo;
335
+ const eNew = one();
336
+ await recordWrite(eNew, { realItem: await fileAt(realTo, ctx), pre: { known: false, before: null } });
337
+ if (eNew.undo)
338
+ undoList.push(eNew.undo);
339
+ await callAs(plan.item, 'delete', {}, ctx);
340
+ const eOld = one();
341
+ recordDelete(eOld, { item: plan.item, pre: preOld });
342
+ if (eOld.undo)
343
+ undoList.push(eOld.undo);
344
+ journal.push(plan);
345
+ lines.push('→ перемещён ' + plan.path + ' → ' + realTo);
346
+ diffs.push('## ' + plan.path + ' → ' + realTo + '\n(имя изменено, содержимое прежнее)');
347
+ }
348
+ }
349
+ }
350
+ catch (fail) {
351
+ // всё или ничего: откат записанного в обратном порядке
352
+ const restoreErrors = [];
353
+ for (const plan of [...journal].reverse()) {
354
+ try {
355
+ await rollbackPlan(plan, ctx, false);
356
+ }
357
+ catch (e) {
358
+ restoreErrors.push(String(e?.message || e).slice(0, 120));
359
+ }
360
+ }
361
+ throw new Error('apply_patch: сбой на «' + (fail?.message || fail) + '» — записанное откачено'
362
+ + (restoreErrors.length ? '; не удалось: ' + restoreErrors.join('; ') + ' — восстанови из истории вручную' : ''), { cause: fail });
363
+ }
364
+ return { lines, diffs, undoList };
365
+ }
366
+
367
+ async function workPatch(args, ctx) {
368
+ const ops = parsePatch(args?.patch);
369
+ const plans = await planWork(ops, ctx);
370
+ const { lines, diffs, undoList } = await commitWork(plans, ctx);
371
+ if (ctx.entry) {
372
+ ctx.entry.path = plans[0].real ?? plans[0].realTo ?? plans[0].path;
373
+ ctx.entry.diff = diffs.join('\n\n');
374
+ if (undoList.length)
375
+ ctx.entry.undoList = undoList;
376
+ }
377
+ return 'применён патч: ' + lines.length + ' файлов\n' + lines.join('\n');
378
+ }
379
+
380
+ // ── арена sandbox ───────────────────────────────────────────────────────────
381
+
382
+ async function sbxCmd(docker, id, cmd) {
383
+ const r = await execRaw(docker, id, { cmd, timeoutSec: SBX_CMD_SEC, maxBytes: 4096 });
384
+ if (r.code !== 0)
385
+ throw new Error('команда «' + cmd[0] + '» в песочнице: код ' + r.code + ' ' + String(r.stderr || '').trim().slice(0, 120));
386
+ return r;
387
+ }
388
+
389
+ /** ФАЗА A (sandbox): чтение и вычисление без записи. */
390
+ async function planSandbox(ops, docker, pc, cfg) {
391
+ const plans = [];
392
+ for (const op of ops) {
393
+ const p = assertSandboxPath(op.path, cfg.workdir);
394
+ const to = op.to ? assertSandboxPath(op.to, cfg.workdir) : null;
395
+ if (op.kind === 'add') {
396
+ const ex = await readText(docker, pc.id, p, cfg).then(() => true).catch(() => false);
397
+ if (ex)
398
+ throw new Error('apply_patch: Add File: файл уже есть — ' + p + ' (используй Update File)');
399
+ plans.push({ op, kind: 'add', path: p, content: op.content.length ? op.content.join('\n') + '\n' : '' });
400
+ }
401
+ else if (op.kind === 'update') {
402
+ let before;
403
+ try {
404
+ before = await readText(docker, pc.id, p, cfg);
405
+ }
406
+ catch {
407
+ throw new Error('apply_patch: Update File: файл не найден — ' + p);
408
+ }
409
+ const after = applyHunks(before, op.hunks, p);
410
+ plans.push({ op, kind: 'update', path: p, before, after });
411
+ }
412
+ else if (op.kind === 'delete') {
413
+ const ex = await readText(docker, pc.id, p, cfg).then(() => true).catch(() => false);
414
+ if (!ex)
415
+ throw new Error('apply_patch: Delete File: файл не найден — ' + p);
416
+ plans.push({ op, kind: 'delete', path: p });
417
+ }
418
+ else {
419
+ let content;
420
+ try {
421
+ content = await readText(docker, pc.id, p, cfg);
422
+ }
423
+ catch {
424
+ throw new Error('apply_patch: Move File: файл не найден — ' + p);
425
+ }
426
+ const ex = to && await readText(docker, pc.id, to, cfg).then(() => true).catch(() => false);
427
+ if (ex)
428
+ throw new Error('apply_patch: Move File: файл уже есть — ' + to);
429
+ plans.push({ op, kind: 'move', path: p, to, content });
430
+ }
431
+ }
432
+ return plans;
433
+ }
434
+
435
+ /** ФАЗА B (sandbox): баки → временный файл → mv; сбой — восстановление из баков. */
436
+ async function commitSandbox(plans, docker, pc, cfg, ctx) {
437
+ const baks = []; // { bak, orig }
438
+ const tmps = []; // временные файлы (убрать при сбое)
439
+ const lines = [];
440
+ const diffs = [];
441
+ const done = [];
442
+ const tmp = p => p + '.ap-tmp';
443
+ try {
444
+ for (const plan of plans) {
445
+ if (plan.kind === 'add') {
446
+ const t = tmp(plan.path);
447
+ await writeText(docker, pc.id, t, plan.content, cfg);
448
+ tmps.push(t);
449
+ await sbxCmd(docker, pc.id, ['mv', '--', t, plan.path]);
450
+ done.push({ undo: async () => sbxCmd(docker, pc.id, ['rm', '--', plan.path]) });
451
+ lines.push('+ создан ' + plan.path);
452
+ diffs.push('## ' + plan.path + '\n' + lineDiff('', plan.content).text);
453
+ }
454
+ else if (plan.kind === 'update') {
455
+ const bak = plan.path + '.ap-bak';
456
+ await sbxCmd(docker, pc.id, ['cp', '--', plan.path, bak]);
457
+ baks.push({ bak, orig: plan.path });
458
+ const t = tmp(plan.path);
459
+ await writeText(docker, pc.id, t, plan.after, cfg);
460
+ tmps.push(t);
461
+ await sbxCmd(docker, pc.id, ['mv', '--', t, plan.path]);
462
+ done.push({ undo: async () => sbxCmd(docker, pc.id, ['mv', '--', bak, plan.path]) });
463
+ const d = lineDiff(plan.before, plan.after);
464
+ lines.push('~ изменён ' + plan.path + ' (+' + d.added + ' −' + d.removed + ')');
465
+ diffs.push('## ' + plan.path + '\n' + d.text);
466
+ }
467
+ else if (plan.kind === 'delete') {
468
+ const bak = plan.path + '.ap-bak';
469
+ await sbxCmd(docker, pc.id, ['cp', '--', plan.path, bak]);
470
+ baks.push({ bak, orig: plan.path });
471
+ await sbxCmd(docker, pc.id, ['rm', '--', plan.path]);
472
+ done.push({ undo: async () => sbxCmd(docker, pc.id, ['mv', '--', bak, plan.path]) });
473
+ lines.push('− удалён ' + plan.path);
474
+ }
475
+ else {
476
+ const bak = plan.path + '.ap-bak';
477
+ await sbxCmd(docker, pc.id, ['cp', '--', plan.path, bak]);
478
+ baks.push({ bak, orig: plan.path });
479
+ await sbxCmd(docker, pc.id, ['mv', '--', plan.path, plan.to]);
480
+ done.push({ undo: async () => sbxCmd(docker, pc.id, ['mv', '--', plan.to, plan.path]) });
481
+ lines.push('→ перемещён ' + plan.path + ' → ' + plan.to);
482
+ }
483
+ }
484
+ }
485
+ catch (fail) {
486
+ const restoreErrors = [];
487
+ for (const d of [...done].reverse()) {
488
+ try {
489
+ await d.undo();
490
+ }
491
+ catch (e) {
492
+ restoreErrors.push(String(e?.message || e).slice(0, 120));
493
+ }
494
+ }
495
+ for (const b of baks)
496
+ await sbxCmd(docker, pc.id, ['rm', '--', b.bak]).catch(() => {});
497
+ for (const t of tmps)
498
+ await sbxCmd(docker, pc.id, ['rm', '--', t]).catch(() => {});
499
+ throw new Error('apply_patch: сбой в песочнице на «' + (fail?.message || fail) + '» — записанное откачено'
500
+ + (restoreErrors.length ? '; не удалось: ' + restoreErrors.join('; ') : ''), { cause: fail });
501
+ }
502
+ // оригиналы хранились до конца вызова — убираем баки
503
+ for (const b of baks)
504
+ await sbxCmd(docker, pc.id, ['rm', '--', b.bak]).catch(() => {});
505
+ if (ctx?.entry) {
506
+ ctx.entry.path = plans[0].to ?? plans[0].path;
507
+ ctx.entry.diff = diffs.length ? diffs.join('\n\n') : undefined;
508
+ }
509
+ return { lines, diffs };
510
+ }
511
+
512
+ async function sandboxPatch(args, ctx) {
513
+ const ops = parsePatch(args?.patch);
514
+ const { cfg, docker, pc } = await useSandbox(args, ctx);
515
+ await markSandboxTaint(docker, pc, cfg, ctx);
516
+ const plans = await planSandbox(ops, docker, pc, cfg);
517
+ const { lines } = await commitSandbox(plans, docker, pc, cfg, ctx);
518
+ return 'применён патч: ' + lines.length + ' файлов\n' + lines.join('\n');
519
+ }
520
+
521
+ // ── инструмент ──────────────────────────────────────────────────────────────
522
+
523
+ const WHERE_PROP = {
524
+ where: {
525
+ type: 'string',
526
+ enum: ['work', 'sandbox'],
527
+ description: 'Где применять: work — дерево WORK (права роли, история, откат ленты), sandbox — ваш компьютер (песочница, от /workspace)',
528
+ },
529
+ };
530
+
531
+ /** Все пути патча (для decide: защищённая зона хотя бы в одном — подтверждение всего патча). */
532
+ function patchTargets(args) {
533
+ if (typeof args?.patch !== 'string')
534
+ return null;
535
+ const out = [];
536
+ for (const m of args.patch.matchAll(/^\*\*\* (?:Add|Update|Delete|Move)(?: File)?:[ \t]*(.+)$/gm))
537
+ out.push(absPath(m[1], null));
538
+ for (const m of args.patch.matchAll(/^\*\*\* Move to:[ \t]*(.+)$/gm))
539
+ out.push(absPath(m[1], null));
540
+ return out.length ? out : null;
541
+ }
542
+
543
+ export const apply_patch = {
544
+ name: 'apply_patch',
545
+ risk: 'write',
546
+ target: args => args?.where === 'sandbox' ? null : patchTargets(args),
547
+ description: 'Многофайловый патч одним вызовом (формат Codex CLI): «*** Begin Patch», секции «*** Add File: путь» (строки с «+»), «*** Update File: путь» (ханки: строки «контекст», «-убрать», «+добавить», «@@» — разделитель), «*** Delete File: путь», «*** Move File: путь» + «*** Move to: путь», «*** End Patch». Атомарно: сначала проверяются все куски, потом запись (всё или ничего). Арена work — дерево WORK (история, откат ленты, права роли; изменение системного кода — с подтверждения человека); sandbox — ваш компьютер (баки оригиналов до конца вызова). До 50 файлов, файл ≤1 МБ, патч ≤4 МБ.',
548
+ parameters: {
549
+ type: 'object',
550
+ properties: {
551
+ ...WHERE_PROP,
552
+ patch: { type: 'string', description: 'Текст патча (*** Begin Patch … *** End Patch)' },
553
+ name: { type: 'string', description: 'Компьютер (только sandbox, по умолчанию main)' },
554
+ },
555
+ required: ['patch'],
556
+ },
557
+ async run(args, ctx) {
558
+ return args?.where === 'sandbox'
559
+ ? ctxRun('apply_patch_sandbox', sandboxPatch)(args, ctx)
560
+ : workPatch(args, ctx);
561
+ },
562
+ };
563
+
564
+ export const devPatchTools = [apply_patch];