@celljs/ta-host 4.5.0 → 4.6.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 (375) hide show
  1. package/README.md +31 -8
  2. package/cell.schema.json +18 -0
  3. package/cell.yml +4 -0
  4. package/esm/node/auth-server-impl.d.ts +61 -0
  5. package/esm/node/auth-server-impl.js +247 -0
  6. package/esm/node/auth-server-impl.js.map +1 -0
  7. package/esm/node/client-tool-broker.d.ts +35 -0
  8. package/esm/node/client-tool-broker.js +82 -0
  9. package/esm/node/client-tool-broker.js.map +1 -0
  10. package/esm/node/exec-environment-factory.d.ts +17 -0
  11. package/esm/node/exec-environment-factory.js +58 -0
  12. package/esm/node/exec-environment-factory.js.map +1 -0
  13. package/esm/node/extension-data-notifier.d.ts +41 -0
  14. package/esm/node/extension-data-notifier.js +119 -0
  15. package/esm/node/extension-data-notifier.js.map +1 -0
  16. package/esm/node/extension-data.d.ts +45 -0
  17. package/esm/node/extension-data.js +181 -0
  18. package/esm/node/extension-data.js.map +1 -0
  19. package/esm/node/host-protocol.d.ts +29 -1
  20. package/esm/node/host-protocol.js +2 -0
  21. package/esm/node/host-protocol.js.map +1 -1
  22. package/esm/node/index.d.ts +24 -1
  23. package/esm/node/index.js +24 -1
  24. package/esm/node/index.js.map +1 -1
  25. package/esm/node/package-host-extension.d.ts +9 -0
  26. package/esm/node/package-host-extension.js +18 -0
  27. package/esm/node/package-host-extension.js.map +1 -0
  28. package/esm/node/package-hosts.d.ts +44 -0
  29. package/esm/node/package-hosts.js +167 -0
  30. package/esm/node/package-hosts.js.map +1 -0
  31. package/esm/node/package-server-impl.d.ts +25 -0
  32. package/esm/node/package-server-impl.js +94 -0
  33. package/esm/node/package-server-impl.js.map +1 -0
  34. package/esm/node/package-switch.d.ts +29 -0
  35. package/esm/node/package-switch.js +68 -0
  36. package/esm/node/package-switch.js.map +1 -0
  37. package/esm/node/relay-bridge.d.ts +34 -0
  38. package/esm/node/relay-bridge.js +105 -0
  39. package/esm/node/relay-bridge.js.map +1 -0
  40. package/esm/node/session-info-util.d.ts +16 -0
  41. package/esm/node/session-info-util.js +49 -0
  42. package/esm/node/session-info-util.js.map +1 -0
  43. package/esm/node/session-storage/file-session-storage.d.ts +27 -0
  44. package/esm/node/session-storage/file-session-storage.js +139 -0
  45. package/esm/node/session-storage/file-session-storage.js.map +1 -0
  46. package/esm/node/session-storage/index.d.ts +3 -0
  47. package/esm/node/session-storage/index.js +4 -0
  48. package/esm/node/session-storage/index.js.map +1 -0
  49. package/esm/node/session-storage/session-storage-protocol.d.ts +57 -0
  50. package/esm/node/session-storage/session-storage-protocol.js +40 -0
  51. package/esm/node/session-storage/session-storage-protocol.js.map +1 -0
  52. package/esm/node/session-storage/stored-session.d.ts +46 -0
  53. package/esm/node/session-storage/stored-session.js +116 -0
  54. package/esm/node/session-storage/stored-session.js.map +1 -0
  55. package/esm/node/settings-server-impl.d.ts +11 -0
  56. package/esm/node/settings-server-impl.js +45 -0
  57. package/esm/node/settings-server-impl.js.map +1 -0
  58. package/esm/node/settings-store.d.ts +56 -0
  59. package/esm/node/settings-store.js +306 -0
  60. package/esm/node/settings-store.js.map +1 -0
  61. package/esm/node/ta-access.d.ts +19 -2
  62. package/esm/node/ta-access.js +64 -7
  63. package/esm/node/ta-access.js.map +1 -1
  64. package/esm/node/ta-errors.d.ts +3 -1
  65. package/esm/node/ta-errors.js +17 -1
  66. package/esm/node/ta-errors.js.map +1 -1
  67. package/esm/node/ta-server-impl.d.ts +17 -5
  68. package/esm/node/ta-server-impl.js +70 -13
  69. package/esm/node/ta-server-impl.js.map +1 -1
  70. package/esm/node/ta-session-factory.d.ts +2 -0
  71. package/esm/node/ta-session-factory.js +25 -11
  72. package/esm/node/ta-session-factory.js.map +1 -1
  73. package/esm/node/ta-session.d.ts +9 -1
  74. package/esm/node/ta-session.js +26 -2
  75. package/esm/node/ta-session.js.map +1 -1
  76. package/esm/node/terminal-protocol.d.ts +18 -0
  77. package/esm/node/terminal-protocol.js +2 -0
  78. package/esm/node/terminal-protocol.js.map +1 -0
  79. package/esm/node/terminal-service.d.ts +59 -0
  80. package/esm/node/terminal-service.js +240 -0
  81. package/esm/node/terminal-service.js.map +1 -0
  82. package/esm/node/terminal-util.d.ts +62 -0
  83. package/esm/node/terminal-util.js +153 -0
  84. package/esm/node/terminal-util.js.map +1 -0
  85. package/esm/node/web-extension-catalog.d.ts +38 -0
  86. package/esm/node/web-extension-catalog.js +160 -0
  87. package/esm/node/web-extension-catalog.js.map +1 -0
  88. package/esm/node/web-extension-util.d.ts +21 -0
  89. package/esm/node/web-extension-util.js +123 -0
  90. package/esm/node/web-extension-util.js.map +1 -0
  91. package/esm/node/working-directory.d.ts +13 -0
  92. package/esm/node/working-directory.js +40 -0
  93. package/esm/node/working-directory.js.map +1 -0
  94. package/esm/node/workspace-files.d.ts +47 -0
  95. package/esm/node/workspace-files.js +265 -0
  96. package/esm/node/workspace-files.js.map +1 -0
  97. package/esm/node/workspace-protocol.d.ts +20 -0
  98. package/esm/node/workspace-protocol.js +3 -0
  99. package/esm/node/workspace-protocol.js.map +1 -0
  100. package/esm/node/workspace-server-impl.d.ts +27 -0
  101. package/esm/node/workspace-server-impl.js +88 -0
  102. package/esm/node/workspace-server-impl.js.map +1 -0
  103. package/esm/node/workspace-service.d.ts +31 -0
  104. package/esm/node/workspace-service.js +209 -0
  105. package/esm/node/workspace-service.js.map +1 -0
  106. package/esm/node/workspace-util.d.ts +29 -0
  107. package/esm/node/workspace-util.js +104 -0
  108. package/esm/node/workspace-util.js.map +1 -0
  109. package/lib/node/auth-server-impl.d.ts +62 -0
  110. package/lib/node/auth-server-impl.d.ts.map +1 -0
  111. package/lib/node/auth-server-impl.js +250 -0
  112. package/lib/node/auth-server-impl.js.map +1 -0
  113. package/lib/node/auth-server-impl.spec.d.ts +2 -0
  114. package/lib/node/auth-server-impl.spec.d.ts.map +1 -0
  115. package/lib/node/auth-server-impl.spec.js +47 -0
  116. package/lib/node/auth-server-impl.spec.js.map +1 -0
  117. package/lib/node/client-tool-broker.d.ts +36 -0
  118. package/lib/node/client-tool-broker.d.ts.map +1 -0
  119. package/lib/node/client-tool-broker.js +86 -0
  120. package/lib/node/client-tool-broker.js.map +1 -0
  121. package/lib/node/client-tool-broker.spec.d.ts +2 -0
  122. package/lib/node/client-tool-broker.spec.d.ts.map +1 -0
  123. package/lib/node/client-tool-broker.spec.js +49 -0
  124. package/lib/node/client-tool-broker.spec.js.map +1 -0
  125. package/lib/node/exec-environment-factory.d.ts +18 -0
  126. package/lib/node/exec-environment-factory.d.ts.map +1 -0
  127. package/lib/node/exec-environment-factory.js +61 -0
  128. package/lib/node/exec-environment-factory.js.map +1 -0
  129. package/lib/node/extension-data-notifier.d.ts +42 -0
  130. package/lib/node/extension-data-notifier.d.ts.map +1 -0
  131. package/lib/node/extension-data-notifier.js +123 -0
  132. package/lib/node/extension-data-notifier.js.map +1 -0
  133. package/lib/node/extension-data-notifier.spec.d.ts +2 -0
  134. package/lib/node/extension-data-notifier.spec.d.ts.map +1 -0
  135. package/lib/node/extension-data-notifier.spec.js +35 -0
  136. package/lib/node/extension-data-notifier.spec.js.map +1 -0
  137. package/lib/node/extension-data.d.ts +46 -0
  138. package/lib/node/extension-data.d.ts.map +1 -0
  139. package/lib/node/extension-data.js +184 -0
  140. package/lib/node/extension-data.js.map +1 -0
  141. package/lib/node/extension-data.spec.d.ts +2 -0
  142. package/lib/node/extension-data.spec.d.ts.map +1 -0
  143. package/lib/node/extension-data.spec.js +99 -0
  144. package/lib/node/extension-data.spec.js.map +1 -0
  145. package/lib/node/host-protocol.d.ts +29 -1
  146. package/lib/node/host-protocol.d.ts.map +1 -1
  147. package/lib/node/host-protocol.js +3 -1
  148. package/lib/node/host-protocol.js.map +1 -1
  149. package/lib/node/index.d.ts +24 -1
  150. package/lib/node/index.d.ts.map +1 -1
  151. package/lib/node/index.js +24 -1
  152. package/lib/node/index.js.map +1 -1
  153. package/lib/node/package-host-extension.d.ts +10 -0
  154. package/lib/node/package-host-extension.d.ts.map +1 -0
  155. package/lib/node/package-host-extension.js +22 -0
  156. package/lib/node/package-host-extension.js.map +1 -0
  157. package/lib/node/package-hosts.d.ts +45 -0
  158. package/lib/node/package-hosts.d.ts.map +1 -0
  159. package/lib/node/package-hosts.js +170 -0
  160. package/lib/node/package-hosts.js.map +1 -0
  161. package/lib/node/package-hosts.spec.d.ts +2 -0
  162. package/lib/node/package-hosts.spec.d.ts.map +1 -0
  163. package/lib/node/package-hosts.spec.js +53 -0
  164. package/lib/node/package-hosts.spec.js.map +1 -0
  165. package/lib/node/package-server-impl.d.ts +26 -0
  166. package/lib/node/package-server-impl.d.ts.map +1 -0
  167. package/lib/node/package-server-impl.js +97 -0
  168. package/lib/node/package-server-impl.js.map +1 -0
  169. package/lib/node/package-switch.d.ts +30 -0
  170. package/lib/node/package-switch.d.ts.map +1 -0
  171. package/lib/node/package-switch.js +71 -0
  172. package/lib/node/package-switch.js.map +1 -0
  173. package/lib/node/relay-bridge.d.ts +35 -0
  174. package/lib/node/relay-bridge.d.ts.map +1 -0
  175. package/lib/node/relay-bridge.js +108 -0
  176. package/lib/node/relay-bridge.js.map +1 -0
  177. package/lib/node/session-info-util.d.ts +17 -0
  178. package/lib/node/session-info-util.d.ts.map +1 -0
  179. package/lib/node/session-info-util.js +52 -0
  180. package/lib/node/session-info-util.js.map +1 -0
  181. package/lib/node/session-info-util.spec.d.ts +2 -0
  182. package/lib/node/session-info-util.spec.d.ts.map +1 -0
  183. package/lib/node/session-info-util.spec.js +22 -0
  184. package/lib/node/session-info-util.spec.js.map +1 -0
  185. package/lib/node/session-storage/file-session-storage.d.ts +28 -0
  186. package/lib/node/session-storage/file-session-storage.d.ts.map +1 -0
  187. package/lib/node/session-storage/file-session-storage.js +143 -0
  188. package/lib/node/session-storage/file-session-storage.js.map +1 -0
  189. package/lib/node/session-storage/file-session-storage.spec.d.ts +2 -0
  190. package/lib/node/session-storage/file-session-storage.spec.d.ts.map +1 -0
  191. package/lib/node/session-storage/file-session-storage.spec.js +70 -0
  192. package/lib/node/session-storage/file-session-storage.spec.js.map +1 -0
  193. package/lib/node/session-storage/index.d.ts +4 -0
  194. package/lib/node/session-storage/index.d.ts.map +1 -0
  195. package/lib/node/session-storage/index.js +20 -0
  196. package/lib/node/session-storage/index.js.map +1 -0
  197. package/lib/node/session-storage/session-storage-protocol.d.ts +58 -0
  198. package/lib/node/session-storage/session-storage-protocol.d.ts.map +1 -0
  199. package/lib/node/session-storage/session-storage-protocol.js +45 -0
  200. package/lib/node/session-storage/session-storage-protocol.js.map +1 -0
  201. package/lib/node/session-storage/stored-session.d.ts +47 -0
  202. package/lib/node/session-storage/stored-session.d.ts.map +1 -0
  203. package/lib/node/session-storage/stored-session.js +120 -0
  204. package/lib/node/session-storage/stored-session.js.map +1 -0
  205. package/lib/node/session-storage/stored-session.spec.d.ts +2 -0
  206. package/lib/node/session-storage/stored-session.spec.d.ts.map +1 -0
  207. package/lib/node/session-storage/stored-session.spec.js +73 -0
  208. package/lib/node/session-storage/stored-session.spec.js.map +1 -0
  209. package/lib/node/settings-server-impl.d.ts +12 -0
  210. package/lib/node/settings-server-impl.d.ts.map +1 -0
  211. package/lib/node/settings-server-impl.js +48 -0
  212. package/lib/node/settings-server-impl.js.map +1 -0
  213. package/lib/node/settings-store.d.ts +57 -0
  214. package/lib/node/settings-store.d.ts.map +1 -0
  215. package/lib/node/settings-store.js +309 -0
  216. package/lib/node/settings-store.js.map +1 -0
  217. package/lib/node/settings-store.spec.d.ts +2 -0
  218. package/lib/node/settings-store.spec.d.ts.map +1 -0
  219. package/lib/node/settings-store.spec.js +145 -0
  220. package/lib/node/settings-store.spec.js.map +1 -0
  221. package/lib/node/ta-access.d.ts +19 -2
  222. package/lib/node/ta-access.d.ts.map +1 -1
  223. package/lib/node/ta-access.js +66 -9
  224. package/lib/node/ta-access.js.map +1 -1
  225. package/lib/node/ta-access.spec.js +8 -0
  226. package/lib/node/ta-access.spec.js.map +1 -1
  227. package/lib/node/ta-errors.d.ts +3 -1
  228. package/lib/node/ta-errors.d.ts.map +1 -1
  229. package/lib/node/ta-errors.js +17 -1
  230. package/lib/node/ta-errors.js.map +1 -1
  231. package/lib/node/ta-errors.spec.d.ts +2 -0
  232. package/lib/node/ta-errors.spec.d.ts.map +1 -0
  233. package/lib/node/ta-errors.spec.js +25 -0
  234. package/lib/node/ta-errors.spec.js.map +1 -0
  235. package/lib/node/ta-server-impl.d.ts +17 -5
  236. package/lib/node/ta-server-impl.d.ts.map +1 -1
  237. package/lib/node/ta-server-impl.js +70 -13
  238. package/lib/node/ta-server-impl.js.map +1 -1
  239. package/lib/node/ta-session-factory.d.ts +2 -0
  240. package/lib/node/ta-session-factory.d.ts.map +1 -1
  241. package/lib/node/ta-session-factory.js +24 -10
  242. package/lib/node/ta-session-factory.js.map +1 -1
  243. package/lib/node/ta-session.d.ts +9 -1
  244. package/lib/node/ta-session.d.ts.map +1 -1
  245. package/lib/node/ta-session.js +26 -2
  246. package/lib/node/ta-session.js.map +1 -1
  247. package/lib/node/terminal-protocol.d.ts +19 -0
  248. package/lib/node/terminal-protocol.d.ts.map +1 -0
  249. package/lib/node/terminal-protocol.js +5 -0
  250. package/lib/node/terminal-protocol.js.map +1 -0
  251. package/lib/node/terminal-service.d.ts +60 -0
  252. package/lib/node/terminal-service.d.ts.map +1 -0
  253. package/lib/node/terminal-service.js +241 -0
  254. package/lib/node/terminal-service.js.map +1 -0
  255. package/lib/node/terminal-service.spec.d.ts +2 -0
  256. package/lib/node/terminal-service.spec.d.ts.map +1 -0
  257. package/lib/node/terminal-service.spec.js +79 -0
  258. package/lib/node/terminal-service.spec.js.map +1 -0
  259. package/lib/node/terminal-util.d.ts +63 -0
  260. package/lib/node/terminal-util.d.ts.map +1 -0
  261. package/lib/node/terminal-util.js +158 -0
  262. package/lib/node/terminal-util.js.map +1 -0
  263. package/lib/node/terminal-util.spec.d.ts +2 -0
  264. package/lib/node/terminal-util.spec.d.ts.map +1 -0
  265. package/lib/node/terminal-util.spec.js +71 -0
  266. package/lib/node/terminal-util.spec.js.map +1 -0
  267. package/lib/node/web-extension-catalog.d.ts +39 -0
  268. package/lib/node/web-extension-catalog.d.ts.map +1 -0
  269. package/lib/node/web-extension-catalog.js +163 -0
  270. package/lib/node/web-extension-catalog.js.map +1 -0
  271. package/lib/node/web-extension-catalog.spec.d.ts +2 -0
  272. package/lib/node/web-extension-catalog.spec.d.ts.map +1 -0
  273. package/lib/node/web-extension-catalog.spec.js +157 -0
  274. package/lib/node/web-extension-catalog.spec.js.map +1 -0
  275. package/lib/node/web-extension-util.d.ts +22 -0
  276. package/lib/node/web-extension-util.d.ts.map +1 -0
  277. package/lib/node/web-extension-util.js +126 -0
  278. package/lib/node/web-extension-util.js.map +1 -0
  279. package/lib/node/working-directory.d.ts +14 -0
  280. package/lib/node/working-directory.d.ts.map +1 -0
  281. package/lib/node/working-directory.js +43 -0
  282. package/lib/node/working-directory.js.map +1 -0
  283. package/lib/node/workspace-files.d.ts +48 -0
  284. package/lib/node/workspace-files.d.ts.map +1 -0
  285. package/lib/node/workspace-files.js +268 -0
  286. package/lib/node/workspace-files.js.map +1 -0
  287. package/lib/node/workspace-files.spec.d.ts +2 -0
  288. package/lib/node/workspace-files.spec.d.ts.map +1 -0
  289. package/lib/node/workspace-files.spec.js +133 -0
  290. package/lib/node/workspace-files.spec.js.map +1 -0
  291. package/lib/node/workspace-protocol.d.ts +21 -0
  292. package/lib/node/workspace-protocol.d.ts.map +1 -0
  293. package/lib/node/workspace-protocol.js +6 -0
  294. package/lib/node/workspace-protocol.js.map +1 -0
  295. package/lib/node/workspace-server-impl.d.ts +28 -0
  296. package/lib/node/workspace-server-impl.d.ts.map +1 -0
  297. package/lib/node/workspace-server-impl.js +91 -0
  298. package/lib/node/workspace-server-impl.js.map +1 -0
  299. package/lib/node/workspace-service.d.ts +32 -0
  300. package/lib/node/workspace-service.d.ts.map +1 -0
  301. package/lib/node/workspace-service.js +212 -0
  302. package/lib/node/workspace-service.js.map +1 -0
  303. package/lib/node/workspace-service.spec.d.ts +2 -0
  304. package/lib/node/workspace-service.spec.d.ts.map +1 -0
  305. package/lib/node/workspace-service.spec.js +104 -0
  306. package/lib/node/workspace-service.spec.js.map +1 -0
  307. package/lib/node/workspace-util.d.ts +30 -0
  308. package/lib/node/workspace-util.d.ts.map +1 -0
  309. package/lib/node/workspace-util.js +107 -0
  310. package/lib/node/workspace-util.js.map +1 -0
  311. package/lib/node/workspace-util.spec.d.ts +2 -0
  312. package/lib/node/workspace-util.spec.d.ts.map +1 -0
  313. package/lib/node/workspace-util.spec.js +44 -0
  314. package/lib/node/workspace-util.spec.js.map +1 -0
  315. package/package.json +14 -9
  316. package/src/node/auth-server-impl.spec.ts +49 -0
  317. package/src/node/auth-server-impl.ts +252 -0
  318. package/src/node/client-tool-broker.spec.ts +53 -0
  319. package/src/node/client-tool-broker.ts +106 -0
  320. package/src/node/exec-environment-factory.ts +46 -0
  321. package/src/node/extension-data-notifier.spec.ts +34 -0
  322. package/src/node/extension-data-notifier.ts +124 -0
  323. package/src/node/extension-data.spec.ts +105 -0
  324. package/src/node/extension-data.ts +180 -0
  325. package/src/node/host-protocol.ts +31 -1
  326. package/src/node/index.ts +24 -1
  327. package/src/node/package-host-extension.ts +20 -0
  328. package/src/node/package-hosts.spec.ts +54 -0
  329. package/src/node/package-hosts.ts +174 -0
  330. package/src/node/package-server-impl.ts +87 -0
  331. package/src/node/package-switch.ts +80 -0
  332. package/src/node/relay-bridge.ts +94 -0
  333. package/src/node/session-info-util.spec.ts +23 -0
  334. package/src/node/session-info-util.ts +55 -0
  335. package/src/node/session-storage/file-session-storage.spec.ts +72 -0
  336. package/src/node/session-storage/file-session-storage.ts +145 -0
  337. package/src/node/session-storage/index.ts +3 -0
  338. package/src/node/session-storage/session-storage-protocol.ts +81 -0
  339. package/src/node/session-storage/stored-session.spec.ts +80 -0
  340. package/src/node/session-storage/stored-session.ts +149 -0
  341. package/src/node/settings-server-impl.ts +33 -0
  342. package/src/node/settings-store.spec.ts +155 -0
  343. package/src/node/settings-store.ts +308 -0
  344. package/src/node/ta-access.spec.ts +9 -0
  345. package/src/node/ta-access.ts +65 -7
  346. package/src/node/ta-errors.spec.ts +25 -0
  347. package/src/node/ta-errors.ts +21 -1
  348. package/src/node/ta-server-impl.ts +75 -12
  349. package/src/node/ta-session-factory.ts +21 -7
  350. package/src/node/ta-session.ts +43 -3
  351. package/src/node/terminal-protocol.ts +18 -0
  352. package/src/node/terminal-service.spec.ts +84 -0
  353. package/src/node/terminal-service.ts +259 -0
  354. package/src/node/terminal-util.spec.ts +78 -0
  355. package/src/node/terminal-util.ts +166 -0
  356. package/src/node/web-extension-catalog.spec.ts +172 -0
  357. package/src/node/web-extension-catalog.ts +172 -0
  358. package/src/node/web-extension-util.ts +144 -0
  359. package/src/node/working-directory.ts +38 -0
  360. package/src/node/workspace-files.spec.ts +145 -0
  361. package/src/node/workspace-files.ts +256 -0
  362. package/src/node/workspace-protocol.ts +22 -0
  363. package/src/node/workspace-server-impl.ts +90 -0
  364. package/src/node/workspace-service.spec.ts +113 -0
  365. package/src/node/workspace-service.ts +223 -0
  366. package/src/node/workspace-util.spec.ts +47 -0
  367. package/src/node/workspace-util.ts +103 -0
  368. package/esm/node/local-exec-environment-factory.d.ts +0 -4
  369. package/esm/node/local-exec-environment-factory.js +0 -18
  370. package/esm/node/local-exec-environment-factory.js.map +0 -1
  371. package/lib/node/local-exec-environment-factory.d.ts +0 -5
  372. package/lib/node/local-exec-environment-factory.d.ts.map +0 -1
  373. package/lib/node/local-exec-environment-factory.js +0 -21
  374. package/lib/node/local-exec-environment-factory.js.map +0 -1
  375. package/src/node/local-exec-environment-factory.ts +0 -9
@@ -0,0 +1,308 @@
1
+ import { mkdir, readFile, rename, rmdir, stat, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { CODING_AGENT_OPTIONS, type CodingAgentOptions, ModelRuntimeProvider, PiSdkUtil } from '@celljs/ai-coding-agent';
4
+ import { Autowired, Component, Value } from '@celljs/core';
5
+ import { TA_SETTINGS, type TaSettingSpec, type TaSettingsScope, type TaSettingsSnapshot } from '@celljs/ta-protocol';
6
+ import { TaSessionRegistry } from './host-protocol';
7
+ import { TaErrors } from './ta-errors';
8
+
9
+ export const TaSettingsStore = Symbol('TaSettingsStore');
10
+
11
+ /** The settings of ta (TA_SETTINGS) in pi's `settings.json` of the user and of a project. */
12
+ export interface TaSettingsStore {
13
+ get(cwd: string): Promise<TaSettingsSnapshot>;
14
+ update(scope: TaSettingsScope, changes: Record<string, unknown>, cwd: string): Promise<TaSettingsSnapshot>;
15
+ }
16
+
17
+ type Json = Record<string, unknown>;
18
+
19
+ export namespace TaSettingsUtil {
20
+ const MODEL = 'model';
21
+
22
+ /** The settings of TA_SETTINGS that a file sets, by key. */
23
+ export function read(data: Json, specs: readonly TaSettingSpec[] = TA_SETTINGS): Json {
24
+ const values: Json = {};
25
+ for (const spec of specs) {
26
+ if (spec.key === MODEL) {
27
+ if (typeof data.defaultProvider === 'string' && typeof data.defaultModel === 'string') {
28
+ values[MODEL] = `${data.defaultProvider}/${data.defaultModel}`;
29
+ }
30
+ continue;
31
+ }
32
+ const value = at(data, spec.key);
33
+ if (value !== undefined && check(spec, value) !== undefined) {
34
+ values[spec.key] = value;
35
+ }
36
+ }
37
+ return values;
38
+ }
39
+
40
+ /** The file with the changes; the other keys stay. Throws for a key or a value ta does not take. */
41
+ export function apply(data: Json, changes: Json, specs: readonly TaSettingSpec[] = TA_SETTINGS): Json {
42
+ const next = structuredClone(data);
43
+ for (const [key, raw] of Object.entries(changes)) {
44
+ const spec = specs.find(candidate => candidate.key === key);
45
+ if (!spec) {
46
+ throw TaErrors.invalidArgument(
47
+ `${key} is not a setting clients change.`,
48
+ `Use one of ${specs.map(other => other.key).join(', ')}; edit settings.json for the others.`,
49
+ );
50
+ }
51
+ // Blank text removes the key, as a cleared field means.
52
+ const removes = raw === null || raw === undefined || (typeof raw === 'string' && !raw.trim());
53
+ const value = removes ? undefined : check(spec, raw);
54
+ if (!removes && value === undefined) {
55
+ throw TaErrors.invalidArgument(`${JSON.stringify(raw)} is not a value of ${key}.`, describe(spec));
56
+ }
57
+ if (key === MODEL) {
58
+ const [provider, ...id] = typeof value === 'string' ? value.split('/') : [];
59
+ put(next, 'defaultProvider', provider);
60
+ put(next, 'defaultModel', provider ? id.join('/') : undefined);
61
+ } else {
62
+ put(next, key, value);
63
+ }
64
+ }
65
+ return next;
66
+ }
67
+
68
+ /** The value as the setting keeps it, or undefined when it is not one. An empty string is no value. */
69
+ export function check(spec: TaSettingSpec, value: unknown): unknown {
70
+ switch (spec.type) {
71
+ case 'boolean':
72
+ return typeof value === 'boolean' ? value : undefined;
73
+ case 'number':
74
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined;
75
+ case 'enum':
76
+ return typeof value === 'string' && spec.values?.includes(value) ? value : undefined;
77
+ case 'model':
78
+ return typeof value === 'string' && /^[^/\s]+\/\S+$/.test(value.trim()) ? value.trim() : undefined;
79
+ default:
80
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
81
+ }
82
+ }
83
+
84
+ function describe(spec: TaSettingSpec): string {
85
+ switch (spec.type) {
86
+ case 'boolean':
87
+ return 'Pass true or false, or null to remove it.';
88
+ case 'number':
89
+ return 'Pass a whole number of 0 or more, or null to remove it.';
90
+ case 'enum':
91
+ return `Pass one of ${spec.values?.join(', ')}, or null to remove it.`;
92
+ case 'model':
93
+ return 'Pass <provider>/<model id>, or null to remove it.';
94
+ default:
95
+ return 'Pass text, or null to remove it.';
96
+ }
97
+ }
98
+
99
+ function at(data: Json, key: string): unknown {
100
+ let value: unknown = data;
101
+ for (const part of key.split('.')) {
102
+ value = value && typeof value === 'object' && !Array.isArray(value) ? (value as Json)[part] : undefined;
103
+ }
104
+ return value;
105
+ }
106
+
107
+ /** Sets a dotted key; undefined removes it, and the objects it leaves empty. */
108
+ function put(data: Json, key: string, value: unknown): void {
109
+ const parts = key.split('.');
110
+ const last = parts.pop() as string;
111
+ const parents: Json[] = [data];
112
+ let target = data;
113
+ for (const part of parts) {
114
+ const child = target[part];
115
+ if (!child || typeof child !== 'object' || Array.isArray(child)) {
116
+ if (value === undefined) {
117
+ return;
118
+ }
119
+ target[part] = {};
120
+ }
121
+ target = target[part] as Json;
122
+ parents.push(target);
123
+ }
124
+ if (value === undefined) {
125
+ delete target[last];
126
+ for (let index = parts.length - 1; index >= 0; index--) {
127
+ if (Object.keys(parents[index + 1]).length === 0) {
128
+ delete parents[index][parts[index]];
129
+ }
130
+ }
131
+ } else {
132
+ target[last] = value;
133
+ }
134
+ }
135
+
136
+ export function parse(text: string | undefined, file: string): Json {
137
+ if (!text?.trim()) {
138
+ return {};
139
+ }
140
+ let data: unknown;
141
+ try {
142
+ data = JSON.parse(text);
143
+ } catch (error) {
144
+ throw TaErrors.invalidArgument(
145
+ `${file} is not valid JSON: ${(error as Error).message}`,
146
+ 'Fix the file by hand first; ta does not overwrite what it cannot read.',
147
+ );
148
+ }
149
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
150
+ throw TaErrors.invalidArgument(`${file} does not hold a JSON object.`, 'Fix the file by hand first; ta does not overwrite what it cannot read.');
151
+ }
152
+ return data as Json;
153
+ }
154
+ }
155
+
156
+ /**
157
+ * The lock pi takes on a settings file while it writes it (proper-lockfile: a directory `<file>.lock`, taken
158
+ * over when older than 10 s), so that a write of ta serve and one of `ta` in a terminal do not lose each
159
+ * other's changes: pi reads the file again under the lock and writes back only what it changed.
160
+ */
161
+ export namespace SettingsLockUtil {
162
+ export const STALE_MS = 10_000;
163
+ const RETRY_MS = 20;
164
+ const ATTEMPTS = 250;
165
+
166
+ export async function run<T>(file: string, work: () => Promise<T>): Promise<T> {
167
+ const lock = `${file}.lock`;
168
+ await mkdir(dirname(file), { recursive: true });
169
+ for (let attempt = 0; ; attempt++) {
170
+ try {
171
+ await mkdir(lock);
172
+ break;
173
+ } catch (error) {
174
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
175
+ throw error;
176
+ }
177
+ const since = await stat(lock).then(
178
+ info => Date.now() - info.mtimeMs,
179
+ () => 0,
180
+ );
181
+ if (since > STALE_MS) {
182
+ await rmdir(lock).catch(() => undefined);
183
+ } else if (attempt >= ATTEMPTS) {
184
+ throw TaErrors.invalidArgument(`${file} stays locked by another process.`, `Try again; if no Ta is running, delete ${lock}.`);
185
+ } else {
186
+ await new Promise(resolve => setTimeout(resolve, RETRY_MS));
187
+ }
188
+ }
189
+ }
190
+ try {
191
+ return await work();
192
+ } finally {
193
+ await rmdir(lock).catch(() => undefined);
194
+ }
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Reads and writes the settings of ta where pi keeps them, under pi's lock of the file (SettingsLockUtil), and has the open sessions read them again. A
200
+ * file is written whole, through a temporary file, with its other keys as they were.
201
+ */
202
+ @Component(TaSettingsStore)
203
+ export class TaSettingsStoreImpl implements TaSettingsStore {
204
+ @Value(CODING_AGENT_OPTIONS)
205
+ protected readonly codingAgentOptions?: CodingAgentOptions;
206
+
207
+ @Autowired(ModelRuntimeProvider)
208
+ protected readonly modelRuntimeProvider: ModelRuntimeProvider;
209
+
210
+ @Autowired(TaSessionRegistry)
211
+ protected readonly sessions: TaSessionRegistry;
212
+
213
+ /** One write at a time, so that two changes of one file both stay. */
214
+ protected writing: Promise<unknown> = Promise.resolve();
215
+
216
+ async get(cwd: string): Promise<TaSettingsSnapshot> {
217
+ const { userFile, projectFile, trusted } = await this.files(cwd);
218
+ const [user, project, models] = await Promise.all([this.read(userFile), this.read(projectFile), this.models()]);
219
+ return {
220
+ user: TaSettingsUtil.read(user),
221
+ project: TaSettingsUtil.read(project),
222
+ cwd,
223
+ userFile,
224
+ projectFile,
225
+ projectTrusted: trusted !== false,
226
+ models,
227
+ };
228
+ }
229
+
230
+ update(scope: TaSettingsScope, changes: Record<string, unknown>, cwd: string): Promise<TaSettingsSnapshot> {
231
+ const next = this.writing.then(() => this.write(scope, changes, cwd));
232
+ this.writing = next.catch(() => undefined);
233
+ return next;
234
+ }
235
+
236
+ protected async write(scope: TaSettingsScope, changes: Record<string, unknown>, cwd: string): Promise<TaSettingsSnapshot> {
237
+ if (!changes || typeof changes !== 'object' || Array.isArray(changes)) {
238
+ throw TaErrors.invalidArgument('The changes are an object of settings.', 'Pass { key: value }, with null to remove a key.');
239
+ }
240
+ const { userFile, projectFile, trusted, trust } = await this.files(cwd);
241
+ if (scope === 'project' && trusted === false) {
242
+ throw TaErrors.invalidArgument(
243
+ `ta does not trust ${cwd}, so it does not read the settings of the project.`,
244
+ 'Run ta in that directory and trust the project, or change the settings of the user.',
245
+ );
246
+ }
247
+ const file = scope === 'user' ? userFile : projectFile;
248
+ await SettingsLockUtil.run(file, async () => {
249
+ const data = TaSettingsUtil.apply(await this.read(file), changes);
250
+ await writeFile(`${file}.tmp`, `${JSON.stringify(data, null, 2)}\n`);
251
+ await rename(`${file}.tmp`, file);
252
+ });
253
+ // A project with nothing pi asks about: the user writing its settings is trusting it, else pi would ignore them.
254
+ if (scope === 'project' && trusted === undefined) {
255
+ trust();
256
+ }
257
+ await this.reloadSessions(scope, cwd);
258
+ return this.get(cwd);
259
+ }
260
+
261
+ /**
262
+ * `trusted`: pi's decision for the project, or false when it has resources pi asks about first;
263
+ * undefined when nobody decided and there is nothing to ask about, as pi trusts it then.
264
+ */
265
+ protected async files(cwd: string): Promise<{ userFile: string; projectFile: string; trusted?: boolean; trust(): void }> {
266
+ const sdk = await PiSdkUtil.load();
267
+ const agentDir = this.codingAgentOptions?.agentDir ?? sdk.getAgentDir();
268
+ const store = new sdk.ProjectTrustStore(agentDir);
269
+ const decision = store.get(cwd);
270
+ return {
271
+ userFile: join(agentDir, 'settings.json'),
272
+ projectFile: join(cwd, sdk.CONFIG_DIR_NAME, 'settings.json'),
273
+ trusted: decision ?? (sdk.hasTrustRequiringProjectResources(cwd) ? false : undefined),
274
+ trust: () => store.set(cwd, true),
275
+ };
276
+ }
277
+
278
+ protected async read(file: string): Promise<Record<string, unknown>> {
279
+ const text = await readFile(file, 'utf8').catch((error: NodeJS.ErrnoException) => {
280
+ if (error.code === 'ENOENT') {
281
+ return undefined;
282
+ }
283
+ throw error;
284
+ });
285
+ return TaSettingsUtil.parse(text, file);
286
+ }
287
+
288
+ protected async models(): Promise<string[]> {
289
+ try {
290
+ const runtime = await this.modelRuntimeProvider.provide();
291
+ return (await runtime.getAvailable()).map(model => `${model.provider}/${model.id}`);
292
+ } catch {
293
+ return [];
294
+ }
295
+ }
296
+
297
+ protected async reloadSessions(scope: TaSettingsScope, cwd: string): Promise<void> {
298
+ for (const session of this.sessions.list()) {
299
+ if (scope === 'user' || session.runtime.cwd === cwd) {
300
+ const manager = session.pi.settingsManager;
301
+ if (scope === 'project' && !manager.isProjectTrusted()) {
302
+ manager.setProjectTrusted(true);
303
+ }
304
+ await manager.reload().catch(() => undefined);
305
+ }
306
+ }
307
+ }
308
+ }
@@ -24,4 +24,13 @@ describe('TaAccessUtil', () => {
24
24
  expect(TaAccessUtil.isLoopbackHost('evil.example:3000')).toBe(false);
25
25
  expect(TaAccessUtil.isLoopbackHost(undefined)).toBe(false);
26
26
  });
27
+
28
+ it('tells calls over plain HTTP from the files and the pages', () => {
29
+ const call = (method: string, url: string) => ({ method, url, headers: {} }) as unknown as IncomingMessage;
30
+ expect(TaAccessUtil.isHttpCall(call('POST', '/api/TaServer'))).toBe(true);
31
+ expect(TaAccessUtil.isHttpCall(call('POST', '/api/TaWorkspaceServer?token=abc'))).toBe(true);
32
+ expect(TaAccessUtil.isHttpCall(call('GET', '/api/files/x/a.png'))).toBe(false);
33
+ expect(TaAccessUtil.isHttpCall(call('GET', '/api/ws'))).toBe(false);
34
+ expect(TaAccessUtil.isHttpCall(call('POST', '/index.html'))).toBe(false);
35
+ });
27
36
  });
@@ -1,3 +1,4 @@
1
+ import { spawn } from 'node:child_process';
1
2
  import { randomBytes, timingSafeEqual } from 'node:crypto';
2
3
  import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
3
4
  import type { IncomingMessage, Server } from 'node:http';
@@ -5,6 +6,7 @@ import type { AddressInfo } from 'node:net';
5
6
  import { join } from 'node:path';
6
7
  import { type Application, ApplicationLifecycle, Autowired, Component, Value } from '@celljs/core';
7
8
  import { RpcContext, RpcWebSocketGuard } from '@celljs/rpc/lib/node';
9
+ import { TaServeStateUtil } from '@celljs/ta-harness/lib/node/serve-state';
8
10
  import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
9
11
  import { TA_SERVE_FILE, TA_WEBSOCKET_PATH, type TaServeInfo } from '@celljs/ta-protocol';
10
12
  import { type Context, Middleware, ServerAware } from '@celljs/web/lib/node';
@@ -12,8 +14,14 @@ import { TaSessionRegistry } from './host-protocol';
12
14
 
13
15
  const LOOPBACK_NAMES = new Set(['127.0.0.1', 'localhost', '[::1]']);
14
16
 
17
+ /** Where the calls go (`rpc.path`); everything else is the web client, if it is installed. */
18
+ const API_PATH = '/api';
19
+
20
+ /** The id of {@link TaAccess}, for what needs the token, as RelayBridge does. */
21
+ export const TA_ACCESS = Symbol('TaAccess');
22
+
15
23
  /** Runs before everything else that handles a request. */
16
- const ACCESS_MIDDLEWARE_PRIORITY = 10000;
24
+ export const ACCESS_MIDDLEWARE_PRIORITY = 10000;
17
25
 
18
26
  export namespace TaAccessUtil {
19
27
  /** From `Authorization: Bearer`, or `?token=` for browsers, whose WebSocket API cannot set headers. */
@@ -34,16 +42,47 @@ export namespace TaAccessUtil {
34
42
  export function isLoopbackHost(host: string | undefined): boolean {
35
43
  return LOOPBACK_NAMES.has((host ?? '').replace(/:\d+$/, ''));
36
44
  }
45
+
46
+ /** The files of the web client are the same for everyone: they hold no data, so they need no token. */
47
+ export function isPublic(request: IncomingMessage): boolean {
48
+ const path = (request.url ?? '/').split('?')[0];
49
+ return (request.method === 'GET' || request.method === 'HEAD') && path !== API_PATH && !path.startsWith(`${API_PATH}/`);
50
+ }
51
+
52
+ /**
53
+ * A JSON-RPC call over plain HTTP (`POST /api/<service>`), which @celljs/rpc answers too: ta serve takes
54
+ * calls on its WebSocket only, where a call knows its connection (attach, terminals) and gets pushes.
55
+ */
56
+ export function isHttpCall(request: IncomingMessage): boolean {
57
+ const path = (request.url ?? '/').split('?')[0];
58
+ return request.method === 'POST' && path.startsWith(`${API_PATH}/`);
59
+ }
60
+
61
+ /** The token goes in the fragment, which the browser does not send to the server or in `Referer`. */
62
+ export function webUrl(httpUrl: string, token: string): string {
63
+ return `${httpUrl}/#token=${token}`;
64
+ }
65
+
66
+ /** Opens a URL in the user's browser. */
67
+ export function openBrowser(url: string): void {
68
+ const [command, ...args] =
69
+ process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['cmd', '/c', 'start', '""', url] : ['xdg-open', url];
70
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
71
+ child.on('error', () => console.log(`ta serve: open ${url} in a browser`));
72
+ child.unref();
73
+ }
37
74
  }
38
75
 
39
76
  /**
40
- * The token of this server: `TA_SERVE_TOKEN`, which a parent process (the desktop app) can choose, or a
41
- * random one. It lets in connections and requests, and is published in a file only this user can read.
77
+ * The token of this server: `TA_SERVE_TOKEN`, which a parent process (the desktop app) can choose, or the
78
+ * one of the last start, or a random one. It lets in connections and requests, and is published in a file
79
+ * only this user can read. It stays across restarts with the port (TaServeStateUtil), so that the web app
80
+ * installed from this address, which remembers both, signs in again by itself.
42
81
  */
43
- @Component([RpcWebSocketGuard, Middleware, ServerAware, ApplicationLifecycle])
82
+ @Component([TA_ACCESS, RpcWebSocketGuard, Middleware, ServerAware, ApplicationLifecycle])
44
83
  export class TaAccess implements RpcWebSocketGuard, Middleware, ServerAware, ApplicationLifecycle<Application> {
45
84
  readonly priority = ACCESS_MIDDLEWARE_PRIORITY;
46
- readonly token = process.env.TA_SERVE_TOKEN || randomBytes(32).toString('base64url');
85
+ readonly token = process.env.TA_SERVE_TOKEN || TaServeStateUtil.read().token || randomBytes(32).toString('base64url');
47
86
 
48
87
  @Value('server.host')
49
88
  protected readonly host?: string;
@@ -60,7 +99,17 @@ export class TaAccess implements RpcWebSocketGuard, Middleware, ServerAware, App
60
99
 
61
100
  /** Calls over a WebSocket were checked when it opened; this covers plain HTTP. */
62
101
  async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
63
- if (RpcContext.connection() || this.allows(ctx.request as unknown as IncomingMessage)) {
102
+ const request = ctx.request as unknown as IncomingMessage;
103
+ if (RpcContext.connection()) {
104
+ await next();
105
+ return;
106
+ }
107
+ if (this.allows(request) && TaAccessUtil.isHttpCall(request)) {
108
+ ctx.response.statusCode = 404;
109
+ ctx.response.end(`Call ta serve over its WebSocket, ${TA_WEBSOCKET_PATH}.`);
110
+ return;
111
+ }
112
+ if (this.allows(request) || (TaAccessUtil.isPublic(request) && this.acceptsHost(request))) {
64
113
  await next();
65
114
  return;
66
115
  }
@@ -88,11 +137,20 @@ export class TaAccess implements RpcWebSocketGuard, Middleware, ServerAware, App
88
137
 
89
138
  protected publish(server: Server): void {
90
139
  const { port } = server.address() as AddressInfo;
91
- const info: TaServeInfo = { url: `ws://${this.host ?? '127.0.0.1'}:${port}${TA_WEBSOCKET_PATH}`, token: this.token, pid: process.pid };
140
+ const origin = `${this.host ?? '127.0.0.1'}:${port}`;
141
+ const info: TaServeInfo = { url: `ws://${origin}${TA_WEBSOCKET_PATH}`, token: this.token, pid: process.pid };
92
142
  mkdirSync(join(this.infoFile, '..'), { recursive: true });
93
143
  writeFileSync(this.infoFile, JSON.stringify(info), { mode: 0o600 });
94
144
  // The mode above only applies to a new file.
95
145
  chmodSync(this.infoFile, 0o600);
146
+ // A token that a parent process chose is its to keep.
147
+ const kept = TaServeStateUtil.read().token;
148
+ TaServeStateUtil.write({ port, token: process.env.TA_SERVE_TOKEN ? kept : this.token });
96
149
  console.log(`ta serve: ${info.url} (token in ${this.infoFile})`);
150
+ if (process.env.TA_SERVE_OPEN_WEB) {
151
+ const url = TaAccessUtil.webUrl(`http://${origin}`, this.token);
152
+ console.log(`ta serve: web client at ${url}`);
153
+ TaAccessUtil.openBrowser(url);
154
+ }
97
155
  }
98
156
  }
@@ -0,0 +1,25 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { TaErrorCode } from '@celljs/ta-protocol';
3
+ import { TaErrors } from './ta-errors';
4
+
5
+ const dataOf = (error: Error) => (error as unknown as { data: { code: string; hint: string } }).data;
6
+
7
+ describe('TaErrors', () => {
8
+ it("names pi's failures for want of a sign-in, without its talk of /login and its paths", () => {
9
+ for (const text of [
10
+ 'No API key found for anthropic.\n\nUse /login to log into a provider via OAuth or API key. See:\n /x/docs/providers.md',
11
+ 'No model selected.\n\nUse /login…',
12
+ 'No models available. Use /login…',
13
+ ]) {
14
+ const error = TaErrors.commandFailed(new Error(text));
15
+ expect(dataOf(error).code).toBe(TaErrorCode.NOT_SIGNED_IN);
16
+ expect(error.message).not.toContain('/login');
17
+ }
18
+ });
19
+
20
+ it('passes on other failures of pi with their message', () => {
21
+ const error = TaErrors.commandFailed(new Error('Agent is already processing.'));
22
+ expect(dataOf(error).code).toBe(TaErrorCode.COMMAND_FAILED);
23
+ expect(error.message).toBe('Agent is already processing.');
24
+ });
25
+ });
@@ -6,7 +6,10 @@ const TaError = ApplicationError.declare<number, TaErrorData>(TA_RPC_ERROR_CODE,
6
6
  data: { code, hint },
7
7
  }));
8
8
 
9
- /** The failures of {@link TaServer} calls, which reach the client with their message and code. */
9
+ /** What pi says when no provider is signed in for the model, or no model can be used. */
10
+ const NOT_SIGNED_IN = /^No (API key found for|model selected|models available)\b/;
11
+
12
+ /** The failures of calls of the services of ta serve ({@link TaServer} and the others), which reach the client with their message and code. */
10
13
  export namespace TaErrors {
11
14
  export function sessionNotFound(sessionId: string): Error {
12
15
  return TaError(
@@ -44,12 +47,29 @@ export namespace TaErrors {
44
47
  return TaError(TaErrorCode.INVALID_ARGUMENT, message, hint);
45
48
  }
46
49
 
50
+ /** Runs a call of a service of ta serve, so that what it throws reaches the client with its message (commandFailed). */
51
+ export async function guard<T>(command: () => T | Promise<T>): Promise<T> {
52
+ try {
53
+ return await command();
54
+ } catch (error) {
55
+ throw commandFailed(error);
56
+ }
57
+ }
58
+
47
59
  /** A command that pi refused or that failed. Other errors would lose their message on the way out. */
48
60
  export function commandFailed(cause: unknown): Error {
49
61
  if (ApplicationError.is(cause as object)) {
50
62
  return cause as Error;
51
63
  }
52
64
  const message = cause instanceof Error ? cause.message : String(cause);
65
+ if (NOT_SIGNED_IN.test(message)) {
66
+ // pi's own words go on about its /login and the paths of its documents, which a client does not have.
67
+ return TaError(
68
+ TaErrorCode.NOT_SIGNED_IN,
69
+ message.split(/\n| Use \/login/)[0].trim(),
70
+ 'Sign in to a provider of models (TaAuthServer.login), then send it again.',
71
+ );
72
+ }
53
73
  return TaError(TaErrorCode.COMMAND_FAILED, message, 'The message comes from the agent; fix what it says and send the command again.');
54
74
  }
55
75
  }
@@ -1,28 +1,62 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { PiSdkUtil } from '@celljs/ai-coding-agent';
1
3
  import { Autowired } from '@celljs/core';
2
4
  import { Rpc } from '@celljs/rpc';
3
5
  import { RpcContext } from '@celljs/rpc/lib/node';
6
+ import { ExecEnvironmentFactory } from '@celljs/ta-exec';
7
+ import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
4
8
  import {
5
9
  type RpcExtensionUIResponse,
6
10
  type TaAttachResult,
7
11
  type TaClientToolResult,
8
12
  type TaCommandResult,
13
+ type TaForkFileResult,
14
+ type TaNavigateResult,
9
15
  type TaOpenSessionOptions,
10
16
  type TaPromptInput,
11
17
  type TaPromptReceipt,
12
18
  TaServer,
19
+ type TaServerInfo,
13
20
  type TaSessionInfo,
14
21
  type ThinkingLevel,
15
22
  } from '@celljs/ta-protocol';
16
23
  import { TaSessionRegistry } from './host-protocol';
24
+ import { SessionInfoUtil } from './session-info-util';
17
25
  import { TaErrors } from './ta-errors';
18
26
  import type { TaSession } from './ta-session';
27
+ import { TaWorkingDirectory } from './working-directory';
19
28
 
20
- /** Each command does what the command of the same name does in pi's RPC mode. */
29
+ /**
30
+ * The sessions of ta serve. Each command of pi's RPC mode does here what it does in pi's `rpc-mode`, which
31
+ * pi exports only bound to stdio: when pi changes one, change it here too (the spec of TaServer in
32
+ * ta-protocol fails to compile when pi adds one).
33
+ */
21
34
  @Rpc(TaServer)
22
35
  export class TaServerImpl implements TaServer {
23
36
  @Autowired(TaSessionRegistry)
24
37
  protected readonly sessions: TaSessionRegistry;
25
38
 
39
+ @Autowired(ExecEnvironmentFactory)
40
+ protected readonly environments: ExecEnvironmentFactory;
41
+
42
+ @Autowired(TaWorkingDirectory)
43
+ protected readonly workingDirectory: TaWorkingDirectory;
44
+
45
+ async getServerInfo(): Promise<TaServerInfo> {
46
+ return this.guard(async () => ({ version: TaBrand.version(), cwd: await this.environments.defaultCwd() }));
47
+ }
48
+
49
+ async setWorkingDirectory(cwd: string): Promise<TaServerInfo> {
50
+ return this.guard(async () => {
51
+ const path = typeof cwd === 'string' ? cwd.trim() : '';
52
+ if (!path || !(await this.environments.create(path).stat(path))?.isDirectory) {
53
+ throw TaErrors.invalidArgument(`${cwd} is not a directory.`, 'Pass the absolute path of a directory that exists on the server.');
54
+ }
55
+ this.workingDirectory.set(path);
56
+ return this.getServerInfo();
57
+ });
58
+ }
59
+
26
60
  async openSession(options: TaOpenSessionOptions): Promise<TaSessionInfo> {
27
61
  return this.guard(async () => (await this.sessions.open(options)).info());
28
62
  }
@@ -47,9 +81,8 @@ export class TaServerImpl implements TaServer {
47
81
  return this.on(sessionId, session => session.respondUi(response));
48
82
  }
49
83
 
50
- /** Client tools are declared in the protocol and not run yet: nobody can be waiting. */
51
- async respondClientTool(_sessionId: string, _result: TaClientToolResult): Promise<boolean> {
52
- return false;
84
+ respondClientTool(sessionId: string, result: TaClientToolResult): Promise<boolean> {
85
+ return this.on(sessionId, session => session.respondClientTool(result));
53
86
  }
54
87
 
55
88
  prompt(sessionId: string, input: TaPromptInput): Promise<TaPromptReceipt> {
@@ -183,13 +216,34 @@ export class TaServerImpl implements TaServer {
183
216
  return this.on(sessionId, ({ runtime }) => runtime.switchSession(sessionPath));
184
217
  }
185
218
 
186
- fork(sessionId: string, entryId: string): Promise<TaCommandResult<'fork'>> {
219
+ fork(sessionId: string, entryId: string, position?: 'before' | 'at'): Promise<TaCommandResult<'fork'>> {
187
220
  return this.on(sessionId, async ({ runtime }) => {
188
- const result = await runtime.fork(entryId);
221
+ const result = await runtime.fork(entryId, { position });
189
222
  return { text: result.selectedText ?? '', cancelled: result.cancelled };
190
223
  });
191
224
  }
192
225
 
226
+ forkToFile(sessionId: string, entryId: string, position: 'before' | 'at' = 'before'): Promise<TaForkFileResult> {
227
+ return this.on(sessionId, async ({ pi }) => {
228
+ const manager = pi.sessionManager;
229
+ const entry = manager.getEntry(entryId);
230
+ const user = entry?.type === 'message' && entry.message.role === 'user' ? entry.message : undefined;
231
+ if (!entry || (position === 'before' && !user)) {
232
+ throw TaErrors.invalidArgument(`No entry to fork from has the id ${entryId}.`, 'Pass the id of a message of the user, or position "at".');
233
+ }
234
+ const text = position === 'before' && user ? SessionInfoUtil.text(user.content) : undefined;
235
+ const leafId = position === 'before' ? entry.parentId : entry.id;
236
+ const file = manager.getSessionFile();
237
+ if (!leafId || !file || !existsSync(file)) {
238
+ return { text };
239
+ }
240
+ // A copy of the session, so that the session itself does not move.
241
+ const sdk = await PiSdkUtil.load();
242
+ const forked = sdk.SessionManager.open(file, manager.getSessionDir()).createBranchedSession(leafId);
243
+ return { sessionFile: forked && existsSync(forked) ? forked : undefined, text };
244
+ });
245
+ }
246
+
193
247
  clone(sessionId: string): Promise<TaCommandResult<'clone'>> {
194
248
  return this.on(sessionId, async ({ pi, runtime }) => {
195
249
  const leafId = pi.sessionManager.getLeafId();
@@ -219,6 +273,10 @@ export class TaServerImpl implements TaServer {
219
273
  return this.on(sessionId, ({ pi }) => ({ tree: pi.sessionManager.getTree(), leafId: pi.sessionManager.getLeafId() }));
220
274
  }
221
275
 
276
+ navigateTree(sessionId: string, targetId: string): Promise<TaNavigateResult> {
277
+ return this.on(sessionId, session => session.navigateTree(targetId));
278
+ }
279
+
222
280
  getLastAssistantText(sessionId: string): Promise<TaCommandResult<'get_last_assistant_text'>> {
223
281
  return this.on(sessionId, ({ pi }) => ({ text: pi.getLastAssistantText() ?? null }));
224
282
  }
@@ -250,15 +308,20 @@ export class TaServerImpl implements TaServer {
250
308
  }));
251
309
  }
252
310
 
311
+ reload(sessionId: string): Promise<void> {
312
+ return this.on(sessionId, ({ pi }) => {
313
+ if (pi.isStreaming) {
314
+ throw TaErrors.invalidArgument('The session is working.', 'Reload it once the run has ended, or abort the run first.');
315
+ }
316
+ return pi.reload();
317
+ });
318
+ }
319
+
253
320
  protected on<T>(sessionId: string, command: (session: TaSession) => T | Promise<T>): Promise<T> {
254
321
  return this.guard(async () => command(this.sessions.require(sessionId)));
255
322
  }
256
323
 
257
- protected async guard<T>(command: () => Promise<T>): Promise<T> {
258
- try {
259
- return await command();
260
- } catch (error) {
261
- throw TaErrors.commandFailed(error);
262
- }
324
+ protected guard<T>(command: () => Promise<T>): Promise<T> {
325
+ return TaErrors.guard(command);
263
326
  }
264
327
  }