@geminixiang/mikan 1.0.0-beta.39 → 1.0.0-beta.40

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 (397) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +50 -23
  3. package/dist/adapter.d.ts +1 -1
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/adapter.js.map +1 -1
  6. package/dist/adapters/discord/bot.d.ts +2 -1
  7. package/dist/adapters/discord/bot.d.ts.map +1 -1
  8. package/dist/adapters/discord/bot.js +3 -3
  9. package/dist/adapters/discord/bot.js.map +1 -1
  10. package/dist/adapters/discord/context.d.ts +2 -1
  11. package/dist/adapters/discord/context.d.ts.map +1 -1
  12. package/dist/adapters/discord/context.js +1 -1
  13. package/dist/adapters/discord/context.js.map +1 -1
  14. package/dist/adapters/github/bot.d.ts +2 -1
  15. package/dist/adapters/github/bot.d.ts.map +1 -1
  16. package/dist/adapters/github/bot.js +11 -7
  17. package/dist/adapters/github/bot.js.map +1 -1
  18. package/dist/adapters/github/client.js +2 -2
  19. package/dist/adapters/github/client.js.map +1 -1
  20. package/dist/adapters/github/context.d.ts +4 -2
  21. package/dist/adapters/github/context.d.ts.map +1 -1
  22. package/dist/adapters/github/context.js +2 -2
  23. package/dist/adapters/github/context.js.map +1 -1
  24. package/dist/adapters/github/gcp-auth.js +2 -2
  25. package/dist/adapters/github/gcp-auth.js.map +1 -1
  26. package/dist/adapters/github/github-ops.d.ts +3 -2
  27. package/dist/adapters/github/github-ops.d.ts.map +1 -1
  28. package/dist/adapters/github/github-ops.js +1 -1
  29. package/dist/adapters/github/github-ops.js.map +1 -1
  30. package/dist/adapters/github/ids.d.ts.map +1 -1
  31. package/dist/adapters/github/ids.js +7 -3
  32. package/dist/adapters/github/ids.js.map +1 -1
  33. package/dist/adapters/github/repo.js +3 -3
  34. package/dist/adapters/github/repo.js.map +1 -1
  35. package/dist/adapters/github/types.d.ts +2 -1
  36. package/dist/adapters/github/types.d.ts.map +1 -1
  37. package/dist/adapters/github/types.js.map +1 -1
  38. package/dist/adapters/progressive-renderer.js +1 -1
  39. package/dist/adapters/progressive-renderer.js.map +1 -1
  40. package/dist/adapters/shared.js +4 -4
  41. package/dist/adapters/shared.js.map +1 -1
  42. package/dist/adapters/slack/blocks.d.ts.map +1 -1
  43. package/dist/adapters/slack/blocks.js +3 -1
  44. package/dist/adapters/slack/blocks.js.map +1 -1
  45. package/dist/adapters/slack/bot.d.ts +12 -2
  46. package/dist/adapters/slack/bot.d.ts.map +1 -1
  47. package/dist/adapters/slack/bot.js +70 -9
  48. package/dist/adapters/slack/bot.js.map +1 -1
  49. package/dist/adapters/slack/context.d.ts +2 -1
  50. package/dist/adapters/slack/context.d.ts.map +1 -1
  51. package/dist/adapters/slack/context.js +1 -0
  52. package/dist/adapters/slack/context.js.map +1 -1
  53. package/dist/adapters/slack/response-lifecycle.d.ts.map +1 -1
  54. package/dist/adapters/slack/response-lifecycle.js +4 -4
  55. package/dist/adapters/slack/response-lifecycle.js.map +1 -1
  56. package/dist/adapters/slack/session.d.ts.map +1 -1
  57. package/dist/adapters/slack/session.js +2 -3
  58. package/dist/adapters/slack/session.js.map +1 -1
  59. package/dist/adapters/slack/tools/attach.js +1 -1
  60. package/dist/adapters/slack/tools/attach.js.map +1 -1
  61. package/dist/adapters/telegram/bot.d.ts +2 -1
  62. package/dist/adapters/telegram/bot.d.ts.map +1 -1
  63. package/dist/adapters/telegram/bot.js +6 -6
  64. package/dist/adapters/telegram/bot.js.map +1 -1
  65. package/dist/adapters/telegram/context.d.ts +2 -1
  66. package/dist/adapters/telegram/context.d.ts.map +1 -1
  67. package/dist/adapters/telegram/context.js.map +1 -1
  68. package/dist/adapters/telegram/html.d.ts.map +1 -1
  69. package/dist/adapters/telegram/html.js +10 -7
  70. package/dist/adapters/telegram/html.js.map +1 -1
  71. package/dist/adapters/types.d.ts +4 -2
  72. package/dist/adapters/types.d.ts.map +1 -1
  73. package/dist/adapters/types.js.map +1 -1
  74. package/dist/agent-events.d.ts +3 -2
  75. package/dist/agent-events.d.ts.map +1 -1
  76. package/dist/agent-events.js +19 -1
  77. package/dist/agent-events.js.map +1 -1
  78. package/dist/agent.d.ts.map +1 -1
  79. package/dist/agent.js +34 -9
  80. package/dist/agent.js.map +1 -1
  81. package/dist/cli/arg-grammar.d.ts.map +1 -1
  82. package/dist/cli/arg-grammar.js +5 -3
  83. package/dist/cli/arg-grammar.js.map +1 -1
  84. package/dist/cli/boot.d.ts.map +1 -1
  85. package/dist/cli/boot.js +5 -3
  86. package/dist/cli/boot.js.map +1 -1
  87. package/dist/cli/download.d.ts.map +1 -1
  88. package/dist/cli/download.js +2 -0
  89. package/dist/cli/download.js.map +1 -1
  90. package/dist/cli/ext-dev.d.ts.map +1 -1
  91. package/dist/cli/ext-dev.js +4 -1
  92. package/dist/cli/ext-dev.js.map +1 -1
  93. package/dist/cli/ext.d.ts.map +1 -1
  94. package/dist/cli/ext.js +123 -23
  95. package/dist/cli/ext.js.map +1 -1
  96. package/dist/cli/office.d.ts.map +1 -1
  97. package/dist/cli/office.js +2 -0
  98. package/dist/cli/office.js.map +1 -1
  99. package/dist/cli/types.d.ts +0 -6
  100. package/dist/cli/types.d.ts.map +1 -1
  101. package/dist/cli/types.js.map +1 -1
  102. package/dist/commands/admin.js +1 -1
  103. package/dist/commands/admin.js.map +1 -1
  104. package/dist/commands/auto-reply.js +2 -2
  105. package/dist/commands/auto-reply.js.map +1 -1
  106. package/dist/commands/extensions.js +1 -1
  107. package/dist/commands/extensions.js.map +1 -1
  108. package/dist/commands/login.js +1 -1
  109. package/dist/commands/login.js.map +1 -1
  110. package/dist/commands/manifest.d.ts +7 -0
  111. package/dist/commands/manifest.d.ts.map +1 -1
  112. package/dist/commands/manifest.js +28 -0
  113. package/dist/commands/manifest.js.map +1 -1
  114. package/dist/commands/model.d.ts.map +1 -1
  115. package/dist/commands/model.js +4 -1
  116. package/dist/commands/model.js.map +1 -1
  117. package/dist/commands/new.js +1 -1
  118. package/dist/commands/new.js.map +1 -1
  119. package/dist/commands/sandbox.js +3 -3
  120. package/dist/commands/sandbox.js.map +1 -1
  121. package/dist/commands/session-view.d.ts.map +1 -1
  122. package/dist/commands/session-view.js +5 -2
  123. package/dist/commands/session-view.js.map +1 -1
  124. package/dist/commands/types.d.ts +1 -1
  125. package/dist/commands/types.d.ts.map +1 -1
  126. package/dist/commands/types.js.map +1 -1
  127. package/dist/config.js +4 -4
  128. package/dist/config.js.map +1 -1
  129. package/dist/env-manifest.d.ts +2 -0
  130. package/dist/env-manifest.d.ts.map +1 -1
  131. package/dist/env-manifest.js +11 -1
  132. package/dist/env-manifest.js.map +1 -1
  133. package/dist/events.d.ts.map +1 -1
  134. package/dist/events.js +7 -6
  135. package/dist/events.js.map +1 -1
  136. package/dist/execution-resolver.d.ts.map +1 -1
  137. package/dist/execution-resolver.js +3 -2
  138. package/dist/execution-resolver.js.map +1 -1
  139. package/dist/extension-schedules.d.ts +31 -0
  140. package/dist/extension-schedules.d.ts.map +1 -0
  141. package/dist/extension-schedules.js +229 -0
  142. package/dist/extension-schedules.js.map +1 -0
  143. package/dist/harness/auth.js +5 -5
  144. package/dist/harness/auth.js.map +1 -1
  145. package/dist/harness/event-format.d.ts +2 -0
  146. package/dist/harness/event-format.d.ts.map +1 -1
  147. package/dist/harness/event-format.js +2 -1
  148. package/dist/harness/event-format.js.map +1 -1
  149. package/dist/harness/extensions/loader.d.ts +2 -2
  150. package/dist/harness/extensions/loader.d.ts.map +1 -1
  151. package/dist/harness/extensions/loader.js +135 -33
  152. package/dist/harness/extensions/loader.js.map +1 -1
  153. package/dist/harness/extensions/registry.d.ts +33 -1
  154. package/dist/harness/extensions/registry.d.ts.map +1 -1
  155. package/dist/harness/extensions/registry.js +79 -2
  156. package/dist/harness/extensions/registry.js.map +1 -1
  157. package/dist/harness/extensions/types.d.ts +165 -21
  158. package/dist/harness/extensions/types.d.ts.map +1 -1
  159. package/dist/harness/extensions/types.js.map +1 -1
  160. package/dist/harness/index.d.ts +2 -2
  161. package/dist/harness/index.d.ts.map +1 -1
  162. package/dist/harness/index.js +1 -1
  163. package/dist/harness/index.js.map +1 -1
  164. package/dist/harness/models.d.ts.map +1 -1
  165. package/dist/harness/models.js +36 -24
  166. package/dist/harness/models.js.map +1 -1
  167. package/dist/harness/runner.js +2 -2
  168. package/dist/harness/runner.js.map +1 -1
  169. package/dist/harness/session-store.d.ts.map +1 -1
  170. package/dist/harness/session-store.js +9 -7
  171. package/dist/harness/session-store.js.map +1 -1
  172. package/dist/harness/skills.js +3 -3
  173. package/dist/harness/skills.js.map +1 -1
  174. package/dist/harness/subagent-profiles.js +2 -2
  175. package/dist/harness/subagent-profiles.js.map +1 -1
  176. package/dist/harness/subagent-runner.js +3 -3
  177. package/dist/harness/subagent-runner.js.map +1 -1
  178. package/dist/index.d.ts +8 -8
  179. package/dist/index.d.ts.map +1 -1
  180. package/dist/index.js +5 -5
  181. package/dist/index.js.map +1 -1
  182. package/dist/main.js +58 -9
  183. package/dist/main.js.map +1 -1
  184. package/dist/observability/instrument.js +1 -1
  185. package/dist/observability/instrument.js.map +1 -1
  186. package/dist/observability/sentry.js +1 -1
  187. package/dist/observability/sentry.js.map +1 -1
  188. package/dist/office/index.d.ts +1 -1
  189. package/dist/office/index.d.ts.map +1 -1
  190. package/dist/office/index.js +1 -1
  191. package/dist/office/index.js.map +1 -1
  192. package/dist/office/layout.d.ts +7 -0
  193. package/dist/office/layout.d.ts.map +1 -1
  194. package/dist/office/layout.js +10 -1
  195. package/dist/office/layout.js.map +1 -1
  196. package/dist/office/registry.d.ts.map +1 -1
  197. package/dist/office/registry.js +7 -5
  198. package/dist/office/registry.js.map +1 -1
  199. package/dist/packages/materialize.js +10 -3
  200. package/dist/packages/materialize.js.map +1 -1
  201. package/dist/packages/source.d.ts +6 -0
  202. package/dist/packages/source.d.ts.map +1 -1
  203. package/dist/packages/source.js +14 -2
  204. package/dist/packages/source.js.map +1 -1
  205. package/dist/packages/types.d.ts +5 -3
  206. package/dist/packages/types.d.ts.map +1 -1
  207. package/dist/packages/types.js.map +1 -1
  208. package/dist/provisioner.js +5 -5
  209. package/dist/provisioner.js.map +1 -1
  210. package/dist/runtime/conversation-runtime.d.ts.map +1 -1
  211. package/dist/runtime/conversation-runtime.js +44 -2
  212. package/dist/runtime/conversation-runtime.js.map +1 -1
  213. package/dist/runtime/types.d.ts +10 -2
  214. package/dist/runtime/types.d.ts.map +1 -1
  215. package/dist/runtime/types.js.map +1 -1
  216. package/dist/sandbox/cloudflare.js +1 -1
  217. package/dist/sandbox/cloudflare.js.map +1 -1
  218. package/dist/sandbox/container.js +1 -2
  219. package/dist/sandbox/container.js.map +1 -1
  220. package/dist/sandbox/firecracker.js +1 -1
  221. package/dist/sandbox/firecracker.js.map +1 -1
  222. package/dist/sandbox/gondolin.d.ts.map +1 -1
  223. package/dist/sandbox/gondolin.js +1 -2
  224. package/dist/sandbox/gondolin.js.map +1 -1
  225. package/dist/sandbox/host.d.ts.map +1 -1
  226. package/dist/sandbox/host.js +4 -5
  227. package/dist/sandbox/host.js.map +1 -1
  228. package/dist/sandbox/index.js +1 -1
  229. package/dist/sandbox/index.js.map +1 -1
  230. package/dist/sandbox/utils.d.ts +2 -0
  231. package/dist/sandbox/utils.d.ts.map +1 -1
  232. package/dist/sandbox/utils.js +30 -1
  233. package/dist/sandbox/utils.js.map +1 -1
  234. package/dist/sessions/chat-history-sync.d.ts.map +1 -1
  235. package/dist/sessions/chat-history-sync.js +9 -8
  236. package/dist/sessions/chat-history-sync.js.map +1 -1
  237. package/dist/sessions/conversation-log.d.ts.map +1 -1
  238. package/dist/sessions/conversation-log.js +5 -2
  239. package/dist/sessions/conversation-log.js.map +1 -1
  240. package/dist/sessions/history-line.d.ts +9 -0
  241. package/dist/sessions/history-line.d.ts.map +1 -1
  242. package/dist/sessions/history-line.js +22 -1
  243. package/dist/sessions/history-line.js.map +1 -1
  244. package/dist/sessions/session-key.d.ts +5 -12
  245. package/dist/sessions/session-key.d.ts.map +1 -1
  246. package/dist/sessions/session-key.js +23 -0
  247. package/dist/sessions/session-key.js.map +1 -1
  248. package/dist/sessions/store.d.ts +2 -6
  249. package/dist/sessions/store.d.ts.map +1 -1
  250. package/dist/sessions/store.js +16 -16
  251. package/dist/sessions/store.js.map +1 -1
  252. package/dist/sessions/types.d.ts +2 -1
  253. package/dist/sessions/types.d.ts.map +1 -1
  254. package/dist/sessions/types.js.map +1 -1
  255. package/dist/tools/bash.js +1 -1
  256. package/dist/tools/bash.js.map +1 -1
  257. package/dist/tools/edit.d.ts.map +1 -1
  258. package/dist/tools/edit.js +4 -1
  259. package/dist/tools/edit.js.map +1 -1
  260. package/dist/tools/event.js +1 -1
  261. package/dist/tools/event.js.map +1 -1
  262. package/dist/tools/generate-image.js +3 -3
  263. package/dist/tools/generate-image.js.map +1 -1
  264. package/dist/tools/read.js +4 -4
  265. package/dist/tools/read.js.map +1 -1
  266. package/dist/tools/subagent.d.ts.map +1 -1
  267. package/dist/tools/subagent.js +9 -2
  268. package/dist/tools/subagent.js.map +1 -1
  269. package/dist/tools/types.d.ts +0 -26
  270. package/dist/tools/types.d.ts.map +1 -1
  271. package/dist/tools/types.js.map +1 -1
  272. package/dist/trigger.d.ts +2 -1
  273. package/dist/trigger.d.ts.map +1 -1
  274. package/dist/trigger.js.map +1 -1
  275. package/dist/types.d.ts +108 -16
  276. package/dist/types.d.ts.map +1 -1
  277. package/dist/types.js +2 -2
  278. package/dist/types.js.map +1 -1
  279. package/dist/utils/file-guards.d.ts +9 -0
  280. package/dist/utils/file-guards.d.ts.map +1 -1
  281. package/dist/utils/file-guards.js +44 -1
  282. package/dist/utils/file-guards.js.map +1 -1
  283. package/dist/vault/disabled.d.ts.map +1 -1
  284. package/dist/vault/disabled.js +3 -0
  285. package/dist/vault/disabled.js.map +1 -1
  286. package/dist/vault/index.d.ts +29 -0
  287. package/dist/vault/index.d.ts.map +1 -1
  288. package/dist/vault/index.js +68 -4
  289. package/dist/vault/index.js.map +1 -1
  290. package/dist/vault/types.d.ts +2 -0
  291. package/dist/vault/types.d.ts.map +1 -1
  292. package/dist/vault/types.js.map +1 -1
  293. package/dist/web/admin/portal.d.ts +1 -1
  294. package/dist/web/admin/portal.d.ts.map +1 -1
  295. package/dist/web/admin/portal.js +194 -22
  296. package/dist/web/admin/portal.js.map +1 -1
  297. package/dist/web/admin/provider-models.js +1 -1
  298. package/dist/web/admin/provider-models.js.map +1 -1
  299. package/dist/web/login/oauth.js +1 -1
  300. package/dist/web/login/oauth.js.map +1 -1
  301. package/dist/web/login/portal.d.ts +1 -1
  302. package/dist/web/login/portal.d.ts.map +1 -1
  303. package/dist/web/login/portal.js +13 -36
  304. package/dist/web/login/portal.js.map +1 -1
  305. package/dist/web/portal-shell.d.ts +17 -0
  306. package/dist/web/portal-shell.d.ts.map +1 -1
  307. package/dist/web/portal-shell.js +66 -1
  308. package/dist/web/portal-shell.js.map +1 -1
  309. package/dist/web/server.d.ts +3 -2
  310. package/dist/web/server.d.ts.map +1 -1
  311. package/dist/web/server.js +3 -3
  312. package/dist/web/server.js.map +1 -1
  313. package/dist/web/session-view/portal.d.ts +1 -1
  314. package/dist/web/session-view/portal.d.ts.map +1 -1
  315. package/dist/web/session-view/portal.js +10 -12
  316. package/dist/web/session-view/portal.js.map +1 -1
  317. package/dist/web/session-view/service.d.ts.map +1 -1
  318. package/dist/web/session-view/service.js +11 -6
  319. package/dist/web/session-view/service.js.map +1 -1
  320. package/dist/web/session-view/types.d.ts +0 -4
  321. package/dist/web/session-view/types.d.ts.map +1 -1
  322. package/dist/web/session-view/types.js.map +1 -1
  323. package/dist/web/token-store.js +1 -1
  324. package/dist/web/token-store.js.map +1 -1
  325. package/package.json +8 -17
  326. package/dist/cli/ext-git.d.ts +0 -17
  327. package/dist/cli/ext-git.d.ts.map +0 -1
  328. package/dist/cli/ext-git.js +0 -107
  329. package/dist/cli/ext-git.js.map +0 -1
  330. package/dist/commands/parse.d.ts +0 -7
  331. package/dist/commands/parse.d.ts.map +0 -1
  332. package/dist/commands/parse.js +0 -14
  333. package/dist/commands/parse.js.map +0 -1
  334. package/dist/commands/text.d.ts +0 -2
  335. package/dist/commands/text.d.ts.map +0 -1
  336. package/dist/commands/text.js +0 -16
  337. package/dist/commands/text.js.map +0 -1
  338. package/dist/harness/extensions/blockkit.d.ts +0 -19
  339. package/dist/harness/extensions/blockkit.d.ts.map +0 -1
  340. package/dist/harness/extensions/blockkit.js +0 -42
  341. package/dist/harness/extensions/blockkit.js.map +0 -1
  342. package/dist/sandbox/path-context.d.ts +0 -3
  343. package/dist/sandbox/path-context.d.ts.map +0 -1
  344. package/dist/sandbox/path-context.js +0 -30
  345. package/dist/sandbox/path-context.js.map +0 -1
  346. package/dist/sessions/metadata.d.ts +0 -3
  347. package/dist/sessions/metadata.d.ts.map +0 -1
  348. package/dist/sessions/metadata.js +0 -11
  349. package/dist/sessions/metadata.js.map +0 -1
  350. package/dist/sessions/policy.d.ts +0 -6
  351. package/dist/sessions/policy.d.ts.map +0 -1
  352. package/dist/sessions/policy.js +0 -25
  353. package/dist/sessions/policy.js.map +0 -1
  354. package/dist/tools/truncate.d.ts +0 -33
  355. package/dist/tools/truncate.d.ts.map +0 -1
  356. package/dist/tools/truncate.js +0 -184
  357. package/dist/tools/truncate.js.map +0 -1
  358. package/dist/utils/date.d.ts +0 -10
  359. package/dist/utils/date.d.ts.map +0 -1
  360. package/dist/utils/date.js +0 -23
  361. package/dist/utils/date.js.map +0 -1
  362. package/dist/utils/env.d.ts +0 -3
  363. package/dist/utils/env.d.ts.map +0 -1
  364. package/dist/utils/env.js +0 -12
  365. package/dist/utils/env.js.map +0 -1
  366. package/dist/utils/fs-atomic.d.ts +0 -10
  367. package/dist/utils/fs-atomic.d.ts.map +0 -1
  368. package/dist/utils/fs-atomic.js +0 -45
  369. package/dist/utils/fs-atomic.js.map +0 -1
  370. package/dist/utils/html.d.ts +0 -2
  371. package/dist/utils/html.d.ts.map +0 -1
  372. package/dist/utils/html.js +0 -4
  373. package/dist/utils/html.js.map +0 -1
  374. package/dist/utils/http-body.d.ts +0 -10
  375. package/dist/utils/http-body.d.ts.map +0 -1
  376. package/dist/utils/http-body.js +0 -34
  377. package/dist/utils/http-body.js.map +0 -1
  378. package/dist/vault/injection.d.ts +0 -12
  379. package/dist/vault/injection.d.ts.map +0 -1
  380. package/dist/vault/injection.js +0 -30
  381. package/dist/vault/injection.js.map +0 -1
  382. package/dist/vault/policy.d.ts +0 -20
  383. package/dist/vault/policy.d.ts.map +0 -1
  384. package/dist/vault/policy.js +0 -20
  385. package/dist/vault/policy.js.map +0 -1
  386. package/dist/web/agent-events/portal.d.ts +0 -3
  387. package/dist/web/agent-events/portal.d.ts.map +0 -1
  388. package/dist/web/agent-events/portal.js +0 -19
  389. package/dist/web/agent-events/portal.js.map +0 -1
  390. package/dist/web/request.d.ts +0 -3
  391. package/dist/web/request.d.ts.map +0 -1
  392. package/dist/web/request.js +0 -13
  393. package/dist/web/request.js.map +0 -1
  394. package/dist/web/session-view/command.d.ts +0 -4
  395. package/dist/web/session-view/command.d.ts.map +0 -1
  396. package/dist/web/session-view/command.js +0 -10
  397. package/dist/web/session-view/command.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"gondolin.js","sourceRoot":"","sources":["../../src/sandbox/gondolin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EACL,SAAS,EACT,SAAS,EACT,YAAY,EACZ,UAAU,EACV,MAAM,EACN,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,+B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E,CAAC;IAED,gBAAgB;QACd,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,sBAAsB,GAA0C;IAC3E,IAAI,EAAE,UAAU;IAChB,WAAW,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,SAAS,EAAE,EAAE,iBAAiB,EAAE,IAAI,EAAE;IACtC,KAAK,EAAE,uBAAuB;IAC9B,QAAQ,EAAE,uBAAuB;IACjC,cAAc,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,IAAI,gBAAgB,CAAC,MAAM,EAAE,GAAG,CAAC;CACnE,CAAC","sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport * as log from \"../log.js\";\nimport type { ResourceLimits, SandboxLimitStatus, SandboxResourceController } from \"../types.js\";\nimport { withRuntimeBootstrap } from \"./container.js\";\nimport { SandboxError } from \"./errors.js\";\nimport { createMountedRuntimePathContext } from \"./path-context.js\";\nimport { execReadFile, execReadFileBase64, execWriteFile, shellEscape } from \"./utils.js\";\nimport type {\n ExecOptions,\n ExecResult,\n Executor,\n GondolinBootstrapOptions,\n GondolinSandboxConfig,\n RuntimePathContext,\n SandboxAdapter,\n SessionClient,\n SessionClientCallbacks,\n} from \"./types.js\";\n\nexport type { GondolinBootstrapOptions, SessionClient, SessionClientCallbacks } from \"./types.js\";\n\n/**\n * Single-host Gondolin sandbox: one microVM per conversation, created and\n * owned by this mikan process.\n *\n * Commands do not go through `vm.exec()` — aborting that only rejects the\n * local promise and leaves the guest process running. They go over Gondolin's\n * session IPC socket instead, one connection per command, so an abort or\n * timeout closes the connection and kills the command inside the guest.\n *\n * Runtimes die with mikan: Gondolin SIGKILLs its VM runners from a\n * `process.exit` hook, and shutdown closes them explicitly so projected files\n * sync back first. A `kill -9` of mikan itself skips both and leaks a runner.\n */\n\ntype GondolinModule = typeof import(\"@earendil-works/gondolin\");\ntype GondolinVm = InstanceType<GondolinModule[\"VM\"]>;\n\nconst MINIMUM_NODE_VERSION = [23, 6, 0] as const;\nconst MIKAN_IMAGE = \"mikan-sandbox:latest\";\n\n/** Write-back cadence for projected `/workspace` files (e.g. MEMORY.md). */\nconst PROJECTION_SYNC_INTERVAL_MS = 2000;\nconst PROJECTION_LOCK_RETRY_MS = 25;\nconst PROJECTION_LOCK_STALE_MS = 60_000;\n\n/**\n * A command may quietly work for a long time, but a session that produces no\n * frame at all for this long is indistinguishable from one wedged on dead\n * storage (for example, blocked guest workspace I/O) — kill it and say so\n * instead of hanging the run.\n */\nconst EXEC_IDLE_TIMEOUT_MS = 10 * 60 * 1000;\n\nconst sessions = new Map<string, GondolinSession>();\nconst transitions = new Map<string, Promise<void>>();\nlet activeShutdowns = 0;\nlet shutdownGeneration = 0;\n\ninterface GondolinSession {\n runtime: Promise<GondolinRuntime>;\n fingerprint: string;\n resourceKey?: string;\n activeOperations: number;\n lastUsed: number;\n idleWaiters: Array<() => void>;\n}\n\n/** A host directory or file offered to the guest. */\ninterface GondolinMount {\n source: string;\n target: string;\n /** Mounted through `ReadonlyProvider`; host-owned content the agent must not edit. */\n readOnly?: boolean;\n}\n\ninterface GondolinDesiredRuntime {\n image: string;\n imageIdentity: string;\n mounts: GondolinMount[];\n /** Content identity of projected credential files (rotation → drift). */\n credentialIdentity: Record<string, string>;\n limits?: ResourceLimits;\n}\n\n/**\n * A single-file mount handled outside the VFS: Gondolin's guest prepares every\n * VFS mount point with `mkdir -p`, so a file target can never bind (the guest\n * ends up bind-mounting a file onto a directory and the VM refuses to start).\n * Files are copied in after boot instead; the ones under /workspace sync guest\n * edits back to the host so agent-maintained files like MEMORY.md persist.\n */\ninterface FileProjection {\n source: string;\n target: string;\n syncBack: boolean;\n /** Hash of the guest content at the last successful or conflict sync. */\n lastHash: string;\n}\n\n/*\n * Crash-recovery vocabulary.\n *\n * - **Gone**: the command never reached the runtime because its session socket\n * refused the connection. Recreating the runtime and retrying is safe.\n * - **Interrupted**: the runtime died or went silent with a command in flight.\n * Side effects may have landed, so the failure must surface.\n */\n\n/**\n * The runtime is gone and the command never reached it (the session socket\n * refused the connection) — safe to recreate the runtime and retry.\n */\nclass GondolinRuntimeGoneError extends Error {}\n\n/** The runtime died with the command in flight — not safe to retry blindly. */\nclass GondolinRuntimeInterruptedError extends Error {}\n\nclass GondolinResourceManager implements SandboxResourceController {\n private defaultLimits?: ResourceLimits;\n private boostLimits?: ResourceLimits;\n private readonly boostedKeys = new Set<string>();\n private readonly overrideLimits = new Map<string, ResourceLimits>();\n\n configure(defaultLimits?: ResourceLimits, boostLimits?: ResourceLimits): void {\n this.defaultLimits = defaultLimits;\n this.boostLimits = boostLimits;\n this.boostedKeys.clear();\n this.overrideLimits.clear();\n }\n\n async boost(key: string): Promise<SandboxLimitStatus> {\n if (this.boostLimits?.cpus || this.boostLimits?.memory) {\n this.overrideLimits.delete(key);\n this.boostedKeys.add(key);\n }\n return this.getLimitStatus(key);\n }\n\n async setLimits(key: string, limits: ResourceLimits): Promise<SandboxLimitStatus> {\n this.boostedKeys.delete(key);\n this.overrideLimits.set(key, { ...this.defaultLimits, ...limits });\n return this.getLimitStatus(key);\n }\n\n getLimitStatus(key: string): SandboxLimitStatus {\n return { limits: this.effectiveLimits(key), boosted: this.boostedKeys.has(key) };\n }\n\n getDefaultLimits(): ResourceLimits | undefined {\n return this.defaultLimits;\n }\n\n getBoostLimits(): ResourceLimits | undefined {\n return this.boostLimits;\n }\n\n clear(key: string): void {\n this.boostedKeys.delete(key);\n this.overrideLimits.delete(key);\n }\n\n private effectiveLimits(key: string): ResourceLimits | undefined {\n const override = this.overrideLimits.get(key);\n if (override) return override;\n if (!this.boostedKeys.has(key)) return this.defaultLimits;\n return { ...this.defaultLimits, ...this.boostLimits };\n }\n}\n\nexport const gondolinResources = new GondolinResourceManager();\n\n/** Configure the Gondolin resource controller. */\nexport function configureGondolinRuntime(options: GondolinBootstrapOptions): void {\n gondolinResources.configure(options.limits, options.boostLimits);\n}\n\nfunction parseGondolinSandboxArg(value: string): GondolinSandboxConfig | undefined {\n if (!value.startsWith(\"gondolin:\")) return undefined;\n\n const profile = value.slice(\"gondolin:\".length);\n if (!profile) {\n throw new SandboxError(\"Error: gondolin sandbox requires a profile (e.g., gondolin:default)\");\n }\n if (profile !== \"default\") {\n throw new SandboxError(\n `Error: unsupported gondolin profile '${profile}'. Use 'gondolin:default'`,\n );\n }\n return { type: \"gondolin\", profile };\n}\n\nfunction assertSupportedNodeVersion(): void {\n const [major = 0, minor = 0] = process.versions.node.split(\".\").map(Number);\n if (major < MINIMUM_NODE_VERSION[0] || (major === MINIMUM_NODE_VERSION[0] && minor < 6)) {\n throw new SandboxError(\n `Error: gondolin:default requires Node.js >=23.6.0 (current: ${process.versions.node}). Other sandbox modes remain available on Node.js >=22.19.0.`,\n );\n }\n}\n\nasync function validateGondolinSandbox(): Promise<void> {\n assertSupportedNodeVersion();\n console.log(\" Gondolin microVM enabled. Profile: default\");\n}\n\nasync function resolveDesiredRuntime(\n config: GondolinSandboxConfig,\n): Promise<GondolinDesiredRuntime> {\n const selector = config.image ?? MIKAN_IMAGE;\n const { ensureImageSelector } = (await import(\"@earendil-works/gondolin\")) as GondolinModule;\n const resolvedImage = await ensureImageSelector(selector);\n const image = resolvedImage.assetDir;\n const imageIdentity = resolvedImage.buildId ?? resolvedImage.assetDir;\n const mounts = (\n config.mounts ?? [{ source: config.workspacePath ?? process.cwd(), target: \"/workspace\" }]\n ).toSorted((left, right) => left.target.localeCompare(right.target));\n return {\n image,\n imageIdentity,\n mounts,\n credentialIdentity: credentialIdentity(mounts),\n limits: config.resourceKey\n ? gondolinResources.getLimitStatus(config.resourceKey).limits\n : undefined,\n };\n}\n\n/**\n * Content hashes of credential file mounts (files projected outside\n * /workspace). Rotating a credential on the host changes the fingerprint, so\n * the next command recreates the runtime with a fresh projection instead of\n * serving the stale copy for the rest of the VM's life. Workspace files are\n * excluded: the guest writes them back, which would drift the runtime it runs\n * in.\n */\nfunction credentialIdentity(mounts: GondolinMount[]): Record<string, string> {\n const identity: Record<string, string> = {};\n for (const mount of mounts) {\n if (mount.target.startsWith(\"/workspace/\") || mount.target === \"/workspace\") continue;\n try {\n if (!statSync(mount.source).isFile()) continue;\n identity[mount.target] = createHash(\"sha256\")\n .update(readFileSync(mount.source))\n .digest(\"hex\");\n } catch {\n // missing source: creation skips it too, so it has no runtime identity\n }\n }\n return identity;\n}\n\nfunction runtimeFingerprint(desired: GondolinDesiredRuntime): string {\n return createHash(\"sha256\")\n .update(\n JSON.stringify({\n image: desired.imageIdentity,\n mounts: desired.mounts,\n credentials: desired.credentialIdentity,\n limits: desired.limits,\n }),\n )\n .digest(\"hex\");\n}\n\nfunction gondolinCpuCount(cpus: string | undefined): number | undefined {\n if (cpus === undefined) return undefined;\n const parsed = Number(cpus);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new SandboxError(`Error: invalid Gondolin CPU limit '${cpus}'`);\n }\n // ponytail: Gondolin exposes whole vCPUs; add host cgroup quotas if fractional enforcement matters.\n return Math.ceil(parsed);\n}\n\nfunction sha256(data: Buffer): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\nfunction partitionMounts(mounts: GondolinMount[]): {\n directories: GondolinMount[];\n files: FileProjection[];\n} {\n const directories: GondolinMount[] = [];\n const files: FileProjection[] = [];\n for (const mount of mounts) {\n let isDirectory: boolean;\n try {\n isDirectory = statSync(mount.source).isDirectory();\n } catch {\n log.logWarning(`Skipping missing Gondolin mount source ${mount.source}`);\n continue;\n }\n if (isDirectory) {\n directories.push(mount);\n } else {\n files.push({\n ...mount,\n syncBack: mount.target.startsWith(\"/workspace/\"),\n lastHash: \"\",\n });\n }\n }\n return { directories, files };\n}\n\n/** Copy file mounts into the guest; credentials get user-only permissions. */\nasync function projectFiles(vm: GondolinVm, files: FileProjection[]): Promise<void> {\n for (const projection of files) {\n const content = readFileSync(projection.source);\n await vm.fs.mkdir(dirname(projection.target), { recursive: true });\n await vm.fs.writeFile(projection.target, content);\n if (!projection.syncBack) {\n // credential projection: no write-back, keep it owner-only\n await vm.exec(`chmod 600 ${shellEscape(projection.target)}`);\n }\n projection.lastHash = sha256(content);\n }\n}\n\nfunction restrictSocketAccess(socketPath: string): void {\n // The session socket grants arbitrary exec inside the VM (and through its\n // mounts, the workspace) — keep it to this user even under a lax umask.\n try {\n chmodSync(dirname(socketPath), 0o700);\n chmodSync(socketPath, 0o600);\n } catch {\n // best-effort hardening\n }\n}\n\nfunction projectionLockIsStale(lockPath: string): boolean {\n let ownerKnown = false;\n let ownerAlive = false;\n try {\n const pid = Number(readFileSync(join(lockPath, \"owner\"), \"utf8\").trim());\n if (Number.isInteger(pid) && pid > 0) {\n ownerKnown = true;\n try {\n process.kill(pid, 0);\n ownerAlive = true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"EPERM\") ownerAlive = true;\n }\n }\n } catch {\n // An owner file may not have been written before its process died.\n }\n try {\n const oldEnough = Date.now() - statSync(lockPath).mtimeMs >= PROJECTION_LOCK_STALE_MS;\n return (ownerKnown && !ownerAlive) || oldEnough;\n } catch {\n return false;\n }\n}\n\nasync function withProjectionLock<T>(source: string, operation: () => Promise<T>): Promise<T> {\n const lockPath = `${source}.mikan-sync.lock`;\n for (;;) {\n try {\n mkdirSync(lockPath, { mode: 0o700 });\n writeFileSync(join(lockPath, \"owner\"), `${process.pid}\\n`, { mode: 0o600 });\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (projectionLockIsStale(lockPath)) {\n rmSync(lockPath, { recursive: true, force: true });\n continue;\n }\n await new Promise((resolve) => setTimeout(resolve, PROJECTION_LOCK_RETRY_MS));\n }\n }\n try {\n return await operation();\n } finally {\n rmSync(lockPath, { recursive: true, force: true });\n }\n}\n\n/** One live microVM owned by this process, addressed by its session socket. */\nclass GondolinRuntime {\n private syncTimer?: NodeJS.Timeout;\n private syncing = false;\n private closing?: Promise<void>;\n\n private constructor(\n private readonly vm: GondolinVm,\n private readonly socketPath: string,\n private readonly projections: FileProjection[],\n ) {}\n\n /** Boot a VM for the desired configuration and make it command-ready. */\n static async create(\n instanceId: string,\n desired: GondolinDesiredRuntime,\n ): Promise<GondolinRuntime> {\n const { VM, RealFSProvider, ReadonlyProvider, findSession } =\n (await import(\"@earendil-works/gondolin\")) as GondolinModule;\n const { directories, files } = partitionMounts(desired.mounts);\n const vm = await VM.create({\n sandbox: { imagePath: desired.image },\n env: { TZ: \"Asia/Taipei\" },\n sessionLabel: `mikan:${instanceId}`,\n cpus: gondolinCpuCount(desired.limits?.cpus),\n memory: desired.limits?.memory,\n vfs: {\n mounts: Object.fromEntries(\n directories.map(({ source, target, readOnly }) => [\n target,\n // ReadonlyProvider blocks every write operation on the backing\n // provider — gondolin's own answer to read-only host directories.\n readOnly\n ? new ReadonlyProvider(new RealFSProvider(source))\n : new RealFSProvider(source),\n ]),\n ),\n },\n });\n\n try {\n await vm.start();\n await projectFiles(vm, files);\n const session = await findSession(vm.id);\n if (!session) throw new Error(`Gondolin session '${vm.id}' did not register`);\n restrictSocketAccess(session.socketPath);\n const runtime = new GondolinRuntime(vm, session.socketPath, files);\n runtime.startProjectionSync();\n return runtime;\n } catch (error) {\n // never leave a half-booted runner (and its overlay disk) behind\n await vm.close().catch(() => {});\n throw error;\n }\n }\n\n /**\n * Run one command over a dedicated session IPC connection. Aborting (or the\n * caller's timeout signal firing) destroys the connection, which kills the\n * in-flight guest process.\n */\n async exec(\n command: string,\n options: { env?: Record<string, string>; signal?: AbortSignal } = {},\n ): Promise<ExecResult> {\n return execOverSessionConnect(\n async (callbacks) => {\n const { connectToSession } = await import(\"@earendil-works/gondolin\");\n return connectToSession(this.socketPath, callbacks);\n },\n command,\n options,\n );\n }\n\n /** Whether the VM runner process is still up. */\n isAlive(): boolean {\n try {\n return this.vm.getHostPid() !== null;\n } catch {\n return false;\n }\n }\n\n /** Sync projected files back one last time, then shut the VM down. */\n async close(): Promise<void> {\n this.closing ??= (async () => {\n clearInterval(this.syncTimer);\n try {\n await this.syncProjections();\n } catch {\n // best effort; the periodic sync already captured earlier edits\n }\n await this.vm.close();\n })();\n return this.closing;\n }\n\n private startProjectionSync(): void {\n if (!this.projections.some((projection) => projection.syncBack)) return;\n this.syncTimer = setInterval(() => void this.syncProjections(), PROJECTION_SYNC_INTERVAL_MS);\n this.syncTimer.unref?.();\n }\n\n private async syncProjections(): Promise<void> {\n if (this.syncing) return;\n this.syncing = true;\n try {\n for (const projection of this.projections) {\n if (!projection.syncBack) continue;\n try {\n const data = await this.vm.fs.readFile(projection.target);\n const content = Buffer.isBuffer(data) ? data : Buffer.from(String(data));\n const hash = sha256(content);\n if (hash === projection.lastHash) continue;\n await withProjectionLock(projection.source, async () => {\n let hostHash: string;\n try {\n hostHash = sha256(readFileSync(projection.source));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n hostHash = \"\";\n }\n if (hostHash !== projection.lastHash) {\n const conflict = `${projection.source}.mikan-conflict.${process.pid}.${randomBytes(8).toString(\"hex\")}`;\n writeFileSync(conflict, content);\n projection.lastHash = hash;\n log.logWarning(\n `Skipped Gondolin projection write-back for '${projection.source}': host content changed; guest content preserved at '${conflict}'`,\n );\n return;\n }\n // atomic host write: a crash mid-sync must not truncate the file\n const staged = `${projection.source}.mikan-sync.${process.pid}.${randomBytes(8).toString(\"hex\")}`;\n try {\n writeFileSync(staged, content);\n renameSync(staged, projection.source);\n projection.lastHash = hash;\n } finally {\n try {\n unlinkSync(staged);\n } catch {\n // rename succeeded or the staging write failed\n }\n }\n });\n } catch {\n // guest file missing or read raced a writer; next tick retries\n }\n }\n } finally {\n this.syncing = false;\n }\n }\n}\n\nfunction abortError(): Error {\n return new Error(\"Error: command aborted\");\n}\n\n/**\n * Run one command through a fresh session connection. Closing the connection\n * (abort, timeout, or the far side dying) kills the in-flight guest process.\n */\nexport async function execOverSessionConnect(\n connect: (callbacks: SessionClientCallbacks) => SessionClient | Promise<SessionClient>,\n command: string,\n options: { env?: Record<string, string>; signal?: AbortSignal; idleTimeoutMs?: number } = {},\n): Promise<ExecResult> {\n if (options.signal?.aborted) throw abortError();\n const idleTimeoutMs = options.idleTimeoutMs ?? EXEC_IDLE_TIMEOUT_MS;\n return await new Promise<ExecResult>((resolve, reject) => {\n let stdout = \"\";\n let stderr = \"\";\n let received = false;\n let settled = false;\n let client: SessionClient | undefined;\n let idleTimer: NodeJS.Timeout | undefined;\n const settle = (fn: () => void): void => {\n if (settled) return;\n settled = true;\n clearTimeout(idleTimer);\n options.signal?.removeEventListener(\"abort\", onAbort);\n fn();\n };\n const onAbort = (): void =>\n settle(() => {\n client?.close();\n reject(abortError());\n });\n const onIdle = (): void =>\n settle(() => {\n client?.close();\n reject(\n new GondolinRuntimeInterruptedError(\n `no session activity for ${Math.round(idleTimeoutMs / 1000)}s — killed the command ` +\n `(guest I/O hangs when the workspace sits on a dead mount; check the workspace health)`,\n ),\n );\n });\n const armIdleTimer = (): void => {\n if (idleTimeoutMs <= 0 || settled) return;\n clearTimeout(idleTimer);\n idleTimer = setTimeout(onIdle, idleTimeoutMs);\n idleTimer.unref?.();\n };\n armIdleTimer();\n const callbacks: SessionClientCallbacks = {\n onJson: (message) => {\n received = true;\n armIdleTimer();\n if (message.type === \"exec_response\" && message.id === 1) {\n settle(() => {\n client?.close();\n resolve({\n stdout,\n stderr,\n code: typeof message.exit_code === \"number\" ? message.exit_code : 1,\n });\n });\n } else if (message.type === \"error\") {\n settle(() => {\n client?.close();\n reject(new Error(`Error: Gondolin exec failed (${message.code}): ${message.message}`));\n });\n }\n },\n onBinary: (frame) => {\n received = true;\n armIdleTimer();\n const tag = frame.readUInt8(0);\n const data = frame.subarray(5).toString(\"utf8\");\n if (tag === 1) stdout += data;\n else stderr += data;\n },\n onClose: (error) => {\n settle(() => {\n const detail = error?.message ?? \"connection closed before the command finished\";\n const code = (error as NodeJS.ErrnoException | undefined)?.code;\n if (!received && (code === \"ENOENT\" || code === \"ECONNREFUSED\")) {\n reject(new GondolinRuntimeGoneError(detail));\n } else {\n reject(new GondolinRuntimeInterruptedError(detail));\n }\n });\n },\n };\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n Promise.resolve(connect(callbacks))\n .then((created) => {\n client = created;\n if (settled) {\n created.close();\n return;\n }\n created.send({\n type: \"exec\",\n id: 1,\n cmd: \"/bin/sh\",\n argv: [\"-c\", command],\n env: Object.entries(options.env ?? {}).map(([key, value]) => `${key}=${value}`),\n cwd: \"/workspace\",\n });\n })\n .catch((err: unknown) =>\n settle(() =>\n reject(new GondolinRuntimeGoneError(err instanceof Error ? err.message : String(err))),\n ),\n );\n });\n}\n\nfunction createSession(\n key: string,\n config: GondolinSandboxConfig,\n desired: GondolinDesiredRuntime,\n fingerprint: string,\n): GondolinSession {\n let session: GondolinSession;\n const runtime = GondolinRuntime.create(key, desired).catch((error: unknown) => {\n if (sessions.get(key) === session) sessions.delete(key);\n throw error;\n });\n session = {\n runtime,\n fingerprint,\n resourceKey: config.resourceKey,\n activeOperations: 0,\n lastUsed: Date.now(),\n idleWaiters: [],\n };\n return session;\n}\n\nasync function acquireSession(\n key: string,\n config: GondolinSandboxConfig,\n generation = shutdownGeneration,\n): Promise<GondolinSession> {\n if (activeShutdowns > 0 || generation !== shutdownGeneration) {\n throw new SandboxError(\"Error: Gondolin runtime is shutting down\");\n }\n\n const pending = transitions.get(key);\n if (pending) {\n await pending;\n return acquireSession(key, config, generation);\n }\n\n const desired = await resolveDesiredRuntime(config);\n if (activeShutdowns > 0 || generation !== shutdownGeneration) {\n throw new SandboxError(\"Error: Gondolin runtime is shutting down\");\n }\n const concurrentTransition = transitions.get(key);\n if (concurrentTransition) {\n await concurrentTransition;\n return acquireSession(key, config, generation);\n }\n\n const fingerprint = runtimeFingerprint(desired);\n const existing = sessions.get(key);\n if (existing?.fingerprint === fingerprint) {\n existing.activeOperations += 1;\n return existing;\n }\n\n const transition = replaceSession(key, config, desired, fingerprint, existing);\n transitions.set(key, transition);\n try {\n await transition;\n } finally {\n if (transitions.get(key) === transition) transitions.delete(key);\n }\n return acquireSession(key, config, generation);\n}\n\nasync function replaceSession(\n key: string,\n config: GondolinSandboxConfig,\n desired: GondolinDesiredRuntime,\n fingerprint: string,\n existing: GondolinSession | undefined,\n): Promise<void> {\n if (existing) {\n await closeSession(key, existing, {\n waitForActiveOperations: true,\n resetResources: false,\n throwOnError: true,\n });\n }\n const replacement = createSession(key, config, desired, fingerprint);\n sessions.set(key, replacement);\n await replacement.runtime;\n}\n\nfunction discardDeadSession(key: string, session: GondolinSession): void {\n if (sessions.get(key) !== session) return;\n sessions.delete(key);\n log.logWarning(`Gondolin runtime for '${key}' died; the session will be recreated`);\n}\n\nasync function withRuntime<T>(\n key: string,\n config: GondolinSandboxConfig,\n operation: (runtime: GondolinRuntime) => Promise<T>,\n): Promise<T> {\n for (let attempt = 0; ; attempt += 1) {\n const session = await acquireSession(key, config);\n let runtime: GondolinRuntime | undefined;\n try {\n runtime = await session.runtime;\n return await operation(runtime);\n } catch (error) {\n const gone = error instanceof GondolinRuntimeGoneError;\n const interrupted = error instanceof GondolinRuntimeInterruptedError;\n if (gone || (interrupted && runtime && !runtime.isAlive())) {\n discardDeadSession(key, session);\n }\n // Nothing reached a gone runtime, so recreating and retrying is safe;\n // an interrupted command may have side effects and must surface.\n if (gone && attempt === 0) continue;\n if (gone || interrupted) {\n throw new SandboxError(\n `Error: Gondolin runtime for '${key}' died (${(error as Error).message}); it is recreated on the next command`,\n );\n }\n throw error;\n } finally {\n session.activeOperations -= 1;\n session.lastUsed = Date.now();\n if (session.activeOperations === 0) {\n for (const resolve of session.idleWaiters.splice(0)) resolve();\n }\n }\n }\n}\n\nfunction waitForIdle(session: GondolinSession): Promise<void> {\n if (session.activeOperations === 0) return Promise.resolve();\n return new Promise((resolve) => session.idleWaiters.push(resolve));\n}\n\nasync function closeSession(\n key: string,\n session: GondolinSession,\n options: {\n waitForActiveOperations?: boolean;\n resetResources?: boolean;\n throwOnError?: boolean;\n } = {},\n): Promise<void> {\n if (sessions.get(key) !== session) return;\n sessions.delete(key);\n try {\n if (options.waitForActiveOperations) await waitForIdle(session);\n const runtime = await session.runtime;\n await runtime.close();\n if (\n options.resetResources !== false &&\n session.resourceKey &&\n !Array.from(sessions.values()).some(({ resourceKey }) => resourceKey === session.resourceKey)\n ) {\n gondolinResources.clear(session.resourceKey);\n }\n } catch (error) {\n session.fingerprint = \"\";\n // Re-track for a retried close, unless a replacement already claimed the\n // key — then the failed runtime stays for the reconcile paths and\n // clobbering the replacement would leak it too.\n if (!sessions.has(key)) sessions.set(key, session);\n if (options.throwOnError) throw error;\n log.logWarning(\n `Failed to close Gondolin session '${key}'`,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\nexport async function stopIdleGondolinVms(maxIdleMs: number, now = Date.now()): Promise<void> {\n const idle = Array.from(sessions.entries()).filter(\n ([key, session]) =>\n !transitions.has(key) &&\n session.activeOperations === 0 &&\n now - session.lastUsed >= maxIdleMs,\n );\n await Promise.all(\n idle.map(([key, session]) => {\n // Register the close as a transition so a concurrent acquire waits for\n // it instead of racing the shared session slot.\n const transition = closeSession(key, session).finally(() => {\n if (transitions.get(key) === transition) transitions.delete(key);\n });\n transitions.set(key, transition);\n return transition;\n }),\n );\n}\n\n/**\n * Drop Gondolin's registry entries for sessions that no longer answer — socket\n * files and metadata left behind by a mikan that died without cleanup.\n */\nexport async function reconcileGondolinRuntimes(): Promise<void> {\n try {\n const { gcSessions } = (await import(\"@earendil-works/gondolin\")) as GondolinModule;\n const collected = await gcSessions();\n log.logInfo(`Reconciled Gondolin sessions (collected=${collected})`);\n } catch (error) {\n log.logWarning(\n \"Failed to collect Gondolin session registry\",\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * Stop every runtime this process owns. Runtimes do not outlive mikan, so\n * shutdown must close them: that syncs projected files back to the host and\n * releases each VM's overlay disk before the process exits.\n */\nexport async function stopAllGondolinRuntimes(): Promise<void> {\n shutdownGeneration += 1;\n activeShutdowns += 1;\n try {\n await Promise.allSettled(transitions.values());\n const current = Array.from(sessions.entries());\n await Promise.all(\n current.map(([key, session]) =>\n closeSession(key, session, { waitForActiveOperations: true }),\n ),\n );\n } finally {\n activeShutdowns -= 1;\n }\n}\n\nfunction executionSignal(options?: ExecOptions): AbortSignal | undefined {\n const signals = [options?.signal];\n if (options?.timeout && options.timeout > 0) {\n signals.push(AbortSignal.timeout(options.timeout * 1000));\n }\n const active = signals.filter((signal): signal is AbortSignal => signal !== undefined);\n return active.length > 0 ? AbortSignal.any(active) : undefined;\n}\n\nexport class GondolinExecutor implements Executor {\n private readonly workspacePath: string;\n private readonly instanceId: string;\n\n constructor(\n private readonly config: GondolinSandboxConfig,\n private readonly env?: Record<string, string>,\n ) {\n assertSupportedNodeVersion();\n this.workspacePath = config.workspacePath ?? process.cwd();\n this.instanceId = config.instanceId ?? this.workspacePath;\n }\n\n async exec(command: string, options?: ExecOptions): Promise<ExecResult> {\n return withRuntime(this.instanceId, this.config, (runtime) =>\n runtime.exec(withRuntimeBootstrap(command, this.env), {\n env: this.env,\n signal: executionSignal(options),\n }),\n );\n }\n\n async readFile(path: string): Promise<string> {\n return execReadFile(this, path);\n }\n\n async readFileBase64(path: string): Promise<string> {\n return execReadFileBase64(this, path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n return execWriteFile(this, path, content);\n }\n\n getWorkspacePath(): string {\n return \"/workspace\";\n }\n\n getPathContext(hostWorkspaceRoot: string): RuntimePathContext {\n return createMountedRuntimePathContext(hostWorkspaceRoot, \"/workspace\");\n }\n\n getSandboxConfig(): GondolinSandboxConfig {\n return this.config;\n }\n}\n\nexport const gondolinSandboxAdapter: SandboxAdapter<GondolinSandboxConfig> = {\n type: \"gondolin\",\n credentials: { env: true, fileMounts: true },\n workspace: { managedProjection: true },\n parse: parseGondolinSandboxArg,\n validate: validateGondolinSandbox,\n createExecutor: (config, env) => new GondolinExecutor(config, env),\n};\n"]}
1
+ {"version":3,"file":"gondolin.js","sourceRoot":"","sources":["../../src/sandbox/gondolin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EACL,SAAS,EACT,SAAS,EACT,YAAY,EACZ,UAAU,EACV,MAAM,EACN,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,+BAA+B,EAC/B,YAAY,EACZ,kBAAkB,EAClB,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AAiCpB,MAAM,oBAAoB,GAAG,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAU,CAAC;AACjD,MAAM,WAAW,GAAG,sBAAsB,CAAC;AAE3C,4EAA4E;AAC5E,MAAM,2BAA2B,GAAG,IAAI,CAAC;AACzC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAExC;;;;;GAKG;AACH,MAAM,oBAAoB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE5C,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA2B,CAAC;AACpD,MAAM,WAAW,GAAG,IAAI,GAAG,EAAyB,CAAC;AACrD,IAAI,eAAe,GAAG,CAAC,CAAC;AACxB,IAAI,kBAAkB,GAAG,CAAC,CAAC;AA2C3B;;;;;;;GAOG;AAEH;;;GAGG;AACH,MAAM,wBAAyB,SAAQ,KAAK;CAAG;AA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AE,eAAe,CAAC,OAAO,CAAC;SACjC,CAAC,CACH,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,IAAY;QACzB,OAAO,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,IAAY;QAC/B,OAAO,kBAAkB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACxC,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,IAAY,EAAE,OAAe;QAC3C,OAAO,aAAa,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;IAED,gBAAgB;QACd,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,cAAc,CAAC,iBAAyB;QACtC,OAAO,+BAA+B,CAAC,iBAAiB,EAAE,YAAY,CAAC,CAAC;IAC1E,CAAC;IAED,gBAAgB;QACd,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,sBAAsB,GAA0C;IAC3E,IAAI,EAAE,UAAU;IAChB,WAAW,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,SAAS,EAAE,EAAE,iBAAiB,EAAE,IAAI,EAAE;IACtC,KAAK,EAAE,uBAAuB;IAC9B,QAAQ,EAAE,uBAAuB;IACjC,cAAc,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,IAAI,gBAAgB,CAAC,MAAM,EAAE,GAAG,CAAC;CACnE,CAAC","sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport * as log from \"../log.js\";\nimport type { ResourceLimits, SandboxLimitStatus, SandboxResourceController } from \"../types.js\";\nimport { withRuntimeBootstrap } from \"./container.js\";\nimport { SandboxError } from \"./errors.js\";\nimport {\n createMountedRuntimePathContext,\n execReadFile,\n execReadFileBase64,\n execWriteFile,\n shellEscape,\n} from \"./utils.js\";\nimport type * as GondolinNamespace from \"@earendil-works/gondolin\";\nimport type {\n ExecOptions,\n ExecResult,\n Executor,\n GondolinBootstrapOptions,\n GondolinSandboxConfig,\n RuntimePathContext,\n SandboxAdapter,\n SessionClient,\n SessionClientCallbacks,\n} from \"./types.js\";\n\nexport type { GondolinBootstrapOptions, SessionClient, SessionClientCallbacks } from \"./types.js\";\n\n/**\n * Single-host Gondolin sandbox: one microVM per conversation, created and\n * owned by this mikan process.\n *\n * Commands do not go through `vm.exec()` — aborting that only rejects the\n * local promise and leaves the guest process running. They go over Gondolin's\n * session IPC socket instead, one connection per command, so an abort or\n * timeout closes the connection and kills the command inside the guest.\n *\n * Runtimes die with mikan: Gondolin SIGKILLs its VM runners from a\n * `process.exit` hook, and shutdown closes them explicitly so projected files\n * sync back first. A `kill -9` of mikan itself skips both and leaks a runner.\n */\n\ntype GondolinModule = typeof GondolinNamespace;\ntype GondolinVm = InstanceType<GondolinModule[\"VM\"]>;\n\nconst MINIMUM_NODE_VERSION = [23, 6, 0] as const;\nconst MIKAN_IMAGE = \"mikan-sandbox:latest\";\n\n/** Write-back cadence for projected `/workspace` files (e.g. MEMORY.md). */\nconst PROJECTION_SYNC_INTERVAL_MS = 2000;\nconst PROJECTION_LOCK_RETRY_MS = 25;\nconst PROJECTION_LOCK_STALE_MS = 60_000;\n\n/**\n * A command may quietly work for a long time, but a session that produces no\n * frame at all for this long is indistinguishable from one wedged on dead\n * storage (for example, blocked guest workspace I/O) — kill it and say so\n * instead of hanging the run.\n */\nconst EXEC_IDLE_TIMEOUT_MS = 10 * 60 * 1000;\n\nconst sessions = new Map<string, GondolinSession>();\nconst transitions = new Map<string, Promise<void>>();\nlet activeShutdowns = 0;\nlet shutdownGeneration = 0;\n\ninterface GondolinSession {\n runtime: Promise<GondolinRuntime>;\n fingerprint: string;\n resourceKey?: string;\n activeOperations: number;\n lastUsed: number;\n idleWaiters: Array<() => void>;\n}\n\n/** A host directory or file offered to the guest. */\ninterface GondolinMount {\n source: string;\n target: string;\n /** Mounted through `ReadonlyProvider`; host-owned content the agent must not edit. */\n readOnly?: boolean;\n}\n\ninterface GondolinDesiredRuntime {\n image: string;\n imageIdentity: string;\n mounts: GondolinMount[];\n /** Content identity of projected credential files (rotation → drift). */\n credentialIdentity: Record<string, string>;\n limits?: ResourceLimits;\n}\n\n/**\n * A single-file mount handled outside the VFS: Gondolin's guest prepares every\n * VFS mount point with `mkdir -p`, so a file target can never bind (the guest\n * ends up bind-mounting a file onto a directory and the VM refuses to start).\n * Files are copied in after boot instead; the ones under /workspace sync guest\n * edits back to the host so agent-maintained files like MEMORY.md persist.\n */\ninterface FileProjection {\n source: string;\n target: string;\n syncBack: boolean;\n /** Hash of the guest content at the last successful or conflict sync. */\n lastHash: string;\n}\n\n/*\n * Crash-recovery vocabulary.\n *\n * - **Gone**: the command never reached the runtime because its session socket\n * refused the connection. Recreating the runtime and retrying is safe.\n * - **Interrupted**: the runtime died or went silent with a command in flight.\n * Side effects may have landed, so the failure must surface.\n */\n\n/**\n * The runtime is gone and the command never reached it (the session socket\n * refused the connection) — safe to recreate the runtime and retry.\n */\nclass GondolinRuntimeGoneError extends Error {}\n\n/** The runtime died with the command in flight — not safe to retry blindly. */\nclass GondolinRuntimeInterruptedError extends Error {}\n\nclass GondolinResourceManager implements SandboxResourceController {\n private defaultLimits?: ResourceLimits;\n private boostLimits?: ResourceLimits;\n private readonly boostedKeys = new Set<string>();\n private readonly overrideLimits = new Map<string, ResourceLimits>();\n\n configure(defaultLimits?: ResourceLimits, boostLimits?: ResourceLimits): void {\n this.defaultLimits = defaultLimits;\n this.boostLimits = boostLimits;\n this.boostedKeys.clear();\n this.overrideLimits.clear();\n }\n\n async boost(key: string): Promise<SandboxLimitStatus> {\n if (this.boostLimits?.cpus || this.boostLimits?.memory) {\n this.overrideLimits.delete(key);\n this.boostedKeys.add(key);\n }\n return this.getLimitStatus(key);\n }\n\n async setLimits(key: string, limits: ResourceLimits): Promise<SandboxLimitStatus> {\n this.boostedKeys.delete(key);\n this.overrideLimits.set(key, { ...this.defaultLimits, ...limits });\n return this.getLimitStatus(key);\n }\n\n getLimitStatus(key: string): SandboxLimitStatus {\n return { limits: this.effectiveLimits(key), boosted: this.boostedKeys.has(key) };\n }\n\n getDefaultLimits(): ResourceLimits | undefined {\n return this.defaultLimits;\n }\n\n getBoostLimits(): ResourceLimits | undefined {\n return this.boostLimits;\n }\n\n clear(key: string): void {\n this.boostedKeys.delete(key);\n this.overrideLimits.delete(key);\n }\n\n private effectiveLimits(key: string): ResourceLimits | undefined {\n const override = this.overrideLimits.get(key);\n if (override) return override;\n if (!this.boostedKeys.has(key)) return this.defaultLimits;\n return { ...this.defaultLimits, ...this.boostLimits };\n }\n}\n\nexport const gondolinResources = new GondolinResourceManager();\n\n/** Configure the Gondolin resource controller. */\nexport function configureGondolinRuntime(options: GondolinBootstrapOptions): void {\n gondolinResources.configure(options.limits, options.boostLimits);\n}\n\nfunction parseGondolinSandboxArg(value: string): GondolinSandboxConfig | undefined {\n if (!value.startsWith(\"gondolin:\")) return undefined;\n\n const profile = value.slice(\"gondolin:\".length);\n if (!profile) {\n throw new SandboxError(\"Error: gondolin sandbox requires a profile (e.g., gondolin:default)\");\n }\n if (profile !== \"default\") {\n throw new SandboxError(\n `Error: unsupported gondolin profile '${profile}'. Use 'gondolin:default'`,\n );\n }\n return { type: \"gondolin\", profile };\n}\n\nfunction assertSupportedNodeVersion(): void {\n const [major = 0, minor = 0] = process.versions.node.split(\".\").map(Number);\n if (major < MINIMUM_NODE_VERSION[0] || (major === MINIMUM_NODE_VERSION[0] && minor < 6)) {\n throw new SandboxError(\n `Error: gondolin:default requires Node.js >=23.6.0 (current: ${process.versions.node}). Other sandbox modes remain available on Node.js >=22.19.0.`,\n );\n }\n}\n\nasync function validateGondolinSandbox(): Promise<void> {\n assertSupportedNodeVersion();\n console.log(\" Gondolin microVM enabled. Profile: default\");\n}\n\nasync function resolveDesiredRuntime(\n config: GondolinSandboxConfig,\n): Promise<GondolinDesiredRuntime> {\n const selector = config.image ?? MIKAN_IMAGE;\n const { ensureImageSelector } = (await import(\"@earendil-works/gondolin\")) as GondolinModule;\n const resolvedImage = await ensureImageSelector(selector);\n const image = resolvedImage.assetDir;\n const imageIdentity = resolvedImage.buildId ?? resolvedImage.assetDir;\n const mounts = (\n config.mounts ?? [{ source: config.workspacePath ?? process.cwd(), target: \"/workspace\" }]\n ).toSorted((left, right) => left.target.localeCompare(right.target));\n return {\n image,\n imageIdentity,\n mounts,\n credentialIdentity: credentialIdentity(mounts),\n limits: config.resourceKey\n ? gondolinResources.getLimitStatus(config.resourceKey).limits\n : undefined,\n };\n}\n\n/**\n * Content hashes of credential file mounts (files projected outside\n * /workspace). Rotating a credential on the host changes the fingerprint, so\n * the next command recreates the runtime with a fresh projection instead of\n * serving the stale copy for the rest of the VM's life. Workspace files are\n * excluded: the guest writes them back, which would drift the runtime it runs\n * in.\n */\nfunction credentialIdentity(mounts: GondolinMount[]): Record<string, string> {\n const identity: Record<string, string> = {};\n for (const mount of mounts) {\n if (mount.target.startsWith(\"/workspace/\") || mount.target === \"/workspace\") continue;\n try {\n if (!statSync(mount.source).isFile()) continue;\n identity[mount.target] = createHash(\"sha256\")\n .update(readFileSync(mount.source))\n .digest(\"hex\");\n } catch {\n // missing source: creation skips it too, so it has no runtime identity\n }\n }\n return identity;\n}\n\nfunction runtimeFingerprint(desired: GondolinDesiredRuntime): string {\n return createHash(\"sha256\")\n .update(\n JSON.stringify({\n image: desired.imageIdentity,\n mounts: desired.mounts,\n credentials: desired.credentialIdentity,\n limits: desired.limits,\n }),\n )\n .digest(\"hex\");\n}\n\nfunction gondolinCpuCount(cpus: string | undefined): number | undefined {\n if (cpus === undefined) return undefined;\n const parsed = Number(cpus);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new SandboxError(`Error: invalid Gondolin CPU limit '${cpus}'`);\n }\n // ponytail: Gondolin exposes whole vCPUs; add host cgroup quotas if fractional enforcement matters.\n return Math.ceil(parsed);\n}\n\nfunction sha256(data: Buffer): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\nfunction partitionMounts(mounts: GondolinMount[]): {\n directories: GondolinMount[];\n files: FileProjection[];\n} {\n const directories: GondolinMount[] = [];\n const files: FileProjection[] = [];\n for (const mount of mounts) {\n let isDirectory: boolean;\n try {\n isDirectory = statSync(mount.source).isDirectory();\n } catch {\n log.logWarning(`Skipping missing Gondolin mount source ${mount.source}`);\n continue;\n }\n if (isDirectory) {\n directories.push(mount);\n } else {\n files.push({\n ...mount,\n syncBack: mount.target.startsWith(\"/workspace/\"),\n lastHash: \"\",\n });\n }\n }\n return { directories, files };\n}\n\n/** Copy file mounts into the guest; credentials get user-only permissions. */\nasync function projectFiles(vm: GondolinVm, files: FileProjection[]): Promise<void> {\n for (const projection of files) {\n const content = readFileSync(projection.source);\n await vm.fs.mkdir(dirname(projection.target), { recursive: true });\n await vm.fs.writeFile(projection.target, content);\n if (!projection.syncBack) {\n // credential projection: no write-back, keep it owner-only\n await vm.exec(`chmod 600 ${shellEscape(projection.target)}`);\n }\n projection.lastHash = sha256(content);\n }\n}\n\nfunction restrictSocketAccess(socketPath: string): void {\n // The session socket grants arbitrary exec inside the VM (and through its\n // mounts, the workspace) — keep it to this user even under a lax umask.\n try {\n chmodSync(dirname(socketPath), 0o700);\n chmodSync(socketPath, 0o600);\n } catch {\n // best-effort hardening\n }\n}\n\nfunction projectionLockIsStale(lockPath: string): boolean {\n let ownerKnown = false;\n let ownerAlive = false;\n try {\n const pid = Number(readFileSync(join(lockPath, \"owner\"), \"utf8\").trim());\n if (Number.isInteger(pid) && pid > 0) {\n ownerKnown = true;\n try {\n process.kill(pid, 0);\n ownerAlive = true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"EPERM\") ownerAlive = true;\n }\n }\n } catch {\n // An owner file may not have been written before its process died.\n }\n try {\n const oldEnough = Date.now() - statSync(lockPath).mtimeMs >= PROJECTION_LOCK_STALE_MS;\n return (ownerKnown && !ownerAlive) || oldEnough;\n } catch {\n return false;\n }\n}\n\nasync function withProjectionLock<T>(source: string, operation: () => Promise<T>): Promise<T> {\n const lockPath = `${source}.mikan-sync.lock`;\n for (;;) {\n try {\n mkdirSync(lockPath, { mode: 0o700 });\n writeFileSync(join(lockPath, \"owner\"), `${process.pid}\\n`, { mode: 0o600 });\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (projectionLockIsStale(lockPath)) {\n rmSync(lockPath, { recursive: true, force: true });\n continue;\n }\n await new Promise((resolve) => setTimeout(resolve, PROJECTION_LOCK_RETRY_MS));\n }\n }\n try {\n return await operation();\n } finally {\n rmSync(lockPath, { recursive: true, force: true });\n }\n}\n\n/** One live microVM owned by this process, addressed by its session socket. */\nclass GondolinRuntime {\n private syncTimer?: NodeJS.Timeout;\n private syncing = false;\n private closing?: Promise<void>;\n\n private constructor(\n private readonly vm: GondolinVm,\n private readonly socketPath: string,\n private readonly projections: FileProjection[],\n ) {}\n\n /** Boot a VM for the desired configuration and make it command-ready. */\n static async create(\n instanceId: string,\n desired: GondolinDesiredRuntime,\n ): Promise<GondolinRuntime> {\n const { VM, RealFSProvider, ReadonlyProvider, findSession } =\n (await import(\"@earendil-works/gondolin\")) as GondolinModule;\n const { directories, files } = partitionMounts(desired.mounts);\n const vm = await VM.create({\n sandbox: { imagePath: desired.image },\n env: { TZ: \"Asia/Taipei\" },\n sessionLabel: `mikan:${instanceId}`,\n cpus: gondolinCpuCount(desired.limits?.cpus),\n memory: desired.limits?.memory,\n vfs: {\n mounts: Object.fromEntries(\n directories.map(({ source, target, readOnly }) => [\n target,\n // ReadonlyProvider blocks every write operation on the backing\n // provider — gondolin's own answer to read-only host directories.\n readOnly\n ? new ReadonlyProvider(new RealFSProvider(source))\n : new RealFSProvider(source),\n ]),\n ),\n },\n });\n\n try {\n await vm.start();\n await projectFiles(vm, files);\n const session = await findSession(vm.id);\n if (!session) throw new Error(`Gondolin session '${vm.id}' did not register`);\n restrictSocketAccess(session.socketPath);\n const runtime = new GondolinRuntime(vm, session.socketPath, files);\n runtime.startProjectionSync();\n return runtime;\n } catch (error) {\n // never leave a half-booted runner (and its overlay disk) behind\n await vm.close().catch(() => {});\n throw error;\n }\n }\n\n /**\n * Run one command over a dedicated session IPC connection. Aborting (or the\n * caller's timeout signal firing) destroys the connection, which kills the\n * in-flight guest process.\n */\n async exec(\n command: string,\n options: { env?: Record<string, string>; signal?: AbortSignal } = {},\n ): Promise<ExecResult> {\n return execOverSessionConnect(\n async (callbacks) => {\n const { connectToSession } = await import(\"@earendil-works/gondolin\");\n return connectToSession(this.socketPath, callbacks);\n },\n command,\n options,\n );\n }\n\n /** Whether the VM runner process is still up. */\n isAlive(): boolean {\n try {\n return this.vm.getHostPid() !== null;\n } catch {\n return false;\n }\n }\n\n /** Sync projected files back one last time, then shut the VM down. */\n async close(): Promise<void> {\n this.closing ??= (async () => {\n clearInterval(this.syncTimer);\n try {\n await this.syncProjections();\n } catch {\n // best effort; the periodic sync already captured earlier edits\n }\n await this.vm.close();\n })();\n return this.closing;\n }\n\n private startProjectionSync(): void {\n if (!this.projections.some((projection) => projection.syncBack)) return;\n this.syncTimer = setInterval(() => void this.syncProjections(), PROJECTION_SYNC_INTERVAL_MS);\n this.syncTimer.unref?.();\n }\n\n private async syncProjections(): Promise<void> {\n if (this.syncing) return;\n this.syncing = true;\n try {\n for (const projection of this.projections) {\n if (!projection.syncBack) continue;\n try {\n const data = await this.vm.fs.readFile(projection.target);\n const content = Buffer.isBuffer(data) ? data : Buffer.from(String(data));\n const hash = sha256(content);\n if (hash === projection.lastHash) continue;\n await withProjectionLock(projection.source, async () => {\n let hostHash: string;\n try {\n hostHash = sha256(readFileSync(projection.source));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n hostHash = \"\";\n }\n if (hostHash !== projection.lastHash) {\n const conflict = `${projection.source}.mikan-conflict.${process.pid}.${randomBytes(8).toString(\"hex\")}`;\n writeFileSync(conflict, content);\n projection.lastHash = hash;\n log.logWarning(\n `Skipped Gondolin projection write-back for '${projection.source}': host content changed; guest content preserved at '${conflict}'`,\n );\n return;\n }\n // atomic host write: a crash mid-sync must not truncate the file\n const staged = `${projection.source}.mikan-sync.${process.pid}.${randomBytes(8).toString(\"hex\")}`;\n try {\n writeFileSync(staged, content);\n renameSync(staged, projection.source);\n projection.lastHash = hash;\n } finally {\n try {\n unlinkSync(staged);\n } catch {\n // rename succeeded or the staging write failed\n }\n }\n });\n } catch {\n // guest file missing or read raced a writer; next tick retries\n }\n }\n } finally {\n this.syncing = false;\n }\n }\n}\n\nfunction abortError(): Error {\n return new Error(\"Error: command aborted\");\n}\n\n/**\n * Run one command through a fresh session connection. Closing the connection\n * (abort, timeout, or the far side dying) kills the in-flight guest process.\n */\nexport async function execOverSessionConnect(\n connect: (callbacks: SessionClientCallbacks) => SessionClient | Promise<SessionClient>,\n command: string,\n options: { env?: Record<string, string>; signal?: AbortSignal; idleTimeoutMs?: number } = {},\n): Promise<ExecResult> {\n if (options.signal?.aborted) throw abortError();\n const idleTimeoutMs = options.idleTimeoutMs ?? EXEC_IDLE_TIMEOUT_MS;\n return await new Promise<ExecResult>((resolve, reject) => {\n let stdout = \"\";\n let stderr = \"\";\n let received = false;\n let settled = false;\n let client: SessionClient | undefined;\n let idleTimer: NodeJS.Timeout | undefined;\n const settle = (fn: () => void): void => {\n if (settled) return;\n settled = true;\n clearTimeout(idleTimer);\n options.signal?.removeEventListener(\"abort\", onAbort);\n fn();\n };\n const onAbort = (): void =>\n settle(() => {\n client?.close();\n reject(abortError());\n });\n const onIdle = (): void =>\n settle(() => {\n client?.close();\n reject(\n new GondolinRuntimeInterruptedError(\n `no session activity for ${Math.round(idleTimeoutMs / 1000)}s — killed the command ` +\n `(guest I/O hangs when the workspace sits on a dead mount; check the workspace health)`,\n ),\n );\n });\n const armIdleTimer = (): void => {\n if (idleTimeoutMs <= 0 || settled) return;\n clearTimeout(idleTimer);\n idleTimer = setTimeout(onIdle, idleTimeoutMs);\n idleTimer.unref?.();\n };\n armIdleTimer();\n const callbacks: SessionClientCallbacks = {\n onJson: (message) => {\n received = true;\n armIdleTimer();\n if (message.type === \"exec_response\" && message.id === 1) {\n settle(() => {\n client?.close();\n resolve({\n stdout,\n stderr,\n code: typeof message.exit_code === \"number\" ? message.exit_code : 1,\n });\n });\n } else if (message.type === \"error\") {\n settle(() => {\n client?.close();\n reject(new Error(`Error: Gondolin exec failed (${message.code}): ${message.message}`));\n });\n }\n },\n onBinary: (frame) => {\n received = true;\n armIdleTimer();\n const tag = frame.readUInt8(0);\n const data = frame.subarray(5).toString(\"utf8\");\n if (tag === 1) stdout += data;\n else stderr += data;\n },\n onClose: (error) => {\n settle(() => {\n const detail = error?.message ?? \"connection closed before the command finished\";\n const code = (error as NodeJS.ErrnoException | undefined)?.code;\n if (!received && (code === \"ENOENT\" || code === \"ECONNREFUSED\")) {\n reject(new GondolinRuntimeGoneError(detail));\n } else {\n reject(new GondolinRuntimeInterruptedError(detail));\n }\n });\n },\n };\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n Promise.resolve(connect(callbacks))\n .then((created) => {\n client = created;\n if (settled) {\n created.close();\n return;\n }\n created.send({\n type: \"exec\",\n id: 1,\n cmd: \"/bin/sh\",\n argv: [\"-c\", command],\n env: Object.entries(options.env ?? {}).map(([key, value]) => `${key}=${value}`),\n cwd: \"/workspace\",\n });\n })\n .catch((err: unknown) =>\n settle(() =>\n reject(new GondolinRuntimeGoneError(err instanceof Error ? err.message : String(err))),\n ),\n );\n });\n}\n\nfunction createSession(\n key: string,\n config: GondolinSandboxConfig,\n desired: GondolinDesiredRuntime,\n fingerprint: string,\n): GondolinSession {\n let session: GondolinSession;\n const runtime = GondolinRuntime.create(key, desired).catch((error: unknown) => {\n if (sessions.get(key) === session) sessions.delete(key);\n throw error;\n });\n session = {\n runtime,\n fingerprint,\n resourceKey: config.resourceKey,\n activeOperations: 0,\n lastUsed: Date.now(),\n idleWaiters: [],\n };\n return session;\n}\n\nasync function acquireSession(\n key: string,\n config: GondolinSandboxConfig,\n generation = shutdownGeneration,\n): Promise<GondolinSession> {\n if (activeShutdowns > 0 || generation !== shutdownGeneration) {\n throw new SandboxError(\"Error: Gondolin runtime is shutting down\");\n }\n\n const pending = transitions.get(key);\n if (pending) {\n await pending;\n return acquireSession(key, config, generation);\n }\n\n const desired = await resolveDesiredRuntime(config);\n if (activeShutdowns > 0 || generation !== shutdownGeneration) {\n throw new SandboxError(\"Error: Gondolin runtime is shutting down\");\n }\n const concurrentTransition = transitions.get(key);\n if (concurrentTransition) {\n await concurrentTransition;\n return acquireSession(key, config, generation);\n }\n\n const fingerprint = runtimeFingerprint(desired);\n const existing = sessions.get(key);\n if (existing?.fingerprint === fingerprint) {\n existing.activeOperations += 1;\n return existing;\n }\n\n const transition = replaceSession(key, config, desired, fingerprint, existing);\n transitions.set(key, transition);\n try {\n await transition;\n } finally {\n if (transitions.get(key) === transition) transitions.delete(key);\n }\n return acquireSession(key, config, generation);\n}\n\nasync function replaceSession(\n key: string,\n config: GondolinSandboxConfig,\n desired: GondolinDesiredRuntime,\n fingerprint: string,\n existing: GondolinSession | undefined,\n): Promise<void> {\n if (existing) {\n await closeSession(key, existing, {\n waitForActiveOperations: true,\n resetResources: false,\n throwOnError: true,\n });\n }\n const replacement = createSession(key, config, desired, fingerprint);\n sessions.set(key, replacement);\n await replacement.runtime;\n}\n\nfunction discardDeadSession(key: string, session: GondolinSession): void {\n if (sessions.get(key) !== session) return;\n sessions.delete(key);\n log.logWarning(`Gondolin runtime for '${key}' died; the session will be recreated`);\n}\n\nasync function withRuntime<T>(\n key: string,\n config: GondolinSandboxConfig,\n operation: (runtime: GondolinRuntime) => Promise<T>,\n): Promise<T> {\n for (let attempt = 0; ; attempt += 1) {\n const session = await acquireSession(key, config);\n let runtime: GondolinRuntime | undefined;\n try {\n runtime = await session.runtime;\n return await operation(runtime);\n } catch (error) {\n const gone = error instanceof GondolinRuntimeGoneError;\n const interrupted = error instanceof GondolinRuntimeInterruptedError;\n if (gone || (interrupted && runtime && !runtime.isAlive())) {\n discardDeadSession(key, session);\n }\n // Nothing reached a gone runtime, so recreating and retrying is safe;\n // an interrupted command may have side effects and must surface.\n if (gone && attempt === 0) continue;\n if (gone || interrupted) {\n throw new SandboxError(\n `Error: Gondolin runtime for '${key}' died (${(error as Error).message}); it is recreated on the next command`,\n );\n }\n throw error;\n } finally {\n session.activeOperations -= 1;\n session.lastUsed = Date.now();\n if (session.activeOperations === 0) {\n for (const resolve of session.idleWaiters.splice(0)) resolve();\n }\n }\n }\n}\n\nfunction waitForIdle(session: GondolinSession): Promise<void> {\n if (session.activeOperations === 0) return Promise.resolve();\n return new Promise((resolve) => session.idleWaiters.push(resolve));\n}\n\nasync function closeSession(\n key: string,\n session: GondolinSession,\n options: {\n waitForActiveOperations?: boolean;\n resetResources?: boolean;\n throwOnError?: boolean;\n } = {},\n): Promise<void> {\n if (sessions.get(key) !== session) return;\n sessions.delete(key);\n try {\n if (options.waitForActiveOperations) await waitForIdle(session);\n const runtime = await session.runtime;\n await runtime.close();\n if (\n options.resetResources !== false &&\n session.resourceKey &&\n !Array.from(sessions.values()).some(({ resourceKey }) => resourceKey === session.resourceKey)\n ) {\n gondolinResources.clear(session.resourceKey);\n }\n } catch (error) {\n session.fingerprint = \"\";\n // Re-track for a retried close, unless a replacement already claimed the\n // key — then the failed runtime stays for the reconcile paths and\n // clobbering the replacement would leak it too.\n if (!sessions.has(key)) sessions.set(key, session);\n if (options.throwOnError) throw error;\n log.logWarning(\n `Failed to close Gondolin session '${key}'`,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\nexport async function stopIdleGondolinVms(maxIdleMs: number, now = Date.now()): Promise<void> {\n const idle = Array.from(sessions.entries()).filter(\n ([key, session]) =>\n !transitions.has(key) &&\n session.activeOperations === 0 &&\n now - session.lastUsed >= maxIdleMs,\n );\n await Promise.all(\n idle.map(([key, session]) => {\n // Register the close as a transition so a concurrent acquire waits for\n // it instead of racing the shared session slot.\n const transition = closeSession(key, session).finally(() => {\n if (transitions.get(key) === transition) transitions.delete(key);\n });\n transitions.set(key, transition);\n return transition;\n }),\n );\n}\n\n/**\n * Drop Gondolin's registry entries for sessions that no longer answer — socket\n * files and metadata left behind by a mikan that died without cleanup.\n */\nexport async function reconcileGondolinRuntimes(): Promise<void> {\n try {\n const { gcSessions } = (await import(\"@earendil-works/gondolin\")) as GondolinModule;\n const collected = await gcSessions();\n log.logInfo(`Reconciled Gondolin sessions (collected=${collected})`);\n } catch (error) {\n log.logWarning(\n \"Failed to collect Gondolin session registry\",\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * Stop every runtime this process owns. Runtimes do not outlive mikan, so\n * shutdown must close them: that syncs projected files back to the host and\n * releases each VM's overlay disk before the process exits.\n */\nexport async function stopAllGondolinRuntimes(): Promise<void> {\n shutdownGeneration += 1;\n activeShutdowns += 1;\n try {\n await Promise.allSettled(transitions.values());\n const current = Array.from(sessions.entries());\n await Promise.all(\n current.map(([key, session]) =>\n closeSession(key, session, { waitForActiveOperations: true }),\n ),\n );\n } finally {\n activeShutdowns -= 1;\n }\n}\n\nfunction executionSignal(options?: ExecOptions): AbortSignal | undefined {\n const signals = [options?.signal];\n if (options?.timeout && options.timeout > 0) {\n signals.push(AbortSignal.timeout(options.timeout * 1000));\n }\n const active = signals.filter((signal): signal is AbortSignal => signal !== undefined);\n return active.length > 0 ? AbortSignal.any(active) : undefined;\n}\n\nexport class GondolinExecutor implements Executor {\n private readonly workspacePath: string;\n private readonly instanceId: string;\n\n constructor(\n private readonly config: GondolinSandboxConfig,\n private readonly env?: Record<string, string>,\n ) {\n assertSupportedNodeVersion();\n this.workspacePath = config.workspacePath ?? process.cwd();\n this.instanceId = config.instanceId ?? this.workspacePath;\n }\n\n async exec(command: string, options?: ExecOptions): Promise<ExecResult> {\n return withRuntime(this.instanceId, this.config, (runtime) =>\n runtime.exec(withRuntimeBootstrap(command, this.env), {\n env: this.env,\n signal: executionSignal(options),\n }),\n );\n }\n\n async readFile(path: string): Promise<string> {\n return execReadFile(this, path);\n }\n\n async readFileBase64(path: string): Promise<string> {\n return execReadFileBase64(this, path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n return execWriteFile(this, path, content);\n }\n\n getWorkspacePath(): string {\n return \"/workspace\";\n }\n\n getPathContext(hostWorkspaceRoot: string): RuntimePathContext {\n return createMountedRuntimePathContext(hostWorkspaceRoot, \"/workspace\");\n }\n\n getSandboxConfig(): GondolinSandboxConfig {\n return this.config;\n }\n}\n\nexport const gondolinSandboxAdapter: SandboxAdapter<GondolinSandboxConfig> = {\n type: \"gondolin\",\n credentials: { env: true, fileMounts: true },\n workspace: { managedProjection: true },\n parse: parseGondolinSandboxArg,\n validate: validateGondolinSandbox,\n createExecutor: (config, env) => new GondolinExecutor(config, env),\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../../src/sandbox/host.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,QAAQ,EACR,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACf,MAAM,YAAY,CAAC;AAWpB,qBAAa,YAAa,YAAW,QAAQ;IACrC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAuEtE;IAEK,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAE5C;IAEK,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAElD;IAEK,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAK5D;IAED,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzC;IAED,cAAc,CAAC,iBAAiB,EAAE,MAAM,GAAG,kBAAkB,CAE5D;IAED,gBAAgB,IAAI,iBAAiB,CAEpC;CACF;AAED,eAAO,MAAM,kBAAkB,EAAE,cAAc,CAAC,iBAAiB,CAMhE,CAAC"}
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../../src/sandbox/host.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,QAAQ,EACR,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACf,MAAM,YAAY,CAAC;AAUpB,qBAAa,YAAa,YAAW,QAAQ;IACrC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAuEtE;IAEK,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAE5C;IAEK,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAElD;IAEK,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAK5D;IAED,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzC;IAED,cAAc,CAAC,iBAAiB,EAAE,MAAM,GAAG,kBAAkB,CAE5D;IAED,gBAAgB,IAAI,iBAAiB,CAEpC;CACF;AAED,eAAO,MAAM,kBAAkB,EAAE,cAAc,CAAC,iBAAiB,CAMhE,CAAC"}
@@ -1,8 +1,7 @@
1
- import { spawn } from "child_process";
2
- import { mkdir, readFile, rename, writeFile } from "fs/promises";
3
- import { dirname } from "path";
4
- import { killProcessTree } from "./utils.js";
5
- import { createMountedRuntimePathContext } from "./path-context.js";
1
+ import { spawn } from "node:child_process";
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { createMountedRuntimePathContext, killProcessTree } from "./utils.js";
6
5
  function parseHostSandboxArg(value) {
7
6
  if (value === "host") {
8
7
  return { type: "host" };
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","sourceRoot":"","sources":["../../src/sandbox/host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAS/B,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AAEpE,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QACrB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAC1B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,OAAO,YAAY;IACvB,KAAK,CAAC,IAAI,CAAC,OAAe,EAAE,OAAqB;QAC/C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,KAAK,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;YAC1D,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAEjE,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,GAAG,SAAS,EAAE,OAAO,CAAC,EAAE;gBAClD,QAAQ,EAAE,IAAI;gBACd,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC;aAClC,CAAC,C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,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACnD,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,IAAY,EAAE,OAAe;QAC3C,MAAM,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAChD,MAAM,KAAK,GAAG,GAAG,IAAI,cAAc,CAAC;QACpC,MAAM,SAAS,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QACzC,MAAM,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED,gBAAgB,CAAC,QAAgB;QAC/B,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,cAAc,CAAC,iBAAyB;QACtC,OAAO,+BAA+B,CAAC,iBAAiB,EAAE,iBAAiB,CAAC,CAAC;IAC/E,CAAC;IAED,gBAAgB;QACd,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAsC;IACnE,IAAI,EAAE,MAAM;IACZ,WAAW,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE;IAC9C,SAAS,EAAE,EAAE,iBAAiB,EAAE,KAAK,EAAE;IACvC,KAAK,EAAE,mBAAmB;IAC1B,cAAc,EAAE,GAAG,EAAE,CAAC,IAAI,YAAY,EAAE;CACzC,CAAC","sourcesContent":["import { spawn } from \"child_process\";\nimport { mkdir, readFile, rename, writeFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport type {\n ExecOptions,\n ExecResult,\n Executor,\n HostSandboxConfig,\n RuntimePathContext,\n SandboxAdapter,\n} from \"./types.js\";\nimport { killProcessTree } from \"./utils.js\";\nimport { createMountedRuntimePathContext } from \"./path-context.js\";\n\nfunction parseHostSandboxArg(value: string): HostSandboxConfig | undefined {\n if (value === \"host\") {\n return { type: \"host\" };\n }\n return undefined;\n}\n\nexport class HostExecutor implements Executor {\n async exec(command: string, options?: ExecOptions): Promise<ExecResult> {\n return new Promise((resolve, reject) => {\n const shell = process.platform === \"win32\" ? \"cmd\" : \"sh\";\n const shellArgs = process.platform === \"win32\" ? [\"/c\"] : [\"-c\"];\n\n const child = spawn(shell, [...shellArgs, command], {\n detached: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n\n const timeoutHandle =\n options?.timeout && options.timeout > 0\n ? setTimeout(() => {\n timedOut = true;\n killProcessTree(child.pid!);\n }, options.timeout * 1000)\n : undefined;\n\n const onAbort = () => {\n if (child.pid) killProcessTree(child.pid);\n };\n\n if (options?.signal) {\n if (options.signal.aborted) {\n onAbort();\n } else {\n options.signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n }\n\n child.stdout?.on(\"data\", (data) => {\n stdout += data.toString();\n if (stdout.length > 10 * 1024 * 1024) {\n stdout = stdout.slice(0, 10 * 1024 * 1024);\n }\n });\n\n child.stderr?.on(\"data\", (data) => {\n stderr += data.toString();\n if (stderr.length > 10 * 1024 * 1024) {\n stderr = stderr.slice(0, 10 * 1024 * 1024);\n }\n });\n\n child.on(\"close\", (code) => {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n if (options?.signal) {\n options.signal.removeEventListener(\"abort\", onAbort);\n }\n\n if (options?.signal?.aborted) {\n reject(new Error(`${stdout}\\n${stderr}\\nCommand aborted`.trim()));\n return;\n }\n\n if (timedOut) {\n reject(\n new Error(\n `${stdout}\\n${stderr}\\nCommand timed out after ${options?.timeout} seconds`.trim(),\n ),\n );\n return;\n }\n\n resolve({ stdout, stderr, code: code ?? 0 });\n });\n });\n }\n\n async readFile(path: string): Promise<string> {\n return readFile(path, \"utf-8\");\n }\n\n async readFileBase64(path: string): Promise<string> {\n return (await readFile(path)).toString(\"base64\");\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const stage = `${path}.mikan-stage`;\n await writeFile(stage, content, \"utf-8\");\n await rename(stage, path);\n }\n\n getWorkspacePath(hostPath: string): string {\n return hostPath;\n }\n\n getPathContext(hostWorkspaceRoot: string): RuntimePathContext {\n return createMountedRuntimePathContext(hostWorkspaceRoot, hostWorkspaceRoot);\n }\n\n getSandboxConfig(): HostSandboxConfig {\n return { type: \"host\" };\n }\n}\n\nexport const hostSandboxAdapter: SandboxAdapter<HostSandboxConfig> = {\n type: \"host\",\n credentials: { env: false, fileMounts: false },\n workspace: { managedProjection: false },\n parse: parseHostSandboxArg,\n createExecutor: () => new HostExecutor(),\n};\n"]}
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../../src/sandbox/host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AASpC,OAAO,EAAE,+BAA+B,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE9E,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QACrB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAC1B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,OAAO,YAAY;IACvB,KAAK,CAAC,IAAI,CAAC,OAAe,EAAE,OAAqB;QAC/C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,KAAK,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;YAC1D,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,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ises\";\nimport { dirname } from \"node:path\";\nimport type {\n ExecOptions,\n ExecResult,\n Executor,\n HostSandboxConfig,\n RuntimePathContext,\n SandboxAdapter,\n} from \"./types.js\";\nimport { createMountedRuntimePathContext, killProcessTree } from \"./utils.js\";\n\nfunction parseHostSandboxArg(value: string): HostSandboxConfig | undefined {\n if (value === \"host\") {\n return { type: \"host\" };\n }\n return undefined;\n}\n\nexport class HostExecutor implements Executor {\n async exec(command: string, options?: ExecOptions): Promise<ExecResult> {\n return new Promise((resolve, reject) => {\n const shell = process.platform === \"win32\" ? \"cmd\" : \"sh\";\n const shellArgs = process.platform === \"win32\" ? [\"/c\"] : [\"-c\"];\n\n const child = spawn(shell, [...shellArgs, command], {\n detached: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n\n const timeoutHandle =\n options?.timeout && options.timeout > 0\n ? setTimeout(() => {\n timedOut = true;\n killProcessTree(child.pid!);\n }, options.timeout * 1000)\n : undefined;\n\n const onAbort = () => {\n if (child.pid) killProcessTree(child.pid);\n };\n\n if (options?.signal) {\n if (options.signal.aborted) {\n onAbort();\n } else {\n options.signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n }\n\n child.stdout?.on(\"data\", (data) => {\n stdout += data.toString();\n if (stdout.length > 10 * 1024 * 1024) {\n stdout = stdout.slice(0, 10 * 1024 * 1024);\n }\n });\n\n child.stderr?.on(\"data\", (data) => {\n stderr += data.toString();\n if (stderr.length > 10 * 1024 * 1024) {\n stderr = stderr.slice(0, 10 * 1024 * 1024);\n }\n });\n\n child.on(\"close\", (code) => {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n if (options?.signal) {\n options.signal.removeEventListener(\"abort\", onAbort);\n }\n\n if (options?.signal?.aborted) {\n reject(new Error(`${stdout}\\n${stderr}\\nCommand aborted`.trim()));\n return;\n }\n\n if (timedOut) {\n reject(\n new Error(\n `${stdout}\\n${stderr}\\nCommand timed out after ${options?.timeout} seconds`.trim(),\n ),\n );\n return;\n }\n\n resolve({ stdout, stderr, code: code ?? 0 });\n });\n });\n }\n\n async readFile(path: string): Promise<string> {\n return readFile(path, \"utf-8\");\n }\n\n async readFileBase64(path: string): Promise<string> {\n return (await readFile(path)).toString(\"base64\");\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const stage = `${path}.mikan-stage`;\n await writeFile(stage, content, \"utf-8\");\n await rename(stage, path);\n }\n\n getWorkspacePath(hostPath: string): string {\n return hostPath;\n }\n\n getPathContext(hostWorkspaceRoot: string): RuntimePathContext {\n return createMountedRuntimePathContext(hostWorkspaceRoot, hostWorkspaceRoot);\n }\n\n getSandboxConfig(): HostSandboxConfig {\n return { type: \"host\" };\n }\n}\n\nexport const hostSandboxAdapter: SandboxAdapter<HostSandboxConfig> = {\n type: \"host\",\n credentials: { env: false, fileMounts: false },\n workspace: { managedProjection: false },\n parse: parseHostSandboxArg,\n createExecutor: () => new HostExecutor(),\n};\n"]}
@@ -5,7 +5,7 @@ import { HostExecutor, hostSandboxAdapter } from "./host.js";
5
5
  import { imageSandboxAdapter } from "./image.js";
6
6
  import { GondolinExecutor, gondolinSandboxAdapter } from "./gondolin.js";
7
7
  import { SandboxError } from "./errors.js";
8
- import { createMountedRuntimePathContext } from "./path-context.js";
8
+ import { createMountedRuntimePathContext } from "./utils.js";
9
9
  export { configureGondolinRuntime } from "./gondolin.js";
10
10
  export { CloudflareSandboxExecutor, ContainerExecutor, FirecrackerExecutor, HostExecutor, GondolinExecutor, };
11
11
  export { SandboxError } from "./errors.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,yBA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OAAO,GAAG,oBAAoB,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtD,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,YAAY,CAAC,oCAAoC,MAAM,CAAC,IAAI,GAAG,CAAC,CAAC;IAC7E,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,CAAC;QAC5B,MAAM,IAAI,YAAY,CAAC,oEAAoE,CAAC,CAAC;IAC/F,CAAC;IACD,OAAO,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;AAC1D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAC7C,aAA4B,EAC5B,iBAAyB;IAEzB,IAAI,aAAa,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACnC,OAAO,+BAA+B,CAAC,iBAAiB,EAAE,YAAY,CAAC,CAAC;IAC1E,CAAC;IAED,OAAO,cAAc,CAAC,aAAa,CAAC,CAAC,cAAc,CAAC,iBAAiB,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { ContainerExecutor, containerSandboxAdapter } from \"./container.js\";\nimport { FirecrackerExecutor, firecrackerSandboxAdapter } from \"./firecracker.js\";\nimport { CloudflareSandboxExecutor, cloudflareSandboxAdapter } from \"./cloudflare.js\";\nimport { HostExecutor, hostSandboxAdapter } from \"./host.js\";\nimport { imageSandboxAdapter } from \"./image.js\";\nimport { GondolinExecutor, gondolinSandboxAdapter } from \"./gondolin.js\";\nimport { SandboxError } from \"./errors.js\";\nimport { createMountedRuntimePathContext } from \"./path-context.js\";\nexport { configureGondolinRuntime } from \"./gondolin.js\";\nexport type { GondolinBootstrapOptions } from \"./types.js\";\nimport type { Executor, RuntimePathContext, SandboxAdapter, SandboxConfig } from \"./types.js\";\n\nexport type {\n CloudflareSandboxConfig,\n ExecOptions,\n ExecResult,\n Executor,\n RuntimePathContext,\n SandboxAdapter,\n SandboxConfig,\n} from \"./types.js\";\nexport {\n CloudflareSandboxExecutor,\n ContainerExecutor,\n FirecrackerExecutor,\n HostExecutor,\n GondolinExecutor,\n};\nexport { SandboxError } from \"./errors.js\";\n\nconst sandboxAdapters = [\n hostSandboxAdapter,\n containerSandboxAdapter,\n imageSandboxAdapter,\n gondolinSandboxAdapter,\n firecrackerSandboxAdapter,\n cloudflareSandboxAdapter,\n] as const;\nconst sandboxAdapterByType = new Map(\n sandboxAdapters.map((adapter) => [adapter.type, adapter]),\n) as Map<SandboxConfig[\"type\"], SandboxAdapter>;\n\nexport function getSandboxAdapters(): readonly [...typeof sandboxAdapters] {\n return sandboxAdapters;\n}\n\nexport function getSandboxCredentialCapabilities(\n type: SandboxConfig[\"type\"],\n): SandboxAdapter[\"credentials\"] {\n const adapter = sandboxAdapterByType.get(type);\n if (!adapter) throw new SandboxError(`Error: Unsupported sandbox type '${type}'`);\n return adapter.credentials;\n}\n\nexport function getSandboxWorkspaceCapabilities(\n type: SandboxConfig[\"type\"],\n): SandboxAdapter[\"workspace\"] {\n const adapter = sandboxAdapterByType.get(type);\n if (!adapter) throw new SandboxError(`Error: Unsupported sandbox type '${type}'`);\n return adapter.workspace;\n}\n\nexport function assertSandboxSupportsWorkspacePolicy(\n sandboxConfig: SandboxConfig,\n doorPolicy: \"isolated\" | \"trusted\",\n): void {\n if (\n doorPolicy === \"isolated\" &&\n !getSandboxWorkspaceCapabilities(sandboxConfig.type).managedProjection\n ) {\n throw new SandboxError(\n `Sandbox '${sandboxConfig.type}' cannot provide an isolated conversation office; use image:* or gondolin:default, or explicitly choose trusted workspace policy`,\n );\n }\n}\n\nexport function parseSandboxArg(value: string): SandboxConfig {\n for (const adapter of sandboxAdapters) {\n const config = adapter.parse(value);\n if (config) {\n return config;\n }\n }\n\n if (value.startsWith(\"docker:\")) {\n throw new SandboxError(\n `Error: '${value}' is not supported. Use 'container:<container-name>' for the shared-container mode or 'image:<image-name>' for mikan-managed per-user containers.`,\n );\n }\n\n throw new SandboxError(\n `Error: Invalid sandbox type '${value}'. Use 'host', 'container:<container-name>', 'image:<image-name>', 'gondolin:default', 'firecracker:<vm-id>:<host-path>', or 'cloudflare:<sandbox-id>'`,\n );\n}\n\nexport async function validateSandbox(config: SandboxConfig): Promise<void> {\n const adapter = sandboxAdapterByType.get(config.type);\n if (!adapter) {\n throw new SandboxError(`Error: Unsupported sandbox type '${config.type}'`);\n }\n\n await adapter.validate?.(config);\n}\n\n/**\n * Create an executor that runs commands on host, in Docker, in a microVM, in a Firecracker VM, or through a Cloudflare sandbox bridge.\n */\nexport function createExecutor(\n config: SandboxConfig,\n env?: Record<string, string>,\n ensureReady?: () => Promise<void>,\n): Executor {\n const adapter = sandboxAdapterByType.get(config.type);\n if (!adapter) {\n throw new SandboxError(`Error: Unsupported sandbox type '${config.type}'`);\n }\n if (!adapter.createExecutor) {\n throw new SandboxError(\"Error: image sandbox must resolve to a concrete container executor\");\n }\n return adapter.createExecutor(config, env, ensureReady);\n}\n\n/**\n * The runtime path context for a sandbox config before an actor-specific\n * executor is resolved. `image` configs are unresolved by nature (the actor\n * decides the concrete container), but their mount layout is fixed, so path\n * mapping is known without resolving.\n */\nexport function getUnresolvedSandboxPathContext(\n sandboxConfig: SandboxConfig,\n hostWorkspaceRoot: string,\n): RuntimePathContext {\n if (sandboxConfig.type === \"image\") {\n return createMountedRuntimePathContext(hostWorkspaceRoot, \"/workspace\");\n }\n\n return createExecutor(sandboxConfig).getPathContext(hostWorkspaceRoot);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AACtF,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,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,EAAE,CAAC;QACb,MAAM,IAAI,YAAY,CAAC,oCAAoC,MAAM,CAAC,IAAI,GAAG,CAAC,CAAC;IAC7E,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,CAAC;QAC5B,MAAM,IAAI,YAAY,CAAC,oEAAoE,CAAC,CAAC;IAC/F,CAAC;IACD,OAAO,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;AAC1D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAC7C,aAA4B,EAC5B,iBAAyB;IAEzB,IAAI,aAAa,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACnC,OAAO,+BAA+B,CAAC,iBAAiB,EAAE,YAAY,CAAC,CAAC;IAC1E,CAAC;IAED,OAAO,cAAc,CAAC,aAAa,CAAC,CAAC,cAAc,CAAC,iBAAiB,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { ContainerExecutor, containerSandboxAdapter } from \"./container.js\";\nimport { FirecrackerExecutor, firecrackerSandboxAdapter } from \"./firecracker.js\";\nimport { CloudflareSandboxExecutor, cloudflareSandboxAdapter } from \"./cloudflare.js\";\nimport { HostExecutor, hostSandboxAdapter } from \"./host.js\";\nimport { imageSandboxAdapter } from \"./image.js\";\nimport { GondolinExecutor, gondolinSandboxAdapter } from \"./gondolin.js\";\nimport { SandboxError } from \"./errors.js\";\nimport { createMountedRuntimePathContext } from \"./utils.js\";\nexport { configureGondolinRuntime } from \"./gondolin.js\";\nexport type { GondolinBootstrapOptions } from \"./types.js\";\nimport type { Executor, RuntimePathContext, SandboxAdapter, SandboxConfig } from \"./types.js\";\n\nexport type {\n CloudflareSandboxConfig,\n ExecOptions,\n ExecResult,\n Executor,\n RuntimePathContext,\n SandboxAdapter,\n SandboxConfig,\n} from \"./types.js\";\nexport {\n CloudflareSandboxExecutor,\n ContainerExecutor,\n FirecrackerExecutor,\n HostExecutor,\n GondolinExecutor,\n};\nexport { SandboxError } from \"./errors.js\";\n\nconst sandboxAdapters = [\n hostSandboxAdapter,\n containerSandboxAdapter,\n imageSandboxAdapter,\n gondolinSandboxAdapter,\n firecrackerSandboxAdapter,\n cloudflareSandboxAdapter,\n] as const;\nconst sandboxAdapterByType = new Map(\n sandboxAdapters.map((adapter) => [adapter.type, adapter]),\n) as Map<SandboxConfig[\"type\"], SandboxAdapter>;\n\nexport function getSandboxAdapters(): readonly [...typeof sandboxAdapters] {\n return sandboxAdapters;\n}\n\nexport function getSandboxCredentialCapabilities(\n type: SandboxConfig[\"type\"],\n): SandboxAdapter[\"credentials\"] {\n const adapter = sandboxAdapterByType.get(type);\n if (!adapter) throw new SandboxError(`Error: Unsupported sandbox type '${type}'`);\n return adapter.credentials;\n}\n\nexport function getSandboxWorkspaceCapabilities(\n type: SandboxConfig[\"type\"],\n): SandboxAdapter[\"workspace\"] {\n const adapter = sandboxAdapterByType.get(type);\n if (!adapter) throw new SandboxError(`Error: Unsupported sandbox type '${type}'`);\n return adapter.workspace;\n}\n\nexport function assertSandboxSupportsWorkspacePolicy(\n sandboxConfig: SandboxConfig,\n doorPolicy: \"isolated\" | \"trusted\",\n): void {\n if (\n doorPolicy === \"isolated\" &&\n !getSandboxWorkspaceCapabilities(sandboxConfig.type).managedProjection\n ) {\n throw new SandboxError(\n `Sandbox '${sandboxConfig.type}' cannot provide an isolated conversation office; use image:* or gondolin:default, or explicitly choose trusted workspace policy`,\n );\n }\n}\n\nexport function parseSandboxArg(value: string): SandboxConfig {\n for (const adapter of sandboxAdapters) {\n const config = adapter.parse(value);\n if (config) {\n return config;\n }\n }\n\n if (value.startsWith(\"docker:\")) {\n throw new SandboxError(\n `Error: '${value}' is not supported. Use 'container:<container-name>' for the shared-container mode or 'image:<image-name>' for mikan-managed per-user containers.`,\n );\n }\n\n throw new SandboxError(\n `Error: Invalid sandbox type '${value}'. Use 'host', 'container:<container-name>', 'image:<image-name>', 'gondolin:default', 'firecracker:<vm-id>:<host-path>', or 'cloudflare:<sandbox-id>'`,\n );\n}\n\nexport async function validateSandbox(config: SandboxConfig): Promise<void> {\n const adapter = sandboxAdapterByType.get(config.type);\n if (!adapter) {\n throw new SandboxError(`Error: Unsupported sandbox type '${config.type}'`);\n }\n\n await adapter.validate?.(config);\n}\n\n/**\n * Create an executor that runs commands on host, in Docker, in a microVM, in a Firecracker VM, or through a Cloudflare sandbox bridge.\n */\nexport function createExecutor(\n config: SandboxConfig,\n env?: Record<string, string>,\n ensureReady?: () => Promise<void>,\n): Executor {\n const adapter = sandboxAdapterByType.get(config.type);\n if (!adapter) {\n throw new SandboxError(`Error: Unsupported sandbox type '${config.type}'`);\n }\n if (!adapter.createExecutor) {\n throw new SandboxError(\"Error: image sandbox must resolve to a concrete container executor\");\n }\n return adapter.createExecutor(config, env, ensureReady);\n}\n\n/**\n * The runtime path context for a sandbox config before an actor-specific\n * executor is resolved. `image` configs are unresolved by nature (the actor\n * decides the concrete container), but their mount layout is fixed, so path\n * mapping is known without resolving.\n */\nexport function getUnresolvedSandboxPathContext(\n sandboxConfig: SandboxConfig,\n hostWorkspaceRoot: string,\n): RuntimePathContext {\n if (sandboxConfig.type === \"image\") {\n return createMountedRuntimePathContext(hostWorkspaceRoot, \"/workspace\");\n }\n\n return createExecutor(sandboxConfig).getPathContext(hostWorkspaceRoot);\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { RuntimePathContext } from "./types.js";
1
2
  export declare function execSimple(cmd: string, args: string[]): Promise<string>;
2
3
  export declare function killProcessTree(pid: number): void;
3
4
  export declare function shellEscape(s: string): string;
@@ -12,5 +13,6 @@ interface ExecLike<TOptions> {
12
13
  export declare function execReadFileBase64<TOptions>(executor: ExecLike<TOptions>, path: string, options?: TOptions): Promise<string>;
13
14
  export declare function execReadFile<TOptions>(executor: ExecLike<TOptions>, path: string, options?: TOptions): Promise<string>;
14
15
  export declare function execWriteFile<TOptions>(executor: ExecLike<TOptions>, path: string, content: string, options?: TOptions): Promise<void>;
16
+ export declare function createMountedRuntimePathContext(hostWorkspaceRoot: string, runtimeWorkspaceRoot: string): RuntimePathContext;
15
17
  export {};
16
18
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/sandbox/utils.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBvE;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAqBjD;AAED,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAG7C;AAWD,UAAU,cAAc;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CACd;AAED,UAAU,QAAQ,CAAC,QAAQ;IACzB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;CACpE;AAED,wBAAsB,kBAAkB,CAAC,QAAQ,EAC/C,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,EAC5B,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,MAAM,CAAC,CAMjB;AAED,wBAAsB,YAAY,CAAC,QAAQ,EACzC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,EAC5B,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,MAAM,CAAC,CAEjB;AAED,wBAAsB,aAAa,CAAC,QAAQ,EAC1C,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,EAC5B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,IAAI,CAAC,CAuBf"}
1
+ {"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M,GAC3B,kBAAkB,CAOpB"}
@@ -1,4 +1,5 @@
1
- import { spawn } from "child_process";
1
+ import { spawn } from "node:child_process";
2
+ import { isAbsolute, relative, resolve as resolvePath, sep } from "node:path";
2
3
  export function execSimple(cmd, args) {
3
4
  return new Promise((resolve, reject) => {
4
5
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
@@ -86,4 +87,32 @@ export async function execWriteFile(executor, path, content, options) {
86
87
  }
87
88
  await run(`base64 -d < ${stageB64} > ${stage} && mv ${stage} ${escapedPath} && rm -f ${stageB64}`);
88
89
  }
90
+ export function createMountedRuntimePathContext(hostWorkspaceRoot, runtimeWorkspaceRoot) {
91
+ return {
92
+ hostWorkspaceRoot,
93
+ runtimeWorkspaceRoot,
94
+ runtimeToHostPath: (runtimePath) => translateMountedRuntimePathToHost(runtimePath, runtimeWorkspaceRoot, hostWorkspaceRoot),
95
+ };
96
+ }
97
+ function translateMountedRuntimePathToHost(runtimePath, runtimeWorkspaceRoot, hostWorkspaceRoot) {
98
+ if (!isAbsolute(runtimePath)) {
99
+ return runtimePath;
100
+ }
101
+ const runtimeRoot = resolvePath(runtimeWorkspaceRoot);
102
+ const normalizedRuntimePath = resolvePath(runtimePath);
103
+ const runtimeRelativePath = relative(runtimeRoot, normalizedRuntimePath);
104
+ const escapesRuntimeRoot = runtimeRelativePath === ".." ||
105
+ runtimeRelativePath.startsWith(`..${sep}`) ||
106
+ isAbsolute(runtimeRelativePath);
107
+ if (escapesRuntimeRoot) {
108
+ return runtimePath;
109
+ }
110
+ const hostRoot = resolvePath(hostWorkspaceRoot);
111
+ const hostPath = resolvePath(hostRoot, runtimeRelativePath);
112
+ const hostRelativePath = relative(hostRoot, hostPath);
113
+ const escapesHostRoot = hostRelativePath === ".." ||
114
+ hostRelativePath.startsWith(`..${sep}`) ||
115
+ isAbsolute(hostRelativePath);
116
+ return escapesHostRoot ? runtimePath : hostPath;
117
+ }
89
118
  //# sourceMappingURL=utils.js.map
@@ -1 +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CAAC,EAAE,MAAM,KAAK,CAAC,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,MAAM,IAAI,iBAAiB,EAAE,CAAC;QAC1F,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,iBAAiB,CAAC,CAAC;QAChE,MAAM,GAAG,CAAC,eAAe,WAAW,CAAC,KAAK,CAAC,OAAO,QAAQ,EAAE,CAAC,CAAC;IAChE,CAAC;IACD,MAAM,GAAG,CACP,eAAe,QAAQ,MAAM,KAAK,UAAU,KAAK,IAAI,WAAW,aAAa,QAAQ,EAAE,CACxF,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from \"child_process\";\n\nexport function execSimple(cmd: string, args: string[]): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (d) => {\n stdout += d;\n });\n child.stderr?.on(\"data\", (d) => {\n stderr += d;\n });\n child.on(\"close\", (code) => {\n if (code === 0) resolve(stdout);\n else reject(new Error(stderr || `Exit code ${code}`));\n });\n });\n}\n\nexport function killProcessTree(pid: number): void {\n if (process.platform === \"win32\") {\n try {\n spawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n detached: true,\n });\n } catch {\n // Ignore errors\n }\n } else {\n try {\n process.kill(-pid, \"SIGKILL\");\n } catch {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n // Process already dead\n }\n }\n }\n}\n\nexport function shellEscape(s: string): string {\n // Escape for passing to sh -c\n return `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Shared exec-backed file transport for executors whose only channel into the\n * runtime is `exec` (docker exec, ssh, HTTP). Contents travel base64-encoded —\n * the base64 alphabet is inert under every shell parse layer — and writes are\n * chunked so no single command approaches the per-argument ARG_MAX limit,\n * staged, then moved into place so an aborted write never truncates the file.\n */\nconst WRITE_CHUNK_CHARS = 65536;\n\ninterface ExecLikeResult {\n stdout: string;\n stderr: string;\n code: number;\n}\n\ninterface ExecLike<TOptions> {\n exec(command: string, options?: TOptions): Promise<ExecLikeResult>;\n}\n\nexport async function execReadFileBase64<TOptions>(\n executor: ExecLike<TOptions>,\n path: string,\n options?: TOptions,\n): Promise<string> {\n const result = await executor.exec(`base64 < ${shellEscape(path)}`, options);\n if (result.code !== 0) {\n throw new Error(result.stderr.trim() || `Failed to read file: ${path}`);\n }\n return result.stdout.replace(/\\s+/g, \"\");\n}\n\nexport async function execReadFile<TOptions>(\n executor: ExecLike<TOptions>,\n path: string,\n options?: TOptions,\n): Promise<string> {\n return Buffer.from(await execReadFileBase64(executor, path, options), \"base64\").toString(\"utf-8\");\n}\n\nexport async function execWriteFile<TOptions>(\n executor: ExecLike<TOptions>,\n path: string,\n content: string,\n options?: TOptions,\n): Promise<void> {\n const encoded = Buffer.from(content, \"utf-8\").toString(\"base64\");\n const escapedPath = shellEscape(path);\n const stage = shellEscape(`${path}.mikan-stage`);\n const stageB64 = shellEscape(`${path}.mikan-stage.b64`);\n\n const run = async (command: string) => {\n const result = await executor.exec(command, options);\n if (result.code !== 0) {\n await executor.exec(`rm -f ${stage} ${stageB64}`, options).catch(() => {});\n throw new Error(result.stderr.trim() || `Failed to write file: ${path}`);\n }\n };\n\n const dir = path.includes(\"/\") ? path.slice(0, path.lastIndexOf(\"/\")) || \"/\" : \".\";\n await run(`mkdir -p ${shellEscape(dir)} && : > ${stageB64}`);\n for (let offset = 0; offset === 0 || offset < encoded.length; offset += WRITE_CHUNK_CHARS) {\n const chunk = encoded.slice(offset, offset + WRITE_CHUNK_CHARS);\n await run(`printf '%s' ${shellEscape(chunk)} >> ${stageB64}`);\n }\n await run(\n `base64 -d < ${stageB64} > ${stage} && mv ${stage} ${escapedPath} && rm -f ${stageB64}`,\n );\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/sand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B,CAAC;IAED,MAAM,QAAQ,GAAG,WAAW,CAAC,iBAAiB,CAAC,CAAC;IAChD,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,EAAE,mBAAmB,CAAC,CAAC;IAC5D,MAAM,gBAAgB,GAAG,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACtD,MAAM,eAAe,GACnB,gBAAgB,KAAK,IAAI;QACzB,gBAAgB,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC;QACvC,UAAU,CAAC,gBAAgB,CAAC,CAAC;IAE/B,OAAO,eAAe,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC;AAClD,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { RuntimePathContext } from \"./types.js\";\n\nexport function execSimple(cmd: string, args: string[]): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (d) => {\n stdout += d;\n });\n child.stderr?.on(\"data\", (d) => {\n stderr += d;\n });\n child.on(\"close\", (code) => {\n if (code === 0) resolve(stdout);\n else reject(new Error(stderr || `Exit code ${code}`));\n });\n });\n}\n\nexport function killProcessTree(pid: number): void {\n if (process.platform === \"win32\") {\n try {\n spawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n detached: true,\n });\n } catch {\n // Ignore errors\n }\n } else {\n try {\n process.kill(-pid, \"SIGKILL\");\n } catch {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n // Process already dead\n }\n }\n }\n}\n\nexport function shellEscape(s: string): string {\n // Escape for passing to sh -c\n return `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Shared exec-backed file transport for executors whose only channel into the\n * runtime is `exec` (docker exec, ssh, HTTP). Contents travel base64-encoded —\n * the base64 alphabet is inert under every shell parse layer — and writes are\n * chunked so no single command approaches the per-argument ARG_MAX limit,\n * staged, then moved into place so an aborted write never truncates the file.\n */\nconst WRITE_CHUNK_CHARS = 65536;\n\ninterface ExecLikeResult {\n stdout: string;\n stderr: string;\n code: number;\n}\n\ninterface ExecLike<TOptions> {\n exec(command: string, options?: TOptions): Promise<ExecLikeResult>;\n}\n\nexport async function execReadFileBase64<TOptions>(\n executor: ExecLike<TOptions>,\n path: string,\n options?: TOptions,\n): Promise<string> {\n const result = await executor.exec(`base64 < ${shellEscape(path)}`, options);\n if (result.code !== 0) {\n throw new Error(result.stderr.trim() || `Failed to read file: ${path}`);\n }\n return result.stdout.replace(/\\s+/g, \"\");\n}\n\nexport async function execReadFile<TOptions>(\n executor: ExecLike<TOptions>,\n path: string,\n options?: TOptions,\n): Promise<string> {\n return Buffer.from(await execReadFileBase64(executor, path, options), \"base64\").toString(\"utf-8\");\n}\n\nexport async function execWriteFile<TOptions>(\n executor: ExecLike<TOptions>,\n path: string,\n content: string,\n options?: TOptions,\n): Promise<void> {\n const encoded = Buffer.from(content, \"utf-8\").toString(\"base64\");\n const escapedPath = shellEscape(path);\n const stage = shellEscape(`${path}.mikan-stage`);\n const stageB64 = shellEscape(`${path}.mikan-stage.b64`);\n\n const run = async (command: string) => {\n const result = await executor.exec(command, options);\n if (result.code !== 0) {\n await executor.exec(`rm -f ${stage} ${stageB64}`, options).catch(() => {});\n throw new Error(result.stderr.trim() || `Failed to write file: ${path}`);\n }\n };\n\n const dir = path.includes(\"/\") ? path.slice(0, path.lastIndexOf(\"/\")) || \"/\" : \".\";\n await run(`mkdir -p ${shellEscape(dir)} && : > ${stageB64}`);\n for (let offset = 0; offset === 0 || offset < encoded.length; offset += WRITE_CHUNK_CHARS) {\n const chunk = encoded.slice(offset, offset + WRITE_CHUNK_CHARS);\n await run(`printf '%s' ${shellEscape(chunk)} >> ${stageB64}`);\n }\n await run(\n `base64 -d < ${stageB64} > ${stage} && mv ${stage} ${escapedPath} && rm -f ${stageB64}`,\n );\n}\n\nexport function createMountedRuntimePathContext(\n hostWorkspaceRoot: string,\n runtimeWorkspaceRoot: string,\n): RuntimePathContext {\n return {\n hostWorkspaceRoot,\n runtimeWorkspaceRoot,\n runtimeToHostPath: (runtimePath) =>\n translateMountedRuntimePathToHost(runtimePath, runtimeWorkspaceRoot, hostWorkspaceRoot),\n };\n}\n\nfunction translateMountedRuntimePathToHost(\n runtimePath: string,\n runtimeWorkspaceRoot: string,\n hostWorkspaceRoot: string,\n): string {\n if (!isAbsolute(runtimePath)) {\n return runtimePath;\n }\n\n const runtimeRoot = resolvePath(runtimeWorkspaceRoot);\n const normalizedRuntimePath = resolvePath(runtimePath);\n const runtimeRelativePath = relative(runtimeRoot, normalizedRuntimePath);\n const escapesRuntimeRoot =\n runtimeRelativePath === \"..\" ||\n runtimeRelativePath.startsWith(`..${sep}`) ||\n isAbsolute(runtimeRelativePath);\n\n if (escapesRuntimeRoot) {\n return runtimePath;\n }\n\n const hostRoot = resolvePath(hostWorkspaceRoot);\n const hostPath = resolvePath(hostRoot, runtimeRelativePath);\n const hostRelativePath = relative(hostRoot, hostPath);\n const escapesHostRoot =\n hostRelativePath === \"..\" ||\n hostRelativePath.startsWith(`..${sep}`) ||\n isAbsolute(hostRelativePath);\n\n return escapesHostRoot ? runtimePath : hostPath;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"chat-history-sync.d.ts","sourceRoot":"","sources":["../../src/sessions/chat-history-sync.ts"],"names":[],"mappings":"AAUA,OAAO,EAYL,KAAK,oBAAoB,EAE1B,MAAM,YAAY,CAAC;AAQpB,YAAY,EACV,sBAAsB,EACtB,6BAA6B,EAC7B,4BAA4B,EAC5B,uBAAuB,EACvB,8BAA8B,EAC9B,sBAAsB,EACtB,0BAA0B,EAC1B,cAAc,GACf,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EACV,sBAAsB,EACtB,6BAA6B,EAC7B,4BAA4B,EAC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EACtB,0BAA0B,EAC1B,cAAc,EAEf,MAAM,YAAY,CAAC;AAEpB,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,6BAA6B,GAAG,OAAO,CAQ1F;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,MAAM,GAAG,IAAI,CAe1F;AAED,wBAAsB,6BAA6B,CACjD,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,OAAO,CAAC,CAqBlB;AAED;;;;;GAKG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAS;IAC7C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAa;IAEjC,YAAY,OAAO,GAAE,sBAA2B,EAI/C;IAEK,mBAAmB,CACvB,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,oBAAoB,CAAC,CAsB/B;IAED,kBAAkB,CAAC,OAAO,EAAE,sBAAsB,GAAG,cAAc,CAUlE;IAED,YAAY,CAAC,OAAO,EAAE,uBAAuB,GAAG,MAAM,CA6CrD;IAED,OAAO,CAAC,0BAA0B;IA2ClC,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,yBAAyB;CAgDlC"}
@@ -1,12 +1,13 @@
1
+ import { officeSessionsDir } from "../office/index.js";
1
2
  import { SessionStore } from "../harness/index.js";
2
3
  import { isRecord } from "../utils/file-guards.js";
3
- import { isCommandText } from "../commands/text.js";
4
+ import { isCommandText } from "../commands/manifest.js";
4
5
  import { readConversationLog } from "./conversation-log.js";
5
6
  import { formatHistoryLine, stripHistoryLinePrefix } from "./history-line.js";
6
- import { isPlatformHistorySession } from "./metadata.js";
7
+ import { isPlatformHistorySession } from "./store.js";
7
8
  import { shouldRotateTopLevelSession } from "./rotation.js";
8
9
  import { isThreadSessionKey } from "./session-key.js";
9
- import { createManagedSessionFile, createManagedSessionFileAtPath, extractSessionSuffix, getChannelSessionDir, getThreadSessionFile, openManagedSession, resolveChannelSessionFile, resolveParentSessionForThread, tryResolveCurrentSession, tryResolveThreadSession, } from "./store.js";
10
+ import { createManagedSessionFile, createManagedSessionFileAtPath, extractSessionSuffix, getThreadSessionFile, openManagedSession, resolveChannelSessionFile, resolveParentSessionForThread, tryResolveCurrentSession, tryResolveThreadSession, } from "./store.js";
10
11
  const DEFAULT_RECENT_DAYS = 14;
11
12
  const DEFAULT_MAX_TOP_LEVEL_MESSAGES = 200;
12
13
  const CHAT_SYNC_CUSTOM_TYPE = "mikan.chat_sync";
@@ -53,7 +54,7 @@ export class ChatHistorySync {
53
54
  }
54
55
  async resolveSessionScope(options) {
55
56
  const cwd = options.cwd ?? options.conversationDir;
56
- const sessionDir = getChannelSessionDir(options.conversationDir);
57
+ const sessionDir = officeSessionsDir(options.conversationDir);
57
58
  if (!isThreadSessionKey(options.sessionKey)) {
58
59
  const contextFile = this.resolveTopLevelSessionFile({
59
60
  conversationDir: options.conversationDir,
@@ -111,7 +112,7 @@ export class ChatHistorySync {
111
112
  resolveParentSessionForThread(options.conversationDir, extractSessionSuffix(options.sessionKey)) ?? undefined;
112
113
  return createManagedSessionFileAtPath(threadFile, cwd, parent);
113
114
  })()
114
- : createManagedSessionFile(getChannelSessionDir(options.conversationDir), cwd);
115
+ : createManagedSessionFile(officeSessionsDir(options.conversationDir), cwd);
115
116
  const records = readConversationLog(options.conversationDir);
116
117
  const lastMessageId = latestSyncMessageId(records, {
117
118
  sessionKey: isThreadSessionKey(options.sessionKey) ? options.sessionKey : null,
@@ -181,7 +182,7 @@ export class ChatHistorySync {
181
182
  }
182
183
  function findLogRecordById(records, messageId) {
183
184
  for (let i = records.length - 1; i >= 0; i--) {
184
- if (records[i].message.ts === messageId)
185
+ if (records[i]?.message.ts === messageId)
185
186
  return records[i];
186
187
  }
187
188
  return undefined;
@@ -343,7 +344,7 @@ function appendLogRecordsToSession(sessionManager, records) {
343
344
  function getLatestChatSyncResetAt(entries) {
344
345
  for (let i = entries.length - 1; i >= 0; i--) {
345
346
  const entry = entries[i];
346
- if (entry.type !== "custom" || entry.customType !== CHAT_SYNC_CUSTOM_TYPE)
347
+ if (entry?.type !== "custom" || entry.customType !== CHAT_SYNC_CUSTOM_TYPE)
347
348
  continue;
348
349
  if (!isRecord(entry.data) || typeof entry.data.resetAt !== "string")
349
350
  continue;
@@ -362,7 +363,7 @@ function isAfterReset(record, resetAt) {
362
363
  function getLatestChatSyncMessageId(entries) {
363
364
  for (let i = entries.length - 1; i >= 0; i--) {
364
365
  const entry = entries[i];
365
- if (entry.type !== "custom" || entry.customType !== CHAT_SYNC_CUSTOM_TYPE)
366
+ if (entry?.type !== "custom" || entry.customType !== CHAT_SYNC_CUSTOM_TYPE)
366
367
  continue;
367
368
  if (!isRecord(entry.data))
368
369
  return undefined;