texlite 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/DESIGN.md +357 -21
  2. package/NPM_TESTING.md +23 -0
  3. package/OPERATIONS.md +185 -6
  4. package/README.md +4 -2
  5. package/README.zh-CN.md +3 -2
  6. package/THIRD_PARTY_NOTICES.md +73 -0
  7. package/dist/client/assets/AdminUsers-DXWi8wl0.js +1 -0
  8. package/dist/client/assets/AdminUsers-DXWi8wl0.js.br +0 -0
  9. package/dist/client/assets/AdminUsers-DXWi8wl0.js.gz +0 -0
  10. package/dist/client/assets/AgentIcon-BlHvdrRo.js +1 -0
  11. package/dist/client/assets/AgentIcon-BlHvdrRo.js.br +0 -0
  12. package/dist/client/assets/AgentIcon-BlHvdrRo.js.gz +0 -0
  13. package/dist/client/assets/AgentIcon-DE7FEpRY.css +1 -0
  14. package/dist/client/assets/AgentIcon-DE7FEpRY.css.br +0 -0
  15. package/dist/client/assets/AgentIcon-DE7FEpRY.css.gz +0 -0
  16. package/dist/client/assets/AgentManagement-CDWaxEmP.js +1 -0
  17. package/dist/client/assets/AgentManagement-CDWaxEmP.js.br +0 -0
  18. package/dist/client/assets/AgentManagement-CDWaxEmP.js.gz +0 -0
  19. package/dist/client/assets/AgentTerminal-BXH3gHWm.js +2 -0
  20. package/dist/client/assets/AgentTerminal-BXH3gHWm.js.br +0 -0
  21. package/dist/client/assets/AgentTerminal-BXH3gHWm.js.gz +0 -0
  22. package/dist/client/assets/AgentTerminalSurface-B5LH8GIb.css +1 -0
  23. package/dist/client/assets/AgentTerminalSurface-B5LH8GIb.css.br +0 -0
  24. package/dist/client/assets/AgentTerminalSurface-B5LH8GIb.css.gz +0 -0
  25. package/dist/client/assets/AgentTerminalSurface-D0MLcJmw.js +16 -0
  26. package/dist/client/assets/AgentTerminalSurface-D0MLcJmw.js.br +0 -0
  27. package/dist/client/assets/AgentTerminalSurface-D0MLcJmw.js.gz +0 -0
  28. package/dist/client/assets/{AvatarSettingsDialog-CIPKapVe.js → AvatarSettingsDialog-CtbzavqH.js} +1 -1
  29. package/dist/client/assets/AvatarSettingsDialog-CtbzavqH.js.br +0 -0
  30. package/dist/client/assets/AvatarSettingsDialog-CtbzavqH.js.gz +0 -0
  31. package/dist/client/assets/{CitationLibraryDialog-BhZX8BV2.js → CitationLibraryDialog-CnQVjovw.js} +1 -1
  32. package/dist/client/assets/CitationLibraryDialog-CnQVjovw.js.br +0 -0
  33. package/dist/client/assets/CitationLibraryDialog-CnQVjovw.js.gz +0 -0
  34. package/dist/client/assets/Dashboard-Dzq1oMZU.js +5 -0
  35. package/dist/client/assets/Dashboard-Dzq1oMZU.js.br +0 -0
  36. package/dist/client/assets/Dashboard-Dzq1oMZU.js.gz +0 -0
  37. package/dist/client/assets/GitDialog-CzgguGGW.js +3 -0
  38. package/dist/client/assets/GitDialog-CzgguGGW.js.br +0 -0
  39. package/dist/client/assets/GitDialog-CzgguGGW.js.gz +0 -0
  40. package/dist/client/assets/{GitHubAccountDialog-hosK9cLW.js → GitHubAccountDialog-lRAWfkKP.js} +1 -1
  41. package/dist/client/assets/GitHubAccountDialog-lRAWfkKP.js.br +0 -0
  42. package/dist/client/assets/GitHubAccountDialog-lRAWfkKP.js.gz +0 -0
  43. package/dist/client/assets/{GitHubIcon-DNR0CleM.js → GitHubIcon-BPTVKTrM.js} +1 -1
  44. package/dist/client/assets/HistoryDialog-Bw3GHfbM.js +8 -0
  45. package/dist/client/assets/HistoryDialog-Bw3GHfbM.js.br +0 -0
  46. package/dist/client/assets/HistoryDialog-Bw3GHfbM.js.gz +0 -0
  47. package/dist/client/assets/{LatexEditor-BzAk3WQM.js → LatexEditor-BDpqgoOa.js} +2 -2
  48. package/dist/client/assets/LatexEditor-BDpqgoOa.js.br +0 -0
  49. package/dist/client/assets/LatexEditor-BDpqgoOa.js.gz +0 -0
  50. package/dist/client/assets/PdfPreview-C2puKgCh.js +1 -0
  51. package/dist/client/assets/PdfPreview-C2puKgCh.js.br +0 -0
  52. package/dist/client/assets/PdfPreview-C2puKgCh.js.gz +0 -0
  53. package/dist/client/assets/{ProjectIconPickerDialog-D8Uo4H10.js → ProjectIconPickerDialog-BzNdyAz6.js} +1 -1
  54. package/dist/client/assets/ProjectIconPickerDialog-BzNdyAz6.js.br +0 -0
  55. package/dist/client/assets/ProjectIconPickerDialog-BzNdyAz6.js.gz +0 -0
  56. package/dist/client/assets/ProjectSettings-B_y5nRgp.js +4 -0
  57. package/dist/client/assets/ProjectSettings-B_y5nRgp.js.br +0 -0
  58. package/dist/client/assets/ProjectSettings-B_y5nRgp.js.gz +0 -0
  59. package/dist/client/assets/ProjectWorkspace-BnT5JPTA.js +30 -0
  60. package/dist/client/assets/ProjectWorkspace-BnT5JPTA.js.br +0 -0
  61. package/dist/client/assets/ProjectWorkspace-BnT5JPTA.js.gz +0 -0
  62. package/dist/client/assets/{QuickOpenDialog-CyqeckBM.js → QuickOpenDialog-CEYxIk4l.js} +1 -1
  63. package/dist/client/assets/QuickOpenDialog-CEYxIk4l.js.br +0 -0
  64. package/dist/client/assets/QuickOpenDialog-CEYxIk4l.js.gz +0 -0
  65. package/dist/client/assets/SelectionHistoryDialog-DBL6vVD4.js +3 -0
  66. package/dist/client/assets/SelectionHistoryDialog-DBL6vVD4.js.br +0 -0
  67. package/dist/client/assets/SelectionHistoryDialog-DBL6vVD4.js.gz +0 -0
  68. package/dist/client/assets/SuccessNotice-C8XV7MAJ.js +1 -0
  69. package/dist/client/assets/SystemMetricsDialog-D2EQX5hh.js +1 -0
  70. package/dist/client/assets/SystemMetricsDialog-D2EQX5hh.js.br +0 -0
  71. package/dist/client/assets/SystemMetricsDialog-D2EQX5hh.js.gz +0 -0
  72. package/dist/client/assets/{TagColorSelect-D3T-rw4K.js → TagColorSelect-CfJaFovr.js} +1 -1
  73. package/dist/client/assets/TagManagementDialog-CiJ6AhVk.js +1 -0
  74. package/dist/client/assets/TagManagementDialog-CiJ6AhVk.js.br +0 -0
  75. package/dist/client/assets/TagManagementDialog-CiJ6AhVk.js.gz +0 -0
  76. package/dist/client/assets/{WordCountDialog-Bp8kYngA.js → WordCountDialog-DaHxqArj.js} +1 -1
  77. package/dist/client/assets/WordCountDialog-DaHxqArj.js.br +0 -0
  78. package/dist/client/assets/WordCountDialog-DaHxqArj.js.gz +0 -0
  79. package/dist/client/assets/arrow-down-BySB1dS6.js +1 -0
  80. package/dist/client/assets/check-B-GEn6vk.js +1 -0
  81. package/dist/client/assets/chevron-up-B0yLKMZJ.js +1 -0
  82. package/dist/client/assets/{chktex-BcGmZVUy.js → chktex-B2-niLAo.js} +1 -1
  83. package/dist/client/assets/circle-check-CfK-oqlC.js +1 -0
  84. package/dist/client/assets/{clock-3-x2vcGFSH.js → clock-3-C_8q2yLj.js} +1 -1
  85. package/dist/client/assets/{dist-D5mbpudl.js → dist-CIxSPQK5.js} +1 -1
  86. package/dist/client/assets/dist-CIxSPQK5.js.br +0 -0
  87. package/dist/client/assets/dist-CIxSPQK5.js.gz +0 -0
  88. package/dist/client/assets/{eye-CvzXPIMu.js → eye-DpIOhQ2p.js} +1 -1
  89. package/dist/client/assets/{hard-drive-BeGQ5o79.js → hard-drive-DRbINIYf.js} +1 -1
  90. package/dist/client/assets/i18n-BzlyqR_B.js +13 -0
  91. package/dist/client/assets/i18n-BzlyqR_B.js.br +0 -0
  92. package/dist/client/assets/i18n-BzlyqR_B.js.gz +0 -0
  93. package/dist/client/assets/index-BHHBwQuG.css +1 -0
  94. package/dist/client/assets/index-BHHBwQuG.css.br +0 -0
  95. package/dist/client/assets/index-BHHBwQuG.css.gz +0 -0
  96. package/dist/client/assets/index-h0BVkT8k.js +42 -0
  97. package/dist/client/assets/index-h0BVkT8k.js.br +0 -0
  98. package/dist/client/assets/index-h0BVkT8k.js.gz +0 -0
  99. package/dist/client/assets/info-DB-RajXx.js +1 -0
  100. package/dist/client/assets/{minimize-2-yYMmsVER.js → minimize-2-DtsKyo4M.js} +1 -1
  101. package/dist/client/assets/{minus-CNHOVLWS.js → minus-CdwrG9Yo.js} +1 -1
  102. package/dist/client/assets/plus-PHvPlka_.js +1 -0
  103. package/dist/client/assets/{refresh-cw-B7vZa5K2.js → refresh-cw-c6Tzy-hb.js} +1 -1
  104. package/dist/client/assets/relativeTime-Cf5dzFc9.js +1 -0
  105. package/dist/client/assets/relativeTime-Cf5dzFc9.js.br +0 -0
  106. package/dist/client/assets/relativeTime-Cf5dzFc9.js.gz +0 -0
  107. package/dist/client/assets/{search-Czv3qsBy.js → search-Cy8DgYGb.js} +1 -1
  108. package/dist/client/assets/{spellCheck-DDCaK8Yx.js → spellCheck-DEQIFH7w.js} +1 -1
  109. package/dist/client/assets/spellCheck-DEQIFH7w.js.br +0 -0
  110. package/dist/client/assets/spellCheck-DEQIFH7w.js.gz +0 -0
  111. package/dist/client/assets/{tags-CLK7WRSs.js → tags-BQ0exG-g.js} +1 -1
  112. package/dist/client/assets/terminal-DaAc1558.js +1 -0
  113. package/dist/client/assets/terminalPreferences-CgacIg2F.js +1 -0
  114. package/dist/client/assets/terminalPreferences-CgacIg2F.js.br +0 -0
  115. package/dist/client/assets/terminalPreferences-CgacIg2F.js.gz +0 -0
  116. package/dist/client/assets/{type-NT195OCy.js → type-Cm3TiSO6.js} +1 -1
  117. package/dist/client/assets/{user-plus-BRuwNzcg.js → user-plus-BLC3_SFQ.js} +1 -1
  118. package/dist/client/index.html +13 -7
  119. package/dist/server/agents/adapters/claude.js +19 -0
  120. package/dist/server/agents/adapters/codex.js +47 -0
  121. package/dist/server/agents/adapters/common.js +86 -0
  122. package/dist/server/agents/adapters/opencode.js +184 -0
  123. package/dist/server/agents/adapters/types.js +1 -0
  124. package/dist/server/agents/execution.js +147 -0
  125. package/dist/server/agents/launcher.js +57 -0
  126. package/dist/server/agents/processIdentity.js +63 -0
  127. package/dist/server/agents/registry.js +72 -0
  128. package/dist/server/agents/sessions.js +564 -0
  129. package/dist/server/agents/terminal.js +84 -0
  130. package/dist/server/agents/workspaces.js +341 -0
  131. package/dist/server/app.js +32 -1
  132. package/dist/server/cli.js +19 -47
  133. package/dist/server/collaboration.js +62 -35
  134. package/dist/server/compileArtifacts.js +11 -44
  135. package/dist/server/compiler.js +16 -38
  136. package/dist/server/config.js +8 -2
  137. package/dist/server/db.js +28 -0
  138. package/dist/server/editHistory.js +59 -65
  139. package/dist/server/history.js +28 -13
  140. package/dist/server/i18n.js +26 -8
  141. package/dist/server/latexRoot.js +4 -2
  142. package/dist/server/locales/zh-Hant.js +145 -0
  143. package/dist/server/lucideIcons.js +14 -17
  144. package/dist/server/projectMutations.js +21 -0
  145. package/dist/server/routes/agents.js +135 -0
  146. package/dist/server/routes/compile.js +23 -43
  147. package/dist/server/routes/projectHistory.js +13 -6
  148. package/dist/server/routes/projects.js +15 -23
  149. package/dist/shared/agentMessages.js +51 -0
  150. package/dist/shared/agentProtocol.js +41 -0
  151. package/dist/shared/historyFiles.js +1 -1
  152. package/dist/shared/historyTracking.js +2 -0
  153. package/dist/shared/locales.js +21 -0
  154. package/package.json +7 -3
  155. package/templates/agents/AGENTS.md +135 -0
  156. package/texlite.config.example.json +3 -2
  157. package/dist/client/assets/AdminUsers-rPpYTAU6.js +0 -1
  158. package/dist/client/assets/AdminUsers-rPpYTAU6.js.br +0 -0
  159. package/dist/client/assets/AdminUsers-rPpYTAU6.js.gz +0 -0
  160. package/dist/client/assets/AvatarSettingsDialog-CIPKapVe.js.br +0 -0
  161. package/dist/client/assets/AvatarSettingsDialog-CIPKapVe.js.gz +0 -0
  162. package/dist/client/assets/CitationLibraryDialog-BhZX8BV2.js.br +0 -0
  163. package/dist/client/assets/CitationLibraryDialog-BhZX8BV2.js.gz +0 -0
  164. package/dist/client/assets/Dashboard-DppEhsjL.js +0 -5
  165. package/dist/client/assets/Dashboard-DppEhsjL.js.br +0 -0
  166. package/dist/client/assets/Dashboard-DppEhsjL.js.gz +0 -0
  167. package/dist/client/assets/GitDialog-BOu46hxA.js +0 -3
  168. package/dist/client/assets/GitDialog-BOu46hxA.js.br +0 -0
  169. package/dist/client/assets/GitDialog-BOu46hxA.js.gz +0 -0
  170. package/dist/client/assets/GitHubAccountDialog-hosK9cLW.js.br +0 -0
  171. package/dist/client/assets/GitHubAccountDialog-hosK9cLW.js.gz +0 -0
  172. package/dist/client/assets/HistoryDialog-BdkuEl8r.js +0 -8
  173. package/dist/client/assets/HistoryDialog-BdkuEl8r.js.br +0 -0
  174. package/dist/client/assets/HistoryDialog-BdkuEl8r.js.gz +0 -0
  175. package/dist/client/assets/LatexEditor-BzAk3WQM.js.br +0 -0
  176. package/dist/client/assets/LatexEditor-BzAk3WQM.js.gz +0 -0
  177. package/dist/client/assets/PdfPreview-DkjI1eCo.js +0 -1
  178. package/dist/client/assets/PdfPreview-DkjI1eCo.js.br +0 -0
  179. package/dist/client/assets/PdfPreview-DkjI1eCo.js.gz +0 -0
  180. package/dist/client/assets/ProjectIconPickerDialog-D8Uo4H10.js.br +0 -0
  181. package/dist/client/assets/ProjectIconPickerDialog-D8Uo4H10.js.gz +0 -0
  182. package/dist/client/assets/ProjectSettings-Jdr94nOc.js +0 -1
  183. package/dist/client/assets/ProjectSettings-Jdr94nOc.js.br +0 -0
  184. package/dist/client/assets/ProjectSettings-Jdr94nOc.js.gz +0 -0
  185. package/dist/client/assets/ProjectWorkspace-D9v3Jj8T.js +0 -30
  186. package/dist/client/assets/ProjectWorkspace-D9v3Jj8T.js.br +0 -0
  187. package/dist/client/assets/ProjectWorkspace-D9v3Jj8T.js.gz +0 -0
  188. package/dist/client/assets/QuickOpenDialog-CyqeckBM.js.br +0 -0
  189. package/dist/client/assets/QuickOpenDialog-CyqeckBM.js.gz +0 -0
  190. package/dist/client/assets/SelectionHistoryDialog-Dlutex-A.js +0 -3
  191. package/dist/client/assets/SelectionHistoryDialog-Dlutex-A.js.br +0 -0
  192. package/dist/client/assets/SelectionHistoryDialog-Dlutex-A.js.gz +0 -0
  193. package/dist/client/assets/SystemMetricsDialog-CCWxXw6g.js +0 -1
  194. package/dist/client/assets/SystemMetricsDialog-CCWxXw6g.js.br +0 -0
  195. package/dist/client/assets/SystemMetricsDialog-CCWxXw6g.js.gz +0 -0
  196. package/dist/client/assets/TagManagementDialog-CxjrSX-o.js +0 -1
  197. package/dist/client/assets/TagManagementDialog-CxjrSX-o.js.br +0 -0
  198. package/dist/client/assets/TagManagementDialog-CxjrSX-o.js.gz +0 -0
  199. package/dist/client/assets/WordCountDialog-Bp8kYngA.js.br +0 -0
  200. package/dist/client/assets/WordCountDialog-Bp8kYngA.js.gz +0 -0
  201. package/dist/client/assets/check-DFoA73zZ.js +0 -1
  202. package/dist/client/assets/chevron-up-C8DyKLxi.js +0 -1
  203. package/dist/client/assets/dist-D5mbpudl.js.br +0 -0
  204. package/dist/client/assets/dist-D5mbpudl.js.gz +0 -0
  205. package/dist/client/assets/i18n-CRWKZA6W.js +0 -9
  206. package/dist/client/assets/i18n-CRWKZA6W.js.br +0 -0
  207. package/dist/client/assets/i18n-CRWKZA6W.js.gz +0 -0
  208. package/dist/client/assets/index-D0eqhDpZ.js +0 -42
  209. package/dist/client/assets/index-D0eqhDpZ.js.br +0 -0
  210. package/dist/client/assets/index-D0eqhDpZ.js.gz +0 -0
  211. package/dist/client/assets/index-DnhiIb1V.css +0 -1
  212. package/dist/client/assets/index-DnhiIb1V.css.br +0 -0
  213. package/dist/client/assets/index-DnhiIb1V.css.gz +0 -0
  214. package/dist/client/assets/plus-BDquy76g.js +0 -1
  215. package/dist/client/assets/relativeTime-DuOytR_J.js +0 -1
  216. package/dist/client/assets/relativeTime-DuOytR_J.js.br +0 -0
  217. package/dist/client/assets/relativeTime-DuOytR_J.js.gz +0 -0
  218. package/dist/client/assets/sigma-CI6gmAkl.js +0 -1
  219. package/dist/client/assets/spellCheck-DDCaK8Yx.js.br +0 -0
  220. package/dist/client/assets/spellCheck-DDCaK8Yx.js.gz +0 -0
  221. package/preview-1.png +0 -0
  222. package/preview-2.png +0 -0
@@ -0,0 +1,564 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomInt, randomUUID } from "node:crypto";
4
+ import { AGENT_TASK_PAGE_SIZE, parseAgentClientMessage } from "../../shared/agentProtocol.js";
5
+ import { httpError } from "../http.js";
6
+ import { accessibleProject, canEdit } from "../projects.js";
7
+ import { requireEditableProject } from "../routes/projectShared.js";
8
+ import { AgentRegistry } from "./registry.js";
9
+ import { agentTaskRoot, AgentSourceSync, ensureAgentInstructions, writeAgentProjectContext } from "./workspaces.js";
10
+ import { sourceRoot } from "../files.js";
11
+ import { loadAgentPty, stopAgentPty } from "./terminal.js";
12
+ import { clearAgentExecution, recoverAgentExecution } from "./execution.js";
13
+ const now = () => new Date().toISOString();
14
+ const taskNameCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-";
15
+ function randomTaskName() {
16
+ return Array.from({ length: 6 }, () => taskNameCharacters[randomInt(taskNameCharacters.length)]).join("");
17
+ }
18
+ /** Owns tasks and executions, not provider quotas or per-user runtime limits. */
19
+ export class AgentService {
20
+ context;
21
+ options;
22
+ registry;
23
+ db;
24
+ executions = new Map();
25
+ operations = new Map();
26
+ activeProjects = new Map();
27
+ recoveries = new Map();
28
+ recovery;
29
+ closing = false;
30
+ constructor(context, options = {}) {
31
+ this.context = context;
32
+ this.options = options;
33
+ this.db = context.db;
34
+ this.registry = options.registry ?? new AgentRegistry();
35
+ this.db.prepare("UPDATE agent_tasks SET state = 'interrupted', ended_at = ?, updated_at = ? WHERE state IN ('starting', 'running', 'stopping')").run(now(), now());
36
+ this.db.prepare("UPDATE agent_tasks SET cleanup_state = 'failed', error_code = 'AGENT_CLEANUP_FAILED' WHERE cleanup_state = 'deleting'").run();
37
+ for (const row of this.db.prepare("SELECT * FROM agent_tasks").all()) {
38
+ if (!fs.existsSync(this.executionFile(row.id)))
39
+ continue;
40
+ this.db.prepare("UPDATE agent_tasks SET state = 'stopping', error_code = 'AGENT_RECOVERY_FAILED' WHERE id = ?").run(row.id);
41
+ this.activeProjects.set(row.project_id, row.id);
42
+ const releaseWriter = this.context.projectMutations.registerExternalWriter(row.project_id, async () => { await this.stop(row.id); });
43
+ this.recoveries.set(row.id, () => {
44
+ if (this.activeProjects.get(row.project_id) === row.id)
45
+ this.activeProjects.delete(row.project_id);
46
+ releaseWriter?.();
47
+ });
48
+ }
49
+ this.recovery = this.recoverOnStartup();
50
+ }
51
+ /** Startup recovery completes before new executions or HTTP traffic are admitted. */
52
+ ready() { return this.recovery; }
53
+ policy() {
54
+ const row = this.db.prepare("SELECT allowed FROM agent_policy WHERE id = 1").get();
55
+ return { allowed: JSON.parse(row.allowed) };
56
+ }
57
+ access(userId, projectId) {
58
+ const { total, activeCount } = this.db.prepare(`SELECT COUNT(*) AS total,
59
+ COUNT(CASE WHEN state IN ('starting', 'running', 'stopping')
60
+ AND (? IS NULL OR project_id = ?) THEN 1 END) AS activeCount
61
+ FROM agent_tasks WHERE user_id = ?`).get(projectId ?? null, projectId ?? null, userId);
62
+ return { visible: this.policy().allowed.length > 0 || total > 0, activeCount };
63
+ }
64
+ async catalog(refresh = false) {
65
+ await this.recovery;
66
+ if (refresh)
67
+ this.registry.refresh();
68
+ const policy = this.policy();
69
+ const [agents, factory] = await Promise.all([this.registry.catalog(policy), (this.options.loadPty ?? loadAgentPty)()]);
70
+ return { policy, agents, ptyAvailable: factory !== null };
71
+ }
72
+ async setPolicy(policy) {
73
+ await this.recovery;
74
+ this.db.prepare("UPDATE agent_policy SET allowed = ? WHERE id = 1").run(JSON.stringify([...new Set(policy.allowed)]));
75
+ await this.reconcilePermissions();
76
+ }
77
+ list(user, admin, query) {
78
+ const conditions = [];
79
+ const values = [];
80
+ if (!admin) {
81
+ conditions.push("user_id = ?");
82
+ values.push(user.id);
83
+ }
84
+ if (query.project) {
85
+ conditions.push("(project_id = ? OR COALESCE(p.name, t.project_name) LIKE ?)");
86
+ values.push(query.project, `%${query.project}%`);
87
+ }
88
+ if (admin && query.user) {
89
+ conditions.push("(user_id = ? OR COALESCE(u.display_name, t.user_name) LIKE ?)");
90
+ values.push(query.user, `%${query.user}%`);
91
+ }
92
+ if (query.agent) {
93
+ conditions.push("agent_id = ?");
94
+ values.push(query.agent);
95
+ }
96
+ if (query.state === "running")
97
+ conditions.push("state IN ('starting', 'running', 'stopping')");
98
+ else if (query.state === "cleanup")
99
+ conditions.push("cleanup_state = 'failed'");
100
+ const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
101
+ const from = "FROM agent_tasks t LEFT JOIN projects p ON p.id = t.project_id LEFT JOIN users u ON u.id = t.user_id";
102
+ const { total } = this.db.prepare(`SELECT count(*) AS total ${from} ${where}`).get(...values);
103
+ const requested = Number(query.page ?? 1);
104
+ const page = Math.min(Math.max(1, Number.isSafeInteger(requested) ? requested : 1), Math.max(1, Math.ceil(total / AGENT_TASK_PAGE_SIZE)));
105
+ const rows = this.db.prepare(`SELECT t.*, COALESCE(p.name, t.project_name) AS project_name,
106
+ COALESCE(u.display_name, t.user_name) AS user_name, u.username AS user_username
107
+ ${from} ${where} ORDER BY t.updated_at DESC, t.id LIMIT ? OFFSET ?`).all(...values, AGENT_TASK_PAGE_SIZE, (page - 1) * AGENT_TASK_PAGE_SIZE);
108
+ const project = query.project ? accessibleProject(this.db, query.project, user) : null;
109
+ return { tasks: rows.map((row) => ({ ...this.json(row), userUsername: row.user_username })), total, page, pageSize: AGENT_TASK_PAGE_SIZE,
110
+ activeTaskId: project && canEdit(project) ? this.activeProjects.get(project.id) ?? null : null };
111
+ }
112
+ task(id, user, administration = false) {
113
+ return this.json(this.owned(id, user, administration));
114
+ }
115
+ async refreshProjectContext(projectId) {
116
+ const id = this.activeProjects.get(projectId);
117
+ if (id)
118
+ await this.withTask(id, async () => {
119
+ if (this.activeProjects.get(projectId) === id)
120
+ await writeAgentProjectContext(this.context, id, projectId);
121
+ });
122
+ }
123
+ async create(projectId, user, agentId, title) {
124
+ await this.recovery;
125
+ this.requireEnabled(agentId);
126
+ const project = requireEditableProject(this.db, projectId, user);
127
+ if (!(await this.registry.detect(agentId)).executable)
128
+ throw httpError(409, "AGENT_UNAVAILABLE");
129
+ if (this.closing)
130
+ throw httpError(409, "AGENT_UNAVAILABLE");
131
+ const id = randomUUID();
132
+ const timestamp = now();
133
+ this.db.prepare(`INSERT INTO agent_tasks
134
+ (id, project_id, user_id, project_name, user_name, agent_id, title, created_at, updated_at)
135
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
136
+ .run(id, projectId, user.id, project.name, user.display_name, agentId, title?.trim() || randomTaskName(), timestamp, timestamp);
137
+ try {
138
+ await fs.promises.mkdir(path.join(agentTaskRoot(this.context.config, id), "state"), { recursive: true, mode: 0o700 });
139
+ requireEditableProject(this.db, projectId, user);
140
+ this.requireEnabled(agentId);
141
+ return this.task(id, user);
142
+ }
143
+ catch (error) {
144
+ await fs.promises.rm(agentTaskRoot(this.context.config, id), { recursive: true, force: true });
145
+ this.db.prepare("DELETE FROM agent_tasks WHERE id = ?").run(id);
146
+ throw error;
147
+ }
148
+ }
149
+ update(id, user, changes) {
150
+ const row = this.owned(id, user);
151
+ if (row.cleanup_state === "deleting")
152
+ throw httpError(409, "AGENT_SESSION_BUSY");
153
+ this.db.prepare("UPDATE agent_tasks SET title = ?, updated_at = ? WHERE id = ?")
154
+ .run(changes.title, now(), id);
155
+ return this.task(id, user);
156
+ }
157
+ async start(id, user) {
158
+ return this.withTask(id, async () => {
159
+ let row = this.owned(id, user);
160
+ this.requireEditable(row);
161
+ if (this.recoveries.has(id))
162
+ throw httpError(409, "AGENT_RECOVERY_FAILED");
163
+ if (this.executions.has(id))
164
+ return this.json(row);
165
+ if (row.cleanup_state !== "none")
166
+ throw httpError(409, "AGENT_SESSION_BUSY");
167
+ // Claim synchronously before discovery/credential preparation can yield.
168
+ // This applies to all users, agents and tasks in this project.
169
+ if (this.activeProjects.has(row.project_id))
170
+ throw httpError(409, "AGENT_PROJECT_BUSY");
171
+ const releaseWriter = this.context.projectMutations.registerExternalWriter(row.project_id, async () => { await this.stop(id); });
172
+ if (!releaseWriter)
173
+ throw httpError(409, "AGENT_PROJECT_BUSY");
174
+ this.activeProjects.set(row.project_id, id);
175
+ const releaseProject = () => {
176
+ if (this.activeProjects.get(row.project_id) === id)
177
+ this.activeProjects.delete(row.project_id);
178
+ releaseWriter();
179
+ };
180
+ let source;
181
+ try {
182
+ // Starting a CLI is not the same as creating its first conversation.
183
+ // A verified empty native store may be launched again in the same task;
184
+ // a known conversation is always resumed, never silently replaced.
185
+ let native;
186
+ if (row.ever_started && !row.native_session_id) {
187
+ native = await this.captureContext(id);
188
+ row = this.owned(id, user);
189
+ }
190
+ const resume = Boolean(row.native_session_id);
191
+ const adapter = this.registry.adapter(row.agent_id);
192
+ const root = agentTaskRoot(this.context.config, id);
193
+ const context = await this.registry.context(row.agent_id, id, root, row.native_session_id, sourceRoot(this.context.config, row.project_id));
194
+ if (!context.executable)
195
+ throw httpError(409, "AGENT_UNAVAILABLE");
196
+ if (!resume && row.ever_started && native?.status !== "empty")
197
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
198
+ if (resume && !adapter.supportsResume)
199
+ throw httpError(409, "AGENT_NO_CONTEXT");
200
+ const spawn = await (this.options.loadPty ?? loadAgentPty)();
201
+ if (!spawn)
202
+ throw httpError(409, "AGENT_PTY_UNAVAILABLE");
203
+ await fs.promises.mkdir(context.stateDirectory, { recursive: true, mode: 0o700 });
204
+ await adapter.prepare(context);
205
+ await ensureAgentInstructions(this.context, row.project_id, user);
206
+ await writeAgentProjectContext(this.context, id, row.project_id);
207
+ source = new AgentSourceSync(this.context, id, row.project_id, row.user_id, (error) => {
208
+ const code = error instanceof Error && "code" in error && error.code === "AGENT_SYNC_CONFLICT" ? "AGENT_SYNC_CONFLICT" : "AGENT_SYNC_FAILED";
209
+ this.db.prepare("UPDATE agent_tasks SET error_code = ? WHERE id = ?").run(code, id);
210
+ this.options.onError?.(error);
211
+ void this.stop(id).catch((failure) => this.options.onError?.(failure));
212
+ });
213
+ await source.start();
214
+ this.requireEditable(row);
215
+ if (this.closing)
216
+ throw httpError(409, "AGENT_UNAVAILABLE");
217
+ this.db.prepare("UPDATE agent_tasks SET state = 'starting', error_code = NULL, updated_at = ? WHERE id = ?").run(now(), id);
218
+ try {
219
+ const command = resume ? adapter.resume({ ...context, nativeSessionId: row.native_session_id }) : adapter.start(context);
220
+ const pty = await spawn(command.executable, command.args, { name: "xterm-256color", cwd: context.workingDirectory, env: command.env, cols: 100, rows: 24,
221
+ executionFile: this.executionFile(id),
222
+ beforeStart: () => { this.db.prepare("UPDATE agent_tasks SET ever_started = 1 WHERE id = ?").run(id); } });
223
+ let finish;
224
+ const execution = { pty, attachments: new Set(), controller: null, output: "", stopping: false, termination: null, exitCode: null,
225
+ finished: new Promise((resolve) => { finish = resolve; }), finish: () => finish(), subscriptions: [], source, releaseProject };
226
+ this.executions.set(id, execution);
227
+ execution.subscriptions.push(pty.onData((data) => this.output(id, execution, data)));
228
+ execution.subscriptions.push(pty.onExit(({ exitCode }) => {
229
+ if (this.executions.get(id) !== execution || execution.exitCode !== null)
230
+ return;
231
+ execution.exitCode = exitCode;
232
+ execution.finish();
233
+ // A CLI may leave workers alive after its parent exits. Reap the
234
+ // remaining owned process group before releasing this execution.
235
+ if (!execution.termination)
236
+ void this.terminate(id, execution, "exited").catch((error) => this.options.onError?.(error));
237
+ }));
238
+ this.db.prepare("UPDATE agent_tasks SET state = 'running', ever_started = 1, started_at = ?, ended_at = NULL, exit_code = NULL, updated_at = ? WHERE id = ?")
239
+ .run(now(), now(), id);
240
+ return this.task(id, user);
241
+ }
242
+ catch (error) {
243
+ this.options.onError?.(error);
244
+ this.db.prepare("UPDATE agent_tasks SET state = 'failed', error_code = 'AGENT_START_FAILED', updated_at = ? WHERE id = ?").run(now(), id);
245
+ throw httpError(409, "AGENT_START_FAILED");
246
+ }
247
+ }
248
+ catch (error) {
249
+ const execution = this.executions.get(id);
250
+ if (execution)
251
+ await this.terminate(id, execution, "stopped");
252
+ else {
253
+ try {
254
+ await source?.close();
255
+ }
256
+ finally {
257
+ releaseProject();
258
+ }
259
+ }
260
+ throw error;
261
+ }
262
+ });
263
+ }
264
+ async stop(id, user, administration = false) {
265
+ return this.withTask(id, async () => {
266
+ if (user)
267
+ this.owned(id, user, administration);
268
+ await this.stopExecution(id);
269
+ await this.captureContext(id);
270
+ const row = this.row(id);
271
+ if (user && row)
272
+ this.audit(id, user.id, "stop", "ok");
273
+ return row ? this.json(row) : null;
274
+ });
275
+ }
276
+ async remove(id, user, administration = false) {
277
+ await this.withTask(id, async () => {
278
+ const row = this.owned(id, user, administration);
279
+ this.db.prepare("UPDATE agent_tasks SET cleanup_state = 'deleting', error_code = NULL, updated_at = ? WHERE id = ?").run(now(), id);
280
+ try {
281
+ await this.stopExecution(id);
282
+ await this.captureContext(id);
283
+ const current = this.row(id);
284
+ const root = agentTaskRoot(this.context.config, id);
285
+ const context = await this.registry.context(row.agent_id, id, root, current.native_session_id, sourceRoot(this.context.config, row.project_id));
286
+ if (row.ever_started)
287
+ await this.registry.adapter(row.agent_id).cleanup(context);
288
+ // Only the task's generated UUID directory is ever removed.
289
+ await fs.promises.rm(root, { recursive: true, force: true });
290
+ this.audit(id, user.id, "delete", "ok");
291
+ this.db.prepare("DELETE FROM agent_tasks WHERE id = ?").run(id);
292
+ }
293
+ catch (error) {
294
+ this.db.prepare("UPDATE agent_tasks SET cleanup_state = 'failed', error_code = ?, updated_at = ? WHERE id = ?")
295
+ .run("AGENT_CLEANUP_FAILED", now(), id);
296
+ this.audit(id, user.id, "delete", "failed");
297
+ if (error instanceof Error && "statusCode" in error)
298
+ throw error;
299
+ this.options.onError?.(error);
300
+ throw httpError(409, "AGENT_CLEANUP_FAILED");
301
+ }
302
+ });
303
+ }
304
+ attach(id, user, socket, authorized) {
305
+ const row = this.owned(id, user);
306
+ this.requireEditable(row);
307
+ const execution = this.executions.get(id);
308
+ if (!execution || execution.stopping)
309
+ throw httpError(409, "AGENT_SESSION_BUSY");
310
+ const attachment = { socket, authorized };
311
+ execution.attachments.add(attachment);
312
+ if (!execution.controller)
313
+ execution.controller = attachment;
314
+ this.send(socket, { type: "state", task: this.json(row) });
315
+ if (execution.output)
316
+ this.send(socket, { type: "output", data: execution.output });
317
+ this.controls(execution);
318
+ socket.on("message", (raw) => {
319
+ if (!authorized()) {
320
+ socket.close(1008, "Authentication expired");
321
+ return;
322
+ }
323
+ if (!this.editable(row)) {
324
+ socket.close(1008, "Access revoked");
325
+ void this.stop(id).catch((error) => this.options.onError?.(error));
326
+ return;
327
+ }
328
+ if (this.executions.get(id) !== execution || execution.stopping)
329
+ return;
330
+ const message = parseAgentClientMessage(raw.toString());
331
+ if (!message) {
332
+ socket.close(1008, "Invalid terminal message");
333
+ return;
334
+ }
335
+ if (message.type === "takeControl") {
336
+ execution.controller = attachment;
337
+ this.controls(execution);
338
+ }
339
+ if (execution.controller !== attachment)
340
+ return;
341
+ if (message.type === "input")
342
+ execution.pty.write(message.data);
343
+ if (message.type === "resize") {
344
+ execution.pty.resize(message.cols, message.rows);
345
+ }
346
+ });
347
+ socket.on("close", () => {
348
+ execution.attachments.delete(attachment);
349
+ if (execution.controller === attachment)
350
+ execution.controller = execution.attachments.values().next().value ?? null;
351
+ this.controls(execution);
352
+ });
353
+ }
354
+ /** Called after permission/policy mutations, not by a perpetual polling timer. */
355
+ async reconcilePermissions(cleanOrphans = false) {
356
+ await this.recovery;
357
+ const stops = [];
358
+ for (const id of new Set([...this.executions.keys(), ...this.recoveries.keys()])) {
359
+ const row = this.row(id);
360
+ if (!row || !this.editable(row))
361
+ stops.push(this.stop(id));
362
+ }
363
+ await Promise.all(stops);
364
+ if (cleanOrphans) {
365
+ const orphaned = this.db.prepare(`SELECT t.id FROM agent_tasks t
366
+ LEFT JOIN projects p ON p.id = t.project_id LEFT JOIN users u ON u.id = t.user_id
367
+ WHERE t.cleanup_state = 'none' AND (p.id IS NULL OR u.id IS NULL)`).all();
368
+ await Promise.all(orphaned.map(async ({ id }) => {
369
+ try {
370
+ await this.remove(id, { id: "system", role: "admin" }, true);
371
+ }
372
+ catch (error) {
373
+ this.options.onError?.(error);
374
+ }
375
+ }));
376
+ }
377
+ }
378
+ async dispose() {
379
+ this.closing = true;
380
+ await this.recovery;
381
+ await Promise.allSettled([...this.operations.values()]);
382
+ // A failed stop must not let app.close() close the database while other
383
+ // executions are still flushing their last source/history changes.
384
+ const results = await Promise.allSettled([...new Set([...this.executions.keys(), ...this.recoveries.keys()])].map((id) => this.stop(id)));
385
+ const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
386
+ if (errors.length)
387
+ throw new AggregateError(errors, "Failed to stop all coding agent tasks");
388
+ }
389
+ async captureContext(id, afterExit = false) {
390
+ const row = this.row(id);
391
+ if (row?.native_session_id)
392
+ return { status: "found", id: row.native_session_id };
393
+ if (!row || !row.ever_started || (!afterExit && this.executions.has(id)))
394
+ return { status: "unknown" };
395
+ const context = await this.registry.context(row.agent_id, id, agentTaskRoot(this.context.config, id), null, sourceRoot(this.context.config, row.project_id));
396
+ const native = await this.registry.adapter(row.agent_id).findNativeSession(context);
397
+ if (native.status === "found")
398
+ this.db.prepare("UPDATE agent_tasks SET native_session_id = ? WHERE id = ?").run(native.id, id);
399
+ return native;
400
+ }
401
+ async stopExecution(id) {
402
+ if (this.recoveries.has(id)) {
403
+ await this.recoverExecution(id, "stopped");
404
+ return;
405
+ }
406
+ const execution = this.executions.get(id);
407
+ if (!execution)
408
+ return;
409
+ return this.terminate(id, execution, "stopped");
410
+ }
411
+ terminate(id, execution, finalState) {
412
+ if (execution.termination)
413
+ return execution.termination;
414
+ execution.stopping = true;
415
+ this.db.prepare("UPDATE agent_tasks SET state = 'stopping', updated_at = ? WHERE id = ?").run(now(), id);
416
+ const termination = Promise.resolve().then(async () => {
417
+ await (this.options.stopPty ?? stopAgentPty)(execution.pty);
418
+ let timer;
419
+ try {
420
+ await Promise.race([execution.finished, new Promise((_resolve, reject) => {
421
+ timer = setTimeout(() => reject(httpError(409, "AGENT_STOP_FAILED")), 3_000);
422
+ })]);
423
+ }
424
+ finally {
425
+ clearTimeout(timer);
426
+ }
427
+ if (this.executions.get(id) !== execution)
428
+ return;
429
+ try {
430
+ await this.captureContext(id, true);
431
+ }
432
+ catch (error) {
433
+ this.options.onError?.(error);
434
+ }
435
+ try {
436
+ await execution.source.close();
437
+ }
438
+ catch (error) {
439
+ this.db.prepare("UPDATE agent_tasks SET error_code = 'AGENT_SYNC_FAILED' WHERE id = ?").run(id);
440
+ this.options.onError?.(error);
441
+ }
442
+ clearAgentExecution(this.executionFile(id));
443
+ this.executions.delete(id);
444
+ execution.releaseProject();
445
+ this.db.prepare("UPDATE agent_tasks SET state = ?, exit_code = ?, ended_at = ?, updated_at = ? WHERE id = ?")
446
+ .run(finalState, execution.exitCode, now(), now(), id);
447
+ const row = this.row(id);
448
+ if (row)
449
+ for (const attachment of execution.attachments) {
450
+ this.send(attachment.socket, { type: "state", task: this.json(row) });
451
+ attachment.socket.close(1000, "Execution ended");
452
+ }
453
+ for (const subscription of execution.subscriptions)
454
+ subscription.dispose();
455
+ });
456
+ execution.termination = termination;
457
+ void termination.catch(() => {
458
+ execution.termination = null;
459
+ this.db.prepare("UPDATE agent_tasks SET error_code = 'AGENT_STOP_FAILED' WHERE id = ?").run(id);
460
+ });
461
+ return termination;
462
+ }
463
+ output(id, execution, data) {
464
+ const row = this.row(id);
465
+ if (!row || !this.editable(row)) {
466
+ void this.stop(id).catch((error) => this.options.onError?.(error));
467
+ return;
468
+ }
469
+ execution.output = (execution.output + data).slice(-256 * 1024);
470
+ for (const attachment of execution.attachments) {
471
+ if (!attachment.authorized()) {
472
+ attachment.socket.close(1008, "Authentication expired");
473
+ continue;
474
+ }
475
+ if (attachment.socket.bufferedAmount > 512 * 1024) {
476
+ attachment.socket.close(1013, "Reconnect to redraw terminal");
477
+ continue;
478
+ }
479
+ this.send(attachment.socket, { type: "output", data });
480
+ }
481
+ }
482
+ controls(execution) {
483
+ for (const attachment of execution.attachments)
484
+ this.send(attachment.socket, { type: "control", writable: execution.controller === attachment });
485
+ }
486
+ send(socket, message) { if (socket.readyState === 1)
487
+ socket.send(JSON.stringify(message)); }
488
+ audit(id, actorId, action, result) {
489
+ const row = this.row(id);
490
+ this.db.prepare("INSERT INTO agent_cleanup_events (task_id, actor_id, project_id, agent_id, action, result, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
491
+ .run(id, actorId, row.project_id, row.agent_id, action, result, now());
492
+ }
493
+ row(id) { return this.db.prepare("SELECT * FROM agent_tasks WHERE id = ?").get(id); }
494
+ owned(id, user, administration = false) {
495
+ const row = this.row(id);
496
+ if (!row || (row.user_id !== user.id && !(administration && user.role === "admin")))
497
+ throw httpError(404, "AGENT_SESSION_NOT_FOUND");
498
+ return row;
499
+ }
500
+ editable(row) {
501
+ const user = this.db.prepare("SELECT * FROM users WHERE id = ? AND disabled = 0").get(row.user_id);
502
+ if (!user || user.must_change_password)
503
+ return false;
504
+ const project = accessibleProject(this.db, row.project_id, user);
505
+ const policy = this.policy();
506
+ return Boolean(project && canEdit(project) && policy.allowed.includes(row.agent_id));
507
+ }
508
+ requireEditable(row) { if (!this.editable(row))
509
+ throw httpError(403, "AGENT_DISABLED"); }
510
+ requireEnabled(id) {
511
+ const policy = this.policy();
512
+ if (!policy.allowed.includes(id))
513
+ throw httpError(403, "AGENT_DISABLED");
514
+ }
515
+ json(row) {
516
+ return { id: row.id, projectId: row.project_id, projectName: row.project_name, userId: row.user_id, userName: row.user_name,
517
+ agentId: row.agent_id, title: row.title, state: row.state, cleanupState: row.cleanup_state,
518
+ errorCode: row.error_code, createdAt: row.created_at, updatedAt: row.updated_at, startedAt: row.started_at,
519
+ endedAt: row.ended_at, exitCode: row.exit_code, nativeSessionId: row.native_session_id,
520
+ canResume: Boolean(row.native_session_id && this.registry.adapter(row.agent_id).supportsResume) };
521
+ }
522
+ executionFile(id) { return path.join(agentTaskRoot(this.context.config, id), "execution.json"); }
523
+ async recoverOnStartup() {
524
+ await Promise.all([...this.recoveries.keys()].map(async (id) => {
525
+ try {
526
+ await this.recoverExecution(id, "interrupted");
527
+ }
528
+ catch { /* Failure is logged and its task/claim remains available for retry. */ }
529
+ }));
530
+ }
531
+ async recoverExecution(id, state) {
532
+ try {
533
+ await recoverAgentExecution(this.executionFile(id));
534
+ const row = this.row(id);
535
+ // Source files left by an interrupted CLI are authoritative at startup.
536
+ // Preserve them in snapshot history before releasing its project claim.
537
+ if (row && this.db.prepare("SELECT 1 FROM projects WHERE id = ?").get(row.project_id)) {
538
+ const author = this.db.prepare("SELECT 1 FROM users WHERE id = ?").get(row.user_id) ? row.user_id : null;
539
+ this.context.recordHistory(row.project_id, author, "file");
540
+ }
541
+ this.db.prepare("UPDATE agent_tasks SET state = ?, error_code = NULL, ended_at = ?, updated_at = ? WHERE id = ?").run(state, now(), now(), id);
542
+ this.recoveries.get(id)?.();
543
+ this.recoveries.delete(id);
544
+ }
545
+ catch (error) {
546
+ this.db.prepare("UPDATE agent_tasks SET state = 'stopping', error_code = 'AGENT_RECOVERY_FAILED' WHERE id = ?").run(id);
547
+ this.options.onError?.(error);
548
+ throw httpError(409, "AGENT_RECOVERY_FAILED");
549
+ }
550
+ }
551
+ async withTask(id, operation) {
552
+ await this.recovery;
553
+ const previous = this.operations.get(id) ?? Promise.resolve();
554
+ const pending = previous.catch(() => undefined).then(operation);
555
+ this.operations.set(id, pending);
556
+ try {
557
+ return await pending;
558
+ }
559
+ finally {
560
+ if (this.operations.get(id) === pending)
561
+ this.operations.delete(id);
562
+ }
563
+ }
564
+ }
@@ -0,0 +1,84 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ /** The native module is optional and must never break normal application startup. */
4
+ export async function loadAgentPty() {
5
+ try {
6
+ const pty = await import("node-pty");
7
+ const spawn = (executable, args, options) => {
8
+ if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(executable)) {
9
+ // npm's Windows entrypoints are command scripts. CreateProcess cannot
10
+ // launch them directly; use the OS command processor for this fixed CLI.
11
+ const command = windowsAgentCommand(executable, args);
12
+ return pty.spawn(command.executable, command.args, options);
13
+ }
14
+ return pty.spawn(executable, args, options);
15
+ };
16
+ return async (executable, args, { executionFile, beforeStart, ...options }) => {
17
+ if (!executionFile) {
18
+ beforeStart?.();
19
+ return spawn(executable, args, options);
20
+ }
21
+ const { spawnRecoverableAgent } = await import("./execution.js");
22
+ return spawnRecoverableAgent(spawn, executable, args, options, executionFile, beforeStart);
23
+ };
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ export function windowsAgentCommand(executable, args) {
30
+ const quote = (value) => {
31
+ // Registered CLI flags/IDs never require shell expansion. Refuse values
32
+ // that cmd.exe would reinterpret even within double quotes.
33
+ if (/["%\r\n]/.test(value))
34
+ throw new Error("Unsupported Windows command argument");
35
+ return `"${value}"`;
36
+ };
37
+ const command = [executable, ...args].map(quote).join(" ");
38
+ return { executable: process.env.COMSPEC ?? process.env.ComSpec ?? "cmd.exe", args: `/d /v:off /s /c "${command}"` };
39
+ }
40
+ /** Caller must own the live PTY or verify the persisted launcher's birth identity. */
41
+ export async function stopAgentPty(pty) {
42
+ if (process.platform === "win32") {
43
+ // Natural exit (or another stop) may have already removed the process.
44
+ // Do not interpret localized taskkill output/exit codes as proof of this:
45
+ // access denied and a genuinely failed tree termination must stay retryable.
46
+ if (processHasExited(pty.pid))
47
+ return;
48
+ try {
49
+ await promisify(execFile)("taskkill", ["/pid", String(pty.pid), "/T", "/F"], { windowsHide: true });
50
+ }
51
+ catch (error) {
52
+ // The parent can exit between the initial probe and taskkill.
53
+ if (!processHasExited(pty.pid))
54
+ throw error;
55
+ }
56
+ return;
57
+ }
58
+ try {
59
+ process.kill(-pty.pid, "SIGTERM");
60
+ }
61
+ catch (error) {
62
+ if (error.code !== "ESRCH")
63
+ throw error;
64
+ return;
65
+ }
66
+ // A termination grace period, not a limit on the duration of a user's task.
67
+ await new Promise((resolve) => setTimeout(resolve, 500));
68
+ try {
69
+ process.kill(-pty.pid, "SIGKILL");
70
+ }
71
+ catch (error) {
72
+ if (error.code !== "ESRCH")
73
+ throw error;
74
+ }
75
+ }
76
+ function processHasExited(pid) {
77
+ try {
78
+ process.kill(pid, 0);
79
+ }
80
+ catch (error) {
81
+ return error.code === "ESRCH";
82
+ }
83
+ return false;
84
+ }