@bastani/atomic 0.10.2 → 0.10.3

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 (499) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +22 -0
  3. package/dist/builtin/intercom/broker/broker-instance.ts +2 -13
  4. package/dist/builtin/intercom/broker/broker.ts +158 -73
  5. package/dist/builtin/intercom/broker/durable-ended-queue.ts +14 -2
  6. package/dist/builtin/intercom/broker/host-command-environment.ts +13 -0
  7. package/dist/builtin/intercom/broker/hosted-session-errors.ts +1 -0
  8. package/dist/builtin/intercom/broker/multinode-router.ts +111 -16
  9. package/dist/builtin/intercom/broker/multinode-state-store.ts +50 -4
  10. package/dist/builtin/intercom/broker/open-broker-state.ts +5 -4
  11. package/dist/builtin/intercom/broker/spawn.ts +144 -25
  12. package/dist/builtin/intercom/broker/sql-add-column.ts +33 -0
  13. package/dist/builtin/intercom/broker/sql-known-session-store.ts +120 -36
  14. package/dist/builtin/intercom/broker/sql-outbox-store.ts +75 -13
  15. package/dist/builtin/intercom/broker/start-announcement.ts +55 -10
  16. package/dist/builtin/intercom/broker/watchdog.ts +10 -7
  17. package/dist/builtin/intercom/index.bundle.mjs +111 -27
  18. package/dist/builtin/intercom/package.json +1 -1
  19. package/dist/builtin/mcp/package.json +1 -1
  20. package/dist/builtin/subagents/CHANGELOG.md +26 -0
  21. package/dist/builtin/subagents/package.json +1 -1
  22. package/dist/builtin/subagents/skills/skill-creator/SKILL.md +30 -52
  23. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +34 -40
  24. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/viewer.html +2 -2
  25. package/dist/builtin/subagents/skills/skill-creator/scripts/atomic_cli.py +731 -0
  26. package/dist/builtin/subagents/skills/skill-creator/scripts/generate_report.py +3 -3
  27. package/dist/builtin/subagents/skills/skill-creator/scripts/improve_description.py +41 -38
  28. package/dist/builtin/subagents/skills/skill-creator/scripts/run_eval.py +276 -176
  29. package/dist/builtin/subagents/skills/skill-creator/scripts/run_loop.py +20 -11
  30. package/dist/builtin/subagents/skills/skill-creator/scripts/utils.py +1 -1
  31. package/dist/builtin/subagents/src/extension/index.bundle.mjs +163 -97
  32. package/dist/builtin/web-access/CHANGELOG.md +14 -0
  33. package/dist/builtin/web-access/index.bundle.mjs +5 -4
  34. package/dist/builtin/web-access/package.json +1 -1
  35. package/dist/core/agent-session-auto-compaction.d.ts +10 -1
  36. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  37. package/dist/core/agent-session-auto-compaction.js +54 -2
  38. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  39. package/dist/core/agent-session-compaction.d.ts +4 -0
  40. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  41. package/dist/core/agent-session-compaction.js +17 -2
  42. package/dist/core/agent-session-compaction.js.map +1 -1
  43. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
  44. package/dist/core/agent-session-custom-message-commit.js +3 -1
  45. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  46. package/dist/core/agent-session-events.d.ts +2 -0
  47. package/dist/core/agent-session-events.d.ts.map +1 -1
  48. package/dist/core/agent-session-events.js +34 -13
  49. package/dist/core/agent-session-events.js.map +1 -1
  50. package/dist/core/agent-session-export.d.ts.map +1 -1
  51. package/dist/core/agent-session-export.js +3 -0
  52. package/dist/core/agent-session-export.js.map +1 -1
  53. package/dist/core/agent-session-message-queue.d.ts +27 -0
  54. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  55. package/dist/core/agent-session-message-queue.js +213 -30
  56. package/dist/core/agent-session-message-queue.js.map +1 -1
  57. package/dist/core/agent-session-methods.d.ts +6 -1
  58. package/dist/core/agent-session-methods.d.ts.map +1 -1
  59. package/dist/core/agent-session-methods.js.map +1 -1
  60. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  61. package/dist/core/agent-session-prompt.js +35 -3
  62. package/dist/core/agent-session-prompt.js.map +1 -1
  63. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  64. package/dist/core/agent-session-runtime.js +2 -2
  65. package/dist/core/agent-session-runtime.js.map +1 -1
  66. package/dist/core/agent-session-state.d.ts.map +1 -1
  67. package/dist/core/agent-session-state.js +6 -1
  68. package/dist/core/agent-session-state.js.map +1 -1
  69. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  70. package/dist/core/agent-session-tool-hooks.js +15 -2
  71. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  72. package/dist/core/agent-session-typed-queue.d.ts +14 -1
  73. package/dist/core/agent-session-typed-queue.d.ts.map +1 -1
  74. package/dist/core/agent-session-typed-queue.js +26 -1
  75. package/dist/core/agent-session-typed-queue.js.map +1 -1
  76. package/dist/core/agent-session-types.d.ts +5 -0
  77. package/dist/core/agent-session-types.d.ts.map +1 -1
  78. package/dist/core/agent-session-types.js.map +1 -1
  79. package/dist/core/agent-session.d.ts.map +1 -1
  80. package/dist/core/agent-session.js +2 -1
  81. package/dist/core/agent-session.js.map +1 -1
  82. package/dist/core/async-scope.d.ts +9 -4
  83. package/dist/core/async-scope.d.ts.map +1 -1
  84. package/dist/core/async-scope.js +13 -5
  85. package/dist/core/async-scope.js.map +1 -1
  86. package/dist/core/builtin-diagnostics.js +2 -2
  87. package/dist/core/builtin-diagnostics.js.map +1 -1
  88. package/dist/core/chat-admission-order.d.ts.map +1 -1
  89. package/dist/core/chat-admission-order.js +2 -1
  90. package/dist/core/chat-admission-order.js.map +1 -1
  91. package/dist/core/chat-record-saves.d.ts +4 -0
  92. package/dist/core/chat-record-saves.d.ts.map +1 -0
  93. package/dist/core/chat-record-saves.js +25 -0
  94. package/dist/core/chat-record-saves.js.map +1 -0
  95. package/dist/core/command-deliveries.d.ts +62 -0
  96. package/dist/core/command-deliveries.d.ts.map +1 -0
  97. package/dist/core/command-deliveries.js +139 -0
  98. package/dist/core/command-deliveries.js.map +1 -0
  99. package/dist/core/diagnostic-writer.d.ts.map +1 -1
  100. package/dist/core/diagnostic-writer.js +5 -4
  101. package/dist/core/diagnostic-writer.js.map +1 -1
  102. package/dist/core/extension-startup-close.d.ts +1 -2
  103. package/dist/core/extension-startup-close.d.ts.map +1 -1
  104. package/dist/core/extension-startup-close.js +2 -2
  105. package/dist/core/extension-startup-close.js.map +1 -1
  106. package/dist/core/extensions/jiti-aliases.d.ts +11 -0
  107. package/dist/core/extensions/jiti-aliases.d.ts.map +1 -0
  108. package/dist/core/extensions/jiti-aliases.js +28 -0
  109. package/dist/core/extensions/jiti-aliases.js.map +1 -0
  110. package/dist/core/extensions/loader-api.js +3 -3
  111. package/dist/core/extensions/loader-api.js.map +1 -1
  112. package/dist/core/extensions/loader-bindings.js +2 -2
  113. package/dist/core/extensions/loader-bindings.js.map +1 -1
  114. package/dist/core/extensions/loader-rollback.d.ts +1 -2
  115. package/dist/core/extensions/loader-rollback.d.ts.map +1 -1
  116. package/dist/core/extensions/loader-rollback.js +2 -2
  117. package/dist/core/extensions/loader-rollback.js.map +1 -1
  118. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  119. package/dist/core/extensions/loader-virtual-modules.js +53 -9
  120. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  121. package/dist/core/extensions/native-builtin-entries.d.ts +5 -0
  122. package/dist/core/extensions/native-builtin-entries.d.ts.map +1 -1
  123. package/dist/core/extensions/native-builtin-entries.js +8 -1
  124. package/dist/core/extensions/native-builtin-entries.js.map +1 -1
  125. package/dist/core/extensions/reloadable-scripts.d.ts +21 -2
  126. package/dist/core/extensions/reloadable-scripts.d.ts.map +1 -1
  127. package/dist/core/extensions/reloadable-scripts.js +11 -3
  128. package/dist/core/extensions/reloadable-scripts.js.map +1 -1
  129. package/dist/core/extensions/source-builtin-imports.d.ts +40 -0
  130. package/dist/core/extensions/source-builtin-imports.d.ts.map +1 -0
  131. package/dist/core/extensions/source-builtin-imports.js +142 -0
  132. package/dist/core/extensions/source-builtin-imports.js.map +1 -0
  133. package/dist/core/extensions/transform-graph.d.ts +15 -0
  134. package/dist/core/extensions/transform-graph.d.ts.map +1 -0
  135. package/dist/core/extensions/transform-graph.js +85 -0
  136. package/dist/core/extensions/transform-graph.js.map +1 -0
  137. package/dist/core/extensions/ts-source-specifiers.d.ts +2 -0
  138. package/dist/core/extensions/ts-source-specifiers.d.ts.map +1 -1
  139. package/dist/core/extensions/ts-source-specifiers.js +7 -0
  140. package/dist/core/extensions/ts-source-specifiers.js.map +1 -1
  141. package/dist/core/extensions/ts-transform-worker.d.ts +2 -0
  142. package/dist/core/extensions/ts-transform-worker.d.ts.map +1 -0
  143. package/dist/core/extensions/ts-transform-worker.js +43 -0
  144. package/dist/core/extensions/ts-transform-worker.js.map +1 -0
  145. package/dist/core/message-admission.d.ts.map +1 -1
  146. package/dist/core/message-admission.js +4 -4
  147. package/dist/core/message-admission.js.map +1 -1
  148. package/dist/core/messages.d.ts +5 -0
  149. package/dist/core/messages.d.ts.map +1 -1
  150. package/dist/core/messages.js +35 -0
  151. package/dist/core/messages.js.map +1 -1
  152. package/dist/core/model-fallback-failures.d.ts +1 -1
  153. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  154. package/dist/core/model-fallback-failures.js +18 -1
  155. package/dist/core/model-fallback-failures.js.map +1 -1
  156. package/dist/core/process-start-token.d.ts +7 -0
  157. package/dist/core/process-start-token.d.ts.map +1 -1
  158. package/dist/core/process-start-token.js +14 -0
  159. package/dist/core/process-start-token.js.map +1 -1
  160. package/dist/core/project-trust-electorate.d.ts +24 -0
  161. package/dist/core/project-trust-electorate.d.ts.map +1 -0
  162. package/dist/core/project-trust-electorate.js +52 -0
  163. package/dist/core/project-trust-electorate.js.map +1 -0
  164. package/dist/core/project-trust-state.d.ts +15 -0
  165. package/dist/core/project-trust-state.d.ts.map +1 -1
  166. package/dist/core/project-trust-state.js +15 -0
  167. package/dist/core/project-trust-state.js.map +1 -1
  168. package/dist/core/provider-request-admission.d.ts.map +1 -1
  169. package/dist/core/provider-request-admission.js +2 -2
  170. package/dist/core/provider-request-admission.js.map +1 -1
  171. package/dist/core/queued-input-admission.js +2 -2
  172. package/dist/core/queued-input-admission.js.map +1 -1
  173. package/dist/core/queued-message-delivery.d.ts +2 -2
  174. package/dist/core/queued-message-delivery.d.ts.map +1 -1
  175. package/dist/core/queued-message-delivery.js +6 -3
  176. package/dist/core/queued-message-delivery.js.map +1 -1
  177. package/dist/core/resource-admission-scope.js +2 -2
  178. package/dist/core/resource-admission-scope.js.map +1 -1
  179. package/dist/core/resume/blueprint/process.d.ts +3 -4
  180. package/dist/core/resume/blueprint/process.d.ts.map +1 -1
  181. package/dist/core/resume/blueprint/process.js +33 -17
  182. package/dist/core/resume/blueprint/process.js.map +1 -1
  183. package/dist/core/resume/path-mapping.js +4 -4
  184. package/dist/core/resume/path-mapping.js.map +1 -1
  185. package/dist/core/resume/session-resume.d.ts +9 -0
  186. package/dist/core/resume/session-resume.d.ts.map +1 -1
  187. package/dist/core/resume/session-resume.js +27 -2
  188. package/dist/core/resume/session-resume.js.map +1 -1
  189. package/dist/core/resume-cache-checkpoint.d.ts +27 -1
  190. package/dist/core/resume-cache-checkpoint.d.ts.map +1 -1
  191. package/dist/core/resume-cache-checkpoint.js +45 -0
  192. package/dist/core/resume-cache-checkpoint.js.map +1 -1
  193. package/dist/core/sdk.d.ts.map +1 -1
  194. package/dist/core/sdk.js +7 -31
  195. package/dist/core/sdk.js.map +1 -1
  196. package/dist/core/session-lifecycle-scope.d.ts +1 -2
  197. package/dist/core/session-lifecycle-scope.d.ts.map +1 -1
  198. package/dist/core/session-lifecycle-scope.js +2 -2
  199. package/dist/core/session-lifecycle-scope.js.map +1 -1
  200. package/dist/core/session-lifecycle-work.js +2 -2
  201. package/dist/core/session-lifecycle-work.js.map +1 -1
  202. package/dist/core/session-manager-core.d.ts.map +1 -1
  203. package/dist/core/session-manager-core.js +3 -0
  204. package/dist/core/session-manager-core.js.map +1 -1
  205. package/dist/core/session-storage.d.ts +12 -0
  206. package/dist/core/session-storage.d.ts.map +1 -1
  207. package/dist/core/session-storage.js +68 -1
  208. package/dist/core/session-storage.js.map +1 -1
  209. package/dist/core/settings-lock-directory.d.ts.map +1 -1
  210. package/dist/core/settings-lock-directory.js +4 -3
  211. package/dist/core/settings-lock-directory.js.map +1 -1
  212. package/dist/core/settings-write-ownership.d.ts +1 -2
  213. package/dist/core/settings-write-ownership.d.ts.map +1 -1
  214. package/dist/core/settings-write-ownership.js +2 -2
  215. package/dist/core/settings-write-ownership.js.map +1 -1
  216. package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -1
  217. package/dist/core/storage/node-sqlite-thread.js +6 -4
  218. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  219. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  220. package/dist/core/storage/node-sqlite.js +22 -8
  221. package/dist/core/storage/node-sqlite.js.map +1 -1
  222. package/dist/core/system-prompt.d.ts +16 -2
  223. package/dist/core/system-prompt.d.ts.map +1 -1
  224. package/dist/core/system-prompt.js +33 -6
  225. package/dist/core/system-prompt.js.map +1 -1
  226. package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
  227. package/dist/core/tasks/agent-adapter.js +2 -1
  228. package/dist/core/tasks/agent-adapter.js.map +1 -1
  229. package/dist/core/tasks/completion.d.ts +3 -2
  230. package/dist/core/tasks/completion.d.ts.map +1 -1
  231. package/dist/core/tasks/completion.js.map +1 -1
  232. package/dist/core/tasks/execution-scope.js +2 -2
  233. package/dist/core/tasks/execution-scope.js.map +1 -1
  234. package/dist/core/tools/bash.d.ts.map +1 -1
  235. package/dist/core/tools/bash.js +2 -1
  236. package/dist/core/tools/bash.js.map +1 -1
  237. package/dist/core/tools/history-regex-worker.d.ts.map +1 -1
  238. package/dist/core/tools/history-regex-worker.js +3 -2
  239. package/dist/core/tools/history-regex-worker.js.map +1 -1
  240. package/dist/core/tools/shell-task-render.d.ts +3 -2
  241. package/dist/core/tools/shell-task-render.d.ts.map +1 -1
  242. package/dist/core/tools/shell-task-render.js +7 -5
  243. package/dist/core/tools/shell-task-render.js.map +1 -1
  244. package/dist/core/tools/shell-task-status.d.ts +6 -2
  245. package/dist/core/tools/shell-task-status.d.ts.map +1 -1
  246. package/dist/core/tools/shell-task-status.js +13 -8
  247. package/dist/core/tools/shell-task-status.js.map +1 -1
  248. package/dist/core/tools/sqlite-selector-connection.d.ts.map +1 -1
  249. package/dist/core/tools/sqlite-selector-connection.js +4 -3
  250. package/dist/core/tools/sqlite-selector-connection.js.map +1 -1
  251. package/dist/core/tools/windows-directory-security.d.ts.map +1 -1
  252. package/dist/core/tools/windows-directory-security.js +2 -1
  253. package/dist/core/tools/windows-directory-security.js.map +1 -1
  254. package/dist/core/worktree-snapshot/git.js +2 -2
  255. package/dist/core/worktree-snapshot/git.js.map +1 -1
  256. package/dist/extensions/mcp/index.d.ts +6 -1
  257. package/dist/extensions/mcp/index.d.ts.map +1 -1
  258. package/dist/extensions/mcp/index.js +150 -18
  259. package/dist/extensions/mcp/index.js.map +1 -1
  260. package/dist/extensions/mcp/tool-records.d.ts +44 -9
  261. package/dist/extensions/mcp/tool-records.d.ts.map +1 -1
  262. package/dist/extensions/mcp/tool-records.js +58 -16
  263. package/dist/extensions/mcp/tool-records.js.map +1 -1
  264. package/dist/index.d.ts +2 -0
  265. package/dist/index.d.ts.map +1 -1
  266. package/dist/index.js +4 -0
  267. package/dist/index.js.map +1 -1
  268. package/dist/main-session.d.ts +3 -1
  269. package/dist/main-session.d.ts.map +1 -1
  270. package/dist/main-session.js +1 -0
  271. package/dist/main-session.js.map +1 -1
  272. package/dist/main.d.ts.map +1 -1
  273. package/dist/main.js +230 -96
  274. package/dist/main.js.map +1 -1
  275. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts +5 -0
  276. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts.map +1 -1
  277. package/dist/modes/interactive/agent-view/agent-view-bridge.js.map +1 -1
  278. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts +5 -2
  279. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts.map +1 -1
  280. package/dist/modes/interactive/agent-view/agent-view-switcher.js +3 -3
  281. package/dist/modes/interactive/agent-view/agent-view-switcher.js.map +1 -1
  282. package/dist/modes/interactive/agent-view/contracts.d.ts +6 -0
  283. package/dist/modes/interactive/agent-view/contracts.d.ts.map +1 -1
  284. package/dist/modes/interactive/agent-view/contracts.js.map +1 -1
  285. package/dist/modes/interactive/agent-view/install.d.ts.map +1 -1
  286. package/dist/modes/interactive/agent-view/install.js +2 -1
  287. package/dist/modes/interactive/agent-view/install.js.map +1 -1
  288. package/dist/modes/interactive/agent-view/open-port.d.ts +4 -2
  289. package/dist/modes/interactive/agent-view/open-port.d.ts.map +1 -1
  290. package/dist/modes/interactive/agent-view/open-port.js +4 -3
  291. package/dist/modes/interactive/agent-view/open-port.js.map +1 -1
  292. package/dist/modes/interactive/agent-view/prompt-retarget.d.ts.map +1 -1
  293. package/dist/modes/interactive/agent-view/prompt-retarget.js +18 -5
  294. package/dist/modes/interactive/agent-view/prompt-retarget.js.map +1 -1
  295. package/dist/modes/interactive/agent-view/remote-port.d.ts +10 -1
  296. package/dist/modes/interactive/agent-view/remote-port.d.ts.map +1 -1
  297. package/dist/modes/interactive/agent-view/remote-port.js +36 -4
  298. package/dist/modes/interactive/agent-view/remote-port.js.map +1 -1
  299. package/dist/modes/interactive/agent-view/viewed-keys.d.ts +56 -0
  300. package/dist/modes/interactive/agent-view/viewed-keys.d.ts.map +1 -0
  301. package/dist/modes/interactive/agent-view/viewed-keys.js +63 -0
  302. package/dist/modes/interactive/agent-view/viewed-keys.js.map +1 -0
  303. package/dist/modes/interactive/agent-view/viewed-submit.d.ts +14 -4
  304. package/dist/modes/interactive/agent-view/viewed-submit.d.ts.map +1 -1
  305. package/dist/modes/interactive/agent-view/viewed-submit.js +51 -17
  306. package/dist/modes/interactive/agent-view/viewed-submit.js.map +1 -1
  307. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  308. package/dist/modes/interactive/components/agent-panel.js +8 -21
  309. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  310. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  311. package/dist/modes/interactive/components/chat-session-host-actions.js +18 -5
  312. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  313. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  314. package/dist/modes/interactive/components/chat-session-host-rendering.js +6 -0
  315. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  316. package/dist/modes/interactive/components/chat-session-host-state.d.ts +1 -0
  317. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  318. package/dist/modes/interactive/components/chat-session-host-state.js +2 -0
  319. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  320. package/dist/modes/interactive/components/chat-session-host-types.d.ts +5 -0
  321. package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
  322. package/dist/modes/interactive/components/chat-session-host-types.js.map +1 -1
  323. package/dist/modes/interactive/components/custom-editor.d.ts +33 -2
  324. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  325. package/dist/modes/interactive/components/custom-editor.js +58 -2
  326. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  327. package/dist/modes/interactive/components/host-session-picker.js +2 -2
  328. package/dist/modes/interactive/components/host-session-picker.js.map +1 -1
  329. package/dist/modes/interactive/components/main-composer-keys.d.ts +16 -5
  330. package/dist/modes/interactive/components/main-composer-keys.d.ts.map +1 -1
  331. package/dist/modes/interactive/components/main-composer-keys.js +27 -8
  332. package/dist/modes/interactive/components/main-composer-keys.js.map +1 -1
  333. package/dist/modes/interactive/components/notice-line.d.ts +8 -25
  334. package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
  335. package/dist/modes/interactive/components/notice-line.js +18 -17
  336. package/dist/modes/interactive/components/notice-line.js.map +1 -1
  337. package/dist/modes/interactive/components/prompt-slot.d.ts +20 -3
  338. package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -1
  339. package/dist/modes/interactive/components/prompt-slot.js +82 -32
  340. package/dist/modes/interactive/components/prompt-slot.js.map +1 -1
  341. package/dist/modes/interactive/components/queued-messages-view.d.ts +5 -2
  342. package/dist/modes/interactive/components/queued-messages-view.d.ts.map +1 -1
  343. package/dist/modes/interactive/components/queued-messages-view.js +12 -5
  344. package/dist/modes/interactive/components/queued-messages-view.js.map +1 -1
  345. package/dist/modes/interactive/components/task-board.d.ts +5 -8
  346. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  347. package/dist/modes/interactive/components/task-board.js +5 -49
  348. package/dist/modes/interactive/components/task-board.js.map +1 -1
  349. package/dist/modes/interactive/components/task-completion-message.d.ts.map +1 -1
  350. package/dist/modes/interactive/components/task-completion-message.js +9 -2
  351. package/dist/modes/interactive/components/task-completion-message.js.map +1 -1
  352. package/dist/modes/interactive/components/task-marks.d.ts +19 -0
  353. package/dist/modes/interactive/components/task-marks.d.ts.map +1 -0
  354. package/dist/modes/interactive/components/task-marks.js +25 -0
  355. package/dist/modes/interactive/components/task-marks.js.map +1 -0
  356. package/dist/modes/interactive/components/task-row.d.ts +10 -2
  357. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  358. package/dist/modes/interactive/components/task-row.js +39 -32
  359. package/dist/modes/interactive/components/task-row.js.map +1 -1
  360. package/dist/modes/interactive/components/task-transcript-page.d.ts +7 -0
  361. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  362. package/dist/modes/interactive/components/task-transcript-page.js +106 -10
  363. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  364. package/dist/modes/interactive/components/tool-block-families.d.ts.map +1 -1
  365. package/dist/modes/interactive/components/tool-block-families.js +8 -9
  366. package/dist/modes/interactive/components/tool-block-families.js.map +1 -1
  367. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  368. package/dist/modes/interactive/components/tool-execution.js +5 -1
  369. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  370. package/dist/modes/interactive/extension-command-hold.d.ts.map +1 -1
  371. package/dist/modes/interactive/extension-command-hold.js +5 -7
  372. package/dist/modes/interactive/extension-command-hold.js.map +1 -1
  373. package/dist/modes/interactive/interactive-extension-dialogs.js +6 -1
  374. package/dist/modes/interactive/interactive-extension-dialogs.js.map +1 -1
  375. package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
  376. package/dist/modes/interactive/interactive-extension-runtime.js +21 -7
  377. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  378. package/dist/modes/interactive/interactive-initial-session-binding.d.ts +1 -2
  379. package/dist/modes/interactive/interactive-initial-session-binding.d.ts.map +1 -1
  380. package/dist/modes/interactive/interactive-initial-session-binding.js +2 -2
  381. package/dist/modes/interactive/interactive-initial-session-binding.js.map +1 -1
  382. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  383. package/dist/modes/interactive/interactive-input-handling.js +13 -4
  384. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  385. package/dist/modes/interactive/interactive-mode-base.d.ts +2 -1
  386. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  387. package/dist/modes/interactive/interactive-mode-base.js +6 -1
  388. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  389. package/dist/modes/interactive/interactive-mode-helpers.d.ts +4 -2
  390. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  391. package/dist/modes/interactive/interactive-mode-helpers.js +6 -0
  392. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  393. package/dist/modes/interactive/interactive-mode-surface.d.ts +5 -0
  394. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  395. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  396. package/dist/modes/interactive/interactive-process-lifecycle.js +96 -17
  397. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  398. package/dist/modes/interactive/interactive-queueing.d.ts +5 -0
  399. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  400. package/dist/modes/interactive/interactive-queueing.js +37 -5
  401. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  402. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  403. package/dist/modes/interactive/interactive-render-chat.js +45 -4
  404. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  405. package/dist/modes/interactive/interactive-resource-disclosure.d.ts +4 -1
  406. package/dist/modes/interactive/interactive-resource-disclosure.d.ts.map +1 -1
  407. package/dist/modes/interactive/interactive-resource-disclosure.js +20 -1
  408. package/dist/modes/interactive/interactive-resource-disclosure.js.map +1 -1
  409. package/dist/modes/interactive/interactive-resource-rendering.js +3 -0
  410. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  411. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  412. package/dist/modes/interactive/interactive-startup.js +43 -5
  413. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  414. package/dist/modes/interactive-engine/activity-watchdog.d.ts +6 -3
  415. package/dist/modes/interactive-engine/activity-watchdog.d.ts.map +1 -1
  416. package/dist/modes/interactive-engine/activity-watchdog.js +3 -2
  417. package/dist/modes/interactive-engine/activity-watchdog.js.map +1 -1
  418. package/dist/modes/interactive-engine/engine-health.d.ts +2 -0
  419. package/dist/modes/interactive-engine/engine-health.d.ts.map +1 -1
  420. package/dist/modes/interactive-engine/engine-health.js.map +1 -1
  421. package/dist/modes/interactive-engine/engine-quit-intent.d.ts +10 -0
  422. package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
  423. package/dist/modes/interactive-engine/engine-quit-intent.js +33 -0
  424. package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
  425. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +7 -1
  426. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  427. package/dist/modes/interactive-engine/extension-ui-bridge.js +15 -2
  428. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  429. package/dist/modes/interactive-engine/host-listener-failures.d.ts +24 -0
  430. package/dist/modes/interactive-engine/host-listener-failures.d.ts.map +1 -0
  431. package/dist/modes/interactive-engine/host-listener-failures.js +98 -0
  432. package/dist/modes/interactive-engine/host-listener-failures.js.map +1 -0
  433. package/dist/modes/interactive-engine/isolated-runtime.d.ts +16 -0
  434. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  435. package/dist/modes/interactive-engine/isolated-runtime.js +74 -7
  436. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  437. package/dist/modes/interactive-engine/protocol.d.ts +5 -0
  438. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  439. package/dist/modes/interactive-engine/protocol.js +8 -2
  440. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  441. package/dist/modes/interactive-engine/remote-component.d.ts +13 -0
  442. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  443. package/dist/modes/interactive-engine/remote-component.js +69 -4
  444. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  445. package/dist/modes/print-mode.d.ts.map +1 -1
  446. package/dist/modes/print-mode.js +34 -6
  447. package/dist/modes/print-mode.js.map +1 -1
  448. package/dist/modes/rpc/agent-panel-bridge.d.ts +7 -0
  449. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  450. package/dist/modes/rpc/agent-panel-bridge.js +11 -1
  451. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  452. package/dist/modes/rpc/agent-view-rpc-panel.d.ts.map +1 -1
  453. package/dist/modes/rpc/agent-view-rpc-panel.js +11 -5
  454. package/dist/modes/rpc/agent-view-rpc-panel.js.map +1 -1
  455. package/dist/modes/rpc/rpc-client-process.d.ts +8 -1
  456. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  457. package/dist/modes/rpc/rpc-client-process.js +89 -65
  458. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  459. package/dist/modes/rpc/rpc-client.d.ts +21 -0
  460. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  461. package/dist/modes/rpc/rpc-client.js +77 -33
  462. package/dist/modes/rpc/rpc-client.js.map +1 -1
  463. package/dist/modes/rpc/rpc-event-buffer.d.ts +5 -0
  464. package/dist/modes/rpc/rpc-event-buffer.d.ts.map +1 -1
  465. package/dist/modes/rpc/rpc-event-buffer.js +8 -2
  466. package/dist/modes/rpc/rpc-event-buffer.js.map +1 -1
  467. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  468. package/dist/modes/rpc/rpc-mode.js +9 -2
  469. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  470. package/dist/utils/shell.d.ts +5 -1
  471. package/dist/utils/shell.d.ts.map +1 -1
  472. package/dist/utils/shell.js +14 -7
  473. package/dist/utils/shell.js.map +1 -1
  474. package/dist/utils/worker-threads.d.ts +10 -4
  475. package/dist/utils/worker-threads.d.ts.map +1 -1
  476. package/dist/utils/worker-threads.js +10 -4
  477. package/dist/utils/worker-threads.js.map +1 -1
  478. package/docs/background-tasks.md +10 -10
  479. package/docs/compaction.md +1 -0
  480. package/docs/development.md +1 -1
  481. package/docs/environment-variables.md +4 -0
  482. package/docs/extensions/api-reference.md +2 -0
  483. package/docs/extensions/events.md +1 -1
  484. package/docs/getting-started/installation.md +1 -0
  485. package/docs/guides/non-interactive.md +2 -0
  486. package/docs/guides/resume-on-any-machine.md +3 -1
  487. package/docs/intercom/reference.md +1 -1
  488. package/docs/keybindings.md +6 -5
  489. package/docs/libraries/ai.md +2 -1
  490. package/docs/mcp-servers.md +1 -1
  491. package/docs/sdk/reference.md +1 -1
  492. package/docs/sdk.md +6 -0
  493. package/docs/security.md +4 -2
  494. package/docs/settings.md +2 -1
  495. package/docs/storage.md +2 -0
  496. package/docs/subagents.md +2 -2
  497. package/docs/tui/reference.md +3 -1
  498. package/npm-shrinkwrap.json +49 -49
  499. package/package.json +6 -6
@@ -0,0 +1,731 @@
1
+ """Start Atomic for the description scripts and stop everything they start.
2
+
3
+ The scripts start `atomic` as their own child processes. Each child stays in
4
+ the shell job the scripts run in, so Ctrl+Z, fg, bg and Ctrl+C reach it
5
+ exactly as they reach the scripts. Each child is set up to start no processes
6
+ of its own: no extensions, MCP servers or command-running tools, and no second
7
+ Node process for a larger heap.
8
+
9
+ Only the thread that started a child signals, waits for and reaps it, so a
10
+ signal never reaches a process ID that the system has given to another
11
+ process. Cancelling only sets a flag. Every wait checks it at least every
12
+ POLL_SECONDS, and the waiting thread then stops its own child: SIGTERM, a
13
+ second SIGTERM if it is still running, then SIGKILL.
14
+
15
+ On Windows a child runs in a job object, which ends it and anything it starts
16
+ when the evaluation stops it or when the scripts' own process ends.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import shutil
23
+ import signal
24
+ import subprocess
25
+ import sys
26
+ import threading
27
+ import time
28
+ from collections.abc import Callable, Iterator, Sequence
29
+ from pathlib import Path
30
+ from queue import Empty, SimpleQueue
31
+
32
+ POLL_SECONDS = 0.1
33
+ _POLL_NS = 100_000_000
34
+ # A child asked to stop has this many polls to exit before it is asked again, and as many again
35
+ # before it is killed. They are counted rather than timed: time the job spends stopped by Ctrl+Z
36
+ # does not use them up.
37
+ STOP_POLLS = 50
38
+ # Node's default heap is enough for one short run; Atomic then runs in a single process instead of
39
+ # starting a second one with a larger heap.
40
+ CHILD_ENVIRONMENT = {"ATOMIC_HEAP_MB": "0"}
41
+ # Nothing that starts processes: extensions, MCP servers, prompt templates. Tools are chosen per use.
42
+ ISOLATED_RUN = ["--no-session", "--no-extensions", "--no-mcp", "--no-prompt-templates"]
43
+ # Exit status of a Windows console program that Ctrl+C, Ctrl+Break or closing the console ended
44
+ # (STATUS_CONTROL_C_EXIT, 0xC000013A, as a signed 32-bit exit code).
45
+ WINDOWS_INTERRUPTED_STATUS = -1073741510
46
+ # Characters cmd.exe interprets in a batch file's arguments.
47
+ _BATCH_UNSAFE = frozenset('"%!^&|<>()\r\n')
48
+
49
+
50
+ class Cancelled(Exception):
51
+ """The evaluation was cancelled by cancel() or by a stop signal."""
52
+
53
+
54
+ class AtomicNotFound(FileNotFoundError):
55
+ """No `atomic` command to run."""
56
+
57
+
58
+ _generation = 0
59
+ # Evaluations, queries and improvement calls in progress, each counted before it creates a temporary
60
+ # folder or a process. While it is zero a stop signal has nothing to clean up and ends the script at once.
61
+ _owners = 0
62
+
63
+
64
+ def cancel() -> None:
65
+ """Cancel every evaluation that started before this call.
66
+
67
+ Running queries stop their Atomic processes, and the evaluation raises
68
+ Cancelled. Safe to call from any thread and from a signal handler.
69
+ """
70
+ global _generation
71
+ _generation += 1
72
+
73
+
74
+ class Cancellation:
75
+ """One evaluation's cancellation: by cancel(), by a stop signal, or by its own cancel()."""
76
+
77
+ def __init__(self) -> None:
78
+ self._generation = _generation
79
+ self._cancelled = False
80
+
81
+ def cancel(self) -> None:
82
+ self._cancelled = True
83
+
84
+ @property
85
+ def cancelled(self) -> bool:
86
+ return self._cancelled or self._generation != _generation or _stop_signal is not None
87
+
88
+ def check(self) -> None:
89
+ if self.cancelled:
90
+ raise Cancelled("The evaluation was cancelled")
91
+
92
+
93
+ class Owner:
94
+ """Counts what is in progress, from before it creates anything until it has cleaned up."""
95
+
96
+ def __enter__(self) -> Owner:
97
+ global _owners
98
+ _owners += 1
99
+ return self
100
+
101
+ def __exit__(self, *_exception: object) -> None:
102
+ global _owners
103
+ _owners -= 1
104
+
105
+
106
+ def atomic_command() -> list[str]:
107
+ """The command that starts Atomic.
108
+
109
+ That is the installation this skill ships in when it can be run directly,
110
+ and otherwise `atomic` on PATH.
111
+ """
112
+ scripts = Path(__file__).resolve().parent
113
+ # <root>/builtin/subagents/skills/skill-creator/scripts, where <root> is an npm or Bun
114
+ # package's dist/ folder or the folder holding the standalone executable.
115
+ builtin = scripts.parents[3]
116
+ if builtin.name == "builtin":
117
+ root = builtin.parent
118
+ for name in ("atomic.exe", "atomic") if os.name == "nt" else ("atomic",):
119
+ executable = root / name
120
+ if executable.is_file() and os.access(executable, os.X_OK):
121
+ return [str(executable)]
122
+ node = shutil.which("node")
123
+ if root.name == "dist" and (root / "cli.js").is_file() and node:
124
+ return [node, str(root / "cli.js")]
125
+ found = shutil.which("atomic")
126
+ if found is None:
127
+ raise AtomicNotFound("Atomic was not found: install it, or add the `atomic` command to PATH")
128
+ if os.name == "nt" and Path(found).suffix.lower() in (".cmd", ".bat"):
129
+ # npm's shim runs <prefix>/node_modules/@bastani/atomic/dist/cli.js with node. Running that
130
+ # directly keeps cmd.exe from reading the arguments.
131
+ cli = Path(found).parent / "node_modules" / "@bastani" / "atomic" / "dist" / "cli.js"
132
+ bundled_node = Path(found).parent / "node.exe"
133
+ node = str(bundled_node) if bundled_node.is_file() else shutil.which("node")
134
+ if cli.is_file() and node:
135
+ return [node, str(cli)]
136
+ return [found]
137
+
138
+
139
+ def _check_batch_arguments(command: Sequence[str], arguments: Sequence[str]) -> None:
140
+ if os.name != "nt" or Path(command[0]).suffix.lower() not in (".cmd", ".bat"):
141
+ return
142
+ for argument in arguments:
143
+ if _BATCH_UNSAFE.intersection(argument):
144
+ raise ValueError(
145
+ f"{command[0]} is a batch file, which cannot be given {argument!r} safely; "
146
+ "add Atomic's own executable to PATH instead"
147
+ )
148
+
149
+
150
+ def remove_path(path: Path) -> None:
151
+ """Remove a temporary file or folder the scripts created, never raising.
152
+
153
+ On Windows a process that has not quite exited, or any other process, can hold one of its files
154
+ open; removal is retried for a bounded time and then left to the system's temporary folder, so
155
+ a query reports its own outcome rather than this cleanup.
156
+ """
157
+ for attempt in range(STOP_POLLS):
158
+ try:
159
+ if path.is_dir() and not path.is_symlink():
160
+ shutil.rmtree(path)
161
+ else:
162
+ path.unlink(missing_ok=True)
163
+ return
164
+ except FileNotFoundError:
165
+ return
166
+ except OSError:
167
+ if os.name != "nt" or attempt == STOP_POLLS - 1:
168
+ return
169
+ time.sleep(POLL_SECONDS)
170
+
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # One Atomic process
174
+ # ---------------------------------------------------------------------------
175
+
176
+ # Started on Windows in the job's place: it starts Atomic only after reading one byte, which the
177
+ # scripts write once the job holds it, so Atomic and everything it starts begin inside the job. If the
178
+ # scripts end first, the byte never comes and nothing is started.
179
+ _WINDOWS_GATE = "import os,subprocess,sys\nif os.read(0,1)!=b'1':sys.exit(1)\nsys.exit(subprocess.call(sys.argv[1:]))"
180
+
181
+
182
+ class AtomicProcess:
183
+ """One `atomic` run: its prompt goes to standard input, its output is read line by line.
184
+
185
+ Use it from one thread only, the one that created it, and close it on every path.
186
+ """
187
+
188
+ def __init__(
189
+ self,
190
+ arguments: Sequence[str],
191
+ prompt: str,
192
+ cwd: str | os.PathLike[str] | None,
193
+ stderr_path: Path,
194
+ cancellation: Cancellation,
195
+ command: Sequence[str] | None = None,
196
+ deadline_ns: int | None = None,
197
+ ) -> None:
198
+ cancellation.check()
199
+ self._cancellation = cancellation
200
+ command = list(command) if command is not None else atomic_command()
201
+ _check_batch_arguments(command, arguments)
202
+ argv = [*command, *arguments]
203
+ environment = {**os.environ, **CHILD_ENVIRONMENT}
204
+ self._stderr_path = stderr_path
205
+ self._stderr = open(stderr_path, "wb")
206
+ self._job: _WindowsJob | None = None
207
+ self._lines: SimpleQueue[bytes | None] = SimpleQueue()
208
+ data = prompt.encode("utf-8")
209
+
210
+ def admit() -> None:
211
+ # Checked again right before the start: a query that waited to start may have been
212
+ # cancelled, or run out of time, in the meantime.
213
+ cancellation.check()
214
+ if deadline_ns is not None and time.monotonic_ns() >= deadline_ns:
215
+ raise TimeoutError("Timed out before Atomic started")
216
+
217
+ try:
218
+ if os.name == "nt":
219
+ self._job = _WindowsJob()
220
+ admit()
221
+ self.process = subprocess.Popen(
222
+ # -I -S: no environment variables, user site or site hooks act before the gate.
223
+ [sys.executable, "-I", "-S", "-c", _WINDOWS_GATE, *argv],
224
+ stdin=subprocess.PIPE,
225
+ stdout=subprocess.PIPE,
226
+ stderr=self._stderr,
227
+ cwd=cwd,
228
+ env=environment,
229
+ # Ctrl+C reaches the scripts, which end the job.
230
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
231
+ )
232
+ try:
233
+ self._job.assign(self.process.pid)
234
+ except BaseException:
235
+ self.process.stdin.close()
236
+ self.process.wait()
237
+ raise
238
+ data = b"1" + data
239
+ else:
240
+ self.process = _start_in_job(argv, cwd, environment, self._stderr, admit)
241
+ except BaseException:
242
+ if self._job is not None:
243
+ self._job.close()
244
+ self._stderr.close()
245
+ raise
246
+ self._writer = threading.Thread(target=self._write, args=(data,), daemon=True)
247
+ self._reader = threading.Thread(target=self._read, daemon=True)
248
+ self._writer.start()
249
+ self._reader.start()
250
+
251
+ def _write(self, data: bytes) -> None:
252
+ try:
253
+ self.process.stdin.write(data)
254
+ self.process.stdin.close()
255
+ except (OSError, ValueError):
256
+ pass # The process ended without reading its prompt; its exit status says why.
257
+
258
+ def _read(self) -> None:
259
+ try:
260
+ for line in iter(self.process.stdout.readline, b""):
261
+ self._lines.put(line)
262
+ except (OSError, ValueError):
263
+ pass
264
+ finally:
265
+ self._lines.put(None)
266
+
267
+ def lines(self, deadline_ns: int | None = None) -> Iterator[bytes]:
268
+ """Output lines until the end of output; the last one may lack its newline.
269
+
270
+ Raises Cancelled when the evaluation is cancelled and TimeoutError once
271
+ the monotonic deadline has passed, even for output that is waiting.
272
+ """
273
+ while True:
274
+ self._cancellation.check()
275
+ wait = POLL_SECONDS
276
+ if deadline_ns is not None:
277
+ remaining = deadline_ns - time.monotonic_ns()
278
+ if remaining <= 0:
279
+ raise TimeoutError("Timed out waiting for Atomic")
280
+ # A large budget need not fit a float or the platform's timer.
281
+ wait = min(remaining, _POLL_NS) / 1_000_000_000
282
+ try:
283
+ line = self._lines.get(timeout=wait)
284
+ except Empty:
285
+ continue
286
+ if line is None:
287
+ return
288
+ self._cancellation.check()
289
+ if deadline_ns is not None and time.monotonic_ns() >= deadline_ns:
290
+ raise TimeoutError("Timed out waiting for Atomic")
291
+ yield line
292
+
293
+ def wait_for_exit(self, deadline_ns: int | None = None, polls: int | None = None) -> int | None:
294
+ """The exit status once the process has exited, or None if it still runs at the deadline
295
+ or after `polls` polls. Raises Cancelled when the evaluation is cancelled."""
296
+ while polls is None or polls > 0:
297
+ self._cancellation.check()
298
+ wait = POLL_SECONDS
299
+ if deadline_ns is not None:
300
+ remaining = deadline_ns - time.monotonic_ns()
301
+ if remaining <= 0:
302
+ break
303
+ wait = min(remaining, _POLL_NS) / 1_000_000_000
304
+ try:
305
+ return self.process.wait(wait)
306
+ except subprocess.TimeoutExpired:
307
+ if polls is not None:
308
+ polls -= 1
309
+ return self.process.poll()
310
+
311
+ def stderr_tail(self, limit: int = 2000) -> str:
312
+ """The end of what the process wrote to standard error."""
313
+ self._stderr.flush()
314
+ with open(self._stderr_path, "rb") as stderr:
315
+ stderr.seek(max(0, stderr.seek(0, os.SEEK_END) - limit))
316
+ return stderr.read(limit).decode("utf-8", errors="replace").strip()
317
+
318
+ def close(self) -> None:
319
+ """Stop the process and anything it started, reap it, and release its pipes."""
320
+ try:
321
+ if self._job is not None:
322
+ self._job.terminate()
323
+ self.process.wait()
324
+ # Every process in the job ends asynchronously and keeps its inherited handles,
325
+ # such as the query's error output file, until it has exited.
326
+ self._job.wait_until_empty()
327
+ else:
328
+ _stop(self.process)
329
+ # A process it left behind can hold its output open, even after it exited by itself.
330
+ # While another query's Atomic runs, an orphan may still be working for that one,
331
+ # such as the rest of its credential command, so only a cancelled evaluation or the
332
+ # last Atomic to end clears them.
333
+ _end_orphans(only_when_idle=not self._cancellation.cancelled)
334
+ finally:
335
+ for thread, stream in ((self._writer, self.process.stdin), (self._reader, self.process.stdout)):
336
+ for _ in range(STOP_POLLS):
337
+ if not thread.is_alive():
338
+ break
339
+ thread.join(POLL_SECONDS)
340
+ if thread.is_alive():
341
+ # Still blocked on a pipe that something else keeps open: closing the stream
342
+ # would wait for that thread. The thread ends once the pipe does.
343
+ continue
344
+ try:
345
+ stream.close()
346
+ except OSError:
347
+ pass
348
+ self._stderr.close()
349
+ if self._job is not None:
350
+ self._job.close()
351
+
352
+ def __enter__(self) -> AtomicProcess:
353
+ return self
354
+
355
+ def __exit__(self, *_exception: object) -> None:
356
+ self.close()
357
+
358
+
359
+ # Process IDs of the Atomic children this process started and has not reaped yet. Changed only with
360
+ # the lock held, around the start of a child, so a child is never seen unregistered.
361
+ _children_lock = threading.Lock()
362
+ _owned_pids: set[int] = set()
363
+ # A script run as a command on Linux adopts orphans from its first Atomic on: orphans of a killed
364
+ # Atomic become its children instead of init's, so they can be found and ended. It starts nothing
365
+ # else from then on, so every child it adopts descends from one of its Atomic processes.
366
+ _run_as_command = False
367
+ _adopts_orphans = False
368
+
369
+
370
+ def _start_in_job(
371
+ argv: list[str], cwd, environment: dict[str, str], stderr, admit: Callable[[], None]
372
+ ) -> subprocess.Popen[bytes]:
373
+ """Start a child in this process's own process group, so the shell's job control reaches it.
374
+
375
+ SIGTSTP stays blocked in this thread while the child is created. CPython may create it with
376
+ vfork, which holds this thread until the child starts its program; a Ctrl+Z that stopped the
377
+ child before then would keep this whole process from stopping, and the shell would never see
378
+ the job stop. The child starts with SIGTSTP blocked; Atomic's runtime clears the mask when it
379
+ starts, and a pending stop then takes effect unless the job was continued in the meantime.
380
+ """
381
+ previous = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTSTP})
382
+ try:
383
+ with _children_lock:
384
+ admit()
385
+ if _run_as_command and not _adopts_orphans:
386
+ _adopt_orphans()
387
+ process = subprocess.Popen(
388
+ argv,
389
+ stdin=subprocess.PIPE,
390
+ stdout=subprocess.PIPE,
391
+ stderr=stderr,
392
+ cwd=cwd,
393
+ env=environment,
394
+ )
395
+ _owned_pids.add(process.pid)
396
+ return process
397
+ finally:
398
+ signal.pthread_sigmask(signal.SIG_SETMASK, previous)
399
+
400
+
401
+ def _stop(process: subprocess.Popen[bytes]) -> None:
402
+ """Ask the child to stop (Atomic ends its own work on SIGTERM), ask again, then kill it.
403
+
404
+ SIGCONT comes first each time, as with the shell's `kill`, so a child stopped on its own while
405
+ this script runs can act on the request. The child is not reaped until it has exited, so its
406
+ process ID still names it here.
407
+ """
408
+ try:
409
+ for _ in range(2):
410
+ if process.poll() is not None:
411
+ return
412
+ process.send_signal(signal.SIGCONT)
413
+ process.send_signal(signal.SIGTERM)
414
+ for _ in range(STOP_POLLS):
415
+ try:
416
+ process.wait(POLL_SECONDS)
417
+ return
418
+ except subprocess.TimeoutExpired:
419
+ continue
420
+ # Atomic ends the processes it started when it handles SIGTERM. One that did not handle
421
+ # either request is killed; on Linux, as a command, close() ends what it left behind.
422
+ process.send_signal(signal.SIGCONT)
423
+ process.kill()
424
+ process.wait()
425
+ finally:
426
+ with _children_lock:
427
+ _owned_pids.discard(process.pid)
428
+
429
+
430
+ def _child_pids() -> set[int]:
431
+ """This process's children: Linux lists each thread's in /proc/self/task/<id>/children, or,
432
+ without that file, each process's parent in /proc/<pid>/stat."""
433
+ pids: set[int] = set()
434
+ tasks = list(Path("/proc/self/task").iterdir())
435
+ if all((task / "children").exists() for task in tasks):
436
+ for task in tasks:
437
+ try:
438
+ pids.update(int(pid) for pid in (task / "children").read_text().split())
439
+ except OSError:
440
+ continue
441
+ return pids
442
+ me = os.getpid()
443
+ for entry in Path("/proc").iterdir():
444
+ if not entry.name.isdigit():
445
+ continue
446
+ try:
447
+ # The parent follows the parenthesized command name, which may itself contain ") ".
448
+ fields = (entry / "stat").read_text().rsplit(")", 1)[1].split()
449
+ except (OSError, IndexError):
450
+ continue
451
+ if int(fields[1]) == me:
452
+ pids.add(int(entry.name))
453
+ return pids
454
+
455
+
456
+ def _end_orphans(only_when_idle: bool = False) -> None:
457
+ """Kill and reap the orphans this process adopted from its Atomic processes, then theirs.
458
+
459
+ Runs only when this process adopts orphans and, with `only_when_idle`, only when none of its
460
+ Atomic processes runs. Each orphan is an unreaped child of this process while the lock is held,
461
+ so its process ID still names it when it is signalled.
462
+ """
463
+ if not _adopts_orphans:
464
+ return
465
+ with _children_lock:
466
+ if only_when_idle and _owned_pids:
467
+ return
468
+ while orphans := _child_pids() - _owned_pids:
469
+ for pid in orphans:
470
+ os.kill(pid, signal.SIGCONT)
471
+ os.kill(pid, signal.SIGKILL)
472
+ for pid in orphans:
473
+ try:
474
+ os.waitpid(pid, 0)
475
+ except ChildProcessError:
476
+ pass
477
+
478
+
479
+ def _adopt_orphans() -> None:
480
+ """Make this process the reaper of its descendants' orphans (Linux, scripts run as commands).
481
+
482
+ Called with the lock held, before the first Atomic starts.
483
+ """
484
+ global _adopts_orphans
485
+ if not sys.platform.startswith("linux") or not Path("/proc/self/task").is_dir():
486
+ return
487
+ import ctypes
488
+
489
+ libc = ctypes.CDLL(None, use_errno=True)
490
+ pr_set_child_subreaper = 36
491
+ if libc.prctl(pr_set_child_subreaper, 1, 0, 0, 0) == 0:
492
+ _adopts_orphans = True
493
+
494
+
495
+ class _WindowsJob:
496
+ """A job object that ends every process in it when it is terminated or its last handle closes."""
497
+
498
+ def __init__(self) -> None:
499
+ import ctypes
500
+ from ctypes import wintypes
501
+
502
+ class IoCounters(ctypes.Structure):
503
+ _fields_ = [
504
+ (name, ctypes.c_ulonglong)
505
+ for name in (
506
+ "ReadOperationCount",
507
+ "WriteOperationCount",
508
+ "OtherOperationCount",
509
+ "ReadTransferCount",
510
+ "WriteTransferCount",
511
+ "OtherTransferCount",
512
+ )
513
+ ]
514
+
515
+ class BasicLimits(ctypes.Structure):
516
+ _fields_ = [
517
+ ("PerProcessUserTimeLimit", ctypes.c_int64),
518
+ ("PerJobUserTimeLimit", ctypes.c_int64),
519
+ ("LimitFlags", wintypes.DWORD),
520
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
521
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
522
+ ("ActiveProcessLimit", wintypes.DWORD),
523
+ ("Affinity", ctypes.c_size_t),
524
+ ("PriorityClass", wintypes.DWORD),
525
+ ("SchedulingClass", wintypes.DWORD),
526
+ ]
527
+
528
+ class ExtendedLimits(ctypes.Structure):
529
+ _fields_ = [
530
+ ("BasicLimitInformation", BasicLimits),
531
+ ("IoInfo", IoCounters),
532
+ ("ProcessMemoryLimit", ctypes.c_size_t),
533
+ ("JobMemoryLimit", ctypes.c_size_t),
534
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
535
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
536
+ ]
537
+
538
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
539
+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE
540
+ kernel32.CreateJobObjectW.argtypes = (ctypes.c_void_p, wintypes.LPCWSTR)
541
+ kernel32.SetInformationJobObject.restype = wintypes.BOOL
542
+ kernel32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD)
543
+ kernel32.OpenProcess.restype = wintypes.HANDLE
544
+ kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
545
+ kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
546
+ kernel32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE)
547
+ class Accounting(ctypes.Structure):
548
+ _fields_ = [
549
+ ("TotalUserTime", ctypes.c_int64),
550
+ ("TotalKernelTime", ctypes.c_int64),
551
+ ("ThisPeriodTotalUserTime", ctypes.c_int64),
552
+ ("ThisPeriodTotalKernelTime", ctypes.c_int64),
553
+ ("TotalPageFaultCount", wintypes.DWORD),
554
+ ("TotalProcesses", wintypes.DWORD),
555
+ ("ActiveProcesses", wintypes.DWORD),
556
+ ("TotalTerminatedProcesses", wintypes.DWORD),
557
+ ]
558
+
559
+ self._accounting = Accounting
560
+ kernel32.QueryInformationJobObject.restype = wintypes.BOOL
561
+ kernel32.QueryInformationJobObject.argtypes = (
562
+ wintypes.HANDLE,
563
+ ctypes.c_int,
564
+ ctypes.c_void_p,
565
+ wintypes.DWORD,
566
+ ctypes.c_void_p,
567
+ )
568
+ kernel32.TerminateJobObject.restype = wintypes.BOOL
569
+ kernel32.TerminateJobObject.argtypes = (wintypes.HANDLE, wintypes.UINT)
570
+ kernel32.CloseHandle.restype = wintypes.BOOL
571
+ kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)
572
+ self._ctypes = ctypes
573
+ self._kernel32 = kernel32
574
+ handle = kernel32.CreateJobObjectW(None, None)
575
+ if not handle:
576
+ raise ctypes.WinError(ctypes.get_last_error())
577
+ self._handle = handle
578
+ limits = ExtendedLimits()
579
+ limits.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
580
+ extended_limit_information = 9
581
+ if not kernel32.SetInformationJobObject(
582
+ handle, extended_limit_information, ctypes.byref(limits), ctypes.sizeof(limits)
583
+ ):
584
+ error = ctypes.WinError(ctypes.get_last_error())
585
+ self.close()
586
+ raise error
587
+
588
+ def assign(self, pid: int) -> None:
589
+ # The caller's Popen holds the process's handle, so this process ID cannot name another one.
590
+ process_set_quota_and_terminate = 0x0100 | 0x0001
591
+ process = self._kernel32.OpenProcess(process_set_quota_and_terminate, False, pid)
592
+ if not process:
593
+ raise self._ctypes.WinError(self._ctypes.get_last_error())
594
+ try:
595
+ if not self._kernel32.AssignProcessToJobObject(self._handle, process):
596
+ raise self._ctypes.WinError(self._ctypes.get_last_error())
597
+ finally:
598
+ self._kernel32.CloseHandle(process)
599
+
600
+ def terminate(self) -> None:
601
+ if self._handle is not None:
602
+ self._kernel32.TerminateJobObject(self._handle, 1)
603
+
604
+ def wait_until_empty(self) -> None:
605
+ """Wait, for a bounded time, until no process of the job is left."""
606
+ basic_accounting_information = 1
607
+ accounting = self._accounting()
608
+ for _ in range(STOP_POLLS):
609
+ if self._handle is None or not self._kernel32.QueryInformationJobObject(
610
+ self._handle,
611
+ basic_accounting_information,
612
+ self._ctypes.byref(accounting),
613
+ self._ctypes.sizeof(accounting),
614
+ None,
615
+ ):
616
+ return
617
+ if accounting.ActiveProcesses == 0:
618
+ return
619
+ time.sleep(POLL_SECONDS)
620
+
621
+ def close(self) -> None:
622
+ if self._handle is not None:
623
+ self._kernel32.CloseHandle(self._handle)
624
+ self._handle = None
625
+
626
+
627
+ # ---------------------------------------------------------------------------
628
+ # Running a script as a command
629
+ # ---------------------------------------------------------------------------
630
+
631
+ _stop_signal: int | None = None
632
+ _finished = threading.Event()
633
+ _console_handler = None
634
+
635
+
636
+ def _on_stop_signal(signum: int, _frame: object) -> None:
637
+ global _stop_signal
638
+ if _stop_signal is None:
639
+ _stop_signal = signum
640
+ cancel()
641
+ if _owners == 0:
642
+ # Nothing started yet or left to clean up: end now, as the signal's default action would,
643
+ # even while the main thread waits for input.
644
+ _exit_by_signal(signum, flush=False)
645
+
646
+
647
+ def _install_stop_handlers() -> None:
648
+ for name in ("SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"):
649
+ signum = getattr(signal, name, None)
650
+ # A signal the shell left ignored (nohup, or a background job's SIGINT) stays ignored.
651
+ if signum is None or signal.getsignal(signum) == signal.SIG_IGN:
652
+ continue
653
+ signal.signal(signum, _on_stop_signal)
654
+ if hasattr(signal, "SIGCHLD"):
655
+ # A child stays unreaped, so its process ID keeps naming it, until this process waits for
656
+ # it, even when SIGCHLD came in ignored.
657
+ signal.signal(signal.SIGCHLD, signal.SIG_DFL)
658
+ if os.name == "nt":
659
+ _install_console_close_handler()
660
+
661
+
662
+ def _install_console_close_handler() -> None:
663
+ """Closing the console, logging off or shutting down: clean up during the time Windows allows."""
664
+ import ctypes
665
+ from ctypes import wintypes
666
+
667
+ global _console_handler
668
+ close_events = {2, 5, 6} # CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT
669
+
670
+ @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD)
671
+ def handler(event: int) -> bool:
672
+ if event not in close_events:
673
+ return False # Ctrl+C and Ctrl+Break reach the SIGINT and SIGBREAK handlers.
674
+ if _owners == 0:
675
+ return False # Nothing to clean up: Windows ends the process.
676
+ _on_stop_signal(signal.SIGINT, None)
677
+ # Windows ends the process about five seconds after a close event: exit with the
678
+ # console-interrupt status once the cleanup is done, before Windows ends it with another.
679
+ _finished.wait(4)
680
+ os._exit(WINDOWS_INTERRUPTED_STATUS)
681
+
682
+ _console_handler = handler
683
+ ctypes.WinDLL("kernel32").SetConsoleCtrlHandler(handler, True)
684
+
685
+
686
+ def open_in_browser(url: str) -> None:
687
+ """Open a page in the user's browser, as webbrowser.open does, from a separate process.
688
+
689
+ The browser is the user's: it is left open when the script ends or is stopped. Opening it
690
+ from a process that has exited before the first Atomic starts keeps the browser outside
691
+ the processes the script adopts and ends.
692
+ """
693
+ subprocess.run([sys.executable, "-I", "-c", "import sys, webbrowser; webbrowser.open(sys.argv[1])", url])
694
+
695
+
696
+ def _exit_by_signal(signum: int, flush: bool = True) -> None:
697
+ if flush:
698
+ sys.stdout.flush()
699
+ sys.stderr.flush()
700
+ if os.name == "nt":
701
+ os._exit(WINDOWS_INTERRUPTED_STATUS)
702
+ signal.signal(signum, signal.SIG_DFL)
703
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signum})
704
+ os.kill(os.getpid(), signum)
705
+ os._exit(128 + signum)
706
+
707
+
708
+ def run_main(main: Callable[[], None]) -> None:
709
+ """Run a script's main() as a command.
710
+
711
+ SIGINT, SIGTERM and SIGHUP (on Windows Ctrl+C, Ctrl+Break and closing the
712
+ console) cancel the run. Its Atomic processes are stopped and its
713
+ temporary files removed, then the script exits with that signal's status.
714
+ Importing a script never installs these handlers.
715
+ """
716
+ global _run_as_command
717
+ _install_stop_handlers()
718
+ _run_as_command = True
719
+ try:
720
+ main()
721
+ except Cancelled:
722
+ if _stop_signal is None:
723
+ raise
724
+ except AtomicNotFound as error:
725
+ print(f"Error: {error}", file=sys.stderr)
726
+ sys.exit(1)
727
+ finally:
728
+ _end_orphans()
729
+ _finished.set()
730
+ if _stop_signal is not None:
731
+ _exit_by_signal(_stop_signal)