@zhivex-ai/harness 1.6.3 → 1.8.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 (391) hide show
  1. package/CHANGELOG.md +16 -3
  2. package/README.md +17 -5
  3. package/SECURITY.md +1 -1
  4. package/SUPPORT.md +2 -2
  5. package/benchmarks/README.md +98 -0
  6. package/contracts/engine-api.json +1587 -0
  7. package/contracts/public-api.json +114 -0
  8. package/contracts/stable-api-signatures.json +17 -17
  9. package/dist/acp-cli.js +37 -1090
  10. package/dist/application/agenda.d.ts +10 -0
  11. package/dist/application/approval-review.d.ts +61 -0
  12. package/dist/application/assistant/automation/scheduler.d.ts +21 -0
  13. package/dist/application/assistant/automation/summary.d.ts +29 -0
  14. package/dist/application/assistant/automation/time.d.ts +10 -0
  15. package/dist/application/assistant/calendar/calendar.d.ts +238 -0
  16. package/dist/application/assistant/calendar/connection.d.ts +50 -0
  17. package/dist/application/assistant/calendar/create-event.d.ts +75 -0
  18. package/dist/application/assistant/calendar/environment.d.ts +2 -0
  19. package/dist/application/assistant/calendar/http.d.ts +6 -0
  20. package/dist/application/assistant/calendar/oauth.d.ts +68 -0
  21. package/dist/application/assistant/calendar/store.d.ts +11 -0
  22. package/dist/application/assistant/calendar/tools.d.ts +78 -0
  23. package/dist/application/assistant/client.d.ts +10 -0
  24. package/dist/application/assistant/config.d.ts +9 -0
  25. package/dist/application/assistant/contracts.d.ts +77 -0
  26. package/dist/application/assistant/daily/service.d.ts +181 -0
  27. package/dist/application/assistant/doctor.d.ts +22 -0
  28. package/dist/application/assistant/evaluation.d.ts +81 -0
  29. package/dist/application/assistant/host.d.ts +399 -0
  30. package/dist/application/assistant/integrations/google.d.ts +117 -0
  31. package/dist/application/assistant/integrations/public-web.d.ts +16 -0
  32. package/dist/application/assistant/managed/secrets.d.ts +10 -0
  33. package/dist/application/assistant/managed/setup-state.d.ts +346 -0
  34. package/dist/application/assistant/managed/setup.d.ts +492 -0
  35. package/dist/application/assistant/microsoft/connection.d.ts +73 -0
  36. package/dist/application/assistant/microsoft/tools.d.ts +78 -0
  37. package/dist/application/assistant/modules/calendar.d.ts +3 -0
  38. package/dist/application/assistant/modules/catalog.d.ts +38 -0
  39. package/dist/application/assistant/modules/daily.d.ts +5 -0
  40. package/dist/application/assistant/modules/github.d.ts +5 -0
  41. package/dist/application/assistant/modules/google.d.ts +3 -0
  42. package/dist/application/assistant/modules/mcp.d.ts +11 -0
  43. package/dist/application/assistant/modules/microsoft.d.ts +3 -0
  44. package/dist/application/assistant/modules/module.d.ts +224 -0
  45. package/dist/application/assistant/modules/tools.d.ts +11 -0
  46. package/dist/application/assistant/modules/web.d.ts +7 -0
  47. package/dist/application/assistant/private-directory.d.ts +3 -0
  48. package/dist/application/assistant/proactive/service.d.ts +142 -0
  49. package/dist/application/assistant/providers/openai-compatible.d.ts +66 -0
  50. package/dist/application/assistant/providers/provider.d.ts +141 -0
  51. package/dist/application/assistant/providers/web-citations.d.ts +2 -0
  52. package/dist/application/assistant/runtime.d.ts +16 -0
  53. package/dist/application/assistant/task-metrics.d.ts +304 -0
  54. package/dist/application/assistant/telegram/api.d.ts +47 -0
  55. package/dist/application/assistant/telegram/bridge.d.ts +69 -0
  56. package/dist/application/assistant/telegram/store.d.ts +10 -0
  57. package/dist/application/automation.d.ts +5 -0
  58. package/dist/application/calendar-review.d.ts +5 -0
  59. package/dist/application/checkpoint-review.d.ts +30 -0
  60. package/dist/application/client.d.ts +18 -0
  61. package/dist/application/code/context.d.ts +5 -0
  62. package/dist/application/code/delivery.d.ts +6 -0
  63. package/dist/application/code/git-delivery.d.ts +54 -0
  64. package/dist/application/code/github-git-transport.d.ts +15 -0
  65. package/dist/application/code/github-pr-transport.d.ts +6 -0
  66. package/dist/application/code/host.d.ts +25 -0
  67. package/dist/application/code/pr-delivery.d.ts +79 -0
  68. package/dist/application/code/projects.d.ts +90 -0
  69. package/dist/application/code/remote-delivery.d.ts +80 -0
  70. package/dist/application/code/repository.d.ts +9 -0
  71. package/dist/application/code/worktrees.d.ts +123 -0
  72. package/dist/application/contracts.d.ts +288 -0
  73. package/dist/application/coordinator-client.d.ts +33 -0
  74. package/dist/application/coordinator-discovery.d.ts +17 -0
  75. package/dist/application/coordinator-launcher.d.ts +2 -0
  76. package/dist/application/coordinator.d.ts +27 -0
  77. package/dist/application/credential-process.d.ts +13 -0
  78. package/dist/application/host.d.ts +7 -0
  79. package/dist/application/management.d.ts +68 -0
  80. package/dist/application/notes.d.ts +5 -0
  81. package/dist/application/offline-migration.d.ts +16 -0
  82. package/dist/application/personal-state.d.ts +5 -0
  83. package/dist/application/review-channel.d.ts +23 -0
  84. package/dist/application/review-tickets.d.ts +29 -0
  85. package/dist/application/runtime-binding.d.ts +4 -0
  86. package/dist/application-cli-wfh08g41.js +184 -0
  87. package/dist/application-cli-z3f9pvcf.js +209 -0
  88. package/dist/arguments-75r85mvc.js +27 -0
  89. package/dist/arguments-x24bbqvd.js +22 -0
  90. package/dist/audit/index.js +16 -472
  91. package/dist/audit-pack-1gnych0m.js +93 -0
  92. package/dist/{audit-pack-s9n693by.js → audit-pack-h44kjkbj.js} +17 -11
  93. package/dist/calendar-2xw0rr7b.js +49 -0
  94. package/dist/cli/application-cli.d.ts +2 -0
  95. package/dist/cli/arguments.d.ts +14 -1
  96. package/dist/cli/auto-approve-setup.d.ts +13 -0
  97. package/dist/cli/configured-harness.d.ts +1 -2
  98. package/dist/cli/console/console-budget.d.ts +16 -2
  99. package/dist/cli/console/console-checkpoints.d.ts +12 -0
  100. package/dist/cli/console/console-commands.d.ts +3 -3
  101. package/dist/cli/console/console-compaction.d.ts +1 -1
  102. package/dist/cli/console/console-diff.d.ts +2 -0
  103. package/dist/cli/console/console-input.d.ts +29 -1
  104. package/dist/cli/console/console-navigation.d.ts +2 -2
  105. package/dist/cli/console/console-outcome.d.ts +10 -0
  106. package/dist/cli/console/console-presentation.d.ts +17 -2
  107. package/dist/cli/console/console-pricing.d.ts +14 -0
  108. package/dist/cli/console/console-reasoning.d.ts +1 -1
  109. package/dist/cli/console/console-recovery.d.ts +2 -0
  110. package/dist/cli/console/console-review.d.ts +34 -0
  111. package/dist/cli/console/console-run-policy.d.ts +5 -0
  112. package/dist/cli/console/console-run-view.d.ts +28 -0
  113. package/dist/cli/console/console-task.d.ts +30 -0
  114. package/dist/cli/console/console-welcome.d.ts +13 -3
  115. package/dist/cli/console/review-diff.d.ts +20 -0
  116. package/dist/cli/presentation.d.ts +8 -6
  117. package/dist/cli/service-checkpoints.d.ts +234 -0
  118. package/dist/cli/terminal/activity-history.d.ts +4 -2
  119. package/dist/cli/terminal/activity-stream.d.ts +33 -0
  120. package/dist/cli/terminal/file-diff.d.ts +11 -0
  121. package/dist/cli/terminal/terminal-theme.d.ts +9 -0
  122. package/dist/cli/terminal/terminal-ui.d.ts +44 -2
  123. package/dist/cli/terminal/tool-activity.d.ts +6 -2
  124. package/dist/{cli-entry-hdtfef27.js → cli-entry-68kqraj7.js} +95 -43
  125. package/dist/{cli-entry-1epvek01.js → cli-entry-86rcbmwh.js} +294 -14
  126. package/dist/cli-entry-btkpb4h1.js +3627 -0
  127. package/dist/cli-entry-bxjbs6qq.js +200 -0
  128. package/dist/cli-entry-cpm89r9q.js +624 -0
  129. package/dist/{cli-entry-mbcq96nx.js → cli-entry-dksm56sj.js} +39 -293
  130. package/dist/{cli-entry-rsx0wpvs.js → cli-entry-eka68ttb.js} +4087 -4625
  131. package/dist/cli-entry-h7dcah4p.js +137 -0
  132. package/dist/cli-entry-kwk23ktq.js +33 -0
  133. package/dist/{cli-entry-nyzyvf24.js → cli-entry-vmce694z.js} +1286 -3142
  134. package/dist/cli-entry-wanv05db.js +1113 -0
  135. package/dist/{cli-yxvq8qf1.js → cli-z7vhm1rk.js} +1767 -380
  136. package/dist/cli.js +8 -6
  137. package/dist/client/json-contracts.d.ts +153 -0
  138. package/dist/client/local-service.d.ts +7 -12
  139. package/dist/client/local-transport.d.ts +14 -0
  140. package/dist/client/protocol.d.ts +43 -1
  141. package/dist/compat/cli-options.d.ts +7 -1
  142. package/dist/compat/cli.d.ts +2 -0
  143. package/dist/compat/cli.js +4043 -0
  144. package/dist/compat/code-support.d.ts +4 -0
  145. package/dist/compat/code-support.js +50 -28
  146. package/dist/{config-r9fdhce6.js → config-hw78440t.js} +5 -5
  147. package/dist/{config-vyajmksy.js → config-v7s8hp37.js} +1 -1
  148. package/dist/context/adaptive-compaction.d.ts +1 -0
  149. package/dist/context/lossless-lines.d.ts +13 -0
  150. package/dist/context/numbered-read-lines.d.ts +15 -0
  151. package/dist/context/read-attempts.d.ts +21 -0
  152. package/dist/context/request-projection.d.ts +32 -4
  153. package/dist/context/scoped-context.d.ts +31 -5
  154. package/dist/context/working-read-replay.d.ts +12 -0
  155. package/dist/coordinator-client-nzysqxf0.js +10 -0
  156. package/dist/engine/acp.js +27 -21
  157. package/dist/engine/application-client.d.ts +11 -0
  158. package/dist/engine/application-client.js +18 -0
  159. package/dist/engine/application-protocol.d.ts +5 -0
  160. package/dist/engine/application-protocol.js +7 -0
  161. package/dist/engine/application.d.ts +43 -0
  162. package/dist/engine/application.js +206 -0
  163. package/dist/engine/assistant/automation/scheduler.d.ts +2 -0
  164. package/dist/engine/assistant/automation/scheduler.js +11 -0
  165. package/dist/engine/assistant/automation/summary.d.ts +3 -0
  166. package/dist/engine/assistant/automation/summary.js +8 -0
  167. package/dist/engine/assistant/automation/time.d.ts +5 -0
  168. package/dist/engine/assistant/automation/time.js +15 -0
  169. package/dist/engine/assistant/calendar/calendar.d.ts +5 -0
  170. package/dist/engine/assistant/calendar/calendar.js +12 -0
  171. package/dist/engine/assistant/calendar/connection.d.ts +2 -0
  172. package/dist/engine/assistant/calendar/connection.js +11 -0
  173. package/dist/engine/assistant/calendar/environment.d.ts +1 -0
  174. package/dist/engine/assistant/calendar/environment.js +7 -0
  175. package/dist/engine/assistant/calendar/http.d.ts +3 -0
  176. package/dist/engine/assistant/calendar/http.js +9 -0
  177. package/dist/engine/assistant/calendar/oauth.d.ts +5 -0
  178. package/dist/engine/assistant/calendar/oauth.js +12 -0
  179. package/dist/engine/assistant/calendar/store.d.ts +2 -0
  180. package/dist/engine/assistant/calendar/store.js +8 -0
  181. package/dist/engine/assistant/calendar/tools.d.ts +2 -0
  182. package/dist/engine/assistant/calendar/tools.js +46 -0
  183. package/dist/engine/assistant/client.d.ts +2 -0
  184. package/dist/engine/assistant/client.js +33 -0
  185. package/dist/engine/assistant/config.d.ts +1 -0
  186. package/dist/engine/assistant/config.js +102 -0
  187. package/dist/engine/assistant/contracts.d.ts +10 -0
  188. package/dist/engine/assistant/contracts.js +78 -0
  189. package/dist/engine/assistant/daily/service.d.ts +12 -0
  190. package/dist/engine/assistant/daily/service.js +27 -0
  191. package/dist/engine/assistant/doctor.d.ts +1 -0
  192. package/dist/engine/assistant/doctor.js +116 -0
  193. package/dist/engine/assistant/evaluation.d.ts +2 -0
  194. package/dist/engine/assistant/evaluation.js +76 -0
  195. package/dist/engine/assistant/host.d.ts +2 -0
  196. package/dist/engine/assistant/host.js +63 -0
  197. package/dist/engine/assistant/integrations/google.d.ts +9 -0
  198. package/dist/engine/assistant/integrations/google.js +30 -0
  199. package/dist/engine/assistant/integrations/public-web.d.ts +3 -0
  200. package/dist/engine/assistant/integrations/public-web.js +11 -0
  201. package/dist/engine/assistant/managed/secrets.d.ts +1 -0
  202. package/dist/engine/assistant/managed/secrets.js +0 -0
  203. package/dist/engine/assistant/managed/setup-state.d.ts +11 -0
  204. package/dist/engine/assistant/managed/setup-state.js +84 -0
  205. package/dist/engine/assistant/managed/setup.d.ts +3 -0
  206. package/dist/engine/assistant/managed/setup.js +85 -0
  207. package/dist/engine/assistant/microsoft/connection.d.ts +7 -0
  208. package/dist/engine/assistant/microsoft/connection.js +21 -0
  209. package/dist/engine/assistant/microsoft/tools.d.ts +8 -0
  210. package/dist/engine/assistant/microsoft/tools.js +30 -0
  211. package/dist/engine/assistant/modules/calendar.d.ts +1 -0
  212. package/dist/engine/assistant/modules/calendar.js +49 -0
  213. package/dist/engine/assistant/modules/catalog.d.ts +3 -0
  214. package/dist/engine/assistant/modules/catalog.js +67 -0
  215. package/dist/engine/assistant/modules/daily.d.ts +1 -0
  216. package/dist/engine/assistant/modules/daily.js +48 -0
  217. package/dist/engine/assistant/modules/github.d.ts +1 -0
  218. package/dist/engine/assistant/modules/github.js +43 -0
  219. package/dist/engine/assistant/modules/google.d.ts +1 -0
  220. package/dist/engine/assistant/modules/google.js +53 -0
  221. package/dist/engine/assistant/modules/mcp.d.ts +1 -0
  222. package/dist/engine/assistant/modules/mcp.js +42 -0
  223. package/dist/engine/assistant/modules/microsoft.d.ts +1 -0
  224. package/dist/engine/assistant/modules/microsoft.js +53 -0
  225. package/dist/engine/assistant/modules/module.d.ts +5 -0
  226. package/dist/engine/assistant/modules/module.js +42 -0
  227. package/dist/engine/assistant/modules/tools.d.ts +2 -0
  228. package/dist/engine/assistant/modules/tools.js +42 -0
  229. package/dist/engine/assistant/modules/web.d.ts +1 -0
  230. package/dist/engine/assistant/modules/web.js +45 -0
  231. package/dist/engine/assistant/private-directory.d.ts +1 -0
  232. package/dist/engine/assistant/private-directory.js +7 -0
  233. package/dist/engine/assistant/proactive/service.d.ts +6 -0
  234. package/dist/engine/assistant/proactive/service.js +16 -0
  235. package/dist/engine/assistant/providers/openai-compatible.d.ts +4 -0
  236. package/dist/engine/assistant/providers/openai-compatible.js +12 -0
  237. package/dist/engine/assistant/providers/provider.d.ts +7 -0
  238. package/dist/engine/assistant/providers/provider.js +54 -0
  239. package/dist/engine/assistant/providers/web-citations.d.ts +1 -0
  240. package/dist/engine/assistant/providers/web-citations.js +7 -0
  241. package/dist/engine/assistant/runtime.d.ts +2 -0
  242. package/dist/engine/assistant/runtime.js +73 -0
  243. package/dist/engine/assistant/task-metrics.d.ts +8 -0
  244. package/dist/engine/assistant/task-metrics.js +17 -0
  245. package/dist/engine/assistant/telegram/api.d.ts +5 -0
  246. package/dist/engine/assistant/telegram/api.js +11 -0
  247. package/dist/engine/assistant/telegram/bridge.d.ts +2 -0
  248. package/dist/engine/assistant/telegram/bridge.js +40 -0
  249. package/dist/engine/assistant/telegram/store.d.ts +2 -0
  250. package/dist/engine/assistant/telegram/store.js +8 -0
  251. package/dist/engine/client.js +26 -18
  252. package/dist/engine/desktop-providers-v1.js +4 -4
  253. package/dist/engine/desktop-state-v1.js +16 -13
  254. package/dist/engine/index.d.ts +4 -0
  255. package/dist/engine/index.js +117 -159
  256. package/dist/engine/mcp-stdio-v1.js +13 -12
  257. package/dist/engine/models.js +65 -23
  258. package/dist/engine/protocol.js +10 -6
  259. package/dist/engine/service.js +32 -21
  260. package/dist/hostile-repository-demo.js +2329 -1096
  261. package/dist/index-09rsdr2d.js +1744 -0
  262. package/dist/index-0csc5sc7.js +139 -0
  263. package/dist/{index-4mn6m3bq.js → index-0dkty795.js} +8 -6
  264. package/dist/index-0kkgqvg7.js +0 -0
  265. package/dist/index-0mzz9axm.js +58 -0
  266. package/dist/index-1e69ar8r.js +38 -0
  267. package/dist/index-1z0xhkh9.js +18 -0
  268. package/dist/index-2cef1k92.js +356 -0
  269. package/dist/{index-rgqzdgv6.js → index-2j0v1xwr.js} +17 -13
  270. package/dist/index-2jw9jd7h.js +116 -0
  271. package/dist/index-2n9qx4km.js +0 -0
  272. package/dist/index-3rvk23e8.js +877 -0
  273. package/dist/index-3wa4j0yk.js +71 -0
  274. package/dist/index-41q1k17x.js +210 -0
  275. package/dist/index-4vz4bqqw.js +33 -0
  276. package/dist/index-5jxm2wy5.js +123 -0
  277. package/dist/index-5rk6ss42.js +216 -0
  278. package/dist/index-5v1skxf7.js +1852 -0
  279. package/dist/{index-fqqz1yt8.js → index-6ehtssyz.js} +369 -335
  280. package/dist/index-76kpdbpw.js +80 -0
  281. package/dist/{index-5nmm0642.js → index-7nbmhmw5.js} +10 -10
  282. package/dist/index-8mx0yrkz.js +31 -0
  283. package/dist/index-8tjev5ds.js +11 -0
  284. package/dist/index-91n5wr6s.js +163 -0
  285. package/dist/index-91trs3ew.js +151 -0
  286. package/dist/index-9y8p5vy5.js +222 -0
  287. package/dist/index-abxahprd.js +55 -0
  288. package/dist/index-aptyr511.js +84 -0
  289. package/dist/{index-8sm2a1wa.js → index-ay26xfxt.js} +28 -20
  290. package/dist/index-b4yed1s3.js +657 -0
  291. package/dist/index-bb7phvtg.js +23 -0
  292. package/dist/index-bk5tn9b8.js +236 -0
  293. package/dist/index-bw34861c.js +292 -0
  294. package/dist/index-c6fnjhgv.js +55 -0
  295. package/dist/{index-qfsrrnz6.js → index-cjevq9s8.js} +2 -2
  296. package/dist/{index-c39197wq.js → index-ctcwrkrc.js} +4 -4
  297. package/dist/{index-yx52bt4a.js → index-cztmcesv.js} +2 -2
  298. package/dist/index-dpbmxnrf.js +564 -0
  299. package/dist/index-ekxdcy36.js +134 -0
  300. package/dist/index-f8zpcsx3.js +289 -0
  301. package/dist/{index-6dxrbnxm.js → index-f970qtb4.js} +7 -143
  302. package/dist/index-fatcn6fp.js +2791 -0
  303. package/dist/index-fbzykqxy.js +105 -0
  304. package/dist/{index-1265j7t2.js → index-fwf274vc.js} +24 -14
  305. package/dist/index-fy4w0a7v.js +0 -0
  306. package/dist/index-gvva3e5x.js +76 -0
  307. package/dist/index-h7dcah4p.js +137 -0
  308. package/dist/index-hm9r120s.js +42 -0
  309. package/dist/index-j3d2tw97.js +328 -0
  310. package/dist/index-jfqj20x8.js +41 -0
  311. package/dist/{index-hhrnrqfc.js → index-k529a278.js} +6 -6
  312. package/dist/{index-bt2p8x7r.js → index-kbrf5bx7.js} +110 -106
  313. package/dist/index-kwk23ktq.js +33 -0
  314. package/dist/index-kz857p1j.js +557 -0
  315. package/dist/{index-j466sekf.js → index-mkt5yrax.js} +31 -105
  316. package/dist/{index-nxmk6re7.js → index-ndgnvjez.js} +18 -18
  317. package/dist/index-nemn4epv.js +43 -0
  318. package/dist/index-nkwy5bjr.js +1225 -0
  319. package/dist/index-nvvzr4ny.js +136 -0
  320. package/dist/index-pkspzsfs.js +78 -0
  321. package/dist/{index-fm84men1.js → index-px1tnqgt.js} +2 -2
  322. package/dist/index-q7qdw883.js +79 -0
  323. package/dist/{index-mzydbzp8.js → index-qvbg6tx1.js} +65 -23
  324. package/dist/index-r3mwr5fb.js +0 -0
  325. package/dist/index-rdr78m0k.js +91 -0
  326. package/dist/index-rtamqsfs.js +59 -0
  327. package/dist/index-s125ss45.js +38 -0
  328. package/dist/{index-vn91b9z1.js → index-sx1t6dnd.js} +3721 -2382
  329. package/dist/index-tar0ngkm.js +359 -0
  330. package/dist/index-tn58cr6w.js +471 -0
  331. package/dist/{index-w0m1nckc.js → index-v79s9bf9.js} +118 -45
  332. package/dist/index-vk3rq21m.js +17 -0
  333. package/dist/index-vmvnr28y.js +72 -0
  334. package/dist/index-vz629cg8.js +49 -0
  335. package/dist/{index-eps3c3g6.js → index-w292hdpz.js} +197 -960
  336. package/dist/{index-amjttjaj.js → index-w9eqg6p9.js} +24 -302
  337. package/dist/index-wj96kdw2.js +57 -0
  338. package/dist/index-wyck5yhd.js +141 -0
  339. package/dist/index-xvtk8pxs.js +674 -0
  340. package/dist/{index-bpc596v3.js → index-xwb691v9.js} +2 -2
  341. package/dist/index-ym69x168.js +518 -0
  342. package/dist/index-yprdjk9v.js +65 -0
  343. package/dist/index-z2a81ccr.js +35 -0
  344. package/dist/{index-3ah1f369.js → index-z69cqk74.js} +3 -3
  345. package/dist/index-zaakvmzq.js +62 -0
  346. package/dist/index-zk3m4mzg.js +232 -0
  347. package/dist/index-zx3wgvx4.js +218 -0
  348. package/dist/index.js +102 -83
  349. package/dist/persistence/migration-guard.d.ts +3 -0
  350. package/dist/runtime/agent-profile.d.ts +12 -0
  351. package/dist/runtime/harness.d.ts +13 -0
  352. package/dist/runtime/known-file-preload.d.ts +35 -0
  353. package/dist/service-cli.js +130 -40
  354. package/dist/service-client-cli-2rzxy5mj.js +1166 -0
  355. package/dist/service-client-cli-5ne8q5ej.js +543 -0
  356. package/dist/tools/ooxml-zip.d.ts +21 -0
  357. package/dist/tools/presentations.d.ts +47 -0
  358. package/dist/tools/tabular-data.d.ts +114 -0
  359. package/dist/tools/workspace.d.ts +76 -0
  360. package/dist/verify-historical-migrations.js +2249 -1016
  361. package/dist/workspace/workspace.d.ts +13 -1
  362. package/dist/zhx.js +8 -6
  363. package/docs/APPLICATION_MIGRATION.md +32 -0
  364. package/docs/CLI.md +166 -2
  365. package/docs/CODE_RELEASE.md +11 -5
  366. package/docs/CODE_WEB_TASKS.md +3 -114
  367. package/docs/CONTEXT_ENGINEERING.md +93 -0
  368. package/docs/ENGINE_API.md +9 -2
  369. package/docs/EXTENSIBILITY.md +1 -1
  370. package/docs/FIRST_USE.md +6 -6
  371. package/docs/INTERNAL_ARCHIVE.md +43 -0
  372. package/docs/LOCAL_SERVICE.md +1 -1
  373. package/docs/MODEL_CATALOG.md +14 -0
  374. package/docs/PROJECT_MEMORY.md +1 -1
  375. package/docs/README.md +23 -4
  376. package/evaluations/representative-assembly-matrix.json +19 -1
  377. package/examples/README.md +4 -4
  378. package/examples/assistant/compatible-calendar.json +17 -0
  379. package/examples/assistant/composed-modules.json +23 -0
  380. package/examples/assistant/connected-tools.json +9 -0
  381. package/examples/assistant/daily-tools.json +6 -0
  382. package/examples/assistant/offline.mjs +24 -0
  383. package/fixtures/cli-compatibility/README.md +10 -0
  384. package/fixtures/cli-compatibility/inventory.json +7858 -0
  385. package/package.json +232 -26
  386. package/dist/cli/console/console-model-catalog.d.ts +0 -8
  387. package/dist/index-2yyfg69h.js +0 -619
  388. package/dist/index-3wwfn5n6.js +0 -270
  389. package/dist/index-4gt045j0.js +0 -288
  390. package/dist/index-4jw3tvy8.js +0 -301
  391. package/dist/service-client-cli-xbj7j5kj.js +0 -1251
@@ -1,619 +0,0 @@
1
- import {
2
- createHarnessClientAdapter
3
- } from "./index-j466sekf.js";
4
- import {
5
- harnessPolicyDecisionEventSchema
6
- } from "./index-bt2p8x7r.js";
7
- import {
8
- openCliSessionStore
9
- } from "./index-fqqz1yt8.js";
10
- import {
11
- SqliteDatabase
12
- } from "./index-6dxrbnxm.js";
13
- import {
14
- harnessClientRequestSchema,
15
- streamEventDocument
16
- } from "./index-4gt045j0.js";
17
- import {
18
- __require
19
- } from "./index-1bx83sw4.js";
20
-
21
- // src/client/service-events.ts
22
- import { createHash } from "node:crypto";
23
- import { createRedactionPolicy } from "@zhivex-ai/agents";
24
- var MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024;
25
- var TEXT_CHUNK_CHARACTERS = 8192;
26
- var serializeBoundedSnapshot = (snapshot, currentRun) => {
27
- let encoded = JSON.stringify(snapshot);
28
- if (Buffer.byteLength(encoded) <= MAX_SNAPSHOT_BYTES)
29
- return encoded;
30
- const historical = Object.keys(snapshot.runs).filter((id) => id !== currentRun);
31
- const compact = (ids) => {
32
- for (const field of ["text", "prompt", "tools"])
33
- for (const id of ids) {
34
- const run = snapshot.runs[id];
35
- if (field === "text") {
36
- if (!run.text)
37
- continue;
38
- run.text = "";
39
- } else {
40
- if (run[field] === undefined)
41
- continue;
42
- delete run[field];
43
- }
44
- run.truncated = true;
45
- encoded = JSON.stringify(snapshot);
46
- if (Buffer.byteLength(encoded) <= MAX_SNAPSHOT_BYTES)
47
- return true;
48
- }
49
- return false;
50
- };
51
- if (compact(historical) || compact([currentRun]))
52
- return encoded;
53
- throw new Error("ACTIVITY_SNAPSHOT_LIMIT");
54
- };
55
- var openHarnessActivityStore = async (config, options = {}) => {
56
- const index = await openCliSessionStore({ workspace: config.workspace, stateDirectory: config.stateDirectory, scope: config.scope });
57
- const scope = `${index.workspaceKey}:${index.scopeKey}`;
58
- const db = new SqliteDatabase(index.databasePath);
59
- index.close();
60
- const maxEvents = options.maxEvents ?? 1e4, retentionMs = options.retentionMs ?? 7 * 24 * 3600 * 1000, now = options.now ?? Date.now;
61
- if (!Number.isSafeInteger(maxEvents) || maxEvents < 1 || maxEvents > 1e5 || !Number.isSafeInteger(retentionMs) || retentionMs < 1) {
62
- db.close();
63
- throw new Error("ACTIVITY_LIMIT_INVALID");
64
- }
65
- db.exec(`CREATE TABLE IF NOT EXISTS client_activity_events(sequence INTEGER PRIMARY KEY AUTOINCREMENT, scope TEXT NOT NULL, session TEXT NOT NULL, run TEXT NOT NULL, at INTEGER NOT NULL, activity TEXT NOT NULL);
66
- CREATE INDEX IF NOT EXISTS client_activity_scope ON client_activity_events(scope, session, sequence);
67
- CREATE TABLE IF NOT EXISTS client_activity_snapshots(scope TEXT NOT NULL, session TEXT NOT NULL, sequence INTEGER NOT NULL, expired_through INTEGER NOT NULL DEFAULT 0, snapshot TEXT NOT NULL, PRIMARY KEY(scope,session));`);
68
- const readSnapshot = db.query("SELECT snapshot,expired_through FROM client_activity_snapshots WHERE scope=? AND session=?");
69
- const expiredEvents = db.query(`SELECT session,MAX(sequence) AS seq FROM client_activity_events WHERE scope=? AND (at < ? OR sequence NOT IN (SELECT sequence FROM client_activity_events WHERE scope=? ORDER BY sequence DESC LIMIT ?)) GROUP BY session`);
70
- const markExpired = db.query("UPDATE client_activity_snapshots SET expired_through=MAX(expired_through,?) WHERE scope=? AND session=?");
71
- const deleteExpired = db.query("DELETE FROM client_activity_events WHERE scope=? AND session=? AND sequence<=?");
72
- const insertEvent = db.query("INSERT INTO client_activity_events(scope,session,run,at,activity) VALUES(?,?,?,?,?)");
73
- const lastSequence = db.query("SELECT last_insert_rowid() AS seq");
74
- const saveSnapshot = db.query("INSERT INTO client_activity_snapshots(scope,session,sequence,snapshot) VALUES(?,?,?,?) ON CONFLICT(scope,session) DO UPDATE SET sequence=excluded.sequence,snapshot=excluded.snapshot");
75
- const readEvents = db.query("SELECT sequence,session,run,at,activity FROM client_activity_events WHERE scope=? AND session=? AND sequence>? ORDER BY sequence LIMIT 201");
76
- const redaction = createRedactionPolicy({ includeEmails: true });
77
- const redact = (text) => {
78
- let result = text;
79
- for (const secret of options.sensitiveValues ?? [])
80
- if (secret)
81
- result = result.split(secret).join("[REDACTED]");
82
- return redaction.redactText(result).replace(/\b(?:sk|ghp|github_pat|xox[baprs])[-_][A-Za-z0-9_-]+/gi, "[REDACTED]");
83
- };
84
- const redactValue = (value) => typeof value === "string" ? redact(value) : Array.isArray(value) ? value.map(redactValue) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactValue(v)])) : value;
85
- const tails = new Map;
86
- const discard = new Set;
87
- const flush = (key, chunk, final = false) => {
88
- let text = (tails.get(key) ?? "") + chunk;
89
- for (const secret of options.sensitiveValues ?? [])
90
- if (secret)
91
- text = text.split(secret).join("[REDACTED]");
92
- if (discard.has(key)) {
93
- const end = text.search(/\s/);
94
- if (end < 0 && !final)
95
- return "";
96
- text = end < 0 ? "" : text.slice(end);
97
- discard.delete(key);
98
- }
99
- let boundary = final ? text.length : text.match(/^[\s\S]*\s/)?.[0].length ?? 0;
100
- if (!final)
101
- for (const secret of options.sensitiveValues ?? []) {
102
- if (!secret)
103
- continue;
104
- let start = text.indexOf(secret[0], Math.max(0, text.length - secret.length + 1));
105
- while (start >= 0 && start < boundary) {
106
- if (secret.startsWith(text.slice(start))) {
107
- boundary = start;
108
- break;
109
- }
110
- start = text.indexOf(secret[0], start + 1);
111
- }
112
- }
113
- let result = redact(text.slice(0, boundary));
114
- text = text.slice(boundary);
115
- if (text.length > 16384) {
116
- result += "[TRUNCATED]";
117
- text = "";
118
- discard.add(key);
119
- }
120
- tails.set(key, text);
121
- return result;
122
- };
123
- const snapshot = (sessionId) => {
124
- const row = readSnapshot.get(scope, sessionId);
125
- return { state: row ? JSON.parse(row.snapshot) : { schemaVersion: 1, sessionId, sequence: 0, runs: {} }, expiredThrough: row?.expired_through ?? 0 };
126
- };
127
- const prune = () => {
128
- const expired = expiredEvents.all(scope, now() - retentionMs, scope, maxEvents);
129
- for (const row of expired) {
130
- markExpired.run(row.seq, scope, row.session);
131
- deleteExpired.run(scope, row.session, row.seq);
132
- }
133
- };
134
- const write = (sessionId, runId, activity) => {
135
- if (!/^[A-Za-z0-9._:-]{1,128}$/.test(sessionId) || !/^[A-Za-z0-9._:-]{1,128}$/.test(runId))
136
- throw new Error("ACTIVITY_ID_INVALID");
137
- const at = now();
138
- const encoded = JSON.stringify(activity);
139
- if (Buffer.byteLength(encoded) > 64 * 1024)
140
- throw new Error("ACTIVITY_TOO_LARGE");
141
- db.exec("BEGIN IMMEDIATE");
142
- try {
143
- const current = snapshot(sessionId).state;
144
- const runs = Object.keys(current.runs);
145
- if (!current.runs[runId] && runs.length >= 1000)
146
- throw new Error("ACTIVITY_RUN_LIMIT");
147
- const state = current.runs[runId] ?? { text: "", status: "running", truncated: false };
148
- if (typeof activity.textDelta === "string") {
149
- state.text += activity.textDelta;
150
- if (state.text.length > 256 * 1024) {
151
- state.text = state.text.slice(-256 * 1024);
152
- state.truncated = true;
153
- }
154
- }
155
- if (activity.type === "user-message" && typeof activity.prompt === "string")
156
- state.prompt = activity.prompt;
157
- if (typeof activity.toolCallId === "string" && typeof activity.toolName === "string") {
158
- state.tools ??= {};
159
- const key = `tool:${activity.toolCallId}`;
160
- if (state.tools[key] || Object.keys(state.tools).length < 256) {
161
- const status = activity.type === "tool-result" ? activity.isError === true || activity.timedOut === true || typeof activity.exitCode === "number" && activity.exitCode !== 0 ? "failed" : "completed" : "running";
162
- state.tools[key] = { name: activity.toolName, status, ...typeof activity.exitCode === "number" ? { exitCode: activity.exitCode } : {}, ...typeof activity.timedOut === "boolean" ? { timedOut: activity.timedOut } : {} };
163
- } else
164
- state.truncated = true;
165
- }
166
- if (typeof activity.status === "string" && (activity.type === "checkpoint" || activity.type === "agent-run-finish"))
167
- state.status = activity.status;
168
- if (activity.type === "agent-run-start")
169
- state.status = "running";
170
- if (activity.type === "tool-approval-request" || activity.type === "agent-approval-request")
171
- state.status = "waiting_approval";
172
- current.runs[runId] = state;
173
- insertEvent.run(scope, sessionId, runId, at, encoded);
174
- current.sequence = lastSequence.get().seq;
175
- const bounded = serializeBoundedSnapshot(current, runId);
176
- saveSnapshot.run(scope, sessionId, current.sequence, bounded);
177
- prune();
178
- db.exec("COMMIT");
179
- } catch (e) {
180
- db.exec("ROLLBACK");
181
- throw e;
182
- }
183
- };
184
- const writeText = (sessionId, runId, text) => {
185
- for (let start = 0;start < text.length; ) {
186
- let end = Math.min(text.length, start + TEXT_CHUNK_CHARACTERS);
187
- if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) && /[\uDC00-\uDFFF]/.test(text[end]))
188
- end--;
189
- write(sessionId, runId, { type: "text-delta", textDelta: text.slice(start, end) });
190
- start = end;
191
- }
192
- };
193
- return {
194
- policyDecision(sessionId, runId, event) {
195
- write(sessionId, runId, redactValue(harnessPolicyDecisionEventSchema.parse(event)));
196
- },
197
- prompt(sessionId, runId, prompt) {
198
- const safe = redact(prompt);
199
- const activity = (value) => ({ type: "user-message", prompt: value });
200
- let bounded = safe;
201
- if (Buffer.byteLength(JSON.stringify(activity(safe))) > 60 * 1024) {
202
- const characters = Array.from(safe);
203
- let lower = 0, upper = characters.length;
204
- while (lower < upper) {
205
- const middle = Math.ceil((lower + upper) / 2);
206
- const candidate = characters.slice(0, middle).join("") + "[TRUNCATED]";
207
- if (Buffer.byteLength(JSON.stringify(activity(candidate))) <= 60 * 1024)
208
- lower = middle;
209
- else
210
- upper = middle - 1;
211
- }
212
- bounded = characters.slice(0, lower).join("") + "[TRUNCATED]";
213
- }
214
- write(sessionId, runId, activity(bounded));
215
- },
216
- append(sessionId, runId, event) {
217
- const key = `${sessionId}:${runId}`;
218
- if (event.type === "text-delta") {
219
- const textDelta = flush(key, event.textDelta);
220
- writeText(sessionId, runId, textDelta);
221
- return;
222
- }
223
- if (event.type === "agent-run-finish" || event.type === "error") {
224
- const textDelta = flush(key, "", true);
225
- writeText(sessionId, runId, textDelta);
226
- tails.delete(key);
227
- }
228
- const projected = streamEventDocument(event);
229
- if (projected) {
230
- let receipt = {};
231
- if (event.type === "tool-result" && event.toolResult.toolName === "run_check") {
232
- const output = event.toolResult.output;
233
- if (output && typeof output === "object" && !Array.isArray(output) && "exitCode" in output && Number.isSafeInteger(output.exitCode))
234
- receipt = { exitCode: output.exitCode, timedOut: "timedOut" in output && output.timedOut === true };
235
- }
236
- write(sessionId, runId, redactValue({ ...projected, ...receipt }));
237
- }
238
- },
239
- checkpoint(sessionId, runId, status) {
240
- const key = `${sessionId}:${runId}`;
241
- const textDelta = flush(key, "", true);
242
- writeText(sessionId, runId, textDelta);
243
- tails.delete(key);
244
- write(sessionId, runId, { type: "checkpoint", status });
245
- },
246
- replay(sessionId, after = 0) {
247
- if (!Number.isSafeInteger(after) || after < 0)
248
- throw new Error("ACTIVITY_CURSOR_INVALID");
249
- db.exec("BEGIN IMMEDIATE");
250
- try {
251
- prune();
252
- db.exec("COMMIT");
253
- } catch (e) {
254
- db.exec("ROLLBACK");
255
- throw e;
256
- }
257
- const current = snapshot(sessionId);
258
- const expired = after < current.expiredThrough;
259
- if (after > current.state.sequence)
260
- throw new Error("ACTIVITY_CURSOR_AHEAD");
261
- if (expired)
262
- return { schemaVersion: 1, cursorExpired: true, hasMore: false, policyEvidenceIncomplete: true, nextCursor: current.state.sequence, events: [], snapshot: current.state };
263
- const rows = readEvents.all(scope, sessionId, after);
264
- const events = rows.slice(0, 200).map((row) => ({ schemaVersion: 1, eventId: createHash("sha256").update(`${scope}:${row.sequence}`).digest("hex"), sequence: row.sequence, sessionId: row.session, runId: row.run, at: row.at, activity: JSON.parse(row.activity) }));
265
- return { schemaVersion: 1, cursorExpired: false, hasMore: rows.length > 200, policyEvidenceIncomplete: current.expiredThrough > 0, nextCursor: events.at(-1)?.sequence ?? after, events };
266
- },
267
- close() {
268
- db.close();
269
- tails.clear();
270
- discard.clear();
271
- }
272
- };
273
- };
274
-
275
- // src/client/local-service.ts
276
- import { createServer, request as httpRequest } from "node:http";
277
- import { randomBytes, timingSafeEqual, createHash as createHash2 } from "node:crypto";
278
- import { mkdir, lstat, realpath, open, unlink, chmod } from "node:fs/promises";
279
- import path from "node:path";
280
- import { z } from "zod";
281
- var harnessLocalCredentialsSchema = z.object({ schemaVersion: z.literal(1), socketPath: z.string().min(1), token: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
282
- var send = (response, status, document) => {
283
- response.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", connection: "close" });
284
- response.end(JSON.stringify(document));
285
- };
286
- var fault = (code) => ({ ok: false, error: { code } });
287
- var body = async (request) => {
288
- const chunks = [];
289
- let size = 0;
290
- for await (const chunk of request) {
291
- const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
292
- size += bytes.length;
293
- if (size > 128 * 1024)
294
- throw new Error("REQUEST_TOO_LARGE");
295
- chunks.push(bytes);
296
- }
297
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
298
- };
299
- var privateFile = async (filename, data) => {
300
- const file = await open(filename, "wx", 384);
301
- try {
302
- await file.writeFile(data);
303
- await file.sync();
304
- } finally {
305
- await file.close();
306
- }
307
- };
308
- var exists = async (filename) => {
309
- try {
310
- return await lstat(filename);
311
- } catch (e) {
312
- if (e.code === "ENOENT")
313
- return;
314
- throw e;
315
- }
316
- };
317
- var startHarnessLocalService = async (harness, options) => {
318
- if (process.platform === "win32")
319
- throw new Error("LOCAL_SERVICE_PLATFORM_UNSUPPORTED");
320
- const directory = path.resolve(options.directory);
321
- await mkdir(directory, { recursive: true, mode: 448 });
322
- const info = await lstat(directory);
323
- if (!info.isDirectory() || info.isSymbolicLink() || (info.mode & 63) !== 0 || info.uid !== process.getuid?.())
324
- throw new Error("LOCAL_SERVICE_DIRECTORY_UNSAFE");
325
- const canonicalDirectory = await realpath(directory);
326
- const workspaceIdentity = createHash2("sha256").update(JSON.stringify([harness.config.workspace, harness.config.scope])).digest("hex").slice(0, 20);
327
- const socketPath = path.join(canonicalDirectory, `${workspaceIdentity}.sock`);
328
- if (Buffer.byteLength(socketPath) > 100)
329
- throw new Error("LOCAL_SERVICE_SOCKET_PATH_TOO_LONG");
330
- const credentialsPath = path.join(canonicalDirectory, `${workspaceIdentity}.json`);
331
- const lockPath = path.join(canonicalDirectory, `${workspaceIdentity}.lock`);
332
- const token = randomBytes(32).toString("hex");
333
- await privateFile(lockPath, JSON.stringify({ schemaVersion: 1, pid: process.pid }));
334
- let adapter;
335
- let activity;
336
- const pending = new Set;
337
- let closing = false, paused = false, activeMutations = 0, closePromise;
338
- const server = createServer((req, res) => {
339
- const operation = (async () => {
340
- const actual = Buffer.from(req.headers.authorization ?? "");
341
- const expected = Buffer.from(`Bearer ${token}`);
342
- if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
343
- return send(res, 401, fault("UNAUTHORIZED"));
344
- if (req.headers.origin !== undefined || req.headers["sec-fetch-site"] !== undefined)
345
- return send(res, 403, fault("ORIGIN_REJECTED"));
346
- if (closing)
347
- return send(res, 503, fault("SERVICE_CLOSING"));
348
- if (req.method === "GET" && req.url === "/health")
349
- return send(res, 200, { ok: true, schemaVersion: 1, status: "ready" });
350
- if (req.method !== "POST" || !["/hello", "/command", "/events"].includes(req.url ?? ""))
351
- return send(res, 404, fault("NOT_FOUND"));
352
- if (req.headers["content-type"] !== "application/json")
353
- return send(res, 415, fault("CONTENT_TYPE_REQUIRED"));
354
- let value;
355
- try {
356
- value = await body(req);
357
- } catch {
358
- return send(res, 400, fault("INVALID_REQUEST"));
359
- }
360
- if (closing)
361
- return send(res, 503, fault("SERVICE_CLOSING"));
362
- if (req.url === "/hello") {
363
- const parsed2 = z.object({ versions: z.array(z.number().int()).min(1).max(16) }).strict().safeParse(value);
364
- return send(res, 200, parsed2.success ? adapter.negotiate(parsed2.data.versions) : fault("INVALID_REQUEST"));
365
- }
366
- if (req.url === "/events") {
367
- const parsed2 = z.object({ projectId: z.string(), sessionId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/), after: z.number().int().nonnegative().safe().optional() }).strict().safeParse(value);
368
- const hello = adapter.negotiate([1]);
369
- if (!parsed2.success)
370
- return send(res, 400, fault("INVALID_REQUEST"));
371
- if (!hello.ok || parsed2.data.projectId !== hello.projectId)
372
- return send(res, 404, fault("NOT_FOUND"));
373
- try {
374
- return send(res, 200, activity.replay(parsed2.data.sessionId, parsed2.data.after));
375
- } catch {
376
- return send(res, 400, fault("INVALID_CURSOR"));
377
- }
378
- }
379
- const parsed = harnessClientRequestSchema.safeParse(value);
380
- const method = parsed.success ? parsed.data.command.method : undefined;
381
- const mutation = method !== undefined && !["task.get", "task.review", "project.get", "policy.get", "session.list", "session.get", "run.get", "checkpoint.list", "checkpoint.inspect", "restore.get"].includes(method);
382
- if (paused && mutation && method !== "run.cancel")
383
- return send(res, 503, fault("SERVICE_PAUSED"));
384
- if (mutation)
385
- activeMutations++;
386
- try {
387
- return send(res, 200, await adapter.dispatch(value));
388
- } finally {
389
- if (mutation)
390
- activeMutations--;
391
- }
392
- })().catch(() => {
393
- if (!res.headersSent)
394
- send(res, 500, fault("EXECUTION_FAILED"));
395
- else
396
- res.destroy();
397
- });
398
- pending.add(operation);
399
- operation.finally(() => pending.delete(operation));
400
- });
401
- server.requestTimeout = Math.max(30000, harness.config.timeoutMs + 1e4);
402
- server.headersTimeout = 1e4;
403
- server.keepAliveTimeout = 1000;
404
- let ownsSocket = false, ownsCredentials = false;
405
- const cleanup = async () => {
406
- if (ownsSocket)
407
- await unlink(socketPath).catch((e) => {
408
- if (e.code !== "ENOENT")
409
- throw e;
410
- });
411
- if (ownsCredentials)
412
- await unlink(credentialsPath).catch((e) => {
413
- if (e.code !== "ENOENT")
414
- throw e;
415
- });
416
- await unlink(lockPath);
417
- };
418
- try {
419
- if (await exists(socketPath) || await exists(credentialsPath))
420
- throw new Error("LOCAL_SERVICE_STALE_STATE");
421
- activity = await openHarnessActivityStore(harness.config, {
422
- sensitiveValues: [token, ...options.sensitiveValues ?? [], ...Object.entries(process.env).filter(([k, v]) => /(?:API_KEY|TOKEN|SECRET|PASSWORD)$/.test(k) && v && v.length >= 8).map(([, v]) => v)],
423
- ...options.maxEvents === undefined ? {} : { maxEvents: options.maxEvents },
424
- ...options.retentionMs === undefined ? {} : { retentionMs: options.retentionMs }
425
- });
426
- adapter = await createHarnessClientAdapter(harness, {
427
- taskProjectionSensitiveValues: [token, ...options.sensitiveValues ?? [], ...Object.entries(process.env).filter(([k, v]) => /(?:API_KEY|TOKEN|SECRET|PASSWORD)$/.test(k) && v && v.length >= 8).map(([, v]) => v)],
428
- ...options.approvalNow ? { now: options.approvalNow } : {},
429
- onPolicyDecision: (sessionId, runId, event) => activity.policyDecision(sessionId, runId, event),
430
- onPrompt: async (sessionId, runId, prompt) => {
431
- await activity.prompt(sessionId, runId, prompt);
432
- await options.onPrompt?.(sessionId, runId, prompt);
433
- },
434
- onEvent: async (sessionId, runId, event) => {
435
- await activity.append(sessionId, runId, event);
436
- await options.onEvent?.(sessionId, runId, event);
437
- },
438
- onCheckpoint: async (sessionId, runId, status) => {
439
- await activity.checkpoint(sessionId, runId, status);
440
- await options.onCheckpoint?.(sessionId, runId, status);
441
- }
442
- });
443
- await new Promise((resolve, reject) => {
444
- server.once("error", reject);
445
- server.listen(socketPath, () => {
446
- server.off("error", reject);
447
- resolve();
448
- });
449
- });
450
- ownsSocket = true;
451
- await chmod(socketPath, 384);
452
- await privateFile(credentialsPath, JSON.stringify({ schemaVersion: 1, socketPath, token }));
453
- ownsCredentials = true;
454
- return {
455
- socketPath,
456
- credentialsPath,
457
- async dispatchReviewed(request) {
458
- if (closing || paused)
459
- throw new Error("SERVICE_ADMISSION_PAUSED");
460
- if (!adapter?.dispatchReviewed)
461
- throw new Error("EXPLICIT_REVIEW_UNAVAILABLE");
462
- activeMutations++;
463
- const operation = adapter.dispatchReviewed(request);
464
- const tracked = operation.then(() => {}, () => {});
465
- pending.add(tracked);
466
- try {
467
- return await operation;
468
- } finally {
469
- pending.delete(tracked);
470
- activeMutations--;
471
- }
472
- },
473
- pauseAdmission() {
474
- if (closing)
475
- throw new Error("SERVICE_CLOSING");
476
- paused = true;
477
- return activeMutations > 0;
478
- },
479
- resumeAdmission() {
480
- if (closing)
481
- throw new Error("SERVICE_CLOSING");
482
- paused = false;
483
- },
484
- cancelActive() {
485
- return adapter.cancelActive();
486
- },
487
- close() {
488
- closePromise ??= (async () => {
489
- closing = true;
490
- const stopped = new Promise((resolve, reject) => server.close((e) => e ? reject(e) : resolve()));
491
- await Promise.allSettled([...pending]);
492
- await stopped;
493
- adapter.close();
494
- activity.close();
495
- await harness.close();
496
- await cleanup();
497
- })();
498
- return closePromise;
499
- }
500
- };
501
- } catch (e) {
502
- if (server.listening)
503
- await new Promise((resolve) => server.close(() => resolve()));
504
- adapter?.close();
505
- activity?.close();
506
- await cleanup();
507
- throw e;
508
- }
509
- };
510
- var readHarnessLocalCredentials = async (filename) => {
511
- const { constants } = await import("node:fs");
512
- const file = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW);
513
- try {
514
- const info = await file.stat();
515
- if (!info.isFile() || (info.mode & 63) !== 0 || info.uid !== process.getuid?.() || info.size > 4096)
516
- throw new Error("LOCAL_SERVICE_CREDENTIALS_UNSAFE");
517
- return harnessLocalCredentialsSchema.parse(JSON.parse(await file.readFile("utf8")));
518
- } finally {
519
- await file.close();
520
- }
521
- };
522
- var requestHarnessLocalService = async (credentials, endpoint, payload) => {
523
- const parsed = harnessLocalCredentialsSchema.parse(credentials);
524
- if (!path.isAbsolute(parsed.socketPath) || process.platform === "win32")
525
- throw new Error("LOCAL_SERVICE_SOCKET_INVALID");
526
- const encoded = JSON.stringify(payload);
527
- if (Buffer.byteLength(encoded) > 131072)
528
- throw new Error("REQUEST_TOO_LARGE");
529
- return new Promise((resolve, reject) => {
530
- const req = httpRequest({ socketPath: parsed.socketPath, path: `/${endpoint}`, method: "POST", headers: {
531
- authorization: `Bearer ${parsed.token}`,
532
- "content-type": "application/json",
533
- "content-length": Buffer.byteLength(encoded)
534
- } }, (res) => {
535
- const chunks = [];
536
- let size = 0;
537
- res.on("data", (chunk) => {
538
- size += chunk.length;
539
- if (size > 4194304)
540
- res.destroy(new Error("RESPONSE_TOO_LARGE"));
541
- else
542
- chunks.push(chunk);
543
- });
544
- res.on("error", reject);
545
- res.on("end", () => {
546
- try {
547
- if (res.statusCode !== 200)
548
- return reject(new Error(`LOCAL_SERVICE_HTTP_${res.statusCode}`));
549
- resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
550
- } catch {
551
- reject(new Error("LOCAL_SERVICE_RESPONSE_INVALID"));
552
- }
553
- });
554
- });
555
- req.on("error", () => reject(new Error("LOCAL_SERVICE_UNAVAILABLE")));
556
- req.end(encoded);
557
- });
558
- };
559
- var recoverHarnessLocalService = async (harness, directory) => {
560
- const info = await lstat(directory);
561
- if (!info.isDirectory() || info.isSymbolicLink() || (info.mode & 63) !== 0 || info.uid !== process.getuid?.())
562
- throw new Error("LOCAL_SERVICE_DIRECTORY_UNSAFE");
563
- const root = await realpath(directory);
564
- const identity = createHash2("sha256").update(JSON.stringify([harness.config.workspace, harness.config.scope])).digest("hex").slice(0, 20);
565
- const lockPath = path.join(root, `${identity}.lock`);
566
- const index = await openCliSessionStore({ workspace: harness.config.workspace, stateDirectory: harness.config.stateDirectory, scope: harness.config.scope, busyTimeoutMs: 0 });
567
- const databasePath = index.databasePath;
568
- index.close();
569
- const db = new SqliteDatabase(databasePath);
570
- let locked = false;
571
- try {
572
- db.exec("PRAGMA busy_timeout = 0");
573
- db.exec("BEGIN IMMEDIATE");
574
- locked = true;
575
- const { constants } = await import("node:fs");
576
- const handle = await open(lockPath, constants.O_RDONLY | constants.O_NOFOLLOW);
577
- let owner;
578
- try {
579
- const stat = await handle.stat();
580
- if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 63) !== 0 || stat.size > 4096)
581
- throw new Error("LOCAL_SERVICE_LOCK_UNSAFE");
582
- owner = z.object({ schemaVersion: z.literal(1), pid: z.number().int().positive().max(2147483647) }).strict().parse(JSON.parse(await handle.readFile("utf8")));
583
- } finally {
584
- await handle.close();
585
- }
586
- try {
587
- process.kill(owner.pid, 0);
588
- throw new Error("LOCAL_SERVICE_OWNER_ALIVE");
589
- } catch (e) {
590
- if (e.code !== "ESRCH")
591
- throw e;
592
- }
593
- for (const extension of ["sock", "json"]) {
594
- const filename = path.join(root, `${identity}.${extension}`);
595
- const entry = await exists(filename);
596
- if (!entry)
597
- continue;
598
- if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0 || (extension === "sock" ? !entry.isSocket() : !entry.isFile()))
599
- throw new Error("LOCAL_SERVICE_RECOVERY_UNSAFE");
600
- }
601
- for (const extension of ["sock", "json"])
602
- await unlink(path.join(root, `${identity}.${extension}`)).catch((e) => {
603
- if (e.code !== "ENOENT")
604
- throw e;
605
- });
606
- await unlink(lockPath);
607
- db.exec("COMMIT");
608
- locked = false;
609
- } finally {
610
- try {
611
- if (locked)
612
- db.exec("ROLLBACK");
613
- } finally {
614
- db.close();
615
- }
616
- }
617
- };
618
-
619
- export { openHarnessActivityStore, harnessLocalCredentialsSchema, startHarnessLocalService, readHarnessLocalCredentials, requestHarnessLocalService, recoverHarnessLocalService };