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,86 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ export const executeAgentCommand = promisify(execFile);
6
+ export const noAgentFeatures = async () => new Set();
7
+ export function hostAgentEnvironment() {
8
+ const env = {};
9
+ const names = /^(?:PATH|HOME|USER|USERNAME|USERPROFILE|SHELL|COMSPEC|SystemRoot|SYSTEMROOT|WINDIR|APPDATA|LOCALAPPDATA|TEMP|TMP|TMPDIR|LANG|LC_.*|COLORTERM|XDG_.*|https?_proxy|HTTPS?_PROXY|ALL_PROXY|all_proxy|NO_PROXY|no_proxy|SSL_CERT_FILE|SSL_CERT_DIR|NODE_EXTRA_CA_CERTS|SSH_AUTH_SOCK|OPENAI_.*|ANTHROPIC_.*|GOOGLE_.*|GEMINI_.*|OPENCODE_CONFIG(?:_DIR|_CONTENT)?|CODEX_API_KEY|CLAUDE_CODE_OAUTH_TOKEN|CLAUDE_CODE_USE_BEDROCK|CLAUDE_CODE_USE_VERTEX)$/;
10
+ for (const [key, value] of Object.entries(process.env))
11
+ if (value !== undefined && names.test(key))
12
+ env[key] = value;
13
+ env.TERM = "xterm-256color";
14
+ return env;
15
+ }
16
+ export function agentLaunch(context, args, overrides = {}) {
17
+ // Inherit host cache settings for reuse across tasks and native terminals.
18
+ // Adapters define native state/session ownership independently of caching.
19
+ return { executable: context.executable, args, env: { ...hostAgentEnvironment(),
20
+ // Development data may itself live below the TexLite checkout. Keep Git
21
+ // discovery from treating that ancestor repository as the paper's repo.
22
+ GIT_CEILING_DIRECTORIES: path.dirname(context.workingDirectory),
23
+ TEXLITE_PROJECT_CONTEXT: path.join(context.stateDirectory, "project-context.json"),
24
+ TEXLITE_COMPILE_LOG: path.join(context.stateDirectory, "compile.log"), ...overrides } };
25
+ }
26
+ /** Copy an explicit credential/config file; never share native conversation history. */
27
+ export async function copyAgentSetting(source, target) {
28
+ try {
29
+ if (fs.existsSync(target))
30
+ return;
31
+ await fs.promises.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
32
+ await fs.promises.copyFile(source, target);
33
+ await fs.promises.chmod(target, 0o600);
34
+ }
35
+ catch (error) {
36
+ if (error.code !== "ENOENT")
37
+ throw error;
38
+ }
39
+ }
40
+ export async function transcriptIds(root) {
41
+ const ids = new Set();
42
+ const visit = async (directory) => {
43
+ let entries;
44
+ try {
45
+ entries = await fs.promises.readdir(directory, { withFileTypes: true });
46
+ }
47
+ catch (error) {
48
+ if (error.code === "ENOENT")
49
+ return;
50
+ throw error;
51
+ }
52
+ for (const entry of entries) {
53
+ if (entry.isSymbolicLink())
54
+ continue;
55
+ if (entry.isDirectory())
56
+ await visit(path.join(directory, entry.name));
57
+ else {
58
+ const match = entry.name.match(/([a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12})\.jsonl$/i);
59
+ if (match)
60
+ ids.add(match[1]);
61
+ }
62
+ }
63
+ };
64
+ await visit(root);
65
+ return ids;
66
+ }
67
+ /** Inspect only this task's CLI home; missing/unreadable homes are not proof of an unused conversation. */
68
+ export async function inspectTranscriptSession(root, directories, expectedId) {
69
+ try {
70
+ if (!(await fs.promises.lstat(root)).isDirectory())
71
+ return { status: "unknown" };
72
+ const ids = new Set();
73
+ for (const directory of directories) {
74
+ for (const id of await transcriptIds(path.join(root, directory)))
75
+ ids.add(id);
76
+ }
77
+ if (ids.size === 0)
78
+ return { status: "empty" };
79
+ if (expectedId)
80
+ return ids.has(expectedId) ? { status: "found", id: expectedId } : { status: "unknown" };
81
+ return ids.size === 1 ? { status: "found", id: [...ids][0] } : { status: "unknown" };
82
+ }
83
+ catch {
84
+ return { status: "unknown" };
85
+ }
86
+ }
@@ -0,0 +1,184 @@
1
+ import os from "node:os";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import Database from "better-sqlite3";
5
+ import { agentLaunch, copyAgentSetting, executeAgentCommand } from "./common.js";
6
+ import { httpError } from "../../http.js";
7
+ const validSessionId = (id) => typeof id === "string" && /^ses_[\w-]+$/.test(id);
8
+ const privateDatabase = (context) => path.join(context.stateDirectory, "data", "opencode", "opencode.db");
9
+ const bindingFile = (context) => path.join(context.stateDirectory, "opencode-session.json");
10
+ const taskSessionId = (context) => `ses_texlite${context.taskId.replaceAll("-", "")}`;
11
+ function sharedSession(context) {
12
+ try {
13
+ const value = JSON.parse(fs.readFileSync(bindingFile(context), "utf8"));
14
+ if (!value || typeof value !== "object" || !("database" in value) || typeof value.database !== "string"
15
+ || !path.isAbsolute(value.database) || !("sessionId" in value) || value.sessionId !== taskSessionId(context)) {
16
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
17
+ }
18
+ return { database: value.database, sessionId: value.sessionId };
19
+ }
20
+ catch (error) {
21
+ if (error.code === "ENOENT")
22
+ return null;
23
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
24
+ }
25
+ }
26
+ function nativeState(context) {
27
+ const binding = sharedSession(context);
28
+ if (binding)
29
+ return { shared: true, registered: true, ...binding };
30
+ // Keep existing private conversations where they were created. Empty private
31
+ // stores can be upgraded in prepare(), but are never silently abandoned.
32
+ if (!context.features.has("standalone") || fs.existsSync(privateDatabase(context))) {
33
+ return { shared: false, registered: false, database: privateDatabase(context), sessionId: context.nativeSessionId };
34
+ }
35
+ const data = process.env.XDG_DATA_HOME ?? path.join(os.homedir(), ".local", "share");
36
+ return { shared: true, registered: false, database: process.env.OPENCODE_DB ?? path.join(data, "opencode", "opencode.db"), sessionId: taskSessionId(context) };
37
+ }
38
+ function inspectDatabase(filename, expectedId) {
39
+ const db = new Database(filename, { readonly: true });
40
+ try {
41
+ // V2 may retain the legacy table after migration. Its current projection is
42
+ // authoritative: a deleted V2 session must not reappear from a legacy row.
43
+ const table = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('session_v2', 'session')
44
+ ORDER BY CASE name WHEN 'session_v2' THEN 0 ELSE 1 END LIMIT 1`).get();
45
+ if (!table)
46
+ return { status: "unknown" };
47
+ if (expectedId) {
48
+ const found = db.prepare(`SELECT id FROM ${table.name} WHERE id = ?`).get(expectedId);
49
+ return found && validSessionId(found.id) ? { status: "found", id: found.id } : { status: "empty" };
50
+ }
51
+ const rows = db.prepare(`SELECT id FROM ${table.name} LIMIT 2`).all();
52
+ if (rows.length === 0)
53
+ return { status: "empty" };
54
+ return rows.length === 1 && validSessionId(rows[0].id) ? { status: "found", id: rows[0].id } : { status: "unknown" };
55
+ }
56
+ finally {
57
+ db.close();
58
+ }
59
+ }
60
+ export const opencodeAdapter = {
61
+ id: "opencode", label: "OpenCode", supportsResume: true,
62
+ async discoverFeatures(executable) {
63
+ const { stdout } = await executeAgentCommand(executable, ["--help"], { timeout: 5_000, maxBuffer: 128 * 1024, windowsHide: true });
64
+ return new Set(/(?:^|\s)--standalone(?:\s|$)/m.test(stdout) ? ["standalone"] : []);
65
+ },
66
+ async prepare(context) {
67
+ if (context.nativeSessionId) {
68
+ // Newer CLIs can CREATE a conversation for an unknown --session ID.
69
+ // Verify it first so a missing saved conversation is never replaced.
70
+ const native = await this.findNativeSession(context);
71
+ if (native.status === "unknown")
72
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
73
+ if (native.status !== "found" || native.id !== context.nativeSessionId)
74
+ throw httpError(409, "AGENT_NO_CONTEXT");
75
+ }
76
+ const state = nativeState(context);
77
+ if (state.shared && !context.features.has("standalone"))
78
+ throw httpError(409, "AGENT_UNAVAILABLE");
79
+ if (state.shared && state.registered)
80
+ return;
81
+ if (!state.shared && (context.nativeSessionId || !context.features.has("standalone"))) {
82
+ const host = path.join(process.env.XDG_DATA_HOME ?? path.join(os.homedir(), ".local", "share"), "opencode");
83
+ await copyAgentSetting(path.join(host, "auth.json"), path.join(context.stateDirectory, "data", "opencode", "auth.json"));
84
+ return;
85
+ }
86
+ if (!state.shared && (await this.findNativeSession(context)).status !== "empty")
87
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
88
+ // Ask the native CLI, rather than guessing release-channel/platform paths.
89
+ // Authentication stays entirely in the host database; no credentials are copied.
90
+ const env = agentLaunch(context, []).env;
91
+ if (process.env.OPENCODE_DB)
92
+ env.OPENCODE_DB = process.env.OPENCODE_DB;
93
+ let database;
94
+ try {
95
+ const { stdout } = await executeAgentCommand(context.executable, ["debug", "paths", "db"], {
96
+ cwd: context.workingDirectory, env, timeout: 5_000, maxBuffer: 16 * 1024, windowsHide: true
97
+ });
98
+ database = stdout.trim();
99
+ }
100
+ catch {
101
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
102
+ }
103
+ if (!path.isAbsolute(database) || /[\r\n\0]/.test(database))
104
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
105
+ const sessionId = taskSessionId(context);
106
+ // Register ownership before launching, and never claim an existing native
107
+ // conversation merely because it is the newest/only one in the database.
108
+ if (fs.existsSync(database) && inspectDatabase(database, sessionId).status !== "empty")
109
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
110
+ await fs.promises.mkdir(context.stateDirectory, { recursive: true, mode: 0o700 });
111
+ await fs.promises.writeFile(bindingFile(context), JSON.stringify({ database, sessionId }), { flag: "wx", mode: 0o600 });
112
+ },
113
+ start(context) {
114
+ const state = nativeState(context);
115
+ const args = context.features.has("standalone") ? ["--standalone"] : [];
116
+ return state.shared
117
+ ? agentLaunch(context, [...args, "--session", state.sessionId], { OPENCODE_DB: state.database })
118
+ : agentLaunch(context, args, { OPENCODE_DB: state.database, XDG_DATA_HOME: path.join(context.stateDirectory, "data"),
119
+ XDG_STATE_HOME: path.join(context.stateDirectory, "runtime") });
120
+ },
121
+ resume(context) {
122
+ const state = nativeState(context);
123
+ if (state.shared && (!state.registered || state.sessionId !== context.nativeSessionId))
124
+ throw httpError(409, "AGENT_CONTEXT_CHECK_FAILED");
125
+ const launch = this.start(context);
126
+ return state.shared ? launch : { ...launch, args: [...launch.args, "--session", context.nativeSessionId] };
127
+ },
128
+ async findNativeSession(context) {
129
+ try {
130
+ // The list command may create a database itself. A missing task database
131
+ // must never be mistaken for a verified empty one after state loss.
132
+ const state = nativeState(context);
133
+ if (state.shared && (!state.registered || (context.nativeSessionId && context.nativeSessionId !== state.sessionId)))
134
+ return { status: "unknown" };
135
+ if (!(await fs.promises.stat(state.database)).isFile())
136
+ return { status: "unknown" };
137
+ // A shared database is queried by this task's registered ID only.
138
+ try {
139
+ return inspectDatabase(state.database, state.shared ? state.sessionId : context.nativeSessionId);
140
+ }
141
+ catch { /* Other native versions/formats can still be identified by the CLI. */ }
142
+ if (state.shared || context.features.has("standalone"))
143
+ return { status: "unknown" };
144
+ const launch = this.start(context);
145
+ const { stdout } = await executeAgentCommand(context.executable, ["session", "list", "--format", "json"], {
146
+ // OpenCode resolves project sessions from cwd as well as its state DB.
147
+ cwd: context.workingDirectory, env: launch.env, timeout: 5_000, maxBuffer: 1024 * 1024, windowsHide: true
148
+ });
149
+ const records = JSON.parse(stdout);
150
+ if (Array.isArray(records) && records.length === 0)
151
+ return { status: "empty" };
152
+ if (Array.isArray(records) && records.length === 1 && validSessionId(records[0]?.id))
153
+ return { status: "found", id: records[0].id };
154
+ }
155
+ catch { /* Version-dependent management capability. */ }
156
+ return { status: "unknown" };
157
+ },
158
+ async cleanup(context) {
159
+ const state = nativeState(context);
160
+ if (state.shared) {
161
+ if (!state.registered || (context.nativeSessionId && context.nativeSessionId !== state.sessionId))
162
+ throw httpError(409, "AGENT_CLEANUP_FAILED");
163
+ const native = await this.findNativeSession(context);
164
+ if (native.status === "unknown")
165
+ throw httpError(409, "AGENT_CLEANUP_FAILED");
166
+ if (native.status === "empty")
167
+ return; // An exact-ID deletion already succeeded.
168
+ await executeAgentCommand(context.executable, ["session", "delete", state.sessionId, "--standalone"], {
169
+ cwd: context.workingDirectory, env: this.start(context).env, timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true
170
+ });
171
+ if ((await this.findNativeSession(context)).status !== "empty")
172
+ throw httpError(409, "AGENT_CLEANUP_FAILED");
173
+ return;
174
+ }
175
+ // Private state can be removed with the task after its process tree stops.
176
+ if (context.features.has("standalone"))
177
+ return;
178
+ const native = context.nativeSessionId && context.executable ? await this.findNativeSession(context) : null;
179
+ if (native?.status === "found" && native.id === context.nativeSessionId)
180
+ await executeAgentCommand(context.executable, ["session", "delete", native.id], {
181
+ cwd: context.workingDirectory, env: this.start(context).env, timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true
182
+ });
183
+ }
184
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,147 @@
1
+ import fs from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { fileURLToPath } from "node:url";
4
+ import { inspectAgentProcess, agentProcessGroupAlive } from "./processIdentity.js";
5
+ import { stopAgentPty, windowsAgentCommand } from "./terminal.js";
6
+ import { httpError } from "../http.js";
7
+ function readRecord(filename) {
8
+ let value;
9
+ try {
10
+ value = JSON.parse(fs.readFileSync(filename, "utf8"));
11
+ }
12
+ catch (error) {
13
+ if (error.code === "ENOENT")
14
+ return null;
15
+ throw error;
16
+ }
17
+ if (value?.version !== 1 || !/^[a-f\d-]{36}$/.test(value.executionId) || value.platform !== process.platform
18
+ || !(value.pid === null && value.identity === null || Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.identity === "string" && value.identity)) {
19
+ throw httpError(409, "AGENT_RECOVERY_FAILED");
20
+ }
21
+ return value;
22
+ }
23
+ export function clearAgentExecution(filename) {
24
+ const record = readRecord(filename);
25
+ if (record) {
26
+ fs.rmSync(`${filename}.${record.executionId}.exit`, { force: true });
27
+ fs.rmSync(`${filename}.${record.executionId}.exit.tmp`, { force: true });
28
+ }
29
+ fs.rmSync(`${filename}.tmp`, { force: true });
30
+ fs.rmSync(filename, { force: true });
31
+ }
32
+ /** Only verified launchers may be signalled. Ambiguity keeps the durable lease. */
33
+ export async function recoverAgentExecution(filename) {
34
+ const record = readRecord(filename);
35
+ if (!record)
36
+ return;
37
+ if (record.pid !== null) {
38
+ const process = await inspectAgentProcess(record.pid, record.executionId);
39
+ if (process && process.identity === record.identity && process.owned) {
40
+ // Verify twice before signalling; a recycled PID must never be targeted.
41
+ const current = await inspectAgentProcess(record.pid, record.executionId);
42
+ if (!current || current.identity !== record.identity || !current.owned)
43
+ throw httpError(409, "AGENT_RECOVERY_FAILED");
44
+ await stopAgentPty({ pid: record.pid });
45
+ const deadline = Date.now() + 3_000;
46
+ while (true) {
47
+ const remaining = await inspectAgentProcess(record.pid, record.executionId);
48
+ if ((!remaining || remaining.identity !== record.identity) && !await agentProcessGroupAlive(record.pid))
49
+ break;
50
+ if (Date.now() >= deadline)
51
+ throw httpError(409, "AGENT_RECOVERY_FAILED");
52
+ await new Promise((resolve) => setTimeout(resolve, 50));
53
+ }
54
+ }
55
+ else if (process && process.identity === record.identity) {
56
+ throw httpError(409, "AGENT_RECOVERY_FAILED");
57
+ }
58
+ else if (!process && await agentProcessGroupAlive(record.pid)) {
59
+ // The wrapper was independently killed. Do not guess ownership of a
60
+ // leaderless group; the administrator can stop it on the host and retry.
61
+ throw httpError(409, "AGENT_RECOVERY_FAILED");
62
+ }
63
+ }
64
+ // An uncommitted launch cannot start the CLI. Removing its permit makes a
65
+ // delayed launcher exit, closing the spawn-before-identity-persistence gap.
66
+ clearAgentExecution(filename);
67
+ }
68
+ /** Start a gated, identifiable group leader without changing the CLI's TTY. */
69
+ export async function spawnRecoverableAgent(spawn, executable, args, options, filename, beforeStart) {
70
+ const record = { version: 1, executionId: randomUUID(), platform: process.platform, pid: null, identity: null };
71
+ fs.writeFileSync(filename, JSON.stringify(record), { flag: "wx", mode: 0o600 });
72
+ const compiled = new URL("./launcher.js", import.meta.url);
73
+ const launcher = fileURLToPath(fs.existsSync(compiled) ? compiled : new URL("./launcher.ts", import.meta.url));
74
+ let launch = { executable, args, windowsVerbatimArguments: false };
75
+ if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(executable)) {
76
+ const command = windowsAgentCommand(executable, args);
77
+ launch = { executable: command.executable, args: ["/d", "/v:off", "/s", "/c", command.args.slice("/d /v:off /s /c ".length)], windowsVerbatimArguments: true };
78
+ }
79
+ let pty;
80
+ try {
81
+ pty = await spawn(process.execPath, [launcher, filename, record.executionId], {
82
+ ...options, env: { ...options.env, TEXLITE_AGENT_LAUNCH: JSON.stringify(launch) }
83
+ });
84
+ const wrapped = observeCliExit(pty, filename, record.executionId);
85
+ let identity = await inspectAgentProcess(pty.pid, record.executionId);
86
+ // Some PTY backends briefly expose their fork/exec helper's command line.
87
+ const deadline = Date.now() + 3_000;
88
+ while (!identity?.owned && Date.now() < deadline) {
89
+ await new Promise((resolve) => setTimeout(resolve, 25));
90
+ identity = await inspectAgentProcess(pty.pid, record.executionId);
91
+ }
92
+ if (!identity?.owned)
93
+ throw httpError(409, "AGENT_START_FAILED");
94
+ record.pid = pty.pid;
95
+ record.identity = identity.identity;
96
+ // Conversation cleanup ownership must be durable before the CLI is allowed
97
+ // to create any native state, not after the launch promise returns.
98
+ beforeStart?.();
99
+ const temporary = `${filename}.tmp`;
100
+ fs.writeFileSync(temporary, JSON.stringify(record), { mode: 0o600 });
101
+ fs.renameSync(temporary, filename);
102
+ return wrapped;
103
+ }
104
+ catch (error) {
105
+ // No permit was issued, so the CLI cannot have started. Keep any failed
106
+ // cleanup lease so service recovery can cancel the waiting launcher.
107
+ if (pty)
108
+ await stopAgentPty(pty);
109
+ clearAgentExecution(filename);
110
+ throw error;
111
+ }
112
+ }
113
+ function observeCliExit(pty, filename, executionId) {
114
+ const resultFile = `${filename}.${executionId}.exit`;
115
+ const listeners = new Set();
116
+ let exited;
117
+ const notify = (event) => {
118
+ if (exited)
119
+ return;
120
+ exited = event;
121
+ for (const listener of listeners)
122
+ listener(event);
123
+ };
124
+ const readExit = () => {
125
+ try {
126
+ const result = JSON.parse(fs.readFileSync(resultFile, "utf8"));
127
+ if (result.executionId === executionId && Number.isInteger(result.exitCode))
128
+ notify({ exitCode: result.exitCode });
129
+ }
130
+ catch (error) {
131
+ if (error.code !== "ENOENT")
132
+ notify({ exitCode: 1 });
133
+ }
134
+ };
135
+ fs.watchFile(resultFile, { interval: 100, persistent: false }, readExit);
136
+ pty.onExit((event) => { fs.unwatchFile(resultFile, readExit); notify(event); });
137
+ return { pid: pty.pid, write: (data) => pty.write(data), resize: (cols, rows) => pty.resize(cols, rows), onData: (callback) => pty.onData(callback),
138
+ onExit: (callback) => {
139
+ listeners.add(callback);
140
+ if (exited) {
141
+ const event = exited;
142
+ queueMicrotask(() => { if (listeners.has(callback))
143
+ callback(event); });
144
+ }
145
+ return { dispose: () => { listeners.delete(callback); } };
146
+ } };
147
+ }
@@ -0,0 +1,57 @@
1
+ // Deliberately imports only Node builtins: the same file runs as compiled JS in
2
+ // npm installs and with Node 24's native TypeScript support in development.
3
+ import fs from "node:fs";
4
+ import { spawn } from "node:child_process";
5
+ import { constants } from "node:os";
6
+ const [recordFile, executionId] = process.argv.slice(2);
7
+ const launch = JSON.parse(process.env.TEXLITE_AGENT_LAUNCH ?? "null");
8
+ delete process.env.TEXLITE_AGENT_LAUNCH;
9
+ if (!recordFile || !executionId || !launch)
10
+ throw new Error("Missing agent launch context");
11
+ // Keep the identifiable group leader alive until TexLite reaps the whole group,
12
+ // even if the service dies or the CLI exits before its workers do.
13
+ process.on("SIGTERM", () => undefined);
14
+ process.on("SIGINT", () => undefined);
15
+ if (process.platform !== "win32")
16
+ process.on("SIGHUP", () => undefined);
17
+ const deadline = Date.now() + 10_000;
18
+ while (true) {
19
+ let record;
20
+ try {
21
+ record = JSON.parse(fs.readFileSync(recordFile, "utf8"));
22
+ }
23
+ catch {
24
+ process.exit(1);
25
+ }
26
+ if (record.executionId !== executionId)
27
+ process.exit(1);
28
+ if (record.pid === process.pid && record.identity)
29
+ break;
30
+ if (Date.now() >= deadline)
31
+ process.exit(1);
32
+ await new Promise((resolve) => setTimeout(resolve, 25));
33
+ }
34
+ // This interval only keeps the launcher available for verified tree cleanup;
35
+ // it imposes no time limit on the user's task.
36
+ setInterval(() => undefined, 60_000);
37
+ const resultFile = `${recordFile}.${executionId}.exit`;
38
+ let reported = false;
39
+ function report(exitCode) {
40
+ if (reported)
41
+ return;
42
+ reported = true;
43
+ const temporary = `${resultFile}.tmp`;
44
+ fs.writeFileSync(temporary, JSON.stringify({ executionId, exitCode }), { mode: 0o600 });
45
+ fs.renameSync(temporary, resultFile);
46
+ }
47
+ try {
48
+ const child = spawn(launch.executable, launch.args, {
49
+ stdio: "inherit", shell: false, windowsVerbatimArguments: launch.windowsVerbatimArguments
50
+ });
51
+ child.on("error", (error) => { console.error(error.message); report(1); });
52
+ child.on("exit", (code, signal) => report(code ?? (128 + (signal ? constants.signals[signal] ?? 0 : 0))));
53
+ }
54
+ catch (error) {
55
+ console.error(error instanceof Error ? error.message : error);
56
+ report(1);
57
+ }
@@ -0,0 +1,63 @@
1
+ import fs from "node:fs/promises";
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ const systemIO = {
5
+ platform: process.platform,
6
+ read: (filename) => fs.readFile(filename, "utf8"),
7
+ command: async (command, args) => (await promisify(execFile)(command, args, { timeout: 5_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true })).stdout
8
+ };
9
+ const missing = (error) => ["ENOENT", "ESRCH"].includes(error.code ?? "");
10
+ const marker = (command, executionId) => command.includes(executionId) && /(?:^|[\\/])launcher\.(?:js|ts)(?:[\s"\0]|$)/.test(command);
11
+ /** Birth identity plus a per-execution launcher marker; never trust a stored PID alone. */
12
+ export async function inspectAgentProcess(pid, executionId, io = systemIO) {
13
+ if (!Number.isSafeInteger(pid) || pid <= 0)
14
+ throw new Error("Invalid agent process ID");
15
+ if (io.platform === "linux") {
16
+ try {
17
+ const [stat, command, boot] = await Promise.all([io.read(`/proc/${pid}/stat`), io.read(`/proc/${pid}/cmdline`), io.read("/proc/sys/kernel/random/boot_id")]);
18
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(/\s+/);
19
+ if (fields.length < 20 || !/^\d+$/.test(fields[19]))
20
+ throw new Error("Cannot verify agent process birth");
21
+ if (fields[0] === "Z" || fields[0] === "X")
22
+ return null;
23
+ return { identity: `${boot.trim()}:${fields[19]}`, owned: marker(command.replaceAll("\0", " "), executionId) };
24
+ }
25
+ catch (error) {
26
+ if (missing(error))
27
+ return null;
28
+ throw error;
29
+ }
30
+ }
31
+ if (io.platform === "win32") {
32
+ const output = await io.command("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
33
+ `Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -ErrorAction Stop | Select-Object CreationDate,CommandLine | ConvertTo-Json -Compress`]);
34
+ if (!output.trim())
35
+ return null;
36
+ const value = JSON.parse(output);
37
+ if (value === null)
38
+ return null;
39
+ if (typeof value.CreationDate !== "string" || typeof value.CommandLine !== "string")
40
+ throw new Error("Cannot verify agent process birth");
41
+ return { identity: value.CreationDate, owned: marker(value.CommandLine, executionId) };
42
+ }
43
+ // macOS and other POSIX hosts expose a start time and full command via ps.
44
+ // Querying the full table distinguishes a missing PID from ps invocation errors.
45
+ const output = await io.command("ps", ["-ww", "-axo", "pid=,lstart=,args="]);
46
+ const line = output.split("\n").find((line) => Number(line.trim().match(/^\d+/)?.[0]) === pid);
47
+ if (!line)
48
+ return null;
49
+ const match = line.trim().match(/^\d+\s+(\w+\s+\w+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.+)$/);
50
+ if (!match)
51
+ throw new Error("Cannot verify agent process birth");
52
+ return { identity: match[1].replace(/\s+/g, " "), owned: marker(match[2], executionId) };
53
+ }
54
+ /** A vanished leader is not proof that all members of its POSIX group exited. */
55
+ export async function agentProcessGroupAlive(pid, io = systemIO) {
56
+ if (io.platform === "win32")
57
+ return false;
58
+ const output = await io.command("ps", ["-axo", "pgid=,stat="]);
59
+ return output.split("\n").some((line) => {
60
+ const [group, state] = line.trim().split(/\s+/);
61
+ return Number(group) === pid && state && !/^[ZX]/.test(state);
62
+ });
63
+ }
@@ -0,0 +1,72 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { AGENT_IDS } from "../../shared/agentProtocol.js";
4
+ import { executeAgentCommand } from "./adapters/common.js";
5
+ import { codexAdapter } from "./adapters/codex.js";
6
+ import { opencodeAdapter } from "./adapters/opencode.js";
7
+ import { claudeAdapter } from "./adapters/claude.js";
8
+ export function findAgentExecutable(name) {
9
+ const suffixes = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
10
+ for (const directory of (process.env.PATH ?? "").split(path.delimiter).filter(Boolean)) {
11
+ for (const suffix of suffixes) {
12
+ const candidate = path.join(directory, `${name}${suffix}`);
13
+ try {
14
+ fs.accessSync(candidate, process.platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
15
+ if (fs.statSync(candidate).isFile())
16
+ return candidate;
17
+ }
18
+ catch { /* Try the next PATH entry. */ }
19
+ }
20
+ }
21
+ return null;
22
+ }
23
+ /** Registration/discovery only: native flags belong in individual adapters. */
24
+ export class AgentRegistry {
25
+ resolveExecutable;
26
+ detected = new Map();
27
+ adapters;
28
+ constructor(resolveExecutable = findAgentExecutable, adapters = [codexAdapter, opencodeAdapter, claudeAdapter]) {
29
+ this.resolveExecutable = resolveExecutable;
30
+ this.adapters = new Map(adapters.map((adapter) => [adapter.id, adapter]));
31
+ }
32
+ adapter(id) { return this.adapters.get(id); }
33
+ refresh() { this.detected.clear(); }
34
+ detect(id) {
35
+ let result = this.detected.get(id);
36
+ if (!result) {
37
+ result = this.probe(id);
38
+ this.detected.set(id, result);
39
+ }
40
+ return result;
41
+ }
42
+ async catalog(policy) {
43
+ return Promise.all(AGENT_IDS.map(async (id) => {
44
+ const detected = await this.detect(id);
45
+ const adapter = this.adapter(id);
46
+ return { id, label: adapter.label, installed: detected.executable !== null,
47
+ version: detected.version, enabled: policy.allowed.includes(id) };
48
+ }));
49
+ }
50
+ async context(id, taskId, root, nativeSessionId, workingDirectory) {
51
+ const detected = await this.detect(id);
52
+ return { taskId, stateDirectory: path.join(root, "state"), workingDirectory,
53
+ nativeSessionId, executable: detected.executable ?? "", features: detected.features };
54
+ }
55
+ async probe(id) {
56
+ const executable = this.resolveExecutable(id);
57
+ if (!executable)
58
+ return { executable: null, version: null, features: new Set() };
59
+ let version = null;
60
+ let features = new Set();
61
+ try {
62
+ const { stdout } = await executeAgentCommand(executable, ["--version"], { timeout: 5_000, maxBuffer: 64 * 1024, windowsHide: true });
63
+ version = stdout.match(/\bv?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1] ?? null;
64
+ }
65
+ catch { /* Installed agents need not implement --version. */ }
66
+ try {
67
+ features = await this.adapter(id).discoverFeatures(executable);
68
+ }
69
+ catch { /* Optional capabilities. */ }
70
+ return { executable, version, features };
71
+ }
72
+ }